jsrepo 1.41.3 → 1.41.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 +34 -35
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {h,g,f,u,c,l,n,t,a,b,w,v,s,k}from'./chunk-J7BJNBQR.js';import {Command,program,Argument,Option}from'commander';import ie from'node:fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,password,spinner,intro}from'@clack/prompts';import E from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Y from'pathe';import*as $ from'valibot';import
|
|
3
|
-
${JSON.stringify(a,null," ")}`);let c=await Sn({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:
|
|
4
|
-
${JSON.stringify(a,null," ")}`);let c=await
|
|
5
|
-
${JSON.stringify(
|
|
6
|
-
${JSON.stringify(i,null," ")}`);let a=await jn({model:"phi4",prompt:i,messages:s});return o||r.stop("Phi4 updated the file"),a?{content:Vt(a),prompt:i.message}:{content:t.content,prompt:i.message}}}},co=async({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n})=>{let a=(await new Rn({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},Sn=async({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n})=>{let s=new bn({apiKey:n}),i=[];if(t)for(let l of t)i.push({role:l.role,content:[{type:"text",text:l.content}]});i.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await s.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:i})).content[0];return c.type!=="text"?null:c.text},jn=async({prompt:e,messages:t,model:r})=>(await Cn.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content,Mt=({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o})=>({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,u,c,l,n,t,a,b,w,v,s,k}from'./chunk-J7BJNBQR.js';import {Command,program,Argument,Option}from'commander';import ie from'node:fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,password,spinner,intro}from'@clack/prompts';import E from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Y from'pathe';import*as $ from'valibot';import pn from'is-unicode-supported';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as yr from'css-dependency';import {walk}from'estree-walker';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import*as Po from'parse5';import*as De from'prettier';import*as Io from'svelte/compiler';import {Project,SyntaxKind}from'ts-morph';import es from'validate-npm-package-name';import*as Gt from'vue/compiler-sfc';import mn from'node:os';import {stripVTControlCharacters}from'node:util';import Yn from'escape-string-regexp';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import yo from'boxen';import {diffLines,diffChars}from'diff';import fo from'semver';import {cursor,erase}from'sisteransi';import wn from'@anthropic-ai/sdk';import xn from'ollama';import Cn from'openai';import vn from'conf';import $r from'node-fetch';import Gs from'ignore';var pt={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"1.41.4"};var fn=pn(),se=(e,t)=>fn?e:t,Hr=se("\u25C6","*"),qr=se("\u25C6","*"),Yr=se("\u25A0","x"),O=E.gray(se("\u2502","|")),Ct=E.gray(se("\u2500","-")),Qr=E.gray(se("\u2510","+")),Xr=E.gray(se("\u2518","+")),Rt=E.gray(se("\u251C","+")),Zr=E.gray(se("\u252C","+"));E.gray(se("\u250C","T"));var eo=E.gray(se("\u2514","-")),we=E.bgRgb(245,149,66).black(" WARN "),Pe=E.bgBlueBright.white(" INFO "),St=E.bgRedBright.white(" ERROR "),Ie=E.hex("#f7df1e")("jsrepo");var to=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r},ro=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var jt=(e,t,r=" ")=>{if(stripVTControlCharacters(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-stripVTControlCharacters(e).length)+e};var un=/\n|\r\n/g,Z=e=>e.split(un),ee=(e,{lineNumbers:t=false,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${jt(`${i+1}`,n)} ${s}`);}return r!==void 0&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(mn.EOL)};var gn={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},hn={"install-as-dev-dependency":"-D"},yn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},so={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},io={"no-workspace":"--focus","install-as-dev-dependency":"-D"},sr={bun:gn,npm:yn,pnpm:so,deno:hn,yarn:io,"yarn@berry":io,"pnpm@6":so};var Ce=()=>new vn({projectName:"jsrepo"});var Ue=class{#e;constructor(t){this.#e=t??Ce();}getKey(t){return `${t}-token`.toLowerCase()}get(t){let r=this.getKey(t);return this.#e.get(r,void 0)}set(t,r){let o=this.getKey(t);this.#e.set(o,r);}delete(t){let r=this.getKey(t);this.#e.delete(r);}};var cr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{let i=await ao("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=ir({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
|
|
3
|
+
${JSON.stringify(a,null," ")}`);let c=await Sn({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content:ar(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:s})=>{let i=await ao("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=ir({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting OpenAI o3-mini with:
|
|
4
|
+
${JSON.stringify(a,null," ")}`);let c=await Rn({model:"o3-mini",prompt:a,apiKey:i,messages:s,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("OpenAI o3-mini updated the file"),c?{content:ar(c),prompt:a.message}:{content:t.content,prompt:a.message}}},Phi4:{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:s})=>{o||r.start("Asking Phi4");let i=ir({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:s!==void 0&&s.length>0});o?.(`Prompting Phi4 with:
|
|
5
|
+
${JSON.stringify(i,null," ")}`);let a=await jn({model:"phi4",prompt:i,messages:s});return o||r.stop("Phi4 updated the file"),a?{content:ar(a),prompt:i.message}:{content:t.content,prompt:i.message}}}},Rn=async({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n})=>{let a=(await new Cn({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},Sn=async({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n})=>{let s=new wn({apiKey:n}),i=[];if(t)for(let l of t)i.push({role:l.role,content:[{type:"text",text:l.content}]});i.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await s.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:i})).content[0];return c.type!=="text"?null:c.text},jn=async({prompt:e,messages:t,model:r})=>(await xn.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content,ir=({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o})=>({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??"":`
|
|
7
6
|
This is my current file ${e.path}:
|
|
8
7
|
<code>
|
|
9
8
|
${e.content}
|
|
@@ -13,49 +12,49 @@ This is the file that has changes I want to update with ${t.path}:
|
|
|
13
12
|
<code>
|
|
14
13
|
${t.content}
|
|
15
14
|
</code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
|
|
16
|
-
`}),
|
|
15
|
+
`}),ar=e=>{let t=e.trim();if(t.startsWith("```")&&(t=Z(t).slice(1).join(`
|
|
17
16
|
`).trim()),t.endsWith("```")){let r=Z(t);t=r.slice(0,r.length-1).join(`
|
|
18
|
-
`).trim();}return t},
|
|
19
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},
|
|
17
|
+
`).trim();}return t},ao=async e=>{let t=new Ue,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 Re=pt;var co=e=>/^\s+$/g.test(e),ft=e=>{let t=e.length-1;for(;co(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},lo=({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:s=E.redBright,colorAdded:i=E.greenBright,colorCharsRemoved:a=E.bgRedBright,colorCharsAdded:c=E.bgGreenBright,prefix:l,onUnchanged:d,intro:m})=>{let h="",u=ro(r,g=>g.count??0).toString().length+1,y=0;if(r.length===1&&!r[0].added&&!r[0].removed)return d({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:l,onUnchanged:d,intro:m});h+=m({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:l,onUnchanged:d,intro:m});let f=g=>E.gray(`${l?.()??""}${jt(`${g+1+y} `,u)} `);for(let g=0;g<r.length;g++){let p=r[g],P=r[g-1]?.added||r[g-1]?.removed,x=r[g+1]?.added||r[g+1]?.removed;if(!p.added&&!p.removed){if(!o&&p.count!==void 0&&p.count>n){let C=y,R=Z(ft(p.value)),I=0;if(x&&(I+=n),P&&(I+=n),I>=R.length){h+=`${ee(R,{prefix:f})}
|
|
20
19
|
`,y+=R.length;continue}if(P&&(h+=`${ee(R.slice(0,n),{prefix:f})}
|
|
21
|
-
`),R.length>I){let
|
|
20
|
+
`),R.length>I){let z=R.length-I;h+=`${ee(Z(E.gray(`+ ${z} more unchanged (${E.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${jt(" ",u)} `})}
|
|
22
21
|
`;}x&&(y=y+R.length-n,h+=`${ee(R.slice(R.length-n),{prefix:f})}
|
|
23
22
|
`),y=C+p.count;continue}h+=`${ee(Z(ft(p.value)),{prefix:f})}
|
|
24
|
-
`,y+=p.count??0;continue}let v=C=>C.added?i(ft(C.value)):C.removed?s(ft(C.value)):C.value,k=C=>C.added?c(ft(C.value)):C.removed?a(ft(C.value)):C.value;if(p.removed&&p.count===1&&r[g+1]?.added&&r[g+1]?.count===1){let R=diffChars(p.value,r[g+1].value).map(I=>k(I)).join("");h+=`${f(0)}${R}`,y+=1,g++;}else
|
|
23
|
+
`,y+=p.count??0;continue}let v=C=>C.added?i(ft(C.value)):C.removed?s(ft(C.value)):C.value,k=C=>C.added?c(ft(C.value)):C.removed?a(ft(C.value)):C.value;if(p.removed&&p.count===1&&r[g+1]?.added&&r[g+1]?.count===1){let R=diffChars(p.value,r[g+1].value).map(I=>k(I)).join("");h+=`${f(0)}${R}`,y+=1,g++;}else co(p.value)?(h+=`${ee(Z(k(p)),{prefix:C=>`${f(C)}${k({removed:true,value:" ",added:false})}`})}
|
|
25
24
|
`,p.removed||(y+=p.count??0)):(h+=`${ee(Z(v(p)),{prefix:f})}
|
|
26
25
|
`,p.removed||(y+=p.count??0));}return h.endsWith(`
|
|
27
26
|
`)||(h=h+=`
|
|
28
|
-
`),h};var
|
|
29
|
-
`),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Rt),bottomLeft:stripVTControlCharacters(Rt),topRight:stripVTControlCharacters(
|
|
27
|
+
`),h};var lr="latest-version",En=60*60*1e3,po=async({noCache:e=false}={})=>{try{let t=Ce(),r;if(!e){let a$1=t.get(lr);if(a$1){if(a$1.expiration>Date.now())return r=a$1.version,a(r);t.delete(lr);}}let o=new AbortController,n=setTimeout(()=>{o.abort();},1e3),s=await $r("https://raw.githubusercontent.com/ieedan/jsrepo/refs/heads/main/packages/cli/package.json",{signal:o.signal});if(clearTimeout(n),!s.ok)return b("Error getting version");let{version:i}=await s.json();return r=i,t.set(lr,{expiration:Date.now()+En,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}};var Dn=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,On=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,ze=e=>{let t=Dn.exec(e)||On.exec(e);return t?a({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):b(`invalid package name: ${e}`)};var pr=(e,t)=>{let r=Y.join(e,"package.json");if(ie.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return pr(o.slice(0,o.length-1).join("/"),t)},fr=e=>{if(!ie.existsSync(e))return b(`${e} doesn't exist`);let t=ie.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}},Mt=e=>e[0]==="^"?e.slice(1):e,uo=(e,t,{cwd:r})=>{let o=e,n=t,s=fr(Y.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of o){let{name:c,version:l}=ze(a).unwrap(),d=i.dependencies[c];if(l===void 0&&d){o.delete(a);continue}d&&fo.satisfies(Mt(d),l)&&o.delete(a);}if(i.devDependencies)for(let a of n){let{name:c,version:l}=ze(a).unwrap(),d=i.devDependencies[c];if(l===void 0&&d){n.delete(a);continue}d&&fo.satisfies(Mt(d),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}};var vo=async(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);}},wo=async({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);},Ee=({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);}}},et=e=>{let t=yo(e.join(`
|
|
28
|
+
`),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Rt),bottomLeft:stripVTControlCharacters(Rt),topRight:stripVTControlCharacters(Qr),top:stripVTControlCharacters(Ct),bottom:stripVTControlCharacters(Ct),bottomRight:stripVTControlCharacters(Xr),left:stripVTControlCharacters(O),right:stripVTControlCharacters(O)}});return `${O}
|
|
30
29
|
${t}
|
|
31
|
-
`},
|
|
32
|
-
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})},le=async()=>{console.clear();let e=await
|
|
33
|
-
`);let s=false,i=e.content,a=n.get(
|
|
30
|
+
`},bo=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},Un=async(e,t,r)=>{let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),s=[`Update available! ${E.redBright(t)} -> ${E.greenBright(r)}`,`${E.cyan("Changelog")}: https://github.com/ieedan/jsrepo/releases/tag/${e}@${r}`,`Run ${E.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${E.yellowBright("Star")} on GitHub for updates: https://github.com/ieedan/jsrepo`];return yo(s.join(`
|
|
31
|
+
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})},le=async()=>{console.clear();let e=await po();e.isOk()&&fo.lt(Re.version,e.unwrap())&&console.info(await Un(Re.name,Re.version,e.unwrap())),intro(`${E.bgHex("#f7df1e").black(` ${Re.name} `)}${E.gray(` v${Re.version} `)}`);},ho="model-preference",mt=async({incoming:e,current:t,config:r,options:o})=>{let n=Ce();process.stdout.write(`${O}
|
|
32
|
+
`);let s=false,i=e.content,a=n.get(ho,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,i),d=lo({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${O} `,onUnchanged:({from:m,to:h,prefix:u})=>`${u?.()??""}${E.cyan(m)} \u2192 ${E.gray(h)} ${E.gray("(unchanged)")}
|
|
34
33
|
`,intro:({from:m,to:h,changes:u,prefix:y})=>{let f=u.filter(g=>g.added||g.removed).length;return `${y?.()??""}${E.cyan(m)} \u2192 ${E.gray(h)} (${f} change${f===1?"":"s"})
|
|
35
34
|
${y?.()??""}
|
|
36
|
-
`}});if(process.stdout.write(d),(l.length>1||t.content==="")&&(s=o.yes,!o.yes&&!o.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${E.yellow("Update with AI")} \u2728 ${E.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${E.yellow("Update with AI")} \u2728 ${E.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${E.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:m});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let u=await select({message:"Select a model",options:Object.keys(
|
|
37
|
-
`);continue}i=await
|
|
38
|
-
`);continue}s=h==="accept";break}break}return s?{applyChanges:true,updatedContent:i}:{applyChanges:false}},Me=async(e,t,{yes:r,no:o=false,cwd:n,pm:s,ignoreWorkspace:i=false})=>{let{dependencies:a,devDependencies:c}=
|
|
35
|
+
`}});if(process.stdout.write(d),(l.length>1||t.content==="")&&(s=o.yes,!o.yes&&!o.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${E.yellow("Update with AI")} \u2728 ${E.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${E.yellow("Update with AI")} \u2728 ${E.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${E.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:m});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let u=await select({message:"Select a model",options:Object.keys(cr).map(f=>({label:f,value:f})),initialValue:a});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!==a&&n.set(ho,u),a=u;let y=await text({message:"Additional instructions:",defaultValue:"None",validate:f=>{if(c.length!==0&&f.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(y)&&(cancel("Canceled!"),process.exit(0));try{let{content:f,prompt:g}=await cr[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?i:e.content,path:e.path},additionalInstructions:y!=="None"?y:void 0,loading:o.loading,verbose:o.verbose,messages:c});i=f,c.push({role:"user",content:g}),c.push({role:"assistant",content:f});}catch(f){o.loading.stop(),log.error(E.red(`Error getting completions: ${f}`)),process.stdout.write(`${O}
|
|
36
|
+
`);continue}i=await Jt({file:{content:i,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${O}
|
|
37
|
+
`);continue}s=h==="accept";break}break}return s?{applyChanges:true,updatedContent:i}:{applyChanges:false}},Me=async(e,t,{yes:r,no:o=false,cwd:n,pm:s,ignoreWorkspace:i=false})=>{let{dependencies:a,devDependencies:c}=uo(e,t,{cwd:n});if(a.size>0||c.size>0){let d=r;if(!r&&!o){let m=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),d=m;}if(d)return a.size>0&&await mr({pm:s,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:i}),c.size>0&&await mr({pm:s,deps:Array.from(c),dev:false,cwd:n,ignoreWorkspace:i}),{installed:true,dependencies:a,devDependencies:c}}return {installed:false,dependencies:a,devDependencies:c}},ko=e=>{let t=E.dim(O),r=E.green(Hr),o=E.green(qr),n=E.red(Yr);process.stdout.write(`${t}
|
|
39
38
|
`),process.stdout.write(`${r} ${e}
|
|
40
39
|
`);let s="",i="",a=(l=false)=>{if(!i)return;let d=process.stdout.columns,h=i.split(`
|
|
41
40
|
`).reduce((u,y)=>u+Math.ceil(y.length/d),0)+(l?1:0);process.stdout.write(cursor.up(h)),process.stdout.write(erase.down());},c=(l=0)=>{let d=s.split(`
|
|
42
41
|
`).slice(-l);i="";for(let m of d)i+=`${t} ${m}
|
|
43
42
|
`;process.stdout.write(E.dim(i));};return {set text(l){a(),s+=l;let d=Math.ceil(process.stdout.rows/2);c(d);},fail(l){a(true),process.stdout.write(`${n} ${l}
|
|
44
43
|
`),c();},success(l){a(true),process.stdout.write(`${o} ${l}
|
|
45
|
-
`);}}};var
|
|
44
|
+
`);}}};var mr=async({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false})=>{let s=[...t];let i=sr[e]["no-workspace"];n&&i&&s.push(i);let a=resolveCommand$1(e,"add",s);a==null&&program.error(E.red(`Could not resolve add command for '${e}'.`));let c=ko(`Installing dependencies with ${e}...`);try{let l=execa(a.command,[...a.args],{cwd:o});l.stdout.on("data",d=>{c.text=d;}),l.stderr.on("data",d=>{c.text=d;}),await l,c.success(`Installed ${E.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}},Hn=/\{\{([^\/]+)\/([^\}]+)\}\}/g,xo=({template:e,config:t,destPath:r,cwd:o})=>{let n=Y.join(r,"../");return e.replace(Hn,(s,i,a)=>{if(t.paths[i]===void 0){if(t.paths["*"].startsWith(".")){let c=Y.relative(n,Y.join(o,t.paths["*"],i,a));return c.startsWith(".")?c:`./${c}`}return Y.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let c=Y.relative(n,Y.join(o,t.paths[i],a));return c.startsWith(".")?c:`./${c}`}return Y.join(t.paths[i],a)})};var It=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:s,cwd:i,verbose:a$1})=>{let c=rt.find(d=>d.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
|
|
46
45
|
|
|
47
|
-
${l}`),a$1?.(`Formatting ${E.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(d){return b(`Error formatting ${E.bold(e.destPath)} ${d}`)}}for(let[d,m]of Object.entries(r)){let h=
|
|
46
|
+
${l}`),a$1?.(`Formatting ${E.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(d){return b(`Error formatting ${E.bold(e.destPath)} ${d}`)}}for(let[d,m]of Object.entries(r)){let h=xo({template:m,config:t,destPath:e.destPath,cwd:i}),u=new RegExp(`(['"])${Yn(d)}\\1`,"g");l=l.replaceAll(u,`$1${h}$1`);}return a(l)},Jt=async({file:e,formatter:t,prettierOptions:r,biomeOptions:o})=>{let n=rt.find(i=>i.matches(e.destPath)),s=e.content;if(n)try{s=await n.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r,biomeOptions:o});}catch{return s}return s},Ro=e=>{let t=[".js",".ts",".cjs",".mjs"];if(!k(e,t))return;let r=Y.dirname(e),o=ie.readdirSync(r),n=Y.parse(e);for(let s of o)if(k(s,t)&&Y.parse(s).name===n.name)return Y.join(r,s)},ut=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 ${E.bold("tsconfig.json")}: ${r}`)}return a(t)};var ts={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=yr.parse(i,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=ht({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(d=>gt(d)).join(`
|
|
48
47
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
49
48
|
${ee(Z(e),{prefix:()=>" "})}
|
|
50
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},rs={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=
|
|
49
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},rs={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=Po.parse(i),c=[],l=(m,h)=>{if(m&&(h(m),m.childNodes&&m.childNodes.length>0))for(let u of m.childNodes)l(u,h);};for(let m of a$1.childNodes)l(m,h=>{if(h.tagName==="script")for(let u of h.attrs)u.name==="src"&&c.push(u.value);if(h.tagName==="link"&&h.attrs.find(u=>u.name==="rel"&&u.value==="stylesheet"))for(let u of h.attrs)u.name==="href"&&!u.value.startsWith("http")&&c.push(u.value);});let d=ht({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(m=>gt(m)).join(`
|
|
51
50
|
`)):a(d.unwrap())},comment:e=>`<!--
|
|
52
51
|
${ee(Z(e),{prefix:()=>" "})}
|
|
53
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"html",...r}):e},
|
|
52
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"html",...r}):e},vr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},os={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
54
53
|
${ee(Z(e),{prefix:()=>" "})}
|
|
55
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:true}}}),s.formatContent(e,{filePath:n}).content}},ns={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=
|
|
54
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:true}}}),s.formatContent(e,{filePath:n}).content}},ns={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=yr.parse(i);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=ht({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(d=>gt(d)).join(`
|
|
56
55
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
57
56
|
${ee(Z(e),{prefix:()=>" "})}
|
|
58
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"scss",...r}):e},ss={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=
|
|
57
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"scss",...r}):e},ss={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=Io.parse(i,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=m=>{(m.type==="ImportDeclaration"||m.type==="ExportAllDeclaration"||m.type==="ExportNamedDeclaration")&&typeof m.source?.value=="string"&&c.push(m.source.value),m.type==="ImportExpression"&&m.source.type==="Literal"&&typeof m.source.value=="string"&&c.push(m.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let d=ht({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(m=>gt(m)).join(`
|
|
59
58
|
`)):a(d.unwrap())},comment:e=>`<!--
|
|
60
59
|
${ee(Z(e),{prefix:()=>" "})}
|
|
61
60
|
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await De.format(e,{filepath:r,...o}):e},is={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
@@ -63,21 +62,21 @@ ${ee(Z(e),{prefix:()=>" "})}
|
|
|
63
62
|
-->`,format:async e=>e},as={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:s})=>{let a$1=new Project().addSourceFileAtPath(e),c=a$1.getImportDeclarations().map(h=>h.getModuleSpecifierValue()),l=a$1.getDescendantsOfKind(SyntaxKind.CallExpression);for(let h of l)if(h.getExpression().getKind()===SyntaxKind.ImportKeyword){let y=h.getArguments()[0];y.getKind()===SyntaxKind.StringLiteral&&c.push(y.getLiteralValue());}let d=a$1.getExportDeclarations().map(h=>h.getModuleSpecifierValue()).filter(h=>h!==void 0);c.push(...d);let m=ht({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:r});return m.isErr()?b(m.unwrapErr().map(h=>gt(h)).join(`
|
|
64
63
|
`)):a(m.unwrap())},comment:e=>`/*
|
|
65
64
|
${ee(Z(e),{prefix:()=>" "})}
|
|
66
|
-
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},cs={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=
|
|
65
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await De.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},cs={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:s})=>{let i=ie.readFileSync(e).toString(),a$1=Gt.parse(i,{filename:e});if(!a$1.descriptor.script?.content&&!a$1.descriptor.scriptSetup?.content)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c;try{c=Gt.compileScript(a$1.descriptor,{id:"shut-it"});}catch(m){return b(`Compile error: ${m}`)}if(!c.imports)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Object.values(c.imports).map(m=>m.source),d=ht({moduleSpecifiers:l,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:s,doNotInstall:["vue","nuxt",...r]});return d.isErr()?b(d.unwrapErr().map(m=>gt(m)).join(`
|
|
67
66
|
`)):a(d.unwrap())},comment:e=>`<!--
|
|
68
67
|
${ee(Z(e),{prefix:()=>" "})}
|
|
69
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"vue",...r}):e},ls={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>ee(Z(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"yaml",...r}):e},gt=e=>`${ee(Z(e),{prefix:t=>t===0?`${O} ${St} `:`${O} `})}`,ht=({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:s,cwd:i})=>{let a$1=[],c=new Set,l=new Set,d={};for(let u of e){if(u.startsWith(".")){let g=
|
|
70
|
-
${s||e} references code not contained in ${E.bold(i.join(", "))} and cannot be resolved.`)},Po=(e,t=true)=>{let[r,o,...n]=e.split("/");o===void 0&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-Y.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=Y.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},ds=(e,t,{filePath:r,dirs:o,cwd:n,containingDir:s})=>{let i=ut(r);if(i.isErr())return b(i.unwrapErr());let a$1=i.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let d of l){let m=fs(d);if(!m)continue;let h=Y.relative(Y.resolve(Y.join(r,"../")),m.prettyPath),u=ps(m.prettyPath,m.path,[".js",".ts"]),y=Do(h,t,{filePath:r,containingDir:s,alias:e,dropExtension:u,dirs:o,cwd:n,modIsFile:m.type==="file"});if(y.isErr())return b(y.unwrapErr());if(y.unwrap())return a(y.unwrap());break}}return a(void 0)},ps=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let o=Y.parse(e),n=Y.parse(t),s=Y.join(o.dir,o.name),i=Y.join(n.dir,n.name);return s!==i?false:!!(r.includes(o.ext)&&r.includes(n.ext))},fs=e=>{if(ie.existsSync(e))return {path:e,prettyPath:e,type:ie.statSync(e).isDirectory()?"directory":"file"};let t=Y.join(e,"../");if(!ie.existsSync(t))return;let r=Y.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(ie.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=ie.readdirSync(t);for(let n of o){let s=Y.parse(n);if(s.name===r.base){let i=Y.join(t,n),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:ie.statSync(i).isDirectory()?"directory":"file"}}}},ms=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(c=>!builtinModules.includes(c)&&!c.startsWith("node:")),s=fr(Y.dirname(t),""),i=new Set,a=new Set;if(s){let{devDependencies:c,dependencies:l}=JSON.parse(ie.readFileSync(s,"utf-8"));for(let d of n){let m=Ue(d);if(m.isErr()){console.warn(`${O} ${we} Skipped adding import \`${E.cyan(d)}\`. Reason: Couldn't parse package name`);continue}let h=m.unwrap();if(!es(h.name).validForNewPackages){console.warn(`${O} ${we} Skipped adding import \`${E.cyan(d)}\`. Reason: Not a valid package name`);continue}if(o.has(h.name))continue;let u;if(l!==void 0&&(u=l[h.name]),u!==void 0){i.add(`${h.name}@${u}`);continue}if(c!==void 0&&(u=c[h.name]),u!==void 0){a.add(`${h.name}@${u}`);continue}i.add(h.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(a)}},rt=[ts,rs,wr,os,ns,ss,is,as,cs,ls];var To=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),No=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),gs=$.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")]),Ao={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${E.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,s]=o.split("/"),i=t.categories.find(c=>c.name.trim()===n.trim()),a=`${E.bold(`${e.category}/${e.name}`)} depends on local dependency ${E.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(c=>c.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.categories.find(c=>c.name===n);!i||!i.blocks.find(c=>c.name===s)||r.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${E.bold(`${e.category}/${e.name}`)} has too many local dependencies (${E.bold(e.localDependencies.length)}) limit (${E.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=Yt(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${E.bold(o)}: ${E.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(Yt(r,n,t.categories))return;return [`${E.bold(r)} is unused and will be ${E.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=>Ue(o).unwrap().name).filter(o=>To.has(o));if(r.length>0)for(let o of r)t.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.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)ie.existsSync(Y.join(t,o.path))||r.push(`The ${E.bold(o.name)} config file doesn't exist at ${E.bold(Y.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=>Ue(n).unwrap().name).filter(n=>To.has(n));if(o.length>0)for(let n of o)t.push(`${E.bold(r.name)} depends on ${E.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 ${E.bold(o)}`);return t.length>0?t:void 0}}}},Fo=$.record(gs,$.union([No,$.tupleWithRest([No,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),br={"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"},Lo=(e,t,r,o=br)=>{let n=[],s=[];for(let[i,a]of Object.entries(Ao)){if(a.scope==="block")continue;let c=o[i],l,d=[];if(Array.isArray(c)?(l=c[0],d.push(...c.slice(1))):l=c,l==="off")continue;let m=a.check({manifest:e,options:d,cwd:r,config:t});if(m){if(l==="error"){s.push(...m.map(h=>`${O} ${St} ${E.red(h)} ${E.gray(i)}`));continue}n.push(...m.map(h=>`${O} ${we} ${h} ${E.gray(i)}`));}}for(let i of e.categories)for(let a of i.blocks)for(let[c,l]of Object.entries(Ao)){if(l.scope==="global")continue;let d=o[c],m,h=[];if(Array.isArray(d)?(m=d[0],h.push(...d.slice(1))):m=d,m==="off")continue;let u=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(u){if(m==="error"){s.push(...u.map(y=>`${O} ${St} ${E.red(y)} ${E.gray(c)}`));continue}n.push(...u.map(y=>`${O} ${we} ${y} ${E.gray(c)}`));}}return {warnings:n,errors:s}},Yt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),c=r.find(d=>d.name===i)?.blocks.find(d=>d.name===a);if(!c)continue;let l=Yt(e,c,r,n);if(l)return [...l,e]}},Bo=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Yt(e,o,t))return true}return false};var Wo=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],ze=e=>Wo.find(t=>e.endsWith(t))!==void 0,Jo=(e,{cwd:t,ignore:r,config:o})=>{let n;try{n=ie.readdirSync(e);}catch{program.error(E.red(`Couldn't read the ${E.bold(e)} directory.`));}let s=[];for(let i of n){let a=Y.join(e,i);if(ie.statSync(a).isFile())continue;let c=`${Y.relative(t,a)}/`;if(r.ignores(c))continue;let l=Y.basename(i);if(!ys(l,o))continue;let d=hs(l,o),m={name:l,blocks:[]},h=ie.readdirSync(a);for(let u of h){let y=Y.join(a,u);if(ie.statSync(y).isFile()){if(ze(u))continue;let f=vs(u),g=_o(f,o);if(!Mo(f,o))continue;let p=rt.find(I=>I.matches(u));if(!p){console.warn(`${O} ${we} Skipped \`${E.bold(y)}\` \`*${E.bold(Y.parse(u).ext)}\` files are not currently supported!`);continue}let P=h.find(I=>Wo.find(U=>I===`${f}${U}`)),{dependencies:x,devDependencies:v,local:k,imports:C}=p.resolveDependencies({filePath:y,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(I=>I,I=>{program.error(E.red(I));}),R={name:f,directory:Y.relative(t,a),category:l,tests:P!==void 0,subdirectory:false,list:d?g:false,files:[u],localDependencies:k,_imports_:C,dependencies:x,devDependencies:v};P!==void 0&&R.files.push(P),m.blocks.push(R);}else {let f=u,g=_o(f,o);if(!Mo(f,o))continue;let p=new Set,P=new Set,x=new Set,v={},k=false,C=[],R=(U,K)=>{for(let H of K){let b=Y.join(U,H),T=b.slice(y.length+1);if(ze(H)){k=true,C.push(T);continue}if(ie.statSync(b).isDirectory()){if(!o.allowSubdirectories){console.warn(`${O} ${we} Skipped \`${E.bold(Y.join(y,H))}\` subdirectories are not allowed! Allow them with ${E.bold("--allow-subdirectories")}!`);continue}let F=ie.readdirSync(b);R(b,F);continue}let w=rt.find(F=>F.matches(H));if(!w){console.warn(`${O} ${we} Skipped \`${b}\` \`*${E.bold(Y.parse(H).ext)}\` files are not currently supported!`);continue}let{local:V,dependencies:N,devDependencies:W,imports:A}=w.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:y,filePath:b,cwd:t}).match(F=>F,F=>{program.error(E.red(F));});for(let F of V)F!==`${l}/${f}`&&p.add(F);for(let F of N)P.add(F);for(let F of W)x.add(F);for(let[F,je]of Object.entries(A))v[F]=je;C.push(T);}};R(y,ie.readdirSync(y));let I={name:f,directory:Y.relative(t,y),category:l,tests:k,subdirectory:true,list:d?g:false,files:C,localDependencies:Array.from(p.keys()),dependencies:Array.from(P.keys()),devDependencies:Array.from(x.keys()),_imports_:v};m.blocks.push(I);}}s.push(m);}return s},Go=(e,{cwd:t})=>{if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=rt.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:s,devDependencies:i,local:a}=n.resolveDependencies({filePath:Y.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(E.red(c));});a.length>0&&program.error(E.red(`${E.bold(o.name)} ${E.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:s,devDependencies:i});}return r},_o=(e,t)=>t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true,Mo=(e,t)=>t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true,hs=(e,t)=>t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true,ys=(e,t)=>t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true,vs=e=>Y.parse(Y.basename(e)).name,Uo=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!Bo(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var nt="jsrepo.json",He="jsrepo-build-config.json",kr=$.union([$.literal("prettier"),$.literal("biome")]),bs=$.objectWithRest({"*":$.string()},$.string()),$r=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:bs,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(kr)}),Te=e=>{if(!ie.existsSync(Y.join(e,nt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse($r,JSON.parse(ie.readFileSync(Y.join(e,nt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${nt}\` file!`)},ks=$.object({$schema:$.string(),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(Fo)}),Zt=e=>{if(!ie.existsSync(Y.join(e,He)))return a(null);let t=$.safeParse(ks,JSON.parse(ie.readFileSync(Y.join(e,He)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${He}\` file!`)},Ne=(e,t)=>{let r=ut(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[s,i]of Object.entries(e)){if(i.startsWith("./")){n[s]=Y.relative(t,Y.join(Y.resolve(t),i));continue}if(o===null)return b(`Cannot resolve ${E.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${E.bold("`./`")}.`);let a=$s(i,o,t);if(!a)return b(`Cannot resolve ${E.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${E.bold("`./`")}.`);n[s]=a;}return a(n)},$s=(e,t,r)=>{let o=t(e);return o.length>0?Y.relative(r,o[0]):void 0},Dt=(e,t,r)=>{let o;return t[e.category]!==void 0?o=Y.join(r,t[e.category]):o=Y.join(r,t["*"],e.category),o};var qe=async(e,t,{verbose:r}={})=>await v(e,t,{verbose:r,fetch:xr,token:Cr(e.provider)}),er=async(e,{verbose:t}={})=>await w(e,{verbose:t,fetch:xr,token:Cr(e.provider)}),Cr=e=>{if(e.name==="http")return;let t=Ce().get(`${e.name}-token`);if(t)return t},Ot=async(e,{noCache:t$1=false}={})=>{let r=u(e);if(r){let o=Ce();if(r.name!==s.name&&!t$1){let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=await r.state(e,{token:Cr(r),fetch:xr});return r.name!==s.name&&!t$1&&o.set(`${e}-state`,n),a(n)}return b(`Only ${t.map((o,n)=>`${n===t.length-1?"and ":""}${E.bold(o.name)}`).join(", ")} registries are supported at this time!`)},Ye=async(e,{noCache:t=false}={})=>{let r=[],n=(await Promise.all(e.map(async s=>{let i=await Ot(s,{noCache:t});if(i.isErr())return b({message:i.unwrapErr(),repo:s});let a=i.unwrap();r.push(a);}))).find(s=>s!==void 0);return n||a(r)},Tt=async(...e)=>{let t=new Map,o=(await Promise.all(e.map(async n=>{let s=await er(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();for(let a of i.categories)for(let c$1 of a.blocks)t.set(c(n.url,`${c$1.category}/${c$1.name}`),{...c$1,sourceRepo:n});}))).find(n=>n!==void 0);return o||a(t)},tr=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},rr=async(...e)=>{let t=[],o=(await Promise.all(e.map(async n=>{let s=await er(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();t.push({state:n,manifest:i});}))).find(n=>n!==void 0);return o||a(t)};var st=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i,a=u(s);if(a){let{url:l,specifier:d}=a.parse(s,{fullyQualified:true});i=t.get(c(l,d));}else {if(r.length===0)return b(E.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${E.bold(`github/ieedan/std/${s}`)}\`!`));for(let l of r){let{url:d,specifier:m}=l.provider.parse(c(l.url,s),{fullyQualified:true}),h=t.get(c(d,m));if(h!==void 0){i=h;break}}}if(!i)return b(`Invalid block! ${E.bold(s)} does not exist!`);let c$1=`${i.category}/${i.name}`;if(n.set(c$1,i),i.localDependencies&&i.localDependencies.length>0){let l=await st(i.localDependencies.filter(d=>!n.has(d)&&!o.has(d)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let d of l.unwrap())n.set(`${d.category}/${d.name}`,d);}}return a(ro(n,(s,i)=>i))},it=(e,t,r)=>{let o=[],n=Ne(t.paths,r).match(s=>s,s=>program.error(E.red(s)));for(let[s,i]of e){let a=Dt(i,n,r),c=Y.join(a,i.files[0]);i.subdirectory&&(c=Y.join(a,i.name)),ie.existsSync(c)&&o.push({specifier:`${i.category}/${i.name}`,path:c,block:i});}return o},nr=(e,t)=>{let r=[];for(let o of e){let n=o.files.filter(i=>ze(i)?t.includeTests:true),s=Promise.all(n.map(async i=>{let a=await qe(o.sourceRepo,Y.join(o.directory,i));return {name:i,content:a}}));r.push({block:o,files:s});}return r},At=(e,t,r,o)=>{let n=Dt(t,r,o);return t.subdirectory?Y.join(n,t.name,e):Y.join(n,e)};var Ko=e=>new Promise(t=>t(e));var at=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await De.resolveConfig(Y.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Y.join(t,"biome.json");ie.existsSync(n)&&(o=JSON.parse(ie.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Ft=e=>`jsrepo ${Re.version}
|
|
68
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"vue",...r}):e},ls={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>ee(Z(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await De.format(e,{parser:"yaml",...r}):e},gt=e=>`${ee(Z(e),{prefix:t=>t===0?`${O} ${St} `:`${O} `})}`,ht=({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:s,cwd:i})=>{let a$1=[],c=new Set,l=new Set,d={};for(let u of e){if(u.startsWith(".")){let g=Eo(u,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(g.isErr()){a$1.push(g.unwrapErr());continue}let p=g.unwrap();p&&(l.add(p.dependency),d[u]=p.template);continue}let y=ds(u,t,{filePath:r,containingDir:o,dirs:s,cwd:i});if(y.isErr()){a$1.push(y.unwrapErr());continue}let f=y.unwrap();f?(l.add(f.dependency),d[u]=f.template):c.add(u);}if(a$1.length>0)return b(a$1);let{devDependencies:m,dependencies:h}=ms(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:m,local:Array.from(l),imports:d})},Eo=(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:s,dirs:i,cwd:a$1})=>{if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=t?Y.join(o,"../"):Y.join(r,"../"),l=Y.join(Y.join(r,"../"),e),d=Y.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(d))return a(jo(l.slice(d.length),n));for(let m of i){let h=Y.resolve(Y.join(a$1,m)),u=Y.resolve(l);if(u.startsWith(h))return a(jo(u.slice(h.length+1),n))}return b(`${r}:
|
|
69
|
+
${s||e} references code not contained in ${E.bold(i.join(", "))} and cannot be resolved.`)},jo=(e,t=true)=>{let[r,o,...n]=e.split("/");o===void 0&&(o="index");let s=o;t&&s.includes(".")&&(s=s.slice(0,s.length-Y.parse(s).ext.length));let i=`${r}/${s}`,a=`{{${i}}}`;return n.length===0?s.length!==o.length&&(a+=Y.parse(o).ext):a+=`/${n.join("/")}`,{dependency:i,template:a}},ds=(e,t,{filePath:r,dirs:o,cwd:n,containingDir:s})=>{let i=ut(r);if(i.isErr())return b(i.unwrapErr());let a$1=i.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let d of l){let m=fs(d);if(!m)continue;let h=Y.relative(Y.resolve(Y.join(r,"../")),m.prettyPath),u=ps(m.prettyPath,m.path,[".js",".ts"]),y=Eo(h,t,{filePath:r,containingDir:s,alias:e,dropExtension:u,dirs:o,cwd:n,modIsFile:m.type==="file"});if(y.isErr())return b(y.unwrapErr());if(y.unwrap())return a(y.unwrap());break}}return a(void 0)},ps=(e,t,r=[".ts",".js",""])=>{if(e===t)return true;let o=Y.parse(e),n=Y.parse(t),s=Y.join(o.dir,o.name),i=Y.join(n.dir,n.name);return s!==i?false:!!(r.includes(o.ext)&&r.includes(n.ext))},fs=e=>{if(ie.existsSync(e))return {path:e,prettyPath:e,type:ie.statSync(e).isDirectory()?"directory":"file"};let t=Y.join(e,"../");if(!ie.existsSync(t))return;let r=Y.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(ie.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=ie.readdirSync(t);for(let n of o){let s=Y.parse(n);if(s.name===r.base){let i=Y.join(t,n),a=i.slice(0,i.length-s.ext.length);return {path:i,prettyPath:a,type:ie.statSync(i).isDirectory()?"directory":"file"}}}},ms=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(c=>!builtinModules.includes(c)&&!c.startsWith("node:")),s=pr(Y.dirname(t),""),i=new Set,a=new Set;if(s){let{devDependencies:c,dependencies:l}=JSON.parse(ie.readFileSync(s,"utf-8"));for(let d of n){let m=ze(d);if(m.isErr()){console.warn(`${O} ${we} Skipped adding import \`${E.cyan(d)}\`. Reason: Couldn't parse package name`);continue}let h=m.unwrap();if(!es(h.name).validForNewPackages){console.warn(`${O} ${we} Skipped adding import \`${E.cyan(d)}\`. Reason: Not a valid package name`);continue}if(o.has(h.name))continue;let u;if(l!==void 0&&(u=l[h.name]),u!==void 0){i.add(`${h.name}@${u}`);continue}if(c!==void 0&&(u=c[h.name]),u!==void 0){a.add(`${h.name}@${u}`);continue}i.add(h.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(a)}},rt=[ts,rs,vr,os,ns,ss,is,as,cs,ls];var Oo=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),No=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),gs=$.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")]),To={"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 ${E.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,s]=o.split("/"),i=t.categories.find(c=>c.name.trim()===n.trim()),a=`${E.bold(`${e.category}/${e.name}`)} depends on local dependency ${E.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(c=>c.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.categories.find(c=>c.name===n);!i||!i.blocks.find(c=>c.name===s)||r.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${E.bold(`${e.category}/${e.name}`)} has too many local dependencies (${E.bold(e.localDependencies.length)}) limit (${E.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=Ht(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${E.bold(o)}: ${E.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(Ht(r,n,t.categories))return;return [`${E.bold(r)} is unused and will be ${E.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>ze(o).unwrap().name).filter(o=>Oo.has(o));if(r.length>0)for(let o of r)t.push(`${E.bold(`${e.category}/${e.name}`)} depends on ${E.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)ie.existsSync(Y.join(t,o.path))||r.push(`The ${E.bold(o.name)} config file doesn't exist at ${E.bold(Y.join(t,o.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>ze(n).unwrap().name).filter(n=>Oo.has(n));if(o.length>0)for(let n of o)t.push(`${E.bold(r.name)} depends on ${E.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 ${E.bold(o)}`);return t.length>0?t:void 0}}}},Ao=$.record(gs,$.union([No,$.tupleWithRest([No,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),wr={"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"},Fo=(e,t,r,o=wr)=>{let n=[],s=[];for(let[i,a]of Object.entries(To)){if(a.scope==="block")continue;let c=o[i],l,d=[];if(Array.isArray(c)?(l=c[0],d.push(...c.slice(1))):l=c,l==="off")continue;let m=a.check({manifest:e,options:d,cwd:r,config:t});if(m){if(l==="error"){s.push(...m.map(h=>`${O} ${St} ${E.red(h)} ${E.gray(i)}`));continue}n.push(...m.map(h=>`${O} ${we} ${h} ${E.gray(i)}`));}}for(let i of e.categories)for(let a of i.blocks)for(let[c,l]of Object.entries(To)){if(l.scope==="global")continue;let d=o[c],m,h=[];if(Array.isArray(d)?(m=d[0],h.push(...d.slice(1))):m=d,m==="off")continue;let u=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(u){if(m==="error"){s.push(...u.map(y=>`${O} ${St} ${E.red(y)} ${E.gray(c)}`));continue}n.push(...u.map(y=>`${O} ${we} ${y} ${E.gray(c)}`));}}return {warnings:n,errors:s}},Ht=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),c=r.find(d=>d.name===i)?.blocks.find(d=>d.name===a);if(!c)continue;let l=Ht(e,c,r,n);if(l)return [...l,e]}},Lo=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Ht(e,o,t))return true}return false};var Vo=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Ge=e=>Vo.find(t=>e.endsWith(t))!==void 0,Wo=(e,{cwd:t,ignore:r,config:o})=>{let n;try{n=ie.readdirSync(e);}catch{program.error(E.red(`Couldn't read the ${E.bold(e)} directory.`));}let s=[];for(let i of n){let a=Y.join(e,i);if(ie.statSync(a).isFile())continue;let c=`${Y.relative(t,a)}/`;if(r.ignores(c))continue;let l=Y.basename(i);if(!ys(l,o))continue;let d=hs(l,o),m={name:l,blocks:[]},h=ie.readdirSync(a);for(let u of h){let y=Y.join(a,u);if(ie.statSync(y).isFile()){if(Ge(u))continue;let f=vs(u),g=Bo(f,o);if(!_o(f,o))continue;let p=rt.find(I=>I.matches(u));if(!p){console.warn(`${O} ${we} Skipped \`${E.bold(y)}\` \`*${E.bold(Y.parse(u).ext)}\` files are not currently supported!`);continue}let P=h.find(I=>Vo.find(z=>I===`${f}${z}`)),{dependencies:x,devDependencies:v,local:k,imports:C}=p.resolveDependencies({filePath:y,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(I=>I,I=>{program.error(E.red(I));}),R={name:f,directory:Y.relative(t,a),category:l,tests:P!==void 0,subdirectory:false,list:d?g:false,files:[u],localDependencies:k,_imports_:C,dependencies:x,devDependencies:v};P!==void 0&&R.files.push(P),m.blocks.push(R);}else {let f=u,g=Bo(f,o);if(!_o(f,o))continue;let p=new Set,P=new Set,x=new Set,v={},k=false,C=[],R=(z,K)=>{for(let H of K){let b=Y.join(z,H),N=b.slice(y.length+1);if(Ge(H)){k=true,C.push(N);continue}if(ie.statSync(b).isDirectory()){if(!o.allowSubdirectories){console.warn(`${O} ${we} Skipped \`${E.bold(Y.join(y,H))}\` subdirectories are not allowed! Allow them with ${E.bold("--allow-subdirectories")}!`);continue}let F=ie.readdirSync(b);R(b,F);continue}let w=rt.find(F=>F.matches(H));if(!w){console.warn(`${O} ${we} Skipped \`${b}\` \`*${E.bold(Y.parse(H).ext)}\` files are not currently supported!`);continue}let{local:V,dependencies:T,devDependencies:W,imports:A}=w.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:y,filePath:b,cwd:t}).match(F=>F,F=>{program.error(E.red(F));});for(let F of V)F!==`${l}/${f}`&&p.add(F);for(let F of T)P.add(F);for(let F of W)x.add(F);for(let[F,je]of Object.entries(A))v[F]=je;C.push(N);}};R(y,ie.readdirSync(y));let I={name:f,directory:Y.relative(t,y),category:l,tests:k,subdirectory:true,list:d?g:false,files:C,localDependencies:Array.from(p.keys()),dependencies:Array.from(P.keys()),devDependencies:Array.from(x.keys()),_imports_:v};m.blocks.push(I);}}s.push(m);}return s},Jo=(e,{cwd:t})=>{if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=rt.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:s,devDependencies:i,local:a}=n.resolveDependencies({filePath:Y.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(E.red(c));});a.length>0&&program.error(E.red(`${E.bold(o.name)} ${E.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:s,devDependencies:i});}return r},Bo=(e,t)=>t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true,_o=(e,t)=>t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true,hs=(e,t)=>t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true,ys=(e,t)=>t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true,vs=e=>Y.parse(Y.basename(e)).name,Uo=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!Lo(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var nt="jsrepo.json",He="jsrepo-build-config.json",br=$.union([$.literal("prettier"),$.literal("biome")]),bs=$.objectWithRest({"*":$.string()},$.string()),kr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:bs,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(br)}),Ne=e=>{if(!ie.existsSync(Y.join(e,nt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(kr,JSON.parse(ie.readFileSync(Y.join(e,nt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${nt}\` file!`)},ks=$.object({$schema:$.string(),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(Ao)}),Qt=e=>{if(!ie.existsSync(Y.join(e,He)))return a(null);let t=$.safeParse(ks,JSON.parse(ie.readFileSync(Y.join(e,He)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${He}\` file!`)},Te=(e,t)=>{let r=ut(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[s,i]of Object.entries(e)){if(i.startsWith("./")){n[s]=Y.relative(t,Y.join(Y.resolve(t),i));continue}if(o===null)return b(`Cannot resolve ${E.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${E.bold("`./`")}.`);let a=$s(i,o,t);if(!a)return b(`Cannot resolve ${E.bold(`\`"${s}": "${i}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${E.bold("`./`")}.`);n[s]=a;}return a(n)},$s=(e,t,r)=>{let o=t(e);return o.length>0?Y.relative(r,o[0]):void 0},Dt=(e,t,r)=>{let o;return t[e.category]!==void 0?o=Y.join(r,t[e.category]):o=Y.join(r,t["*"],e.category),o};var qe=async(e,t,{verbose:r}={})=>await v(e,t,{verbose:r,fetch:$r,token:xr(e.provider)}),Xt=async(e,{verbose:t}={})=>await w(e,{verbose:t,fetch:$r,token:xr(e.provider)}),xr=e=>{if(e.name==="http")return;let t=Ce().get(`${e.name}-token`);if(t)return t},Ot=async(e,{noCache:t$1=false}={})=>{let r=u(e);if(r){let o=Ce();if(r.name!==s.name&&!t$1){let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=await r.state(e,{token:xr(r),fetch:$r});return r.name!==s.name&&!t$1&&o.set(`${e}-state`,n),a(n)}return b(`Only ${t.map((o,n)=>`${n===t.length-1?"and ":""}${E.bold(o.name)}`).join(", ")} registries are supported at this time!`)},Ye=async(e,{noCache:t=false}={})=>{let r=[],n=(await Promise.all(e.map(async s=>{let i=await Ot(s,{noCache:t});if(i.isErr())return b({message:i.unwrapErr(),repo:s});let a=i.unwrap();r.push(a);}))).find(s=>s!==void 0);return n||a(r)},Nt=async(...e)=>{let t=new Map,o=(await Promise.all(e.map(async n=>{let s=await Xt(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();for(let a of i.categories)for(let c$1 of a.blocks)t.set(c(n.url,`${c$1.category}/${c$1.name}`),{...c$1,sourceRepo:n});}))).find(n=>n!==void 0);return o||a(t)},Zt=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},er=async(...e)=>{let t=[],o=(await Promise.all(e.map(async n=>{let s=await Xt(n);if(s.isErr())return b({message:s.unwrapErr(),repo:n.url});let i=s.unwrap();t.push({state:n,manifest:i});}))).find(n=>n!==void 0);return o||a(t)};var st=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i,a=u(s);if(a){let{url:l,specifier:d}=a.parse(s,{fullyQualified:true});i=t.get(c(l,d));}else {if(r.length===0)return b(E.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${E.bold(`github/ieedan/std/${s}`)}\`!`));for(let l of r){let{url:d,specifier:m}=l.provider.parse(c(l.url,s),{fullyQualified:true}),h=t.get(c(d,m));if(h!==void 0){i=h;break}}}if(!i)return b(`Invalid block! ${E.bold(s)} does not exist!`);let c$1=`${i.category}/${i.name}`;if(n.set(c$1,i),i.localDependencies&&i.localDependencies.length>0){let l=await st(i.localDependencies.filter(d=>!n.has(d)&&!o.has(d)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let d of l.unwrap())n.set(`${d.category}/${d.name}`,d);}}return a(to(n,(s,i)=>i))},it=(e,t,r)=>{let o=[],n=Te(t.paths,r).match(s=>s,s=>program.error(E.red(s)));for(let[s,i]of e){let a=Dt(i,n,r),c=Y.join(a,i.files[0]);i.subdirectory&&(c=Y.join(a,i.name)),ie.existsSync(c)&&o.push({specifier:`${i.category}/${i.name}`,path:c,block:i});}return o},rr=(e,t)=>{let r=[];for(let o of e){let n=o.files.filter(i=>Ge(i)?t.includeTests:true),s=Promise.all(n.map(async i=>{let a=await qe(o.sourceRepo,Y.join(o.directory,i));return {name:i,content:a}}));r.push({block:o,files:s});}return r},At=(e,t,r,o)=>{let n=Dt(t,r,o);return t.subdirectory?Y.join(n,t.name,e):Y.join(n,e)};var zo=e=>new Promise(t=>t(e));var at=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await De.resolveConfig(Y.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Y.join(t,"biome.json");ie.existsSync(n)&&(o=JSON.parse(ie.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var Ft=e=>`jsrepo ${Re.version}
|
|
71
70
|
Installed from ${e}
|
|
72
|
-
${new Date().toLocaleDateString().replaceAll("/","-")}`;var wt=(e,t,r)=>{if(!t.peerDependencies)return;let o=
|
|
73
|
-
${E.yellow("\u25B2")} ${
|
|
74
|
-
`);let i=s.map((a,c)=>{let l=s.length-1===c,d;a.exists?d=`${E.yellowBright("x unmet peer")} need ${E.bold(`${a.name}@`)}${E.greenBright.bold(a.expected)} >> found ${E.yellowBright.bold(a.version)}`:d=`${E.red("x missing peer")} need ${E.bold(`${a.name}@`)}${E.greenBright.bold(a.expected)}`;let m=`${O} ${l?
|
|
71
|
+
${new Date().toLocaleDateString().replaceAll("/","-")}`;var wt=(e,t,r)=>{if(!t.peerDependencies)return;let o=fr(Y.join(r,"package.json")).match(i=>i,i=>{i.endsWith("doesn't exist")&&program.error(`Couldn't find your ${E.bold("package.json")}. Please create one.`),program.error(E.red(i));}),n={...o.dependencies,...o.devDependencies},s=[];for(let[i,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let d=n[i];if(!d){s.push({name:i,expected:c,message:l,version:d,exists:false});continue}fo.satisfies(Mt(d),c)||s.push({name:i,expected:c,message:l,version:d,exists:true});}if(s.length>0){process.stdout.write(`${O}
|
|
72
|
+
${E.yellow("\u25B2")} ${Zr} Issues with ${E.bold(e.url)} peer dependencies
|
|
73
|
+
`);let i=s.map((a,c)=>{let l=s.length-1===c,d;a.exists?d=`${E.yellowBright("x unmet peer")} need ${E.bold(`${a.name}@`)}${E.greenBright.bold(a.expected)} >> found ${E.yellowBright.bold(a.version)}`:d=`${E.red("x missing peer")} need ${E.bold(`${a.name}@`)}${E.greenBright.bold(a.expected)}`;let m=`${O} ${l?eo:Rt}${Ct} ${d}`;return a.message?`${m}
|
|
75
74
|
${O} ${l?"":O} ${E.gray(a.message)}`:m}).join(`
|
|
76
75
|
`);process.stdout.write(`${i}
|
|
77
|
-
`);}};var As=$.object({expand:$.boolean(),maxUnchanged:$.number(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),
|
|
78
|
-
`),process.stdout.write(`${O} ${
|
|
79
|
-
`);for(let W of N){let A=W.content.match(ye=>ye,ye=>program.error(E.red(ye))),F=At(W.name,b.block,k,t.cwd),je=(await It({file:{content:A,destPath:F},biomeOptions:v,prettierOptions:x,config:i,imports:b.block._imports_,watermark:Ft(b.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(ye=>ye,ye=>program.error(E.red(ye))),he="";ie.existsSync(F)&&(he=ie.readFileSync(F).toString());let X=await mt({config:{biomeOptions:v,prettierOptions:x,formatter:i.formatter},current:{path:F,content:he},incoming:{path:c(T,W.name),content:je},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});X.applyChanges&&(U.push(Ko({destination:F,content:X.updatedContent,block:b.block})),C.add(w));}continue}}b.files.then(N=>{N.map(async W=>{let A=W.content.match(he=>he,he=>program.error(E.red(he))),F=At(W.name,b.block,k,t.cwd),je=It({file:{content:A,destPath:F},biomeOptions:v,prettierOptions:x,config:i,imports:b.block._imports_,watermark:Ft(b.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(he=>(he.isErr()&&program.error(E.red(he.unwrapErr())),{destination:F,content:he.unwrap(),block:b.block}));U.push(je);});}),C.add(w);}C.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(I.map(b=>b.files)),await Promise.all(U.map(async b=>{let T=await b,w=Y.dirname(T.destination);ie.existsSync(w)||(r(`Creating directory ${E.bold(w)}`),ie.mkdirSync(w,{recursive:true})),r(`Writing to ${E.bold(T.destination)}`),ie.writeFileSync(T.destination,T.content);})),o.stop(`Added blocks ${E.cyan(Array.from(C).join(", "))}`));let K=(await detect({cwd:t.cwd}))?.agent??"npm",H=await Me(p,g,{yes:t.yes,cwd:t.cwd,pm:K});if(H.dependencies.size>0||H.devDependencies.size>0){let b=[];if(!H.installed){if(p.size>0){let w=resolveCommand(K,"add",[...p]);b.push(`Install dependencies \`${E.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(g.size>0){let w=resolveCommand(K,"add",[...g,"-D"]);b.push(`Install dev dependencies \`${E.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}b=b.map((w,V)=>`${V+1}. ${w}`),H.installed||b.push(""),b.push("Import and use the blocks!");let T=et(b);process.stdout.write(T);}};var Js=$.object({token:$.optional($.string()),logout:$.boolean()}),Lt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI"].sort(),Dr=new Command("auth").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Lt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").action(async(e,t)=>{let r=$.parse(Js,t);await le(),await Gs(e,r),outro(E.green("All done!"));}),Gs=async(e,t)=>{let r=Lt.find(n=>n.toLowerCase()===e?.toLowerCase()),o=new Ge;if(t.logout){if(r!==void 0){o.delete(r),log.success(`Logged out of ${r}.`);return}for(let n of Lt){if(o.get(n)===void 0){log.step(E.gray(`Already logged out of ${n}.`));continue}let s=await confirm({message:`Logout of ${n}?`,initialValue:true});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),s&&o.delete(n);}return}if(r===void 0){let n=await select({message:"Which service do you want to authenticate to?",options:Lt.map(s=>({label:s,value:s})),initialValue:Lt[0]});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),r=n;}if(t.token===void 0){let n=await password({message:`Paste your ${E.bold(r)} token:`,validate(s){if(s.trim()==="")return "Please provide a value"}});(isCancel(n)||!n)&&(cancel("Canceled!"),process.exit(0)),t.token=n;}o.set(r,t.token),log.success(`Logged into ${r}.`);};var Hs=[".git","node_modules"],qs=$.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()}),Or=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(qs,e);await le(),await Ys(t),outro(E.green("All done!"));}),Ys=async e=>{let t=y=>{e.verbose&&console.info(`${Pe} ${y}`);},r=Ee({verbose:e.verbose?t:void 0}),o=[],n$1=Zt(e.cwd).match(y=>{if(y===null)return {$schema:"",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 f=y;return e.dirs&&(f.dirs=e.dirs),e.outputDir&&(f.outputDir=e.outputDir),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),e.preview!==void 0&&(f.preview=e.preview),f.rules={...br,...f.rules},f},y=>program.error(E.red(y))),s;n$1.outputDir?s=Y.join(e.cwd,n$1.outputDir):s=e.cwd;let i=Y.join(s,l);if(e.output&&ie.existsSync(i)){if(n$1.outputDir){let y=n(ie.readFileSync(i).toString());if(y.isOk())for(let f of y.unwrap().categories)for(let g of f.blocks){let p=Y.join(s,g.directory);ie.existsSync(p)&&ie.rmSync(p,{recursive:true});}}ie.rmSync(i);}let a=zs();try{let y=ie.readFileSync(Y.join(e.cwd,".gitignore")).toString();a.add(y);}catch{}a.add(Hs);for(let y of n$1.dirs){let f=Y.join(e.cwd,y);r.start(`Building ${E.cyan(f)}`);let g=Jo(f,{cwd:e.cwd,ignore:a,config:n$1});for(let p of g){if(o.find(P=>P.name===p.name)!==void 0){console.warn(`${O} ${we} Skipped adding \`${E.cyan(`${y}/${p.name}`)}\` because a category with the same name already exists!`);continue}o.push(p);}r.stop(`Built ${E.cyan(f)}`);}let c=Go(n$1,{cwd:e.cwd}),l$1=Qs(o,c,n$1);r.start("Checking manifest");let{warnings:d,errors:m}=Lo(l$1,n$1,e.cwd,n$1.rules);r.stop("Completed checking manifest."),(d.length>0||m.length>0)&&console.log(O);for(let y of d)console.log(y);if(m.length>0){for(let y of m)console.log(y);program.error(E.red(`Completed checking manifest with ${E.bold(`${m.length} error(s)`)} and ${E.bold(`${d.length} warning(s)`)}`));}let[h,u]=Uo(l$1.categories);if(l$1.categories=h,u>0&&log.step(`Removed ${u} unused block${u>1?"s":""}.`),n$1.preview){let y=l$1.categories.flatMap(f=>f.blocks.filter(g=>g.list).map(g=>`${E.cyan(g.category)}/${g.name}`));log.message(`${E.yellow("Preview")}:`);for(let f of y)console.log(`${O} \u25FB ${f}`);}if(e.output){if(n$1.outputDir){if(r.start(`Copying registry files to \`${E.cyan(s)}\``),l$1.configFiles)for(let y of l$1.configFiles){let f=Y.join(e.cwd,y.path),g=Y.join(s,y.path),p=Y.join(g,"../");ie.existsSync(p)||ie.mkdirSync(p,{recursive:true}),ie.copyFileSync(f,g);}for(let y of l$1.categories)for(let f of y.blocks){let g=Y.join(e.cwd,f.directory),p=Y.join(s,f.directory);for(let P of f.files){let x=Y.join(p,P,"../");ie.existsSync(x)||ie.mkdirSync(x,{recursive:true}),ie.copyFileSync(Y.join(g,P),Y.join(p,P));}}r.stop(`Copied registry files to \`${E.cyan(s)}\``);}r.start(`Writing output to \`${E.cyan(i)}\``),ie.writeFileSync(i,JSON.stringify(l$1,null," ")),r.stop(`Wrote output to \`${E.cyan(i)}\``);}},Qs=(e,t,r)=>({meta:r.meta,peerDependencies:r.peerDependencies,configFiles:t,categories:e});var ni=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),Ar=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(ni,t);await le(),await si(e,o,r);}),si=async(e,t,r)=>{let o=w=>{t.verbose&&console.info(`${Pe} ${w}`);},n=e,s=Ee({verbose:t.verbose?o:void 0}),i=Te(t.cwd),a=i.isErr(),c$1;i.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=i.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let d=n?u(n):void 0;if(n&&d){let{url:w}=d.parse(n,{fullyQualified:true});if(!l.find(V=>V===w)){if(!t.allow){let V=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(w)}?`,initialValue:true});(isCancel(V)||!V)&&(cancel("Canceled!"),process.exit(0));}l=[w];}}if(!t.allow&&t.repo){let w=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(w)||!w)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(E.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),s.start(`Fetching scripts from ${E.cyan(l.join(", "))}`);let m=(await Ye(l,{noCache:!t.cache})).match(w=>w,({repo:w,message:V})=>{s.stop(`Failed to get info for ${E.cyan(w)}`),program.error(E.red(V));}),h=(await Tt(...m)).match(w=>w,({repo:w,message:V})=>{s.stop(`Failed fetching scripts from ${E.cyan(w)}`),program.error(E.red(V));});if(s.stop(`Retrieved scripts from ${E.cyan(l.join(", "))}`),!n){let w=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([V,N])=>N.list).map(([V,N])=>{let W;return l.length>1?W=`${E.cyan(c(N.sourceRepo.url,N.category))}/${N.name}`:W=`${E.cyan(N.category)}/${N.name}`,{label:W,value:V}})});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),n=w;}let u$1=(await st([n],h,m)).match(w=>w,w=>program.error(w)),y="temp-jsrepo-exec",f=`./${y}/${encodeURIComponent(n)}`,g=Y.join(process.cwd(),f);c$1.paths["*"]=f,ie.mkdirSync(g,{recursive:true});let p=(await detect({cwd:process.cwd()}))?.agent??"npm",P=[],x=new Set,v=new Set,k=Ne(c$1.paths,t.cwd);k.isErr()&&program.error(E.red(k.unwrapErr()));let C=k.unwrap(),R=[];for(let w of u$1){let V=`${w.sourceRepo.url}/${w.category}/${w.name}`,N=`${w.category}/${w.name}`,W=w.sourceRepo,A=Y.join(t.cwd,C["*"],w.category);R.push(N),P.push({run:async({message:F})=>{F(`Adding ${E.cyan(V)}`),ie.mkdirSync(A,{recursive:true});let je=[],he=async X=>{let ye=await qe(W,X);return ye.isErr()&&(s.stop(E.red(`Error fetching ${E.bold(X)}`)),program.error(E.red(`There was an error trying to get ${V}`))),ye.unwrap()};for(let X of w.files){if(!c$1.includeTests&&ze(X))continue;let ye=Y.join(w.directory,X),$t;w.subdirectory?$t=Y.join(A,w.name,X):$t=Y.join(A,X);let ln=await he(ye),dn=$t.slice(0,$t.length-X.length);ie.mkdirSync(dn,{recursive:true}),je.push({content:ln,destPath:$t});}for(let X of je)ie.writeFileSync(X.destPath,X.content);if(c$1.includeTests&&w.tests){let{devDependencies:X}=JSON.parse(ie.readFileSync(Y.join(t.cwd,"package.json")).toString());(X===void 0||X.vitest===void 0)&&x.add("vitest");}for(let X of w.devDependencies)x.add(X);for(let X of w.dependencies)v.add(X);}});}if(await bo({startMessage:"Adding blocks",stopMessage:`Added ${E.cyan(R.join(", "))}`,loading:s,tasks:P}),v.size>0||x.size>0){let w={name:"temp-package",type:"module",version:"0.0.1"},V=Y.join(g,"package.json");ie.writeFileSync(V,JSON.stringify(w,null," "));}await Me(v,x,{yes:true,no:false,cwd:g,pm:p,ignoreWorkspace:true});let U=r.parent.rawArgs.findIndex(w=>w==="--"),K=[];U!==-1&&(K=r.parent.rawArgs.slice(U+1)),o(`Passing args ${E.cyan(K.join(" "))}`),console.clear();let H=u$1[0],b;H.subdirectory?b=Y.join(g,`${H.category}/${H.name}/index.js`):b=Y.join(g,`${H.category}/${H.name}.js`);let T=resolveCommand(p,"execute",["tsx",b,...K]);T||program.error(E.red("Error resolving run command!"));try{await execa(T.command,T.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{ie.rmSync(Y.join(process.cwd(),y),{recursive:true,force:true});}};var fi=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(kr),project:$.optional($.boolean()),registry:$.optional($.boolean()),script:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),Br=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("--script <name>","The name of the build script. (For Registry setup)","build: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(fi,t);if(await le(),r.registry!==void 0&&r.project!==void 0&&program.error(E.red(`You cannot provide both ${E.bold("--project")} and ${E.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${E.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${E.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 mi(e,r):await gi(r),outro(E.green("All done!"));}),mi=async(e,t$1)=>{let r=Te(t$1.cwd),o=spinner(),n,s={},i=ut(t$1.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(x){if(x.trim()==="")return "Please provide a value";if(!x.startsWith("./")){let v="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(i===null)return v;let k=createPathsMatcher(i);if(k&&k(x).length===0)return v}},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},s=r.unwrap().configFiles??{}):n={"*":a},!t$1.formatter){let x=r.isErr()?"none":r.unwrap().formatter??"none";ie.existsSync(Y.join(t$1.cwd,".prettierrc"))&&(x="prettier"),ie.existsSync(Y.join(t$1.cwd,"biome.json"))&&(x="biome");let v=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(k=>({value:k.toLowerCase(),label:k})),initialValue:x});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(t$1.formatter=v);}let c=Array.from(new Set([...e,...t$1.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,d=new Set,m=async x=>{let v=await ui({repo:x,paths:n,configFiles:s,options:t$1,formatter:t$1.formatter});for(let k of v.dependencies)l.add(k);for(let k of v.devDependencies)d.add(k);n=v.paths,s=v.configFiles;};if(c.length>0)for(let x of c){if(!e.find(v=>v===x)&&r.isOk()&&r.unwrap().repos.find(v=>v===x)){let v=await confirm({message:`Initialize ${x}?`,initialValue:t$1.yes});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),!v)continue}log.info(`Initializing ${E.cyan(x)}`),await m(x);}for(;;){let x=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)break;let v=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:k=>{if(k.trim().length===0)return "Please provide a value";if(!u(k))return `Invalid provider! Valid providers (${t.map(C=>C.name).join(", ")})`}});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),await m(v),c.push(v);}let h={$schema:`https://unpkg.com/jsrepo@${Re.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t$1.tests===void 0?r.unwrap().includeTests:t$1.tests??false,watermark:t$1.watermark,formatter:t$1.formatter,configFiles:s,paths:n};o.start(`Writing config to \`${nt}\``);let{prettierOptions:u$1,biomeOptions:y}=await at({formatter:h.formatter,cwd:t$1.cwd}),f=Y.join(t$1.cwd,nt),g=await wr.format(JSON.stringify(h,null," "),{biomeOptions:y,prettierOptions:u$1,filePath:f,formatter:h.formatter});ie.existsSync(t$1.cwd)||ie.mkdirSync(t$1.cwd,{recursive:true}),ie.writeFileSync(f,g),o.stop(`Wrote config to \`${nt}\`.`);let p=(await detect$1({cwd:t$1.cwd}))?.agent??"npm",P=await Me(l,d,{yes:t$1.yes,cwd:t$1.cwd,pm:p});if(P.dependencies.size>0||P.devDependencies.size>0){let x=[];if(!P.installed){if(l.size>0){let k=resolveCommand$1(p,"add",[...l]);x.push(`Install dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(d.size>0){let k=resolveCommand$1(p,"add",[...d,"-D"]);x.push(`Install dev dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}x=x.map((k,C)=>`${C+1}. ${k}`),P.installed||x.push(""),x.push(`Add blocks with ${E.cyan("jsrepo add")}!`);let v=et(x);process.stdout.write(v);}},ui=async({repo:e,paths:t$1,configFiles:r,formatter:o,options:n})=>{let s$1=spinner(),i=new Ge,a=u(e);if(a||program.error(E.red(`Invalid provider! Valid providers (${t.map(u=>u.name).join(", ")})`)),!i.get(a.name)&&a.name!==s.name&&!n.yes){let u=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u){let y=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),i.set(a.name,y);}}s$1.start(`Fetching manifest from ${E.cyan(e)}`);let l=(await Ot(e,{noCache:!n.cache})).match(u=>u,u=>program.error(E.red(u))),d=(await er(l)).match(u=>u,u=>program.error(E.red(u)));s$1.stop(`Fetched manifest from ${E.cyan(e)}`),wt(l,d,n.cwd);let m=[],h=[];if(d.configFiles){let{prettierOptions:u,biomeOptions:y}=await at({formatter:o,cwd:n.cwd});for(let f of d.configFiles){if(f.optional&&!n.yes){let k=await confirm({message:`Would you like to add the ${f.name} file?`,initialValue:true});if(isCancel(k)&&(cancel("Canceled!"),process.exit(0)),!k)continue}if(m.push(...f.dependencies??[]),h.push(...f.devDependencies??[]),!r[f.name]){let k=await text({message:`Where is your ${f.name} file?`,defaultValue:f.expectedPath,initialValue:f.expectedPath,placeholder:f.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),r[f.name]=k;}let g=Y.join(n.cwd,r[f.name]),p;if(ie.existsSync(g))p=ie.readFileSync(g).toString();else {let k=Y.dirname(g);if(ie.existsSync(k)){let C=So(g);if(C){p=ie.readFileSync(C).toString();let R=Y.relative(n.cwd,C);log.warn(`Located ${E.bold(r[f.name])} at ${E.bold(R)}`),r[f.name]=R,g=Y.join(n.cwd,R);}}}s$1.start(`Fetching the ${E.cyan(f.name)} from ${E.cyan(e)}`);let P=(await qe(l,f.path)).match(k=>k,k=>program.error(E.red(k))),x=await Ut({file:{content:P,destPath:g},biomeOptions:y,prettierOptions:u,formatter:o});s$1.stop(`Fetched the ${E.cyan(f.name)} from ${E.cyan(e)}`);let v=n.yes||p===void 0;if(p){if(!n.yes){let k=c(l.url,f.name),C=await mt({config:{biomeOptions:y,prettierOptions:u,formatter:o},current:{content:p,path:g},incoming:{content:x,path:k},options:{...n,loading:s$1,no:false}});C.applyChanges&&(v=true,p=C.updatedContent);}}else {let k=Y.dirname(g);ie.existsSync(k)||ie.mkdirSync(k,{recursive:true}),p=x;}v&&p&&(s$1.start(`Writing ${E.cyan(f.name)} to ${E.cyan(g)}`),ie.writeFileSync(g,p),s$1.stop(`Wrote ${E.cyan(f.name)} to ${E.cyan(g)}`));}}if(!n.yes){let u=await multiselect({message:"Which category paths would you like to configure?",options:d.categories.map(y=>({label:y.name,value:y.name})),required:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u.length>0)for(let y of u){let f=t$1[y],g=await text({message:`Where should ${y} be added in your project?`,validate(p){if(p.trim()==="")return "Please provide a value"},placeholder:f||`./src/${y}`,defaultValue:f,initialValue:f});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),t$1[y]=g;}}return {paths:t$1,configFiles:r,dependencies:m,devDependencies:h}},gi=async e=>{let t=spinner(),r=Y.join(e.cwd,"package.json");ie.existsSync(r)||program.error(E.red(`Couldn't find your ${E.bold("package.json")}!`));let o=Zt(e.cwd).match(g=>g,g=>program.error(E.red(g))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${Re.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let p=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)break}let g=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:p=>{if(p.trim().length===0)return "Please provide a value!"}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(g);}let s=JSON.parse(ie.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let g=await confirm({message:`The \`${E.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),g)break;{let p=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:P=>{if(P.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),e.script=p;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let g=await confirm({message:`Add ${Ie} as a dev dependency?`,initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),a=g;}let c=!n;if(!e.yes&&n){let g=await confirm({message:`Create a \`${E.cyan(He)}\` file?`,initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),c=g;}let l=(await detect$1({cwd:"cwd"}))?.agent??"npm",d="";if(a)d+="jsrepo build";else {let g=resolveCommand$1(l,"execute",["jsrepo","build"]);g||program.error(E.red(`Error resolving execute command for ${l}`)),d+=`${g.command} ${g.args.join(" ")} `;}c||(d+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=d;let m=[];m.push({loadingMessage:`Adding \`${E.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${E.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{ie.writeFileSync(r,JSON.stringify(s,null," "));}catch(g){program.error(E.red(`Error writing to \`${E.bold(r)}\`. Error: ${g}`));}}}),c&&m.push({loadingMessage:`Writing config to \`${E.cyan(He)}\``,completedMessage:`Wrote config to \`${E.cyan(He)}\``,run:async()=>{let g=Y.join(e.cwd,He);try{ie.writeFileSync(Y.join(g),JSON.stringify(o,null," "));}catch(p){program.error(E.red(`Error writing to \`${E.bold(g)}\`. Error: ${p}`));}}}),await wo(m,{loading:t});let h=i;a&&!i&&(h=(await Me(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:l,yes:e.yes})).installed);let u=[];if(!h&&a){let g=resolveCommand$1(l,"add",["jsrepo","-D"]);u.push(`Install ${Ie} as a dev dependency \`${E.cyan(`${g?.command} ${g?.args.join(" ")}`)}\``);}u.push(`Add categories to \`${E.cyan(o.dirs.join(", "))}\`.`);let y=resolveCommand$1(l,"run",[e.script]);u.push(`Run \`${E.cyan(`${y?.command} ${y?.args.join(" ")}`)}\` to build the registry.`),u=u.map((g,p)=>`${p+1}. ${g}`);let f=et(u);process.stdout.write(f);};var Si=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Mr=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(Si,t);await le(),await ji(e,r),outro(E.green("All done!"));}),ji=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Pe} ${p}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Te(t.cwd).match(p=>p,p=>program.error(E.red(p))),n=Ee({verbose:t.verbose?r:void 0}),s=o.repos;if(t.repo&&(s=[t.repo]),!t.allow&&t.repo){let p=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${E.cyan(s.join(", "))}`);let i=(await Ye(s,{noCache:!t.cache})).match(p=>p,({repo:p,message:P})=>{n.stop(`Failed to get info for ${E.cyan(p)}`),program.error(E.red(P));});r(`Resolved ${E.cyan(s.join(", "))}`),r(`Fetching blocks from ${E.cyan(s.join(", "))}`);let a=(await Tt(...i)).match(p=>p,({repo:p,message:P})=>{n.stop(`Failed fetching blocks from ${E.cyan(p)}`),program.error(E.red(P));});r(`Retrieved blocks from ${E.cyan(s.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${E.cyan(s.join(", "))}`);let c$1=Y.resolve(Y.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${E.bold(c$1)}.`),ie.mkdirSync(c$1,{recursive:true});let l=()=>{ie.rmSync(c$1,{recursive:true,force:true});},d=it(a,o,t.cwd).map(p=>p.specifier),m=e;e.length===0&&(m=d),m.length===0&&(l(),program.error(E.red("There were no blocks found in your project!")));let h=[];for(let p of m){let P,x=u(p);if(x){let{url:v}=x.parse(p,{fullyQualified:true}),k=(await Ot(v)).match(R=>R,R=>program.error(E.red(R))),C=(await Tt(k)).match(R=>R,R=>program.error(E.red(R)));for(let[R,I]of C)a.set(R,I);P=a.get(p);}else for(let v of s){let k=u(v);if(!k)continue;let{url:C,specifier:R}=k.parse(c(v,p),{fullyQualified:true}),I=a.get(c(C,R));if(I!==void 0){P=I;break}}P||program.error(E.red(`Invalid block! ${E.bold(p)} does not exist!`)),h.push({name:p,block:P});}let u$1=Ne(o.paths,t.cwd).match(p=>p,p=>program.error(E.red(p)));for(let{block:p}of h){let P=p.sourceRepo,x=c(p.sourceRepo.url,p.category,p.name);if(t.verbose||n.start(`Setting up test file for ${E.cyan(x)}`),!p.tests){n.stop(`No tests found for ${E.cyan(x)}`);continue}let v=Dt(p,u$1,t.cwd);v=Y.relative(c$1,v);let k=async I=>{let U=await qe(P,I);return U.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(I)}`)),program.error(E.red(`There was an error trying to get ${x}`))),U.unwrap()};r(`Downloading and copying test files for ${x}`);let C=[];for(let I of p.files.filter(U=>ze(U))){let U=await k(Y.join(p.directory,I)),K=Y.join(c$1,I);ie.writeFileSync(K,U),C.push(K);}let R=new Project;for(let I of C){r(`Opening test file ${I}`);let U=R.addSourceFileAtPath(I);for(let K of U.getImportDeclarations()){let H=K.getModuleSpecifierValue(),b;H.startsWith(".")&&(p.subdirectory?b=Y.join(v,p.name,H):b=Y.join(v,H)),b&&K.setModuleSpecifier(b.replaceAll(/\\/g,"/"));}}R.saveSync(),r(`Completed ${E.cyan.bold(x)} test file`),t.verbose||n.stop(`Completed setup for ${E.bold(x)}`);}r("Beginning testing");let y=await detect({cwd:t.cwd});y==null&&program.error(E.red("Could not detect package manager"));let f=resolveCommand(y.agent,"execute",["vitest","run",c$1]);f==null&&program.error(E.red(`Could not resolve add command for '${y.agent}'.`));let g=`${f.command} ${f.args.join(" ")}`;r(`Running ${E.cyan(g)} on ${E.cyan(t.cwd)}`);try{await execa(f.command,f.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(p){t.debug?console.info(`${E.bold("--debug")} flag provided. Skipping cleanup. Run '${E.bold(g)}' to retry tests.
|
|
80
|
-
`):l(),program.error(E.red(`Tests failed! Error ${p}`));}};var
|
|
76
|
+
`);}};var As=$.object({expand:$.boolean(),maxUnchanged:$.number(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Rr=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)").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(As,t);await le(),await Fs(e,r),outro(E.green("All done!"));}),Fs=async(e,t)=>{let r=b=>{t.verbose&&console.info(`${Pe} ${b}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=Ee({verbose:t.verbose?r:void 0}),n=Ne(t.cwd),s=n.isErr(),i;if(n.isErr()){let b=t.yes;if(!t.yes){let N=await confirm({message:`You don't have ${Ie} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(N)&&(cancel("Canceled!"),process.exit(0)),b=N;}b||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let b of e){let N=u(b);if(!N){l=true;continue}let{url:w}=N.parse(b,{fullyQualified:true});if(!(!i.repos.find(T=>T===w)&&!c$1.has(w))){if(!t.allow){let T=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(w)}?`,initialValue:true});(isCancel(T)||!T)&&(cancel("Canceled!"),process.exit(0));}a.push(w);}c$1.add(w);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let b=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(b)||!b)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(E.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${E.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${E.cyan(a.join(", "))}`);let d=(await Ye(a,{noCache:!t.cache})).match(b=>b,({repo:b,message:N})=>{o.stop(`Failed to get info for ${E.cyan(b)}`),program.error(E.red(N));});r(`Resolved ${E.cyan(a.join(", "))}`),r(`Fetching blocks from ${E.cyan(a.join(", "))}`);let m=(await er(...d)).match(b=>b,({repo:b,message:N})=>{o.stop(`Failed fetching blocks from ${E.cyan(b)}`),program.error(E.red(N));}),h=Zt(m);t.verbose||o.stop(`Retrieved blocks from ${E.cyan(a.join(", "))}`),r(`Retrieved blocks from ${E.cyan(a.join(", "))}`);for(let b of m)wt(b.state,b.manifest,t.cwd);let u$1=it(h,i,t.cwd).map(b=>b.specifier),y=e;if(y.length===0){let b=await multiselect({message:"Select which blocks to add.",options:Array.from(h.entries()).filter(([N,w])=>w.list).map(([N,w])=>{let V=`${w.category}/${w.name}`,T=u$1.findIndex(A=>A===V)!==-1,W;return a.length>1?W=`${E.cyan(c(w.sourceRepo.url,w.category))}/${w.name}`:W=`${E.cyan(w.category)}/${w.name}`,{label:T?E.gray(W):W,value:N,hint:T?"Installed":void 0}}),required:true});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),y=b;}r(`Installing blocks ${E.cyan(y.join(", "))}`);let f=(await st(y,h,d)).match(b=>b,b=>program.error(b)),g=new Set,p=new Set,P=Ce();if(s){let b=`${t.cwd}-zero-config`,N=$.safeParse(kr,P.get(b)),w=N.success?N.output:i,V=Array.from(new Set(f.map(A=>A.category)));for(let A of V){let F=await text({message:`Where would you like to add ${E.cyan(A)}?`,placeholder:w?w.paths[A]:`./src/${A}`,initialValue:w?w.paths[A]:`./src/${A}`,defaultValue:w?w.paths[A]:`./src/${A}`,validate(je){if(je.trim()==="")return "Please provide a value"}});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.paths[A]=F;}if(!t.yes){let A=await confirm({message:"Include tests?",initialValue:w.includeTests});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=A;let F=await confirm({message:"Add watermark?",initialValue:w.watermark});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),i.watermark=F;}let T="none";ie.existsSync(Y.join(t.cwd,".prettierrc"))&&(T="prettier"),ie.existsSync(Y.join(t.cwd,"biome.json"))&&(T="biome");let W=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(A=>({value:A.toLowerCase(),label:A})),initialValue:T==="none"?w.formatter?w.formatter:"none":T});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),W!=="none"&&(i.formatter=W),P.set(b,i),u$1=it(h,i,t.cwd).map(A=>A.specifier);}let{prettierOptions:x,biomeOptions:v}=await at({formatter:i.formatter,cwd:t.cwd}),k=Te(i.paths,t.cwd).match(b=>b,b=>program.error(E.red(b))),C=new Set,R,I=rr(f,i),z=[];for(let b of I){let N=c(b.block.sourceRepo.url,b.block.category,b.block.name),w=`${b.block.category}/${b.block.name}`;r(`Setting up ${N}`);let V=u$1.find(T=>w===T);i.includeTests&&b.block.tests&&(r("Trying to include tests"),g.add("vitest"));for(let T of b.block.devDependencies)g.add(T);for(let T of b.block.dependencies)p.add(T);if(V&&!t.yes&&!R){if(R===void 0){let T=f.map(A=>`${A.category}/${A.name}`).filter(A=>u$1.find(F=>F===A));log.warn(`The following components ${E.bold.yellow("already exist")}: ${E.cyan(bo(T))}`);let W=await confirm({message:`Would you like to ${E.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 T=await b.files;process.stdout.write(`${O}
|
|
77
|
+
`),process.stdout.write(`${O} ${N}
|
|
78
|
+
`);for(let W of T){let A=W.content.match(ye=>ye,ye=>program.error(E.red(ye))),F=At(W.name,b.block,k,t.cwd),je=(await It({file:{content:A,destPath:F},biomeOptions:v,prettierOptions:x,config:i,imports:b.block._imports_,watermark:Ft(b.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(ye=>ye,ye=>program.error(E.red(ye))),he="";ie.existsSync(F)&&(he=ie.readFileSync(F).toString());let X=await mt({config:{biomeOptions:v,prettierOptions:x,formatter:i.formatter},current:{path:F,content:he},incoming:{path:c(N,W.name),content:je},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});X.applyChanges&&(z.push(zo({destination:F,content:X.updatedContent,block:b.block})),C.add(w));}continue}}b.files.then(T=>{T.map(async W=>{let A=W.content.match(he=>he,he=>program.error(E.red(he))),F=At(W.name,b.block,k,t.cwd),je=It({file:{content:A,destPath:F},biomeOptions:v,prettierOptions:x,config:i,imports:b.block._imports_,watermark:Ft(b.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(he=>(he.isErr()&&program.error(E.red(he.unwrapErr())),{destination:F,content:he.unwrap(),block:b.block}));z.push(je);});}),C.add(w);}C.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(I.map(b=>b.files)),await Promise.all(z.map(async b=>{let N=await b,w=Y.dirname(N.destination);ie.existsSync(w)||(r(`Creating directory ${E.bold(w)}`),ie.mkdirSync(w,{recursive:true})),r(`Writing to ${E.bold(N.destination)}`),ie.writeFileSync(N.destination,N.content);})),o.stop(`Added blocks ${E.cyan(Array.from(C).join(", "))}`));let K=(await detect({cwd:t.cwd}))?.agent??"npm",H=await Me(p,g,{yes:t.yes,cwd:t.cwd,pm:K});if(H.dependencies.size>0||H.devDependencies.size>0){let b=[];if(!H.installed){if(p.size>0){let w=resolveCommand(K,"add",[...p]);b.push(`Install dependencies \`${E.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(g.size>0){let w=resolveCommand(K,"add",[...g,"-D"]);b.push(`Install dev dependencies \`${E.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}b=b.map((w,V)=>`${V+1}. ${w}`),H.installed||b.push(""),b.push("Import and use the blocks!");let N=et(b);process.stdout.write(N);}};var Js=$.object({token:$.optional($.string()),logout:$.boolean()}),Lt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI"].sort(),Er=new Command("auth").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Lt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").action(async(e,t)=>{let r=$.parse(Js,t);await le(),await Us(e,r),outro(E.green("All done!"));}),Us=async(e,t)=>{let r=Lt.find(n=>n.toLowerCase()===e?.toLowerCase()),o=new Ue;if(t.logout){if(r!==void 0){o.delete(r),log.success(`Logged out of ${r}.`);return}for(let n of Lt){if(o.get(n)===void 0){log.step(E.gray(`Already logged out of ${n}.`));continue}let s=await confirm({message:`Logout of ${n}?`,initialValue:true});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),s&&o.delete(n);}return}if(r===void 0){let n=await select({message:"Which service do you want to authenticate to?",options:Lt.map(s=>({label:s,value:s})),initialValue:Lt[0]});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),r=n;}if(t.token===void 0){let n=await password({message:`Paste your ${E.bold(r)} token:`,validate(s){if(s.trim()==="")return "Please provide a value"}});(isCancel(n)||!n)&&(cancel("Canceled!"),process.exit(0)),t.token=n;}o.set(r,t.token),log.success(`Logged into ${r}.`);};var Hs=[".git","node_modules"],qs=$.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()}),Dr=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(qs,e);await le(),await Ys(t),outro(E.green("All done!"));}),Ys=async e=>{let t=y=>{e.verbose&&console.info(`${Pe} ${y}`);},r=Ee({verbose:e.verbose?t:void 0}),o=[],n$1=Qt(e.cwd).match(y=>{if(y===null)return {$schema:"",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 f=y;return e.dirs&&(f.dirs=e.dirs),e.outputDir&&(f.outputDir=e.outputDir),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),e.preview!==void 0&&(f.preview=e.preview),f.rules={...wr,...f.rules},f},y=>program.error(E.red(y))),s;n$1.outputDir?s=Y.join(e.cwd,n$1.outputDir):s=e.cwd;let i=Y.join(s,l);if(e.output&&ie.existsSync(i)){if(n$1.outputDir){let y=n(ie.readFileSync(i).toString());if(y.isOk())for(let f of y.unwrap().categories)for(let g of f.blocks){let p=Y.join(s,g.directory);ie.existsSync(p)&&ie.rmSync(p,{recursive:true});}}ie.rmSync(i);}let a=Gs();try{let y=ie.readFileSync(Y.join(e.cwd,".gitignore")).toString();a.add(y);}catch{}a.add(Hs);for(let y of n$1.dirs){let f=Y.join(e.cwd,y);r.start(`Building ${E.cyan(f)}`);let g=Wo(f,{cwd:e.cwd,ignore:a,config:n$1});for(let p of g){if(o.find(P=>P.name===p.name)!==void 0){console.warn(`${O} ${we} Skipped adding \`${E.cyan(`${y}/${p.name}`)}\` because a category with the same name already exists!`);continue}o.push(p);}r.stop(`Built ${E.cyan(f)}`);}let c=Jo(n$1,{cwd:e.cwd}),l$1=Qs(o,c,n$1);r.start("Checking manifest");let{warnings:d,errors:m}=Fo(l$1,n$1,e.cwd,n$1.rules);r.stop("Completed checking manifest."),(d.length>0||m.length>0)&&console.log(O);for(let y of d)console.log(y);if(m.length>0){for(let y of m)console.log(y);program.error(E.red(`Completed checking manifest with ${E.bold(`${m.length} error(s)`)} and ${E.bold(`${d.length} warning(s)`)}`));}let[h,u]=Uo(l$1.categories);if(l$1.categories=h,u>0&&log.step(`Removed ${u} unused block${u>1?"s":""}.`),n$1.preview){let y=l$1.categories.flatMap(f=>f.blocks.filter(g=>g.list).map(g=>`${E.cyan(g.category)}/${g.name}`));log.message(`${E.yellow("Preview")}:`);for(let f of y)console.log(`${O} \u25FB ${f}`);}if(e.output){if(n$1.outputDir){if(r.start(`Copying registry files to \`${E.cyan(s)}\``),l$1.configFiles)for(let y of l$1.configFiles){let f=Y.join(e.cwd,y.path),g=Y.join(s,y.path),p=Y.join(g,"../");ie.existsSync(p)||ie.mkdirSync(p,{recursive:true}),ie.copyFileSync(f,g);}for(let y of l$1.categories)for(let f of y.blocks){let g=Y.join(e.cwd,f.directory),p=Y.join(s,f.directory);for(let P of f.files){let x=Y.join(p,P,"../");ie.existsSync(x)||ie.mkdirSync(x,{recursive:true}),ie.copyFileSync(Y.join(g,P),Y.join(p,P));}}r.stop(`Copied registry files to \`${E.cyan(s)}\``);}r.start(`Writing output to \`${E.cyan(i)}\``),ie.writeFileSync(i,JSON.stringify(l$1,null," ")),r.stop(`Wrote output to \`${E.cyan(i)}\``);}},Qs=(e,t,r)=>({meta:r.meta,peerDependencies:r.peerDependencies,configFiles:t,categories:e});var ni=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),Tr=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(ni,t);await le(),await si(e,o,r);}),si=async(e,t,r)=>{let o=w=>{t.verbose&&console.info(`${Pe} ${w}`);},n=e,s=Ee({verbose:t.verbose?o:void 0}),i=Ne(t.cwd),a=i.isErr(),c$1;i.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=i.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let d=n?u(n):void 0;if(n&&d){let{url:w}=d.parse(n,{fullyQualified:true});if(!l.find(V=>V===w)){if(!t.allow){let V=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(w)}?`,initialValue:true});(isCancel(V)||!V)&&(cancel("Canceled!"),process.exit(0));}l=[w];}}if(!t.allow&&t.repo){let w=await confirm({message:`Allow ${Ie} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(w)||!w)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(E.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${E.bold("--repo")}\` flag to specify a registry.`)),program.error(E.red(`There were no repos present in your config and you didn't provide the \`${E.bold("--repo")}\` flag with a repo.`))),s.start(`Fetching scripts from ${E.cyan(l.join(", "))}`);let m=(await Ye(l,{noCache:!t.cache})).match(w=>w,({repo:w,message:V})=>{s.stop(`Failed to get info for ${E.cyan(w)}`),program.error(E.red(V));}),h=(await Nt(...m)).match(w=>w,({repo:w,message:V})=>{s.stop(`Failed fetching scripts from ${E.cyan(w)}`),program.error(E.red(V));});if(s.stop(`Retrieved scripts from ${E.cyan(l.join(", "))}`),!n){let w=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([V,T])=>T.list).map(([V,T])=>{let W;return l.length>1?W=`${E.cyan(c(T.sourceRepo.url,T.category))}/${T.name}`:W=`${E.cyan(T.category)}/${T.name}`,{label:W,value:V}})});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),n=w;}let u$1=(await st([n],h,m)).match(w=>w,w=>program.error(w)),y="temp-jsrepo-exec",f=`./${y}/${encodeURIComponent(n)}`,g=Y.join(process.cwd(),f);c$1.paths["*"]=f,ie.mkdirSync(g,{recursive:true});let p=(await detect({cwd:process.cwd()}))?.agent??"npm",P=[],x=new Set,v=new Set,k=Te(c$1.paths,t.cwd);k.isErr()&&program.error(E.red(k.unwrapErr()));let C=k.unwrap(),R=[];for(let w of u$1){let V=`${w.sourceRepo.url}/${w.category}/${w.name}`,T=`${w.category}/${w.name}`,W=w.sourceRepo,A=Y.join(t.cwd,C["*"],w.category);R.push(T),P.push({run:async({message:F})=>{F(`Adding ${E.cyan(V)}`),ie.mkdirSync(A,{recursive:true});let je=[],he=async X=>{let ye=await qe(W,X);return ye.isErr()&&(s.stop(E.red(`Error fetching ${E.bold(X)}`)),program.error(E.red(`There was an error trying to get ${V}`))),ye.unwrap()};for(let X of w.files){if(!c$1.includeTests&&Ge(X))continue;let ye=Y.join(w.directory,X),$t;w.subdirectory?$t=Y.join(A,w.name,X):$t=Y.join(A,X);let cn=await he(ye),ln=$t.slice(0,$t.length-X.length);ie.mkdirSync(ln,{recursive:true}),je.push({content:cn,destPath:$t});}for(let X of je)ie.writeFileSync(X.destPath,X.content);if(c$1.includeTests&&w.tests){let{devDependencies:X}=JSON.parse(ie.readFileSync(Y.join(t.cwd,"package.json")).toString());(X===void 0||X.vitest===void 0)&&x.add("vitest");}for(let X of w.devDependencies)x.add(X);for(let X of w.dependencies)v.add(X);}});}if(await wo({startMessage:"Adding blocks",stopMessage:`Added ${E.cyan(R.join(", "))}`,loading:s,tasks:P}),v.size>0||x.size>0){let w={name:"temp-package",type:"module",version:"0.0.1"},V=Y.join(g,"package.json");ie.writeFileSync(V,JSON.stringify(w,null," "));}await Me(v,x,{yes:true,no:false,cwd:g,pm:p,ignoreWorkspace:true});let z=r.parent.rawArgs.findIndex(w=>w==="--"),K=[];z!==-1&&(K=r.parent.rawArgs.slice(z+1)),o(`Passing args ${E.cyan(K.join(" "))}`),console.clear();let H=u$1[0],b;H.subdirectory?b=Y.join(g,`${H.category}/${H.name}/index.js`):b=Y.join(g,`${H.category}/${H.name}.js`);let N=resolveCommand(p,"execute",["tsx",b,...K]);N||program.error(E.red("Error resolving run command!"));try{await execa(N.command,N.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{ie.rmSync(Y.join(process.cwd(),y),{recursive:true,force:true});}};var fi=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(br),project:$.optional($.boolean()),registry:$.optional($.boolean()),script:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),Lr=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("--script <name>","The name of the build script. (For Registry setup)","build: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(fi,t);if(await le(),r.registry!==void 0&&r.project!==void 0&&program.error(E.red(`You cannot provide both ${E.bold("--project")} and ${E.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${E.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${E.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 mi(e,r):await gi(r),outro(E.green("All done!"));}),mi=async(e,t$1)=>{let r=Ne(t$1.cwd),o=spinner(),n,s={},i=ut(t$1.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(x){if(x.trim()==="")return "Please provide a value";if(!x.startsWith("./")){let v="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(i===null)return v;let k=createPathsMatcher(i);if(k&&k(x).length===0)return v}},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},s=r.unwrap().configFiles??{}):n={"*":a},!t$1.formatter){let x=r.isErr()?"none":r.unwrap().formatter??"none";ie.existsSync(Y.join(t$1.cwd,".prettierrc"))&&(x="prettier"),ie.existsSync(Y.join(t$1.cwd,"biome.json"))&&(x="biome");let v=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(k=>({value:k.toLowerCase(),label:k})),initialValue:x});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(t$1.formatter=v);}let c=Array.from(new Set([...e,...t$1.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,d=new Set,m=async x=>{let v=await ui({repo:x,paths:n,configFiles:s,options:t$1,formatter:t$1.formatter});for(let k of v.dependencies)l.add(k);for(let k of v.devDependencies)d.add(k);n=v.paths,s=v.configFiles;};if(c.length>0)for(let x of c){if(!e.find(v=>v===x)&&r.isOk()&&r.unwrap().repos.find(v=>v===x)){let v=await confirm({message:`Initialize ${x}?`,initialValue:t$1.yes});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),!v)continue}log.info(`Initializing ${E.cyan(x)}`),await m(x);}for(;;){let x=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)break;let v=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:k=>{if(k.trim().length===0)return "Please provide a value";if(!u(k))return `Invalid provider! Valid providers (${t.map(C=>C.name).join(", ")})`}});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),await m(v),c.push(v);}let h={$schema:`https://unpkg.com/jsrepo@${Re.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t$1.tests===void 0?r.unwrap().includeTests:t$1.tests??false,watermark:t$1.watermark,formatter:t$1.formatter,configFiles:s,paths:n};o.start(`Writing config to \`${nt}\``);let{prettierOptions:u$1,biomeOptions:y}=await at({formatter:h.formatter,cwd:t$1.cwd}),f=Y.join(t$1.cwd,nt),g=await vr.format(JSON.stringify(h,null," "),{biomeOptions:y,prettierOptions:u$1,filePath:f,formatter:h.formatter});ie.existsSync(t$1.cwd)||ie.mkdirSync(t$1.cwd,{recursive:true}),ie.writeFileSync(f,g),o.stop(`Wrote config to \`${nt}\`.`);let p=(await detect$1({cwd:t$1.cwd}))?.agent??"npm",P=await Me(l,d,{yes:t$1.yes,cwd:t$1.cwd,pm:p});if(P.dependencies.size>0||P.devDependencies.size>0){let x=[];if(!P.installed){if(l.size>0){let k=resolveCommand$1(p,"add",[...l]);x.push(`Install dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(d.size>0){let k=resolveCommand$1(p,"add",[...d,"-D"]);x.push(`Install dev dependencies \`${E.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}x=x.map((k,C)=>`${C+1}. ${k}`),P.installed||x.push(""),x.push(`Add blocks with ${E.cyan("jsrepo add")}!`);let v=et(x);process.stdout.write(v);}},ui=async({repo:e,paths:t$1,configFiles:r,formatter:o,options:n})=>{let s$1=spinner(),i=new Ue,a=u(e);if(a||program.error(E.red(`Invalid provider! Valid providers (${t.map(u=>u.name).join(", ")})`)),!i.get(a.name)&&a.name!==s.name&&!n.yes){let u=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u){let y=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),i.set(a.name,y);}}s$1.start(`Fetching manifest from ${E.cyan(e)}`);let l=(await Ot(e,{noCache:!n.cache})).match(u=>u,u=>program.error(E.red(u))),d=(await Xt(l)).match(u=>u,u=>program.error(E.red(u)));s$1.stop(`Fetched manifest from ${E.cyan(e)}`),wt(l,d,n.cwd);let m=[],h=[];if(d.configFiles){let{prettierOptions:u,biomeOptions:y}=await at({formatter:o,cwd:n.cwd});for(let f of d.configFiles){if(f.optional&&!n.yes){let k=await confirm({message:`Would you like to add the ${f.name} file?`,initialValue:true});if(isCancel(k)&&(cancel("Canceled!"),process.exit(0)),!k)continue}if(m.push(...f.dependencies??[]),h.push(...f.devDependencies??[]),!r[f.name]){let k=await text({message:`Where is your ${f.name} file?`,defaultValue:f.expectedPath,initialValue:f.expectedPath,placeholder:f.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),r[f.name]=k;}let g=Y.join(n.cwd,r[f.name]),p;if(ie.existsSync(g))p=ie.readFileSync(g).toString();else {let k=Y.dirname(g);if(ie.existsSync(k)){let C=Ro(g);if(C){p=ie.readFileSync(C).toString();let R=Y.relative(n.cwd,C);log.warn(`Located ${E.bold(r[f.name])} at ${E.bold(R)}`),r[f.name]=R,g=Y.join(n.cwd,R);}}}s$1.start(`Fetching the ${E.cyan(f.name)} from ${E.cyan(e)}`);let P=(await qe(l,f.path)).match(k=>k,k=>program.error(E.red(k))),x=await Jt({file:{content:P,destPath:g},biomeOptions:y,prettierOptions:u,formatter:o});s$1.stop(`Fetched the ${E.cyan(f.name)} from ${E.cyan(e)}`);let v=n.yes||p===void 0;if(p){if(!n.yes){let k=c(l.url,f.name),C=await mt({config:{biomeOptions:y,prettierOptions:u,formatter:o},current:{content:p,path:g},incoming:{content:x,path:k},options:{...n,loading:s$1,no:false}});C.applyChanges&&(v=true,p=C.updatedContent);}}else {let k=Y.dirname(g);ie.existsSync(k)||ie.mkdirSync(k,{recursive:true}),p=x;}v&&p&&(s$1.start(`Writing ${E.cyan(f.name)} to ${E.cyan(g)}`),ie.writeFileSync(g,p),s$1.stop(`Wrote ${E.cyan(f.name)} to ${E.cyan(g)}`));}}if(!n.yes){let u=await multiselect({message:"Which category paths would you like to configure?",options:d.categories.map(y=>({label:y.name,value:y.name})),required:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u.length>0)for(let y of u){let f=t$1[y],g=await text({message:`Where should ${y} be added in your project?`,validate(p){if(p.trim()==="")return "Please provide a value"},placeholder:f||`./src/${y}`,defaultValue:f,initialValue:f});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),t$1[y]=g;}}return {paths:t$1,configFiles:r,dependencies:m,devDependencies:h}},gi=async e=>{let t=spinner(),r=Y.join(e.cwd,"package.json");ie.existsSync(r)||program.error(E.red(`Couldn't find your ${E.bold("package.json")}!`));let o=Qt(e.cwd).match(g=>g,g=>program.error(E.red(g))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${Re.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let p=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),!p)break}let g=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:p=>{if(p.trim().length===0)return "Please provide a value!"}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(g);}let s=JSON.parse(ie.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let g=await confirm({message:`The \`${E.cyan(e.script)}\` already exists overwrite?`,initialValue:false});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),g)break;{let p=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:P=>{if(P.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),e.script=p;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let g=await confirm({message:`Add ${Ie} as a dev dependency?`,initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),a=g;}let c=!n;if(!e.yes&&n){let g=await confirm({message:`Create a \`${E.cyan(He)}\` file?`,initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),c=g;}let l=(await detect$1({cwd:"cwd"}))?.agent??"npm",d="";if(a)d+="jsrepo build";else {let g=resolveCommand$1(l,"execute",["jsrepo","build"]);g||program.error(E.red(`Error resolving execute command for ${l}`)),d+=`${g.command} ${g.args.join(" ")} `;}c||(d+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=d;let m=[];m.push({loadingMessage:`Adding \`${E.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${E.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{ie.writeFileSync(r,JSON.stringify(s,null," "));}catch(g){program.error(E.red(`Error writing to \`${E.bold(r)}\`. Error: ${g}`));}}}),c&&m.push({loadingMessage:`Writing config to \`${E.cyan(He)}\``,completedMessage:`Wrote config to \`${E.cyan(He)}\``,run:async()=>{let g=Y.join(e.cwd,He);try{ie.writeFileSync(Y.join(g),JSON.stringify(o,null," "));}catch(p){program.error(E.red(`Error writing to \`${E.bold(g)}\`. Error: ${p}`));}}}),await vo(m,{loading:t});let h=i;a&&!i&&(h=(await Me(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:l,yes:e.yes})).installed);let u=[];if(!h&&a){let g=resolveCommand$1(l,"add",["jsrepo","-D"]);u.push(`Install ${Ie} as a dev dependency \`${E.cyan(`${g?.command} ${g?.args.join(" ")}`)}\``);}u.push(`Add categories to \`${E.cyan(o.dirs.join(", "))}\`.`);let y=resolveCommand$1(l,"run",[e.script]);u.push(`Run \`${E.cyan(`${y?.command} ${y?.args.join(" ")}`)}\` to build the registry.`),u=u.map((g,p)=>`${p+1}. ${g}`);let f=et(u);process.stdout.write(f);};var Si=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),_r=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(Si,t);await le(),await ji(e,r),outro(E.green("All done!"));}),ji=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Pe} ${p}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ne(t.cwd).match(p=>p,p=>program.error(E.red(p))),n=Ee({verbose:t.verbose?r:void 0}),s=o.repos;if(t.repo&&(s=[t.repo]),!t.allow&&t.repo){let p=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t.repo)}?`,initialValue:true});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${E.cyan(s.join(", "))}`);let i=(await Ye(s,{noCache:!t.cache})).match(p=>p,({repo:p,message:P})=>{n.stop(`Failed to get info for ${E.cyan(p)}`),program.error(E.red(P));});r(`Resolved ${E.cyan(s.join(", "))}`),r(`Fetching blocks from ${E.cyan(s.join(", "))}`);let a=(await Nt(...i)).match(p=>p,({repo:p,message:P})=>{n.stop(`Failed fetching blocks from ${E.cyan(p)}`),program.error(E.red(P));});r(`Retrieved blocks from ${E.cyan(s.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${E.cyan(s.join(", "))}`);let c$1=Y.resolve(Y.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${E.bold(c$1)}.`),ie.mkdirSync(c$1,{recursive:true});let l=()=>{ie.rmSync(c$1,{recursive:true,force:true});},d=it(a,o,t.cwd).map(p=>p.specifier),m=e;e.length===0&&(m=d),m.length===0&&(l(),program.error(E.red("There were no blocks found in your project!")));let h=[];for(let p of m){let P,x=u(p);if(x){let{url:v}=x.parse(p,{fullyQualified:true}),k=(await Ot(v)).match(R=>R,R=>program.error(E.red(R))),C=(await Nt(k)).match(R=>R,R=>program.error(E.red(R)));for(let[R,I]of C)a.set(R,I);P=a.get(p);}else for(let v of s){let k=u(v);if(!k)continue;let{url:C,specifier:R}=k.parse(c(v,p),{fullyQualified:true}),I=a.get(c(C,R));if(I!==void 0){P=I;break}}P||program.error(E.red(`Invalid block! ${E.bold(p)} does not exist!`)),h.push({name:p,block:P});}let u$1=Te(o.paths,t.cwd).match(p=>p,p=>program.error(E.red(p)));for(let{block:p}of h){let P=p.sourceRepo,x=c(p.sourceRepo.url,p.category,p.name);if(t.verbose||n.start(`Setting up test file for ${E.cyan(x)}`),!p.tests){n.stop(`No tests found for ${E.cyan(x)}`);continue}let v=Dt(p,u$1,t.cwd);v=Y.relative(c$1,v);let k=async I=>{let z=await qe(P,I);return z.isErr()&&(n.stop(E.red(`Error fetching ${E.bold(I)}`)),program.error(E.red(`There was an error trying to get ${x}`))),z.unwrap()};r(`Downloading and copying test files for ${x}`);let C=[];for(let I of p.files.filter(z=>Ge(z))){let z=await k(Y.join(p.directory,I)),K=Y.join(c$1,I);ie.writeFileSync(K,z),C.push(K);}let R=new Project;for(let I of C){r(`Opening test file ${I}`);let z=R.addSourceFileAtPath(I);for(let K of z.getImportDeclarations()){let H=K.getModuleSpecifierValue(),b;H.startsWith(".")&&(p.subdirectory?b=Y.join(v,p.name,H):b=Y.join(v,H)),b&&K.setModuleSpecifier(b.replaceAll(/\\/g,"/"));}}R.saveSync(),r(`Completed ${E.cyan.bold(x)} test file`),t.verbose||n.stop(`Completed setup for ${E.bold(x)}`);}r("Beginning testing");let y=await detect({cwd:t.cwd});y==null&&program.error(E.red("Could not detect package manager"));let f=resolveCommand(y.agent,"execute",["vitest","run",c$1]);f==null&&program.error(E.red(`Could not resolve add command for '${y.agent}'.`));let g=`${f.command} ${f.args.join(" ")}`;r(`Running ${E.cyan(g)} on ${E.cyan(t.cwd)}`);try{await execa(f.command,f.args,{cwd:t.cwd,stdin:process.stdin,stdout:process.stdout}),l();}catch(p){t.debug?console.info(`${E.bold("--debug")} flag provided. Skipping cleanup. Run '${E.bold(g)}' to retry tests.
|
|
79
|
+
`):l(),program.error(E.red(`Tests failed! Error ${p}`));}};var Ni=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Vr=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(Ni,t);await le(),await Ti(e,r),outro(E.green("All done!"));}),Ti=async(e,t$1)=>{let r=v=>{t$1.verbose&&console.info(`${Pe} ${v}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=Ee({verbose:t$1.verbose?r:void 0}),n=Ne(t$1.cwd).match(v=>v,v=>program.error(E.red(v))),s=n.repos;t$1.repo&&(s=[t$1.repo]);for(let v of e)t.find(k=>v.startsWith(k.name))&&program.error(E.red(`Invalid value provided for block names \`${E.bold(v)}\`. Block names are expected to be provided in the format of \`${E.bold("<category>/<name>")}\``));if(!t$1.allow&&t$1.repo){let v=await confirm({message:`Allow ${E.cyan("jsrepo")} to download and run code from ${E.cyan(t$1.repo)}?`,initialValue:true});(isCancel(v)||!v)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${E.cyan(s.join(", "))}`),t$1.verbose||o.start(`Fetching blocks from ${E.cyan(s.join(", "))}`);let i=(await Ye(s,{noCache:!t$1.cache})).match(v=>v,({repo:v,message:k})=>{o.stop(`Failed to get info for ${E.cyan(v)}`),program.error(E.red(k));});r(`Resolved ${E.cyan(s.join(", "))}`),r(`Fetching blocks from ${E.cyan(s.join(", "))}`);let a=(await er(...i)).match(v=>v,({repo:v,message:k})=>{o.stop(`Failed fetching blocks from ${E.cyan(v)}`),program.error(E.red(k));}),c$1=Zt(a);t$1.verbose||o.stop(`Retrieved blocks from ${E.cyan(s.join(", "))}`),r(`Retrieved blocks from ${E.cyan(s.join(", "))}`);for(let v of a)wt(v.state,v.manifest,t$1.cwd);let l=it(c$1,n,t$1.cwd);l.length===0&&program.error(E.red(`You haven't installed any blocks yet. Did you mean to \`${E.bold("add")}\`?`));let d=e;if(t$1.all&&(d=l.map(v=>v.specifier)),d.length===0){let v=await multiselect({message:`Which blocks would you like to ${t$1.no?"diff":"update"}?`,options:l.filter(k=>k.block.list).map(k=>({label:`${E.cyan(k.block.category)}/${k.block.name}`,value:k.specifier})),required:true});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),d=v;}r(`Preparing to update ${E.cyan(d.join(", "))}`);let m=(await st(d,c$1,i)).match(v=>v,program.error),h=new Set,u=new Set,{prettierOptions:y,biomeOptions:f}=await at({formatter:n.formatter,cwd:t$1.cwd}),g=Te(n.paths,t$1.cwd).match(v=>v,v=>program.error(E.red(v))),p=rr(m,n);for(let v of p){let k=c(v.block.sourceRepo.url,v.block.category,v.block.name),C=Ft(v.block.sourceRepo.url);r(`Attempting to update ${k}`),n.includeTests&&v.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let I of v.block.devDependencies)h.add(I);for(let I of v.block.dependencies)u.add(I);let R=await v.files;process.stdout.write(`${O}
|
|
81
80
|
`),process.stdout.write(`${O} ${k}
|
|
82
|
-
`);for(let I of R){let
|
|
81
|
+
`);for(let I of R){let z=I.content.match(w=>w,w=>program.error(E.red(w))),K=At(I.name,v.block,g,t$1.cwd),H=(await It({file:{content:z,destPath:K},biomeOptions:f,prettierOptions:y,config:n,imports:v.block._imports_,watermark:C,verbose:r,cwd:t$1.cwd})).match(w=>w,w=>program.error(E.red(w))),b="";ie.existsSync(K)&&(b=ie.readFileSync(K).toString());let N=await mt({config:{biomeOptions:f,prettierOptions:y,formatter:n.formatter},current:{path:K,content:b},incoming:{path:c(k,I.name),content:H},options:{...t$1,loading:o,verbose:t$1.verbose?r:void 0}});N.applyChanges&&(o.start(`Writing changes to ${E.cyan(K)}`),ie.writeFileSync(K,N.updatedContent),o.stop(`Wrote changes to ${E.cyan(K)}.`));}}let P=(await detect({cwd:t$1.cwd}))?.agent??"npm",x=await Me(u,h,{yes:t$1.yes,no:t$1.no,cwd:t$1.cwd,pm:P});if(x.dependencies.size>0||x.devDependencies.size>0){let v=[];if(!x.installed){if(u.size>0){let C=resolveCommand(P,"add",[...u]);v.push(`Install dependencies \`${E.cyan(`${C?.command} ${C?.args.join(" ")}`)}\``);}if(h.size>0){let C=resolveCommand(P,"add",[...h,"-D"]);v.push(`Install dev dependencies \`${E.cyan(`${C?.command} ${C?.args.join(" ")}`)}\``);}}v=v.map((C,R)=>`${R+1}. ${C}`),x.installed||v.push(""),v.push("Import and use the blocks!");let k=et(v);process.stdout.write(k);}};var an=program.name(pt.name).description(pt.description).version(pt.version).addCommand(Rr).addCommand(Er).addCommand(Dr).addCommand(Tr).addCommand(Lr).addCommand(_r).addCommand(Vr);an.parse();//# sourceMappingURL=index.js.map
|
|
83
82
|
//# sourceMappingURL=index.js.map
|