jsrepo 2.0.3 → 2.1.0
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 +67 -49
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {h,g,f,j,z,c,w,m,o,p,y,a,v,u,b,B,A,l}from'./chunk-GJE55QJV.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import
|
|
3
|
-
${JSON.stringify(a,null," ")}`);let c=await
|
|
4
|
-
${JSON.stringify(a,null," ")}`);let c=await
|
|
5
|
-
${JSON.stringify(s,null," ")}`);let a=await
|
|
2
|
+
import {h,g,f,j,z,c,w,m,o,p,x as x$1,y,a,v,u,b,B,A,l}from'./chunk-GJE55QJV.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import pe from'node:fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import N from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import Z from'pathe';import*as $ from'valibot';import li from'is-unicode-supported';import {stripVTControlCharacters}from'node:util';import {builtinModules}from'node:module';import {createPathsMatcher,getTsconfig}from'get-tsconfig';import $n from'validate-npm-package-name';import mi from'node:os';import Qi from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import Wo from'boxen';import {diffLines,diffChars}from'diff';import Lo from'semver';import {cursor,erase}from'sisteransi';import wi from'@anthropic-ai/sdk';import xi from'ollama';import Ci from'openai';import vi from'conf';import Ei from'make-fetch-happen';import {Biome,Distribution}from'@biomejs/js-api';import*as Yo from'css-dependency';import*as Qo from'prettier';import*as Zo from'parse5';import is from'oxc-parser';import {walk}from'estree-walker';import*as mn from'svelte/compiler';import*as yn from'vue/compiler-sfc';import zs from'node-machine-id';import Qs from'ignore';import*as Xn from'tar';var St={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.1.0"};var pi=li(),ce=(e,t)=>pi?e:t,vo=ce("\u25C6","*"),wo=ce("\u25C6","*"),bo=ce("\u25A0","x"),T=N.gray(ce("\u2502","|")),Mt=N.gray(ce("\u2500","-")),ko=N.gray(ce("\u2510","+")),$o=N.gray(ce("\u2518","+")),Wt=N.gray(ce("\u251C","+")),xo=N.gray(ce("\u252C","+"));N.gray(ce("\u250C","T"));var Co=N.gray(ce("\u2514","-")),me=N.bgRgb(245,149,66).black(" WARN "),je=N.bgBlueBright.white(" INFO "),Vt=N.bgRedBright.white(" ERROR "),Ke=N.hex("#f7df1e")("jsrepo"),Be=N.hex("#f7df1e").bold("jsrepo.com");function Ro(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function So(e,t){let r=0;for(let o of e)r=r+t(o);return r}function jo(e){let t=0;for(let r of e){let o=stripVTControlCharacters(r);o.length>t&&(t=o.length);}return t}function Jt(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-o)+e}function Eo(e,t,r=" "){let o=stripVTControlCharacters(e).length;if(o>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-o)}var ui=/\n|\r\n/g;function J(e){return e.split(ui)}function G(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Jt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(mi.EOL)}var gi={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},hi={"install-as-dev-dependency":"-D"},yi={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Io={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Oo={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Dr={bun:gi,npm:yi,pnpm:Io,deno:hi,yarn:Oo,"yarn@berry":Oo,"pnpm@6":Io};function _e(){return new vi({projectName:"jsrepo"})}var Tr="http-registries-w-tokens",le=class{#e;constructor(t){this.#e=t??_e();}getKey(t){return `${t}-token`.toLowerCase()}get(t){let r=this.getKey(t),o=this.#e.get(r,void 0);return t==="jsrepo"?o??process.env.JSREPO_TOKEN:o}set(t,r){if(t.startsWith("http")){let n=this.getHttpRegistriesWithTokens(),i=t.slice(5);n||(n=[]),n.includes(i)||n.push(i),this.#e.set(Tr,n);}let o=this.getKey(t);this.#e.set(o,r);}delete(t){if(t.startsWith("http")){let o=this.getHttpRegistriesWithTokens(),n=t.slice(5),i=o.indexOf(n);i!==-1&&(o=[...o.slice(0,i),...o.slice(i+1)]),this.#e.set(Tr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Tr);return t||[]}};var Lr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await Do("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Nr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
|
|
3
|
+
${JSON.stringify(a,null," ")}`);let c=await Si({model:"claude-3-7-sonnet-latest",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("Claude 3.7 Sonnet updated the file"),c?{content: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:i})=>{let s=await Do("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=Nr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting OpenAI o3-mini with:
|
|
4
|
+
${JSON.stringify(a,null," ")}`);let c=await Ri({model:"o3-mini",prompt:a,apiKey:s,messages:i,maxTokens:(e.content.length+t.content.length)*2});return o||r.stop("OpenAI o3-mini updated the file"),c?{content: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:i})=>{o||r.start("Asking Phi4");let s=Nr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Phi4 with:
|
|
5
|
+
${JSON.stringify(s,null," ")}`);let a=await ji({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:Ar(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function Ri({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new Ci({apiKey:o}).chat.completions.create({model:r,max_completion_tokens:t,messages:[{role:"system",content:e.system},...n??[],{role:"user",content:e.message}]})).choices[0];return a.message.content===null?null:a.message.content}async function Si({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new wi({apiKey:n}),s=[];if(t)for(let l of t)s.push({role:l.role,content:[{type:"text",text:l.content}]});s.push({role:"user",content:[{type:"text",text:e.message}]});let c=(await i.messages.create({model:o,max_tokens:Math.min(r,8192),temperature:.5,system:e.system,messages:s})).content[0];return c.type!=="text"?null:c.text}async function ji({prompt:e,messages:t,model:r}){return (await xi.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function Nr({originalFile:e,newFile:t,additionalInstructions:r,rePrompt:o}){return {system:"You will merge two files provided by the user. You will respond only with the resulting code. DO NOT format the code with markdown, DO NOT put the code inside of triple quotes, only return the code as a raw string. DO NOT make unnecessary changes.",message:o?r??"":`
|
|
6
6
|
This is my current file ${e.path}:
|
|
7
7
|
<code>
|
|
8
8
|
${e.content}
|
|
@@ -12,72 +12,90 @@ This is the file that has changes I want to update with ${t.path}:
|
|
|
12
12
|
<code>
|
|
13
13
|
${t.content}
|
|
14
14
|
</code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
|
|
15
|
-
`}}function
|
|
15
|
+
`}}function Ar(e){let t=e.trim();if(t.startsWith("```")&&(t=J(t).slice(1).join(`
|
|
16
16
|
`).trim()),t.endsWith("```")){let r=J(t);t=r.slice(0,r.length-1).join(`
|
|
17
|
-
`).trim();}return t}async function
|
|
18
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function
|
|
19
|
-
`,
|
|
20
|
-
`),C.length>j){let Q=C.length-j;h+=`${G(J(N.gray(`+ ${Q} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${
|
|
21
|
-
`;}R&&(
|
|
22
|
-
`),
|
|
23
|
-
`,
|
|
24
|
-
`,m.removed||(
|
|
25
|
-
`,m.removed||(
|
|
17
|
+
`).trim();}return t}async function Do(e){let t=new le,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 He=St;function To(e){return /^\s+$/g.test(e)}function jt(e){let t=e.length-1;for(;To(e[t])&&t>=0;){if(e[t]===`
|
|
18
|
+
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function No({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:i=N.redBright,colorAdded:s=N.greenBright,colorCharsRemoved:a=N.bgRedBright,colorCharsAdded:c=N.bgGreenBright,prefix:l,onUnchanged:d,intro:g}){let h="",w=So(r,b=>b.count??0).toString().length+1,p=0;if(r.length===1&&!r[0].added&&!r[0].removed)return d({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:d,intro:g});h+=g({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:d,intro:g});let u=b=>N.gray(`${l?.()??""}${Jt(`${b+1+p} `,w)} `);for(let b=0;b<r.length;b++){let m=r[b],S=r[b-1]?.added||r[b-1]?.removed,R=r[b+1]?.added||r[b+1]?.removed;if(!m.added&&!m.removed){if(!o&&m.count!==void 0&&m.count>n){let x=p,C=J(jt(m.value)),j=0;if(R&&(j+=n),S&&(j+=n),j>=C.length){h+=`${G(C,{prefix:u})}
|
|
19
|
+
`,p+=C.length;continue}if(S&&(h+=`${G(C.slice(0,n),{prefix:u})}
|
|
20
|
+
`),C.length>j){let Q=C.length-j;h+=`${G(J(N.gray(`+ ${Q} more unchanged (${N.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Jt(" ",w)} `})}
|
|
21
|
+
`;}R&&(p=p+C.length-n,h+=`${G(C.slice(C.length-n),{prefix:u})}
|
|
22
|
+
`),p=x+m.count;continue}h+=`${G(J(jt(m.value)),{prefix:u})}
|
|
23
|
+
`,p+=m.count??0;continue}let f=x=>x.added?s(jt(x.value)):x.removed?i(jt(x.value)):x.value,v=x=>x.added?c(jt(x.value)):x.removed?a(jt(x.value)):x.value;if(m.removed&&m.count===1&&r[b+1]?.added&&r[b+1]?.count===1){let C=diffChars(m.value,r[b+1].value).map(j=>v(j)).join("");h+=`${u(0)}${C}`,p+=1,b++;}else To(m.value)?(h+=`${G(J(v(m)),{prefix:x=>`${u(x)}${v({removed:true,value:" ",added:false})}`})}
|
|
24
|
+
`,m.removed||(p+=m.count??0)):(h+=`${G(J(f(m)),{prefix:u})}
|
|
25
|
+
`,m.removed||(p+=m.count??0));}return h.endsWith(`
|
|
26
26
|
`)||(h=h+=`
|
|
27
|
-
`),h}var Ne=
|
|
28
|
-
`),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(
|
|
27
|
+
`),h}var Ne=Ei.defaults({cachePath:Z.join(import.meta.dirname,"cache")});var Fr="latest-version",Oi=60*60*1e3;async function Ao({noCache:e=false}={}){try{let t=_e(),r;if(!e){let i=t.get(Fr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Fr);}}let o=await Ne("https://raw.githubusercontent.com/jsrepojs/jsrepo/refs/heads/main/packages/cli/package.json",{timeout:1e3});if(!o.ok)return b("Error getting version");let{version:n}=await o.json();return r=n,t.set(Fr,{expiration:Date.now()+Oi,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}var Di=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Ti=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/;function qe(e){let t=Di.exec(e)||Ti.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function _r(e,t){let r=Z.join(e,"package.json");if(pe.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return _r(o.slice(0,o.length-1).join("/"),t)}function Mr(e){if(!pe.existsSync(e))return b(`${e} doesn't exist`);let t=pe.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function sr(e){return e[0]==="^"?e.slice(1):e}function Bo(e,t,{cwd:r}){let o=e,n=t,i=Mr(Z.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=qe(a).unwrap(),d=s.dependencies[c];if(l===void 0&&d){o.delete(a);continue}d&&Lo.satisfies(sr(d),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=qe(a).unwrap(),d=s.devDependencies[c];if(l===void 0&&d){n.delete(a);continue}d&&Lo.satisfies(sr(d),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}async function Vo(e,{loading:t}){for(let r of e){t.start(r.loadingMessage);try{await r.run();}catch(o){t.stop(`Error while ${r.loadingMessage}`),console.error(o);}t.stop(r.completedMessage);}}async function Jo({tasks:e,startMessage:t,stopMessage:r,loading:o}){o.start(t),await Promise.all([...e.map(n=>n.run({message:o.message}))]),o.stop(r);}function he({verbose:e}={}){let t=spinner();return {message:r=>{e?e(r??""):t.message(r);},stop:r=>{e?e(r??""):t.stop(r);},start:r=>{e?e(r??""):t.start(r);}}}function dt(e){let t=Wo(e.join(`
|
|
28
|
+
`),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Wt),bottomLeft:stripVTControlCharacters(Wt),topRight:stripVTControlCharacters(ko),top:stripVTControlCharacters(Mt),bottom:stripVTControlCharacters(Mt),bottomRight:stripVTControlCharacters($o),left:stripVTControlCharacters(T),right:stripVTControlCharacters(T)}});return `${T}
|
|
29
29
|
${t}
|
|
30
|
-
`}function
|
|
31
|
-
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await
|
|
32
|
-
`);let i=false,s=e.content,a=n.get(
|
|
33
|
-
`,intro:({from:g,to:h,changes:w,prefix:
|
|
34
|
-
${
|
|
35
|
-
`}});if(process.stdout.write(
|
|
36
|
-
`);continue}s=await
|
|
37
|
-
`);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function
|
|
30
|
+
`}function Uo(e,t=3){let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`}async function Gi(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${N.redBright(t)} -> ${N.greenBright(r)}`,`${N.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${N.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${N.yellowBright("Star")} on GitHub for updates: https://github.com/jsrepojs/jsrepo`];return Wo(i.join(`
|
|
31
|
+
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function ie(){console.clear();let e=await Ao();e.isOk()&&Lo.lt(He.version,e.unwrap())&&console.info(await Gi(He.name,He.version,e.unwrap())),intro(`${N.bgHex("#f7df1e").black(` ${He.name} `)}${N.gray(` v${He.version} `)}`);}var Mo="model-preference";async function Pt({incoming:e,current:t,config:r,options:o}){let n=_e();process.stdout.write(`${T}
|
|
32
|
+
`);let i=false,s=e.content,a=n.get(Mo,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),d=No({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:g,to:h,prefix:w})=>`${w?.()??""}${N.cyan(g)} \u2192 ${N.gray(h)} ${N.gray("(unchanged)")}
|
|
33
|
+
`,intro:({from:g,to:h,changes:w,prefix:p})=>{let u=w.filter(b=>b.added||b.removed).length;return `${p?.()??""}${N.cyan(g)} \u2192 ${N.gray(h)} (${u} change${u===1?"":"s"})
|
|
34
|
+
${p?.()??""}
|
|
35
|
+
`}});if(process.stdout.write(d),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let g=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?g.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${N.yellow("Update with AI")} \u2728 ${N.gray("(Start over)")}`,value:"update"}):g.push({label:`\u2728 ${N.yellow("Update with AI")} \u2728`,value:"update"});let h=await select({message:"Accept changes?",options:g});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),h==="update"||h==="update-iterate"){h==="update"&&(c=[]);let w=await select({message:"Select a model",options:Object.keys(Lr).map(u=>({label:u,value:u})),initialValue:a});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!==a&&n.set(Mo,w),a=w;let p=await text({message:"Additional instructions:",defaultValue:"None",validate:u=>{if(c.length!==0&&u.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(p)&&(cancel("Canceled!"),process.exit(0));try{let{content:u,prompt:b}=await Lr[a].updateFile({originalFile:t,newFile:{content:h==="update-iterate"?s:e.content,path:e.path},additionalInstructions:p!=="None"?p:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=u,c.push({role:"user",content:b}),c.push({role:"assistant",content:u});}catch(u){o.loading.stop(),log.error(N.red(`Error getting completions: ${u}`)),process.stdout.write(`${T}
|
|
36
|
+
`);continue}s=await lr({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter}),process.stdout.write(`${T}
|
|
37
|
+
`);continue}i=h==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function Ye(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Bo(e,t,{cwd:n});if(a.size>0||c.size>0){let d=r;if(!r&&!o){let g=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),d=g;}if(d)return a.size>0&&await Wr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Wr({pm:i,deps:Array.from(c),dev:true,cwd:n,ignoreWorkspace:s}),{installed:true,dependencies:a,devDependencies:c}}return {installed:false,dependencies:a,devDependencies:c}}function Go(e){let t=N.dim(T),r=N.green(vo),o=N.green(wo),n=N.red(bo);process.stdout.write(`${t}
|
|
38
38
|
`),process.stdout.write(`${r} ${e}
|
|
39
|
-
`);let i="",s="",a=(l=false)=>{if(!s)return;let
|
|
40
|
-
`).reduce((w,
|
|
41
|
-
`).slice(-l);s="";for(let g of
|
|
42
|
-
`;process.stdout.write(N.dim(s));};return {set text(l){a(),i+=l;let
|
|
39
|
+
`);let i="",s="",a=(l=false)=>{if(!s)return;let d=process.stdout.columns,h=s.split(`
|
|
40
|
+
`).reduce((w,p)=>w+Math.ceil(p.length/d),0)+(l?1:0);process.stdout.write(cursor.up(h)),process.stdout.write(erase.down());},c=(l=0)=>{let d=i.split(`
|
|
41
|
+
`).slice(-l);s="";for(let g of d)s+=`${t} ${g}
|
|
42
|
+
`;process.stdout.write(N.dim(s));};return {set text(l){a(),i+=l;let d=Math.ceil(process.stdout.rows/2);c(d);},fail(l){a(true),process.stdout.write(`${n} ${l}
|
|
43
43
|
`),c();},success(l){a(true),process.stdout.write(`${o} ${l}
|
|
44
|
-
`);}}}async function
|
|
45
|
-
`;c.success(`Installed ${N.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var
|
|
44
|
+
`);}}}async function Wr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Dr[e]["install-as-dev-dependency"]);let s=Dr[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(N.red(`Could not resolve add command for '${e}'.`));let c=Go(`Installing dependencies with ${e}...`);try{let l=x(a.command,[...a.args],{nodeOptions:{cwd:o}});for await(let d of l)c.text=`${d}
|
|
45
|
+
`;c.success(`Installed ${N.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var qi=/\{\{([^\/]+)\/([^\}]+)\}\}/g;function Ko({template:e,config:t,destPath:r,cwd:o}){let n=Z.join(r,"../");return e.replace(qi,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=Z.relative(n,Z.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return Z.join(t.paths[s],a)})}async function Gt({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=mt.find(d=>d.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
|
|
46
46
|
|
|
47
|
-
${l}`),a$1?.(`Formatting ${N.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(
|
|
47
|
+
${l}`),a$1?.(`Formatting ${N.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(d){return b(`Error formatting ${N.bold(e.destPath)} ${d}`)}}for(let[d,g]of Object.entries(r)){let h=Ko({template:g,config:t,destPath:e.destPath,cwd:s}),w=new RegExp(`(['"])${Qi(d)}\\1`,"g");l=l.replaceAll(w,`$1${h}$1`);}return a(l)}async function lr({file:e,formatter:t,prettierOptions:r,biomeOptions:o}){let n=mt.find(s=>s.matches(e.destPath)),i=e.content;if(n)try{i=await n.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r,biomeOptions:o});}catch{return i}return i}function qo(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=Z.dirname(e),o=pe.readdirSync(r),n=Z.parse(e);for(let i of o)if(l(i,t)&&Z.parse(i).name===n.name)return Z.join(r,i)}function Et(e){let t;try{if(t=getTsconfig(e,"tsconfig.json"),!t&&(t=getTsconfig(e,"jsconfig.json"),!t))return a(null)}catch(r){return b(`Error while trying to get ${N.bold("tsconfig.json")}: ${r}`)}return a(t)}var Xo={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=Yo.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ie({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(d=>Ee(d)).join(`
|
|
48
48
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
49
49
|
${G(J(e),{prefix:()=>" "})}
|
|
50
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await
|
|
51
|
-
`)):a(
|
|
50
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Qo.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}};var tn={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=Zo.parse(s),c=[],l=(g,h)=>{if(g&&(h(g),g.childNodes&&g.childNodes.length>0))for(let w of g.childNodes)l(w,h);};for(let g of a$1.childNodes)l(g,h=>{if(h.tagName==="script")for(let w of h.attrs)w.name==="src"&&c.push(w.value);if(h.tagName==="link"&&h.attrs.find(w=>w.name==="rel"&&w.value==="stylesheet"))for(let w of h.attrs)w.name==="href"&&!w.value.startsWith("http")&&c.push(w.value);});let d=Ie({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(g=>Ee(g)).join(`
|
|
51
|
+
`)):a(d.unwrap())},comment:e=>`<!--
|
|
52
52
|
${G(J(e),{prefix:()=>" "})}
|
|
53
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await
|
|
53
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Qo.format(e,{parser:"html",...r}):e};function dr(e,t){let r=is.parseSync(e,t),o=[];for(let n of r.module.staticImports)o.push(n.moduleRequest.value);for(let n of r.module.dynamicImports){let i=t.slice(n.moduleRequest.start+1,n.moduleRequest.end-1);o.push(i);}for(let n of r.module.staticExports)for(let i of n.entries)i.moduleRequest&&o.push(i.moduleRequest.value);return o}var on={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=dr(e,s),c=Ie({moduleSpecifiers:a$1,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return c.isErr()?b(c.unwrapErr().map(l=>Ee(l)).join(`
|
|
54
54
|
`)):a(c.unwrap())},comment:e=>`/*
|
|
55
55
|
${G(J(e),{prefix:()=>" "})}
|
|
56
|
-
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await
|
|
56
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Qo.format(e,{filepath:r,...o});let i=await Biome.create({distribution:Distribution.NODE});return n&&i.applyConfiguration(n),i.formatContent(e,{filePath:r}).content}};var sn=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Qo.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration({...o,json:{parser:{allowComments:true}}}),i.formatContent(e,{filePath:n}).content},fr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:sn},an={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
57
57
|
${G(J(e),{prefix:()=>" "})}
|
|
58
|
-
*/`,format:
|
|
58
|
+
*/`,format:sn};var pn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=Yo.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Ie({moduleSpecifiers:c.map(d=>d.module),filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return l.isErr()?b(l.unwrapErr().map(d=>Ee(d)).join(`
|
|
59
59
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
60
60
|
${G(J(e),{prefix:()=>" "})}
|
|
61
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await
|
|
62
|
-
`)):a(
|
|
61
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Qo.format(e,{parser:"scss",...r}):e};var un={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=mn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=g=>{(g.type==="ImportDeclaration"||g.type==="ExportAllDeclaration"||g.type==="ExportNamedDeclaration")&&typeof g.source?.value=="string"&&c.push(g.source.value),g.type==="ImportExpression"&&g.source.type==="Literal"&&typeof g.source.value=="string"&&c.push(g.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let d=Ie({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(g=>Ee(g)).join(`
|
|
62
|
+
`)):a(d.unwrap())},comment:e=>`<!--
|
|
63
63
|
${G(J(e),{prefix:()=>" "})}
|
|
64
|
-
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await
|
|
64
|
+
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Qo.format(e,{filepath:r,...o}):e};var gn={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
65
65
|
${G(J(e),{prefix:()=>" "})}
|
|
66
|
-
-->`,format:async e=>e};var
|
|
66
|
+
-->`,format:async e=>e};var vn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=pe.readFileSync(e).toString(),a$1=yn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let d=dr("noop.ts",a$1.descriptor.script.content);c.push(...d);}if(a$1.descriptor.scriptSetup?.content){let d=dr("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...d);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Ie({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(d=>Ee(d)).join(`
|
|
67
67
|
`)):a(l.unwrap())},comment:e=>`<!--
|
|
68
68
|
${G(J(e),{prefix:()=>" "})}
|
|
69
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await
|
|
70
|
-
${i||e} references code not contained in ${N.bold(s.join(", "))} and cannot be resolved.`)}function un(e,t=true){let[r,o,...n]=e.split("/");o===void 0&&(o="index");let i=o;t&&i.includes(".")&&(i=i.slice(0,i.length-Z.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=Z.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function os(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Pt(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let p of l){let g=is(p);if(!g)continue;let h=Z.relative(Z.resolve(Z.join(r,"../")),g.prettyPath),w=ns(g.prettyPath,g.path,[".js",".ts"]),d=hn(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:g.type==="file"});if(d.isErr())return b(d.unwrapErr());if(d.unwrap())return a(d.unwrap());break}}return a(void 0)}function ns(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=Z.parse(e),n=Z.parse(t),i=Z.join(o.dir,o.name),s=Z.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function is(e){if(le.existsSync(e))return {path:e,prettyPath:e,type:le.statSync(e).isDirectory()?"directory":"file"};let t=Z.join(e,"../");if(!le.existsSync(t))return;let r=Z.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(le.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=le.readdirSync(t);for(let n of o){let i=Z.parse(n);if(i.name===r.base){let s=Z.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:le.statSync(s).isDirectory()?"directory":"file"}}}}function ss(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Ar(Z.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(le.readFileSync(n,"utf-8"));for(let l of e){let p=Ke(l);if(p.isErr()){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let g=p.unwrap();if(!gn(g.name).validForNewPackages){console.warn(`${T} ${fe} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(g.name))continue;let h;if(c!==void 0&&(h=c[g.name]),h!==void 0){i.add(`${g.name}@${h}`);continue}if(a!==void 0&&(h=a[g.name]),h!==void 0){s.add(`${g.name}@${h}`);continue}i.add(g.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ft=[Go,Ho,lr,Zo,rn,an,cn,Yo,pn,mn];var vn=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),wn=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),cs=$.union([$.literal("no-category-index-file-dependency"),$.literal("no-unpinned-dependency"),$.literal("require-local-dependency-exists"),$.literal("max-local-dependencies"),$.literal("no-circular-dependency"),$.literal("no-unused-block"),$.literal("no-framework-dependency"),$.literal("require-config-file-exists"),$.literal("no-config-file-framework-dependency"),$.literal("no-config-file-unpinned-dependency")]),bn={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${N.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/"),s=t.categories.find(c=>c.name.trim()===n.trim()),a=`${N.bold(`${e.category}/${e.name}`)} depends on local dependency ${N.bold(o)} which doesn't exist`;if(!s){r.push(a);continue}s.blocks.find(c=>c.name===i)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/");if(i!=="index")continue;let s=t.categories.find(c=>c.name===n);!s||!s.blocks.find(c=>c.name===i)||r.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.bold(`${n}/${i}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${N.bold(`${e.category}/${e.name}`)} has too many local dependencies (${N.bold(e.localDependencies.length)}) limit (${N.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=pr(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${N.bold(o)}: ${N.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(pr(r,n,t.categories))return;return [`${N.bold(r)} is unused and will be ${N.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>Ke(o).unwrap().name).filter(o=>vn.has(o));if(r.length>0)for(let o of r)t.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.bold(o)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let o of e.configFiles)le.existsSync(Z.join(t,o.path))||r.push(`The ${N.bold(o.name)} config file doesn't exist at ${N.bold(Z.join(t,o.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>Ke(n).unwrap().name).filter(n=>vn.has(n));if(o.length>0)for(let n of o)t.push(`${N.bold(r.name)} depends on ${N.bold(n)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${N.bold(o)}`);return t.length>0?t:void 0}}}},kn=$.record(cs,$.union([wn,$.tupleWithRest([wn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),Ut={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"};function fr(e,t,r,o=Ut){let n=[],i=[];for(let[s,a]of Object.entries(bn)){if(a.scope==="block")continue;let c=o[s],l,p=[];if(Array.isArray(c)?(l=c[0],p.push(...c.slice(1))):l=c,l==="off")continue;let g=a.check({manifest:e,options:p,cwd:r,config:t});if(g){if(l==="error"){i.push(...g.map(h=>`${T} ${Mt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...g.map(h=>`${T} ${fe} ${h} ${N.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(bn)){if(l.scope==="global")continue;let p=o[c],g,h=[];if(Array.isArray(p)?(g=p[0],h.push(...p.slice(1))):g=p,g==="off")continue;let w=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(w){if(g==="error"){i.push(...w.map(d=>`${T} ${Mt} ${N.red(d)} ${N.gray(c)}`));continue}n.push(...w.map(d=>`${T} ${fe} ${d} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function pr(e,t,r,o=[]){let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;if(o.includes(i))return;let[s,a]=i.split("/"),c=r.find(p=>p.name===s)?.blocks.find(p=>p.name===a);if(!c)continue;let l=pr(e,c,r,n);if(l)return [...l,e]}}function $n(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(pr(e,o,t))return true}return false}var Sn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"];function nt(e){return Sn.find(t=>e.endsWith(t))!==void 0}function mr(e,{cwd:t,ignore:r,config:o}){let n;try{n=le.readdirSync(e);}catch{program.error(N.red(`Couldn't read the ${N.bold(e)} directory.`));}let i=[];for(let s of n){let a=Z.join(e,s);if(le.statSync(a).isFile())continue;let c=`${Z.relative(t,a)}/`;if(r.ignores(c))continue;let l=Z.basename(s);if(!ds(l,o))continue;let p=ls(l,o),g={name:l,blocks:[]},h=le.readdirSync(a);for(let w of h){let d=Z.join(a,w);if(le.statSync(d).isFile()){if(nt(w))continue;let u=ps(w),b=xn(u,o);if(!Cn(u,o))continue;let m=ft.find(j=>j.matches(w));if(!m){console.warn(`${T} ${fe} Skipped \`${N.bold(d)}\` \`*${N.bold(Z.parse(w).ext)}\` files are not currently supported!`);continue}let S=h.find(j=>Sn.find(Q=>j===`${u}${Q}`)),{dependencies:R,devDependencies:f,local:v,imports:x}=m.resolveDependencies({filePath:d,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(j=>j,j=>{program.error(N.red(j));}),C={name:u,directory:Z.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:p?b:false,files:[w],localDependencies:v,_imports_:x,dependencies:R,devDependencies:f};S!==void 0&&C.files.push(S),g.blocks.push(C);}else {let u=w,b=xn(u,o);if(!Cn(u,o))continue;let m=new Set,S=new Set,R=new Set,f={},v=false,x=[],C=(Q,oe)=>{for(let q of oe){let k=Z.join(Q,q),A=k.slice(d.length+1);if(nt(q)){v=true,x.push(A);continue}if(le.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${fe} Skipped \`${N.bold(Z.join(d,q))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let V=le.readdirSync(k);C(k,V);continue}let y=ft.find(V=>V.matches(q));if(!y){console.warn(`${T} ${fe} Skipped \`${k}\` \`*${N.bold(Z.parse(q).ext)}\` files are not currently supported!`);continue}let{local:M,dependencies:P,devDependencies:W,imports:te}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:d,filePath:k,cwd:t}).match(V=>V,V=>{program.error(N.red(V));});for(let V of M)V!==`${l}/${u}`&&m.add(V);for(let V of P)S.add(V);for(let V of W)R.add(V);for(let[V,et]of Object.entries(te))f[V]=et;x.push(A);}};C(d,le.readdirSync(d));let j={name:u,directory:Z.relative(t,d),category:l,tests:v,subdirectory:true,list:p?b:false,files:x,localDependencies:Array.from(m.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(R.keys()),_imports_:f};g.blocks.push(j);}}i.push(g);}return i}function ur(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ft.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:Z.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(N.red(c));});a.length>0&&program.error(N.red(`${N.bold(o.name)} ${N.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:i,devDependencies:s});}return r}function xn(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function Cn(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function ls(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function ds(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function ps(e){return Z.parse(Z.basename(e)).name}function gr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!$n(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var vr=[".git","node_modules"],gt="jsrepo.json",ht="jsrepo-build-config.json",_r=$.union([$.literal("prettier"),$.literal("biome")]),ms=$.objectWithRest({"*":$.string()},$.string()),Mr=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:ms,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(_r)});function Oe(e){if(!le.existsSync(Z.join(e,gt)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(Mr,JSON.parse(le.readFileSync(Z.join(e,gt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${gt}\` file!`)}var us=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),access:$.optional(j),meta:$.optional(f),peerDependencies:$.optional(g),configFiles:$.optional($.array(h)),dirs:$.array($.string()),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string()),[]),includeCategories:$.optional($.array($.string()),[]),excludeBlocks:$.optional($.array($.string()),[]),excludeCategories:$.optional($.array($.string()),[]),doNotListBlocks:$.optional($.array($.string()),[]),doNotListCategories:$.optional($.array($.string()),[]),listBlocks:$.optional($.array($.string()),[]),listCategories:$.optional($.array($.string()),[]),excludeDeps:$.optional($.array($.string()),[]),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),rules:$.optional(kn)});function It(e){if(!le.existsSync(Z.join(e,ht)))return a(null);let t=$.safeParse(us,JSON.parse(le.readFileSync(Z.join(e,ht)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ht}\` file!`)}function We(e,t){let r=Pt(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=Z.relative(t,Z.join(Z.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${N.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${N.bold("`./`")}.`);let a=gs(s,o,t);if(!a)return b(`Cannot resolve ${N.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${N.bold("`./`")}.`);n[i]=a;}return a(n)}function gs(e,t,r){let o=t(e);return o.length>0?Z.relative(r,o[0]):void 0}function zt(e,t,r){let o;return t[e.category]!==void 0?o=Z.join(r,t[e.category]):o=Z.join(r,t["*"],e.category),o}async function it(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:Ne,token:Wr(e.provider,e.url)})}async function wr(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Ne,token:Wr(e.provider,e.url)})}function Wr(e,t){let r=new ge;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function Kt(e,{noCache:t=false}={}){let r=z(e);if(r){let o=_e();if(r.name!==u.name&&!t)if(t)o.delete(`${e}-state`);else {let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=r.parse(e,{fullyQualified:false}),i=await r.state(e,{token:Wr(r,n.url),fetch:Ne});return r.name!==u.name&&!t&&o.set(`${e}-state`,i),a(i)}return b(`Only ${y.map((o,n)=>`${n===y.length-1?"and ":""}${N.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function st(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Kt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function Ht(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await wr(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();for(let c$1 of a.categories)for(let l of c$1.blocks)r.set(c(i.url,`${l.category}/${l.name}`),{...l,sourceRepo:i});}))).find(i=>i!==void 0);return n||a(r)}function br(e){let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t}async function kr(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await wr(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();r.push({state:i,manifest:a});}))).find(i=>i!==void 0);return n||a(r)}async function yt(e,t,r,o=new Map){let n=new Map;for(let i of e){let s,a=z(i);if(a){let{url:l,specifier:p}=a.parse(i,{fullyQualified:true});s=t.get(c(l,p));}else {if(r.length===0)return b(N.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${N.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:p,specifier:g}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(p,g));if(h!==void 0){s=h;break}}}if(!s)return b(`Invalid block! ${N.bold(i)} does not exist!`);let c$1=`${s.category}/${s.name}`;if(n.set(c$1,s),s.localDependencies&&s.localDependencies.length>0){let l=await yt(s.localDependencies.filter(p=>!n.has(p)&&!o.has(p)),t,r,n);if(l.isErr())return b(l.unwrapErr());for(let p of l.unwrap())n.set(`${p.category}/${p.name}`,p);}}return a(bo(n,(i,s)=>s))}function vt(e,t,r){let o=[],n=We(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=zt(s,n,r),c=Z.join(a,s.files[0]);s.subdirectory&&(c=Z.join(a,s.name)),le.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function xr(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>nt(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await it(o.sourceRepo,Z.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function Yt(e,t,r,o){let n=zt(t,r,o);return t.subdirectory?Z.join(n,t.name,e):Z.join(n,e)}function jn(e){if(e===void 0)return;let t={};for(let r of e.split(",")){let[o,n]=r.split("=");if(o===void 0||n===void 0)throw new InvalidArgumentError("Expected map to be provided in the following format: `--option key=value,key=value`");t[o]=n;}return t}function Pn(e){return new Promise(t=>t(e))}async function wt({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await Uo.resolveConfig(Z.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Z.join(t,"biome.json");le.existsSync(n)&&(o=JSON.parse(le.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function Qt(e){return `Installed from ${e}`}function Dt(e,t,r){if(!t.peerDependencies)return;let o=Fr(Z.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${N.bold("package.json")}. Please create one.`),program.error(N.red(s));}),n={...o.dependencies,...o.devDependencies},i=[];for(let[s,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let p=n[s];if(!p){i.push({name:s,expected:c,message:l,version:p,exists:false});continue}Io.satisfies(or(p),c)||i.push({name:s,expected:c,message:l,version:p,exists:true});}if(i.length>0){process.stdout.write(`${T}
|
|
71
|
-
${N.yellow("\u25B2")} ${
|
|
72
|
-
`);let s=i.map((a,c)=>{let l=i.length-1===c,
|
|
69
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Qo.format(e,{parser:"vue",...r}):e};var bn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>G(J(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Qo.format(e,{parser:"yaml",...r}):e};function Ee(e){return `${G(J(e),{prefix:t=>t===0?`${T} ${Vt} `:`${T} `})}`}function Ie({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,d={};for(let w of e){if(builtinModules.includes(w)||w.startsWith("node:"))continue;if(w.startsWith(".")){let m=xn(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(m.isErr()){a$1.push(m.unwrapErr());continue}let S=m.unwrap();S&&(l.add(S.dependency),d[w]=S.template);continue}let p=qe(w);if(!p.isErr()){let m=p.unwrap();if($n(m.name).validForNewPackages){c.add(w);continue}}let u=ms(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(u.isErr()){a$1.push(u.unwrapErr());continue}let b=u.unwrap();b?(l.add(b.dependency),d[w]=b.template):console.warn(`${T} ${me} Skipped adding import \`${N.cyan(w)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:g,dependencies:h}=hs(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:h,devDependencies:g,local:Array.from(l),imports:d})}function xn(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:i,dirs:s,cwd:a$1}){if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=t?Z.join(o,"../"):Z.join(r,"../"),l=Z.join(Z.join(r,"../"),e),d=Z.join(c,"../");if(o&&l.startsWith(o))return a(void 0);if(l.startsWith(d))return a(kn(l.slice(d.length),n));let g=Z.resolve(l),h=null;for(let w of s){let p=Z.resolve(Z.join(a$1,w));g.startsWith(p)&&(h===null||h.length<p.length)&&(h=p);}return h!==null?a(kn(g.slice(h.length+1),n)):b(`${r}:
|
|
70
|
+
${i||e} references code not contained in ${N.bold(s.join(", "))} and cannot be resolved.`)}function kn(e,t=true){let[r,o,...n]=e.split("/");o===void 0&&(o="index");let i=o;t&&i.includes(".")&&(i=i.slice(0,i.length-Z.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=Z.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function ms(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=Et(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=createPathsMatcher(a$1);if(c){let l=c(e);for(let d of l){let g=gs(d);if(!g)continue;let h=Z.relative(Z.resolve(Z.join(r,"../")),g.prettyPath),w=us(g.prettyPath,g.path,[".js",".ts"]),p=xn(h,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:g.type==="file"});if(p.isErr())return b(p.unwrapErr());if(p.unwrap())return a(p.unwrap());break}}return a(void 0)}function us(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=Z.parse(e),n=Z.parse(t),i=Z.join(o.dir,o.name),s=Z.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function gs(e){if(pe.existsSync(e))return {path:e,prettyPath:e,type:pe.statSync(e).isDirectory()?"directory":"file"};let t=Z.join(e,"../");if(!pe.existsSync(t))return;let r=Z.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(pe.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=pe.readdirSync(t);for(let n of o){let i=Z.parse(n);if(i.name===r.base){let s=Z.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:pe.statSync(s).isDirectory()?"directory":"file"}}}}function hs(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=_r(Z.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(pe.readFileSync(n,"utf-8"));for(let l of e){let d=qe(l);if(d.isErr()){console.warn(`${T} ${me} Skipped adding import \`${N.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let g=d.unwrap();if(!$n(g.name).validForNewPackages){console.warn(`${T} ${me} Skipped adding import \`${N.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(g.name))continue;let h;if(c!==void 0&&(h=c[g.name]),h!==void 0){i.add(`${g.name}@${h}`);continue}if(a!==void 0&&(h=a[g.name]),h!==void 0){s.add(`${g.name}@${h}`);continue}i.add(g.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var mt=[Xo,tn,fr,an,pn,un,gn,on,vn,bn];var Rn=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"]),Sn=$.union([$.literal("off"),$.literal("warn"),$.literal("error")]),vs=$.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")]),jn={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${N.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/"),s=t.categories.find(c=>c.name.trim()===n.trim()),a=`${N.bold(`${e.category}/${e.name}`)} depends on local dependency ${N.bold(o)} which doesn't exist`;if(!s){r.push(a);continue}s.blocks.find(c=>c.name===i)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/");if(i!=="index")continue;let s=t.categories.find(c=>c.name===n);!s||!s.blocks.find(c=>c.name===i)||r.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.bold(`${n}/${i}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${N.bold(`${e.category}/${e.name}`)} has too many local dependencies (${N.bold(e.localDependencies.length)}) limit (${N.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=ur(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${N.bold(o)}: ${N.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(ur(r,n,t.categories))return;return [`${N.bold(r)} is unused and will be ${N.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>qe(o).unwrap().name).filter(o=>Rn.has(o));if(r.length>0)for(let o of r)t.push(`${N.bold(`${e.category}/${e.name}`)} depends on ${N.bold(o)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let o of e.configFiles)pe.existsSync(Z.join(t,o.path))||r.push(`The ${N.bold(o.name)} config file doesn't exist at ${N.bold(Z.join(t,o.path))}`);return r.length>0?r:void 0}}},"no-config-file-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies of config files.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles!==void 0){for(let r of e.configFiles){let o=[...r.devDependencies??[],...r.dependencies??[]].map(n=>qe(n).unwrap().name).filter(n=>Rn.has(n));if(o.length>0)for(let n of o)t.push(`${N.bold(r.name)} depends on ${N.bold(n)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${N.bold(o)}`);return t.length>0?t:void 0}}}},Pn=$.record(vs,$.union([Sn,$.tupleWithRest([Sn,$.union([$.string(),$.number()])],$.union([$.string(),$.number()]))])),zt={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"};function gr(e,t,r,o=zt){let n=[],i=[];for(let[s,a]of Object.entries(jn)){if(a.scope==="block")continue;let c=o[s],l,d=[];if(Array.isArray(c)?(l=c[0],d.push(...c.slice(1))):l=c,l==="off")continue;let g=a.check({manifest:e,options:d,cwd:r,config:t});if(g){if(l==="error"){i.push(...g.map(h=>`${T} ${Vt} ${N.red(h)} ${N.gray(s)}`));continue}n.push(...g.map(h=>`${T} ${me} ${h} ${N.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(jn)){if(l.scope==="global")continue;let d=o[c],g,h=[];if(Array.isArray(d)?(g=d[0],h.push(...d.slice(1))):g=d,g==="off")continue;let w=l.check(a,{manifest:e,options:h,cwd:r,config:t});if(w){if(g==="error"){i.push(...w.map(p=>`${T} ${Vt} ${N.red(p)} ${N.gray(c)}`));continue}n.push(...w.map(p=>`${T} ${me} ${p} ${N.gray(c)}`));}}return {warnings:n,errors:i}}function ur(e,t,r,o=[]){let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;if(o.includes(i))return;let[s,a]=i.split("/"),c=r.find(d=>d.name===s)?.blocks.find(d=>d.name===a);if(!c)continue;let l=ur(e,c,r,n);if(l)return [...l,e]}}function En(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(ur(e,o,t))return true}return false}var Tn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"];function st(e){return Tn.find(t=>e.endsWith(t))!==void 0}function hr(e,{cwd:t,ignore:r,config:o}){let n;try{n=pe.readdirSync(e);}catch{program.error(N.red(`Couldn't read the ${N.bold(e)} directory.`));}let i=[];for(let s of n){let a=Z.join(e,s);if(pe.statSync(a).isFile())continue;let c=`${Z.relative(t,a)}/`;if(r.ignores(c))continue;let l=Z.basename(s);if(!bs(l,o))continue;let d=ws(l,o),g={name:l,blocks:[]},h=pe.readdirSync(a);for(let w of h){let p=Z.join(a,w);if(pe.statSync(p).isFile()){if(st(w))continue;let u=ks(w),b=In(u,o);if(!On(u,o))continue;let m=mt.find(j=>j.matches(w));if(!m){console.warn(`${T} ${me} Skipped \`${N.bold(p)}\` \`*${N.bold(Z.parse(w).ext)}\` files are not currently supported!`);continue}let S=h.find(j=>Tn.find(Q=>j===`${u}${Q}`)),{dependencies:R,devDependencies:f,local:v,imports:x}=m.resolveDependencies({filePath:p,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(j=>j,j=>{program.error(N.red(j));}),C={name:u,directory:Z.relative(t,a),category:l,tests:S!==void 0,subdirectory:false,list:d?b:false,files:[w],localDependencies:v,_imports_:x,dependencies:R,devDependencies:f};S!==void 0&&C.files.push(S),g.blocks.push(C);}else {let u=w,b=In(u,o);if(!On(u,o))continue;let m=new Set,S=new Set,R=new Set,f={},v=false,x=[],C=(Q,oe)=>{for(let q of oe){let k=Z.join(Q,q),A=k.slice(p.length+1);if(st(q)){v=true,x.push(A);continue}if(pe.statSync(k).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${me} Skipped \`${N.bold(Z.join(p,q))}\` subdirectories are not allowed! Allow them with ${N.bold("--allow-subdirectories")}!`);continue}let V=pe.readdirSync(k);C(k,V);continue}let y=mt.find(V=>V.matches(q));if(!y){console.warn(`${T} ${me} Skipped \`${k}\` \`*${N.bold(Z.parse(q).ext)}\` files are not currently supported!`);continue}let{local:M,dependencies:P,devDependencies:W,imports:te}=y.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:p,filePath:k,cwd:t}).match(V=>V,V=>{program.error(N.red(V));});for(let V of M)V!==`${l}/${u}`&&m.add(V);for(let V of P)S.add(V);for(let V of W)R.add(V);for(let[V,rt]of Object.entries(te))f[V]=rt;x.push(A);}};C(p,pe.readdirSync(p));let j={name:u,directory:Z.relative(t,p),category:l,tests:v,subdirectory:true,list:d?b:false,files:x,localDependencies:Array.from(m.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(R.keys()),_imports_:f};g.blocks.push(j);}}i.push(g);}return i}function yr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=mt.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:Z.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(N.red(c));});a.length>0&&program.error(N.red(`${N.bold(o.name)} ${N.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:i,devDependencies:s});}return r}function In(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function On(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function ws(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function bs(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function ks(e){return Z.parse(Z.basename(e)).name}function vr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!En(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var kr=[".git","node_modules"],ht="jsrepo.json",yt="jsrepo-build-config.json",Jr=$.union([$.literal("prettier"),$.literal("biome")]),xs=$.objectWithRest({"*":$.string()},$.string()),Ur=$.object({$schema:$.string(),repos:$.optional($.array($.string()),[]),includeTests:$.boolean(),paths:xs,configFiles:$.optional($.record($.string(),$.string())),watermark:$.optional($.boolean(),true),formatter:$.optional(Jr)});function Oe(e){if(!pe.existsSync(Z.join(e,ht)))return b("Could not find your configuration file! Please run `init`.");let t=$.safeParse(Ur,JSON.parse(pe.readFileSync(Z.join(e,ht)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${ht}\` file!`)}var Cs=$.object({$schema:$.string(),name:$.optional($.string()),version:$.optional($.string()),readme:$.optional($.string(),"README.md"),access:$.optional(j),meta:$.optional(f),peerDependencies:$.optional(g),configFiles:$.optional($.array(h)),dirs:$.array($.string()),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string()),[]),includeCategories:$.optional($.array($.string()),[]),excludeBlocks:$.optional($.array($.string()),[]),excludeCategories:$.optional($.array($.string()),[]),doNotListBlocks:$.optional($.array($.string()),[]),doNotListCategories:$.optional($.array($.string()),[]),listBlocks:$.optional($.array($.string()),[]),listCategories:$.optional($.array($.string()),[]),excludeDeps:$.optional($.array($.string()),[]),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),rules:$.optional(Pn)});function It(e){if(!pe.existsSync(Z.join(e,yt)))return a(null);let t=$.safeParse(Cs,JSON.parse(pe.readFileSync(Z.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}function We(e,t){let r=Et(t).unwrapOr(null),o=r?createPathsMatcher(r):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=Z.relative(t,Z.join(Z.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${N.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${N.bold("`./`")}.`);let a=Rs(s,o,t);if(!a)return b(`Cannot resolve ${N.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${N.bold("`./`")}.`);n[i]=a;}return a(n)}function Rs(e,t,r){let o=t(e);return o.length>0?Z.relative(r,o[0]):void 0}function Ht(e,t,r){let o;return t[e.category]!==void 0?o=Z.join(r,t[e.category]):o=Z.join(r,t["*"],e.category),o}async function at(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:Ne,token:Gr(e.provider,e.url)})}async function $r(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Ne,token:Gr(e.provider,e.url)})}function Gr(e,t){let r=new le;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function qt(e,{noCache:t=false}={}){let r=z(e);if(r){let o=_e();if(r.name!==u.name&&!t)if(t)o.delete(`${e}-state`);else {let s=o.get(`${e}-state`);if(s)return a({...s,provider:r})}let n=r.parse(e,{fullyQualified:false}),i=await r.state(e,{token:Gr(r,n.url),fetch:Ne});return r.name!==u.name&&!t&&o.set(`${e}-state`,i),a(i)}return b(`Only ${y.map((o,n)=>`${n===y.length-1?"and ":""}${N.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function ct(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await qt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function Yt(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await $r(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();for(let c$1 of a.categories)for(let l of c$1.blocks)r.set(c(i.url,`${l.category}/${l.name}`),{...l,sourceRepo:i});}))).find(i=>i!==void 0);return n||a(r)}function xr(e){let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t}async function Cr(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await $r(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();r.push({state:i,manifest:a});}))).find(i=>i!==void 0);return n||a(r)}async function vt(e,t,r,o=new Map){let n=new Map;for(let i of e){let s,a=z(i);if(a){let{url:l,specifier:d}=a.parse(i,{fullyQualified:true});s=t.get(c(l,d));}else {if(r.length===0)return b(N.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${N.bold(`github/ieedan/std/${i}`)}\`!`));for(let l of r){let{url:d,specifier:g}=l.provider.parse(c(l.url,i),{fullyQualified:true}),h=t.get(c(d,g));if(h!==void 0){s=h;break}}}if(!s)return b(`Invalid block! ${N.bold(i)} does not exist!`);let c$1=`${s.category}/${s.name}`;if(n.set(c$1,s),s.localDependencies&&s.localDependencies.length>0){let l=await vt(s.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,(i,s)=>s))}function wt(e,t,r){let o=[],n=We(t.paths,r).match(i=>i,i=>program.error(N.red(i)));for(let[i,s]of e){let a=Ht(s,n,r),c=Z.join(a,s.files[0]);s.subdirectory&&(c=Z.join(a,s.name)),pe.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function Sr(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>st(s)?t.includeTests:true),i=Promise.all(n.map(async s=>{let a=await at(o.sourceRepo,Z.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function Xt(e,t,r,o){let n=Ht(t,r,o);return t.subdirectory?Z.join(n,t.name,e):Z.join(n,e)}function Nn(e){if(e===void 0)return;let t={};for(let r of e.split(",")){let[o,n]=r.split("=");if(o===void 0||n===void 0)throw new InvalidArgumentError("Expected map to be provided in the following format: `--option key=value,key=value`");t[o]=n;}return t}function An(e){return new Promise(t=>t(e))}async function bt({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await Qo.resolveConfig(Z.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Z.join(t,"biome.json");pe.existsSync(n)&&(o=JSON.parse(pe.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function Zt(e){return `Installed from ${e}`}function Tt(e,t,r){if(!t.peerDependencies)return;let o=Mr(Z.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${N.bold("package.json")}. Please create one.`),program.error(N.red(s));}),n={...o.dependencies,...o.devDependencies},i=[];for(let[s,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let d=n[s];if(!d){i.push({name:s,expected:c,message:l,version:d,exists:false});continue}Lo.satisfies(sr(d),c)||i.push({name:s,expected:c,message:l,version:d,exists:true});}if(i.length>0){process.stdout.write(`${T}
|
|
71
|
+
${N.yellow("\u25B2")} ${xo} Issues with ${N.bold(e.url)} peer dependencies
|
|
72
|
+
`);let s=i.map((a,c)=>{let l=i.length-1===c,d;a.exists?d=`${N.yellowBright("x unmet peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)} >> found ${N.yellowBright.bold(a.version)}`:d=`${N.red("x missing peer")} need ${N.bold(`${a.name}@`)}${N.greenBright.bold(a.expected)}`;let g=`${T} ${l?Co:Wt}${Mt} ${d}`;return a.message?`${g}
|
|
73
73
|
${T} ${l?"":T} ${N.gray(a.message)}`:g}).join(`
|
|
74
74
|
`);process.stdout.write(`${s}
|
|
75
|
-
`);}}var
|
|
75
|
+
`);}}var _s=$.object({watermark:$.optional($.boolean()),tests:$.optional($.boolean()),formatter:$.optional($.union([$.literal("prettier"),$.literal("biome"),$.literal("none")])),paths:$.optional($.record($.string(),$.string())),expand:$.boolean(),maxUnchanged:$.number(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Hr=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").addOption(new Option("--formatter <choice>","The formatter to use when adding blocks.").choices(["prettier","biome","none"])).addOption(new Option("--watermark <choice>","Include a watermark at the top of added files.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--tests <choice>","Include tests when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",Nn,void 0).option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=$.parse(_s,t);await ie(),await Ms(e,r),outro(N.green("All done!"));});async function Ms(e,t){let r=k=>{t.verbose&&console.info(`${je} ${k}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(t.cwd),i=n.isErr(),s;if(n.isErr()){let k=t.yes;if(!t.yes){let A=await confirm({message:`You don't have ${Ke} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),k=A;}k||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else s=n.unwrap();s.formatter=t.formatter!==void 0&&t.formatter!=="none"?t.formatter:s.formatter,s.watermark=t.watermark!==void 0?t.watermark:s.watermark,s.includeTests=t.tests!==void 0?t.tests:s.includeTests,s.paths=t.paths!==void 0?{...s.paths,...t.paths}:s.paths;let a=s.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let k of e){let A=z(k);if(!A){l=true;continue}let{url:y}=A.parse(k,{fullyQualified:true});if(!(!s.repos.find(P=>P===y)&&!c$1.has(y))){if(!t.allow){let P=await confirm({message:`Allow ${Ke} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(P)||!P)&&(cancel("Canceled!"),process.exit(0));}a.push(y);}c$1.add(y);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let k=await confirm({message:`Allow ${Ke} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(k)||!k)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(N.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${N.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(a.join(", "))}`);let d=(await ct(a,{noCache:!t.cache})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed to get info for ${N.cyan(k)}`),program.error(N.red(A));});r(`Resolved ${N.cyan(a.join(", "))}`),r(`Fetching blocks from ${N.cyan(a.join(", "))}`);let g=(await Cr(d,{verbose:t.verbose?r:void 0})).match(k=>k,({repo:k,message:A})=>{o.stop(`Failed fetching blocks from ${N.cyan(k)}`),program.error(N.red(A));}),h=xr(g);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(a.join(", "))}`),r(`Retrieved blocks from ${N.cyan(a.join(", "))}`);for(let k of g)Tt(k.state,k.manifest,t.cwd);let w=wt(h,s,t.cwd).map(k=>k.specifier),p=e;if(p.length===0){let k=await multiselect({message:"Select which blocks to add.",options:Array.from(h.entries()).filter(([A,y])=>y.list).map(([A,y])=>{let M=`${y.category}/${y.name}`,P=w.findIndex(te=>te===M)!==-1,W;return a.length>1?W=`${N.cyan(c(y.sourceRepo.url,y.category))}/${y.name}`:W=`${N.cyan(y.category)}/${y.name}`,{label:P?N.gray(W):W,value:A,hint:P?"Installed":void 0}}),required:true});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),p=k;}r(`Installing blocks ${N.cyan(p.join(", "))}`);let u=(await vt(p,h,d)).match(k=>k,k=>program.error(k)),b=new Set,m=new Set,S=_e();if(i){let k=`${t.cwd}-zero-config`,A=$.safeParse(Ur,S.get(k)),y=A.success?A.output:s,M=Array.from(new Set(u.map(P=>P.category)));if(t.paths===void 0)for(let P of M){let W=await text({message:`Where would you like to add ${N.cyan(P)}?`,placeholder:y?y.paths[P]:`./src/${P}`,initialValue:y?y.paths[P]:`./src/${P}`,defaultValue:y?y.paths[P]:`./src/${P}`,validate(te){if(te.trim()==="")return "Please provide a value"}});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),s.paths[P]=W;}if(!t.yes&&t.tests===void 0){let P=await confirm({message:"Include tests?",initialValue:y.includeTests});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=P;}if(!t.yes&&t.watermark===void 0){let P=await confirm({message:"Add watermark?",initialValue:y.watermark});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),s.watermark=P;}if(t.formatter===void 0){let P="none";pe.existsSync(Z.join(t.cwd,".prettierrc"))&&(P="prettier"),pe.existsSync(Z.join(t.cwd,"biome.json"))&&(P="biome");let W=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(te=>({value:te.toLowerCase(),label:te})),initialValue:P==="none"?y.formatter?y.formatter:"none":P});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),W!=="none"&&(s.formatter=W);}S.set(k,s),w=wt(h,s,t.cwd).map(P=>P.specifier);}let{prettierOptions:R,biomeOptions:f}=await bt({formatter:s.formatter,cwd:t.cwd}),v=We(s.paths,t.cwd).match(k=>k,k=>program.error(N.red(k))),x=new Set,C,j=Sr(u,s),Q=[];for(let k of j){let A=c(k.block.sourceRepo.url,k.block.category,k.block.name),y=`${k.block.category}/${k.block.name}`;r(`Setting up ${A}`);let M=w.find(P=>y===P);s.includeTests&&k.block.tests&&(r("Trying to include tests"),b.add("vitest"));for(let P of k.block.devDependencies)b.add(P);for(let P of k.block.dependencies)m.add(P);if(M&&!t.yes&&!C){if(C===void 0){let P=u.map(te=>`${te.category}/${te.name}`).filter(te=>w.find(V=>V===te));log.warn(`The following components ${N.bold.yellow("already exist")}: ${N.cyan(Uo(P))}`);let W=await confirm({message:`Would you like to ${N.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(W)&&(cancel("Canceled!"),process.exit(0)),C=W;}if(!C){let P=await k.files;process.stdout.write(`${T}
|
|
76
76
|
`),process.stdout.write(`${T} ${A}
|
|
77
|
-
`);for(let W of P){let te=W.content.match(Se=>Se,Se=>program.error(N.red(Se))),V=Yt(W.name,k.block,v,t.cwd),et=(await Jt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Se=>Se,Se=>program.error(N.red(Se))),Re="";le.existsSync(V)&&(Re=le.readFileSync(V).toString());let re=await jt({config:{biomeOptions:f,prettierOptions:R,formatter:s.formatter},current:{path:V,content:Re},incoming:{path:c(A,W.name),content:et},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});re.applyChanges&&(Q.push(Pn({destination:V,content:re.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(P=>{P.map(async W=>{let te=W.content.match(Re=>Re,Re=>program.error(N.red(Re))),V=Yt(W.name,k.block,v,t.cwd),et=Jt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Qt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Re=>(Re.isErr()&&program.error(N.red(Re.unwrapErr())),{destination:V,content:Re.unwrap(),block:k.block}));Q.push(et);});}),x.add(y);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(j.map(k=>k.files)),await Promise.all(Q.map(async k=>{let A=await k,y=Z.dirname(A.destination);le.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),le.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),le.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",q=await He(m,b,{yes:t.yes,cwd:t.cwd,pm:oe});if(q.dependencies.size>0||q.devDependencies.size>0){let k=[];if(!q.installed){if(m.size>0){let y=resolveCommand(oe,"add",[...m]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(b.size>0){let y=resolveCommand(oe,"add",[...b,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,M)=>`${M+1}. ${y}`),q.installed||k.push(""),k.push("Import and use the blocks!");let A=dt(k);process.stdout.write(A);}}function An(e){return new Promise(t=>setTimeout(t,e))}var Bs=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),zr=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Bs,e);await ie(),await _s(t),outro(N.green("All done!"));});async function _s(e){let t=new ge;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Be}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Be}!`);return}if(t.get("jsrepo")!==void 0){let a=await confirm({message:"You are currently signed into jsrepo do you want to sign out?",initialValue:false});(isCancel(a)||!a)&&(cancel("Canceled!"),process.exit(0));}let r=Ls.machineIdSync(true),o;try{let a=await Ne(`${w}/api/login/device`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!a.ok)throw new Error("There was an error creating the session");o=(await a.json()).id;}catch(a){program.error(N.red(a));}log.step(`Sign in at ${N.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=he(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(N.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await An(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Ne(a,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!c.ok)continue;clearTimeout(s);let l=await c.text();t.set("jsrepo",l),i.stop(`Logged into ${Be}!`);break}catch{}}}var Js=$.object({dirs:$.optional($.array($.string())),outputDir:$.optional($.string()),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),preview:$.optional($.boolean()),output:$.boolean(),verbose:$.boolean(),cwd:$.string()}),Kr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${m}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Js,e);await ie(),await Us(t),outro(N.green("All done!"));});async function Us(e){let t=d=>{e.verbose&&console.info(`${je} ${d}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n=It(e.cwd).match(d=>{if(d===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let u=d;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(u.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(u.preview=e.preview),u.rules={...Ut,...u.rules},u},d=>program.error(N.red(d))),i;n.outputDir?i=Z.join(e.cwd,n.outputDir):i=e.cwd;let s=Z.join(i,m);if(e.output&&le.existsSync(s)){if(n.outputDir){let d=o(le.readFileSync(s).toString());if(d.isOk())for(let u of d.unwrap().categories)for(let b of u.blocks){let m=Z.join(i,b.directory);le.existsSync(m)&&le.rmSync(m,{recursive:true});}}le.rmSync(s);}let a=Vs();try{let d=le.readFileSync(Z.join(e.cwd,".gitignore")).toString();a.add(d);}catch{}a.add(vr);for(let d of n.dirs){let u=Z.join(e.cwd,d);r.start(`Building ${N.cyan(u)}`);let b=mr(u,{cwd:e.cwd,ignore:a,config:n});for(let m of b){if(o$1.find(S=>S.name===m.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${d}/${m.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(m);}r.stop(`Built ${N.cyan(u)}`);}let c=ur(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:p$1,errors:g}=fr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(p$1.length>0||g.length>0)&&console.log(T);for(let d of p$1)console.log(d);if(g.length>0){for(let d of g)console.log(d);program.error(N.red(`Completed checking manifest with ${N.bold(`${g.length} error(s)`)} and ${N.bold(`${p$1.length} warning(s)`)}`));}let[h,w]=gr(l.categories);if(l.categories=h,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n.preview){let d=l.categories.flatMap(u=>u.blocks.filter(b=>b.list).map(b=>`${N.cyan(b.category)}/${b.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of d)console.log(`${T} \u25FB ${u}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l.configFiles)for(let d of l.configFiles){let u=Z.join(e.cwd,d.path),b=Z.join(i,d.path),m=Z.join(b,"../");le.existsSync(m)||le.mkdirSync(m,{recursive:true}),le.copyFileSync(u,b);}for(let d of l.categories)for(let u of d.blocks){let b=Z.join(e.cwd,u.directory),m=Z.join(i,u.directory);for(let S of u.files){let R=Z.join(m,S,"../");le.existsSync(R)||le.mkdirSync(R,{recursive:true}),le.copyFileSync(Z.join(b,S),Z.join(m,S));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),le.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var Qs=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),Yr=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=$.parse(Qs,t);await ie(),await Xs(e,o,r);});async function Xs(e,t,r){let o=y=>{t.verbose&&console.info(`${je} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=Oe(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let p=n?z(n):void 0;if(n&&p){let{url:y}=p.parse(n,{fullyQualified:true});if(!l.find(M=>M===y)){if(!t.allow){let M=await confirm({message:`Allow ${Ge} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(M)||!M)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Ge} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(N.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${N.cyan(l.join(", "))}`);let g=(await st(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(M));}),h=(await Ht(g,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(M));});if(i.stop(`Retrieved scripts from ${N.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([M,P])=>P.list).map(([M,P])=>{let W;return l.length>1?W=`${N.cyan(c(P.sourceRepo.url,P.category))}/${P.name}`:W=`${N.cyan(P.category)}/${P.name}`,{label:W,value:M}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let w=(await yt([n],h,g)).match(y=>y,y=>program.error(y)),d="temp-jsrepo-exec",u=`./${d}/${encodeURIComponent(n)}`,b=Z.join(process.cwd(),u);c$1.paths["*"]=u,le.mkdirSync(b,{recursive:true});let m=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],R=new Set,f=new Set,v=We(c$1.paths,t.cwd);v.isErr()&&program.error(N.red(v.unwrapErr()));let x$1=v.unwrap(),C=[];for(let y of w){let M=`${y.sourceRepo.url}/${y.category}/${y.name}`,P=`${y.category}/${y.name}`,W=y.sourceRepo,te=Z.join(t.cwd,x$1["*"],y.category);C.push(P),S.push({run:async({message:V})=>{V(`Adding ${N.cyan(M)}`),le.mkdirSync(te,{recursive:true});let et=[],Re=async re=>{let Se=await it(W,re);return Se.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(re)}`)),program.error(N.red(`There was an error trying to get ${M}`))),Se.unwrap()};for(let re of y.files){if(!c$1.includeTests&&nt(re))continue;let Se=Z.join(y.directory,re),Lt;y.subdirectory?Lt=Z.join(te,y.name,re):Lt=Z.join(te,re);let Qn=await Re(Se),Xn=Lt.slice(0,Lt.length-re.length);le.mkdirSync(Xn,{recursive:true}),et.push({content:Qn,destPath:Lt});}for(let re of et)le.writeFileSync(re.destPath,re.content);if(c$1.includeTests&&y.tests){let{devDependencies:re}=JSON.parse(le.readFileSync(Z.join(t.cwd,"package.json")).toString());(re===void 0||re.vitest===void 0)&&R.add("vitest");}for(let re of y.devDependencies)R.add(re);for(let re of y.dependencies)f.add(re);}});}if(await Fo({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(C.join(", "))}`,loading:i,tasks:S}),f.size>0||R.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},M=Z.join(b,"package.json");le.writeFileSync(M,JSON.stringify(y,null," "));}await He(f,R,{yes:true,no:false,cwd:b,pm:m,ignoreWorkspace:true});let Q=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];Q!==-1&&(oe=r.parent.rawArgs.slice(Q+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let q=w[0],k;q.subdirectory?k=Z.join(b,`${q.category}/${q.name}/index.js`):k=Z.join(b,`${q.category}/${q.name}.js`);let A=resolveCommand(m,"execute",["tsx",k,...oe]);A||program.error(N.red("Error resolving run command!"));try{let y=x(A.command,A.args,{nodeOptions:{cwd:process.cwd()}});for await(let M of y)process.stdout.write(`${M}
|
|
78
|
-
`);}finally{le.rmSync(Z.join(process.cwd(),d),{recursive:true,force:true});}}var ia=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(_r),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),Zr=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=$.parse(ia,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(N.red(`You cannot provide both ${N.bold("--project")} and ${N.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${N.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${N.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await sa(e,r):await ca(r),outro(N.green("All done!"));}),sa=async(e,t)=>{let r=Oe(t.cwd),o=spinner(),n,i={},s=Pt(t.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(R){if(R.trim()==="")return "Please provide a value";if(!R.startsWith("./")){let f="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return f;let v=createPathsMatcher(s);if(v&&v(R).length===0)return f}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},!t.formatter){let R=r.isErr()?"none":r.unwrap().formatter??"none";le.existsSync(Z.join(t.cwd,".prettierrc"))&&(R="prettier"),le.existsSync(Z.join(t.cwd,"biome.json"))&&(R="biome");let f=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(v=>({value:v.toLowerCase(),label:v})),initialValue:R});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f!=="none"&&(t.formatter=f);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,p=new Set,g=async R=>{let f=await aa({url:R,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let v of f.dependencies)l.add(v);for(let v of f.devDependencies)p.add(v);n=f.paths,i=f.configFiles;};if(c.length>0)for(let R of c){if(!e.find(f=>f===R)&&r.isOk()&&r.unwrap().repos.find(f=>f===R)){let f=await confirm({message:`Initialize ${R}?`,initialValue:t.yes});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)continue}log.info(`Initializing ${N.cyan(R)}`),await g(R);}for(;;){let R=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break;let f=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:v=>{if(v.trim().length===0)return "Please provide a value";if(!z(v))return `Invalid provider! Valid providers (${y.map(x=>x.name).join(", ")})`}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),await g(f),c.push(f);}let h={$schema:`https://unpkg.com/jsrepo@${ze.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${gt}\``);let{prettierOptions:w,biomeOptions:d}=await wt({formatter:h.formatter,cwd:t.cwd}),u=Z.join(t.cwd,gt),b=await lr.format(JSON.stringify(h,null," "),{biomeOptions:d,prettierOptions:w,filePath:u,formatter:h.formatter});le.existsSync(t.cwd)||le.mkdirSync(t.cwd,{recursive:true}),le.writeFileSync(u,b),o.stop(`Wrote config to \`${gt}\`.`);let m=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await He(l,p,{yes:t.yes,cwd:t.cwd,pm:m});if(S.dependencies.size>0||S.devDependencies.size>0){let R=[];if(!S.installed){if(l.size>0){let v=resolveCommand$1(m,"add",[...l]);R.push(`Install dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(p.size>0){let v=resolveCommand$1(m,"add",[...p,"-D"]);R.push(`Install dev dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}R=R.map((v,x)=>`${x+1}. ${v}`),S.installed||R.push(""),R.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let f=dt(R);process.stdout.write(f);}};async function aa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new ge,a=z(e);a||program.error(N.red(`Invalid provider! Valid providers (${y.map(d=>d.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let d=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(d.url).origin}`;}if(!s.get(c$1)&&!n.yes){let d=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d){let u=await password({message:"Paste your token",validate(b){if(b.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,u);}}i.start(`Fetching manifest from ${N.cyan(e)}`);let p=(await Kt(e,{noCache:!n.cache})).match(d=>d,d=>program.error(N.red(d))),g=(await wr(p)).match(d=>d,d=>program.error(N.red(d)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Dt(p,g,n.cwd);let h=[],w=[];if(g.configFiles){let{prettierOptions:d,biomeOptions:u}=await wt({formatter:o,cwd:n.cwd});for(let b of g.configFiles){if(b.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${b.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...b.dependencies??[]),w.push(...b.devDependencies??[]),!r[b.name]){let x=await text({message:`Where is your ${b.name} file?`,defaultValue:b.expectedPath,initialValue:b.expectedPath,placeholder:b.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[b.name]=x;}let m=Z.join(n.cwd,r[b.name]),S;if(le.existsSync(m))S=le.readFileSync(m).toString();else {let x=Z.dirname(m);if(le.existsSync(x)){let C=Vo(m);if(C){S=le.readFileSync(C).toString();let j=Z.relative(n.cwd,C);log.warn(`Located ${N.bold(r[b.name])} at ${N.bold(j)}`),r[b.name]=j,m=Z.join(n.cwd,j);}}}i.start(`Fetching the ${N.cyan(b.name)} from ${N.cyan(e)}`);let R=(await it(p,b.path)).match(x=>x,x=>program.error(N.red(x))),f=await sr({file:{content:R,destPath:m},biomeOptions:u,prettierOptions:d,formatter:o});i.stop(`Fetched the ${N.cyan(b.name)} from ${N.cyan(e)}`);let v=n.yes||S===void 0;if(S){if(!n.yes){let x=c(p.url,b.name),C=await jt({config:{biomeOptions:u,prettierOptions:d,formatter:o},current:{content:S,path:m},incoming:{content:f,path:x},options:{...n,loading:i,no:false}});C.applyChanges&&(v=true,S=C.updatedContent);}}else {let x=Z.dirname(m);le.existsSync(x)||le.mkdirSync(x,{recursive:true}),S=f;}v&&S&&(i.start(`Writing ${N.cyan(b.name)} to ${N.cyan(m)}`),le.writeFileSync(m,S),i.stop(`Wrote ${N.cyan(b.name)} to ${N.cyan(m)}`));}}if(!n.yes){let d=await multiselect({message:"Which category paths would you like to configure?",options:g.categories.map(u=>({label:u.name,value:u.name})),required:false});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d.length>0)for(let u of d){let b=t[u],m=await text({message:`Where should ${u} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:b||`./src/${u}`,defaultValue:b,initialValue:b});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),t[u]=m;}}return {paths:t,configFiles:r,dependencies:h,devDependencies:w}}var ca=async e=>{let t=spinner(),r=Z.join(e.cwd,"package.json");le.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=It(e.cwd).match(d=>d,d=>program.error(N.red(d)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${ze.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let u=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),!u)break}let d=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(d);}let n=JSON.parse(le.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let d=await confirm({message:`Configure to publish to ${Be}?`,initialValue:true});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),i=d;}if(i){if(!o.name){let d=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o.name=d;}o.version||(o.version="0.0.1"),e.publishScript=await Mn(e.publishScript,n,e,"release:registry");}else e.buildScript=await Mn(e.buildScript,n,e,"build:registry");let s=n.devDependencies&&n.devDependencies.jsrepo!==void 0,a=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="jsrepo build",l="jsrepo publish";n.scripts===void 0&&(n.scripts={}),i?n.scripts[e.publishScript]=l:n.scripts[e.buildScript]=c;let p=[];p.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{le.writeFileSync(r,JSON.stringify(n,null," "));}catch(d){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${d}`));}}}),p.push({loadingMessage:`Writing config to \`${N.cyan(ht)}\``,completedMessage:`Wrote config to \`${N.cyan(ht)}\``,run:async()=>{let d=Z.join(e.cwd,ht);try{le.writeFileSync(Z.join(d),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(d)}\`. Error: ${u}`));}}}),await Ao(p,{loading:t});let g=s;s||(g=(await He(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!g){let d=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Ge} as a dev dependency \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let d=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to publish the registry.`);}else {let d=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${d?.command} ${d?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((d,u)=>`${u+1}. ${d}`);let w=dt(h);process.stdout.write(w);};async function Mn(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${N.cyan(n)}\` already exists overwrite?`,initialValue:false});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),i)break;{let s=await text({message:"What would you like to call the script?",placeholder:o,validate:a=>{if(a.trim().length===0)return "Please provide a value!"}});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),n=s;}}return n}var ma=$.object({private:$.boolean(),dryRun:$.boolean(),name:$.optional($.string()),ver:$.optional($.string()),dirs:$.optional($.array($.string())),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),verbose:$.boolean(),cwd:$.string()}),eo=new Command("publish").description("Publish a registry to jsrepo.com.").option("--private","When publishing the first version of the registry make it private.",false).option("--dry-run","Test the publish but don't list on jsrepo.com.",false).option("--name <name>","The name of the registry. i.e. @ieedan/std").option("--ver <version>","The version of the registry. i.e. 0.0.1").option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(ma,e);await ie(),await ua(t),outro(N.green("All done!"));});async function ua(e){let t=f=>{e.verbose&&console.info(`${je} ${f}`);},r=he({verbose:e.verbose?t:void 0}),o=It(e.cwd).match(f=>{if(f===null)return {$schema:"",access:"public",readme:"README.md",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories};let v=f;return e.private&&(v.access="private"),e.name&&(v.name=e.name),e.ver&&(v.version=e.ver),e.dirs&&(v.dirs=e.dirs),e.doNotListBlocks&&(v.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(v.doNotListCategories=e.doNotListCategories),e.listBlocks&&(v.listBlocks=e.listBlocks),e.listCategories&&(v.listCategories=e.listCategories),e.includeBlocks&&(v.includeBlocks=e.includeBlocks),e.includeCategories&&(v.includeCategories=e.includeCategories),e.excludeBlocks&&(v.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(v.excludeCategories=e.excludeCategories),e.excludeDeps&&(v.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(v.allowSubdirectories=e.allowSubdirectories),v.rules={...Ut,...v.rules},v},f=>program.error(N.red(f)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[f,v$1,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!f.startsWith("@"))throw new Error;if(!f.slice(1).match(v))throw new Error;if(!v$1.match(v))throw new Error}catch{program.error(N.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(N.red(`To publish to ${N.bold("jsrepo.com")} you need to provide the \`name\` field in the \`jsrepo-build-config.json\``));if(o.version!==void 0){if(o.version==="package"){let v=Z.join(e.cwd,"package.json");le.existsSync(v)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:x}=JSON.parse(le.readFileSync(v).toString());o.version=x;}Io.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(N.red(`To publish to ${N.bold("jsrepo.com")} you need to provide the \`version\` field in the \`jsrepo-build-config.json\``));let n=new ge().get("jsrepo");n===void 0&&program.error(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${Be}.`));let i=[],s=Vs();try{let f=le.readFileSync(Z.join(e.cwd,".gitignore")).toString();s.add(f);}catch{}s.add(vr);for(let f of o.dirs){let v=Z.join(e.cwd,f);r.start(`Building ${N.cyan(v)}`);let x=mr(v,{cwd:e.cwd,ignore:s,config:o});for(let C of x){if(i.find(j=>j.name===C.name)!==void 0){console.warn(`${T} ${fe} Skipped adding \`${N.cyan(`${f}/${C.name}`)}\` because a category with the same name already exists!`);continue}i.push(C);}r.stop(`Built ${N.cyan(v)}`);}let a=ur(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:p$1}=fr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||p$1.length>0)&&console.log(T);for(let f of l)console.log(f);if(p$1.length>0){for(let f of p$1)console.log(f);program.error(N.red(`Completed checking manifest with ${N.bold(`${p$1.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[g,h]=gr(c.categories);c.categories=g,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let w$1=Z.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${w$1}`),le.mkdirSync(w$1,{recursive:true}),t("Writing manifest to temp dir"),le.writeFileSync(Z.resolve(w$1,"jsrepo-manifest.json"),JSON.stringify(c));let d=Z.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),le.copyFileSync(d,Z.join(w$1,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let f of c.configFiles){let v=Z.join(e.cwd,f.path),x=Z.join(w$1,f.path),C=Z.join(x,"../");le.existsSync(C)||le.mkdirSync(C,{recursive:true}),le.copyFileSync(v,x);}t("Copied config files");}t("Copying registry files");for(let f of c.categories)for(let v of f.blocks){let x=Z.join(e.cwd,v.directory),C=Z.join(w$1,v.directory);for(let j of v.files){let Q=Z.join(C,j,"../");le.existsSync(Q)||le.mkdirSync(Q,{recursive:true}),le.copyFileSync(Z.join(x,j),Z.join(C,j));}}t("Copied registry files");let u=Z.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),b=le.readdirSync(w$1);t("Creating archive file"),await Jn.create({z:true,cwd:w$1,file:u},b),t("Created archive file"),t("Removing temp directory"),le.rmSync(w$1,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u)}...`);let m=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${N.cyan(m)}`),r.start(`Publishing ${N.bold(c.name)} to ${Be}...`);let S=le.readFileSync(u);t("Removing archive file"),le.rmSync(u,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let R=await Ne(`${w}/api/publish`,{body:S,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":m},method:"POST"});if(r.stop(`Got response from ${Be}.`),R.ok){let f=await R.json();f.status==="dry-run"?log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} published ${N.greenBright(`@${f.scope}`)}/${f.registry}${N.greenBright(`@${f.version}`)}!`);}else {let f=await R.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(R.status)} ${f.message}`));}}var Sa=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),to=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=$.parse(Sa,t);await ie(),await ja(e,r),outro(N.green("All done!"));});async function ja(e,t){let r=m=>{t.verbose&&console.info(`${je} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Oe(t.cwd).match(m=>m,m=>program.error(N.red(m))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await st(i,{noCache:!t.cache})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed to get info for ${N.cyan(m)}`),program.error(N.red(S));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Ht(s,{verbose:t.verbose?r:void 0})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed fetching blocks from ${N.cyan(m)}`),program.error(N.red(S));});r(`Retrieved blocks from ${N.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`);let c$1=Z.resolve(Z.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${N.bold(c$1)}.`),le.mkdirSync(c$1,{recursive:true});let l=()=>{le.rmSync(c$1,{recursive:true,force:true});},p=vt(a,o,t.cwd).map(m=>m.specifier),g=e;e.length===0&&(g=p),g.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let m of g){let S,R=z(m);if(R){let{url:f}=R.parse(m,{fullyQualified:true}),v=(await Kt(f)).match(C=>C,C=>program.error(N.red(C))),x=(await Ht([v])).match(C=>C,C=>program.error(N.red(C)));for(let[C,j]of x)a.set(C,j);S=a.get(m);}else for(let f of i){let v=z(f);if(!v)continue;let{url:x,specifier:C}=v.parse(c(f,m),{fullyQualified:true}),j=a.get(c(x,C));if(j!==void 0){S=j;break}}S||program.error(N.red(`Invalid block! ${N.bold(m)} does not exist!`)),h.push({name:m,block:S});}let w=We(o.paths,t.cwd).match(m=>m,m=>program.error(N.red(m)));for(let{block:m}of h){let S=m.sourceRepo,R=c(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(R)}`),!m.tests){n.stop(`No tests found for ${N.cyan(R)}`);continue}let f=zt(m,w,t.cwd);f=Z.relative(c$1,f);let v=async C=>{let j=await it(S,C);return j.isErr()&&(n.stop(N.red(`Error fetching ${N.bold(C)}`)),program.error(N.red(`There was an error trying to get ${R}`))),j.unwrap()};r(`Downloading and copying test files for ${R}`);let x=[];for(let C of m.files.filter(j=>nt(j))){let j=await v(Z.join(m.directory,C)),Q=Z.join(c$1,C);le.writeFileSync(Q,j),x.push(Q);}for(let C of x){r(`Opening test file ${C}`);let j=le.readFileSync(C).toString(),Q=qi.parseSync(C,j);for(let oe of Q.module.staticImports){let q=oe.moduleRequest.value,k;if(q.startsWith(".")&&(m.subdirectory?k=Z.join(f,m.name,q):k=Z.join(f,q)),k){let A=new RegExp(`(['"])${Wi(q)}\\1`,"g");j=j.replaceAll(A,`$1${k}$1`);}}le.writeFileSync(C,j);}r(`Completed ${N.cyan.bold(R)} test file`),t.verbose||n.stop(`Completed setup for ${N.bold(R)}`);}r("Beginning testing");let d=await detect({cwd:t.cwd});d==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(d.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${d.agent}'.`));let b=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(b)} on ${N.cyan(t.cwd)}`);try{let m=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let S of m)process.stdout.write(`${S}
|
|
77
|
+
`);for(let W of P){let te=W.content.match(Se=>Se,Se=>program.error(N.red(Se))),V=Xt(W.name,k.block,v,t.cwd),rt=(await Gt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Zt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Se=>Se,Se=>program.error(N.red(Se))),Re="";pe.existsSync(V)&&(Re=pe.readFileSync(V).toString());let re=await Pt({config:{biomeOptions:f,prettierOptions:R,formatter:s.formatter},current:{path:V,content:Re},incoming:{path:c(A,W.name),content:rt},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});re.applyChanges&&(Q.push(An({destination:V,content:re.updatedContent,block:k.block})),x.add(y));}continue}}k.files.then(P=>{P.map(async W=>{let te=W.content.match(Re=>Re,Re=>program.error(N.red(Re))),V=Xt(W.name,k.block,v,t.cwd),rt=Gt({file:{content:te,destPath:V},biomeOptions:f,prettierOptions:R,config:s,imports:k.block._imports_,watermark:Zt(k.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(Re=>(Re.isErr()&&program.error(N.red(Re.unwrapErr())),{destination:V,content:Re.unwrap(),block:k.block}));Q.push(rt);});}),x.add(y);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(j.map(k=>k.files)),await Promise.all(Q.map(async k=>{let A=await k,y=Z.dirname(A.destination);pe.existsSync(y)||(r(`Creating directory ${N.bold(y)}`),pe.mkdirSync(y,{recursive:true})),r(`Writing to ${N.bold(A.destination)}`),pe.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${N.cyan(Array.from(x).join(", "))}`));let oe=(await detect({cwd:t.cwd}))?.agent??"npm",q=await Ye(m,b,{yes:t.yes,cwd:t.cwd,pm:oe});if(q.dependencies.size>0||q.devDependencies.size>0){let k=[];if(!q.installed){if(m.size>0){let y=resolveCommand(oe,"add",[...m]);k.push(`Install dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}if(b.size>0){let y=resolveCommand(oe,"add",[...b,"-D"]);k.push(`Install dev dependencies \`${N.cyan(`${y?.command} ${y?.args.join(" ")}`)}\``);}}k=k.map((y,M)=>`${M+1}. ${y}`),q.installed||k.push(""),k.push("Import and use the blocks!");let A=dt(k);process.stdout.write(A);}}function Vn(e){return new Promise(t=>setTimeout(t,e))}var Ks=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Yr=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Ks,e);await ie(),await Hs(t),outro(N.green("All done!"));});async function Hs(e){let t=new le;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Be}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Be}!`);return}if(t.get("jsrepo")!==void 0){let a=await confirm({message:"You are currently signed into jsrepo do you want to sign out?",initialValue:false});(isCancel(a)||!a)&&(cancel("Canceled!"),process.exit(0));}let r=zs.machineIdSync(true),o;try{let a=await Ne(`${w}/api/login/device`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!a.ok)throw new Error("There was an error creating the session");o=(await a.json()).id;}catch(a){program.error(N.red(a));}log.step(`Sign in at ${N.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=he(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(N.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await Vn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Ne(a,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!c.ok)continue;clearTimeout(s);let l=await c.text();t.set("jsrepo",l),i.stop(`Logged into ${Be}!`);break}catch{}}}var Xs=$.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()}),Qr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${m}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(Xs,e);await ie(),await Zs(t),outro(N.green("All done!"));});async function Zs(e){let t=p=>{e.verbose&&console.info(`${je} ${p}`);},r=he({verbose:e.verbose?t:void 0}),o$1=[],n=It(e.cwd).match(p=>{if(p===null)return {$schema:"",readme:"README.md",dirs:e.dirs??[],outputDir:e.outputDir,doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview};let u=p;return e.dirs&&(u.dirs=e.dirs),e.outputDir&&(u.outputDir=e.outputDir),e.doNotListBlocks&&(u.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(u.doNotListCategories=e.doNotListCategories),e.listBlocks&&(u.listBlocks=e.listBlocks),e.listCategories&&(u.listCategories=e.listCategories),e.includeBlocks&&(u.includeBlocks=e.includeBlocks),e.includeCategories&&(u.includeCategories=e.includeCategories),e.excludeBlocks&&(u.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(u.excludeCategories=e.excludeCategories),e.excludeDeps&&(u.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(u.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(u.preview=e.preview),u.rules={...zt,...u.rules},u},p=>program.error(N.red(p))),i;n.outputDir?i=Z.join(e.cwd,n.outputDir):i=e.cwd;let s=Z.join(i,m);if(e.output&&pe.existsSync(s)){if(n.outputDir){let p=o(pe.readFileSync(s).toString());if(p.isOk())for(let u of p.unwrap().categories)for(let b of u.blocks){let m=Z.join(i,b.directory);pe.existsSync(m)&&pe.rmSync(m,{recursive:true});}}pe.rmSync(s);}let a=Qs();try{let p=pe.readFileSync(Z.join(e.cwd,".gitignore")).toString();a.add(p);}catch{}a.add(kr);for(let p of n.dirs){let u=Z.join(e.cwd,p);r.start(`Building ${N.cyan(u)}`);let b=hr(u,{cwd:e.cwd,ignore:a,config:n});for(let m of b){if(o$1.find(S=>S.name===m.name)!==void 0){console.warn(`${T} ${me} Skipped adding \`${N.cyan(`${p}/${m.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(m);}r.stop(`Built ${N.cyan(u)}`);}let c=yr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:d,errors:g}=gr(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(d.length>0||g.length>0)&&console.log(T);for(let p of d)console.log(p);if(g.length>0){for(let p of g)console.log(p);program.error(N.red(`Completed checking manifest with ${N.bold(`${g.length} error(s)`)} and ${N.bold(`${d.length} warning(s)`)}`));}let[h,w]=vr(l.categories);if(l.categories=h,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n.preview){let p=l.categories.flatMap(u=>u.blocks.filter(b=>b.list).map(b=>`${N.cyan(b.category)}/${b.name}`));log.message(`${N.yellow("Preview")}:`);for(let u of p)console.log(`${T} \u25FB ${u}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${N.cyan(i)}\``),l.configFiles)for(let p of l.configFiles){let u=Z.join(e.cwd,p.path),b=Z.join(i,p.path),m=Z.join(b,"../");pe.existsSync(m)||pe.mkdirSync(m,{recursive:true}),pe.copyFileSync(u,b);}for(let p of l.categories)for(let u of p.blocks){let b=Z.join(e.cwd,u.directory),m=Z.join(i,u.directory);for(let S of u.files){let R=Z.join(m,S,"../");pe.existsSync(R)||pe.mkdirSync(R,{recursive:true}),pe.copyFileSync(Z.join(b,S),Z.join(m,S));}}r.stop(`Copied registry files to \`${N.cyan(i)}\``);}r.start(`Writing output to \`${N.cyan(s)}\``),pe.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${N.cyan(s)}\``);}}var sa=$.objectWithRest({repo:$.optional($.string()),allow:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()},$.unknown()),eo=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(sa,t);await ie(),await aa(e,o,r);});async function aa(e,t,r){let o=y=>{t.verbose&&console.info(`${je} ${y}`);},n=e,i=he({verbose:t.verbose?o:void 0}),s=Oe(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let d=n?z(n):void 0;if(n&&d){let{url:y}=d.parse(n,{fullyQualified:true});if(!l.find(M=>M===y)){if(!t.allow){let M=await confirm({message:`Allow ${Ke} to download and run code from ${N.cyan(y)}?`,initialValue:true});(isCancel(M)||!M)&&(cancel("Canceled!"),process.exit(0));}l=[y];}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Ke} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(N.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${N.bold("--repo")}\` flag to specify a registry.`)),program.error(N.red(`There were no repos present in your config and you didn't provide the \`${N.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${N.cyan(l.join(", "))}`);let g=(await ct(l,{noCache:!t.cache})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed to get info for ${N.cyan(y)}`),program.error(N.red(M));}),h=(await Yt(g,{verbose:t.verbose?o:void 0})).match(y=>y,({repo:y,message:M})=>{i.stop(`Failed fetching scripts from ${N.cyan(y)}`),program.error(N.red(M));});if(i.stop(`Retrieved scripts from ${N.cyan(l.join(", "))}`),!n){let y=await select({message:"Select which script to run.",options:Array.from(h.entries()).filter(([M,P])=>P.list).map(([M,P])=>{let W;return l.length>1?W=`${N.cyan(c(P.sourceRepo.url,P.category))}/${P.name}`:W=`${N.cyan(P.category)}/${P.name}`,{label:W,value:M}})});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),n=y;}let w=(await vt([n],h,g)).match(y=>y,y=>program.error(y)),p="temp-jsrepo-exec",u=`./${p}/${encodeURIComponent(n)}`,b=Z.join(process.cwd(),u);c$1.paths["*"]=u,pe.mkdirSync(b,{recursive:true});let m=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],R=new Set,f=new Set,v=We(c$1.paths,t.cwd);v.isErr()&&program.error(N.red(v.unwrapErr()));let x$1=v.unwrap(),C=[];for(let y of w){let M=`${y.sourceRepo.url}/${y.category}/${y.name}`,P=`${y.category}/${y.name}`,W=y.sourceRepo,te=Z.join(t.cwd,x$1["*"],y.category);C.push(P),S.push({run:async({message:V})=>{V(`Adding ${N.cyan(M)}`),pe.mkdirSync(te,{recursive:true});let rt=[],Re=async re=>{let Se=await at(W,re);return Se.isErr()&&(i.stop(N.red(`Error fetching ${N.bold(re)}`)),program.error(N.red(`There was an error trying to get ${M}`))),Se.unwrap()};for(let re of y.files){if(!c$1.includeTests&&st(re))continue;let Se=Z.join(y.directory,re),_t;y.subdirectory?_t=Z.join(te,y.name,re):_t=Z.join(te,re);let si=await Re(Se),ai=_t.slice(0,_t.length-re.length);pe.mkdirSync(ai,{recursive:true}),rt.push({content:si,destPath:_t});}for(let re of rt)pe.writeFileSync(re.destPath,re.content);if(c$1.includeTests&&y.tests){let{devDependencies:re}=JSON.parse(pe.readFileSync(Z.join(t.cwd,"package.json")).toString());(re===void 0||re.vitest===void 0)&&R.add("vitest");}for(let re of y.devDependencies)R.add(re);for(let re of y.dependencies)f.add(re);}});}if(await Jo({startMessage:"Adding blocks",stopMessage:`Added ${N.cyan(C.join(", "))}`,loading:i,tasks:S}),f.size>0||R.size>0){let y={name:"temp-package",type:"module",version:"0.0.1"},M=Z.join(b,"package.json");pe.writeFileSync(M,JSON.stringify(y,null," "));}await Ye(f,R,{yes:true,no:false,cwd:b,pm:m,ignoreWorkspace:true});let Q=r.parent.rawArgs.findIndex(y=>y==="--"),oe=[];Q!==-1&&(oe=r.parent.rawArgs.slice(Q+1)),o(`Passing args ${N.cyan(oe.join(" "))}`),console.clear();let q=w[0],k;q.subdirectory?k=Z.join(b,`${q.category}/${q.name}/index.js`):k=Z.join(b,`${q.category}/${q.name}.js`);let A=resolveCommand(m,"execute",["tsx",k,...oe]);A||program.error(N.red("Error resolving run command!"));try{let y=x(A.command,A.args,{nodeOptions:{cwd:process.cwd()}});for await(let M of y)process.stdout.write(`${M}
|
|
78
|
+
`);}finally{pe.rmSync(Z.join(process.cwd(),p),{recursive:true,force:true});}}var pa=$.object({json:$.boolean()}),to=new Command("info").description("Get info about a registry on jsrepo.com").argument("registry","Name of the registry to get the info for i.e. @ieedan/std").option("--json","Output the response in formatted JSON.",false).action(async(e,t)=>{let r=$.parse(pa,t);await da(e,r);});async function da(e,t){let o=new le().get(x$1.name),n={};if(o){let[c,l]=x$1.authHeader(o);n[c]=l;}let i=new URL(`/api/scopes/${e}`,w).toString(),s=await Ei(i,{headers:n});s.ok||(s.status===404?program.error(N.red("Registry not found!")):program.error(N.red(`Error fetching registry! Error: ${s.status} - ${s.statusText}`)));let a=await s.json();if(t.json)return process.stdout.write(JSON.stringify(a,null," "));process.stdout.write(fa(a));}function fa(e){let t=`${N.cyan(`${e.name}@${e.version}`)} | versions: ${N.cyan(e.versions.length.toString())}
|
|
79
|
+
`;e.meta.description&&(t+=`${e.meta.description}
|
|
80
|
+
`),e.meta.homepage&&(t+=`${N.blue(e.meta.homepage)}
|
|
81
|
+
`),t+=`
|
|
82
|
+
`,e.meta.tags&&(t+=`keywords: ${e.meta.tags.map(i=>N.cyan(i)).join(", ")}
|
|
83
|
+
|
|
84
|
+
`);let r=i=>i%3===0,o=e.categories.flatMap(i=>i.blocks).map(i=>i.list?N.blue(`${i.category}/${i.name}`):N.dim(`${i.category}/${i.name}`)),n=jo(o)+4;return t+=`blocks:
|
|
85
|
+
${o.map((i,s)=>{let a=r(s+1),c=s+1>=o.length;return a?`${i}
|
|
86
|
+
`:`${Eo(i,n," ")}${c?`
|
|
87
|
+
`:""}`}).join("")}
|
|
88
|
+
`,e.meta.authors&&(t+=`authors:
|
|
89
|
+
${e.meta.authors.map(i=>`- ${N.blue(i)}`).join(`
|
|
90
|
+
`)}
|
|
91
|
+
|
|
92
|
+
`),t+=`tags:
|
|
93
|
+
${Object.entries(e.tags).map(([i,s])=>`${N.blue(i)}: ${s}`).join(`
|
|
94
|
+
`)}
|
|
95
|
+
|
|
96
|
+
`,t}var wa=$.object({repos:$.optional($.array($.string())),watermark:$.boolean(),tests:$.optional($.boolean()),formatter:$.optional(Jr),project:$.optional($.boolean()),registry:$.optional($.boolean()),buildScript:$.string(),publishScript:$.string(),expand:$.boolean(),maxUnchanged:$.number(),yes:$.boolean(),cache:$.boolean(),cwd:$.string()}),no=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=$.parse(wa,t);if(await ie(),r.registry!==void 0&&r.project!==void 0&&program.error(N.red(`You cannot provide both ${N.bold("--project")} and ${N.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${N.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${N.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await ba(e,r):await $a(r),outro(N.green("All done!"));}),ba=async(e,t)=>{let r=Oe(t.cwd),o=spinner(),n,i={},s=Et(t.cwd).unwrapOr(null),a=await text({message:"Please enter a default path to install the blocks",validate(R){if(R.trim()==="")return "Please provide a value";if(!R.startsWith("./")){let f="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return f;let v=createPathsMatcher(s);if(v&&v(R).length===0)return f}},placeholder:"./src/blocks",initialValue:r.isOk()?r.unwrap().paths["*"]:void 0});if(isCancel(a)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},!t.formatter){let R=r.isErr()?"none":r.unwrap().formatter??"none";pe.existsSync(Z.join(t.cwd,".prettierrc"))&&(R="prettier"),pe.existsSync(Z.join(t.cwd,"biome.json"))&&(R="biome");let f=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(v=>({value:v.toLowerCase(),label:v})),initialValue:R});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f!=="none"&&(t.formatter=f);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,d=new Set,g=async R=>{let f=await ka({url:R,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let v of f.dependencies)l.add(v);for(let v of f.devDependencies)d.add(v);n=f.paths,i=f.configFiles;};if(c.length>0)for(let R of c){if(!e.find(f=>f===R)&&r.isOk()&&r.unwrap().repos.find(f=>f===R)){let f=await confirm({message:`Initialize ${R}?`,initialValue:t.yes});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)continue}log.info(`Initializing ${N.cyan(R)}`),await g(R);}for(;;){let R=await confirm({message:`Add ${c.length>0?"another":"a"} repo?`,initialValue:c.length===0});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break;let f=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:v=>{if(v.trim().length===0)return "Please provide a value";if(!z(v))return `Invalid provider! Valid providers (${y.map(x=>x.name).join(", ")})`}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),await g(f),c.push(f);}let h={$schema:`https://unpkg.com/jsrepo@${He.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${ht}\``);let{prettierOptions:w,biomeOptions:p}=await bt({formatter:h.formatter,cwd:t.cwd}),u=Z.join(t.cwd,ht),b=await fr.format(JSON.stringify(h,null," "),{biomeOptions:p,prettierOptions:w,filePath:u,formatter:h.formatter});pe.existsSync(t.cwd)||pe.mkdirSync(t.cwd,{recursive:true}),pe.writeFileSync(u,b),o.stop(`Wrote config to \`${ht}\`.`);let m=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await Ye(l,d,{yes:t.yes,cwd:t.cwd,pm:m});if(S.dependencies.size>0||S.devDependencies.size>0){let R=[];if(!S.installed){if(l.size>0){let v=resolveCommand$1(m,"add",[...l]);R.push(`Install dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(d.size>0){let v=resolveCommand$1(m,"add",[...d,"-D"]);R.push(`Install dev dependencies \`${N.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}R=R.map((v,x)=>`${x+1}. ${v}`),S.installed||R.push(""),R.push(`Add blocks with ${N.cyan("jsrepo add")}!`);let f=dt(R);process.stdout.write(f);}};async function ka({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new le,a=z(e);a||program.error(N.red(`Invalid provider! Valid providers (${y.map(p=>p.name).join(", ")})`));let c$1=a.name;if(a.name===u.name){let p=u.parse(e,{fullyQualified:false});c$1=`http-${new URL(p.url).origin}`;}if(!s.get(c$1)&&!n.yes){let p=await confirm({message:"Would you like to add an auth token?",initialValue:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p){let u=await password({message:"Paste your token",validate(b){if(b.trim()==="")return "Please provide a value"}});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,u);}}i.start(`Fetching manifest from ${N.cyan(e)}`);let d=(await qt(e,{noCache:!n.cache})).match(p=>p,p=>program.error(N.red(p))),g=(await $r(d)).match(p=>p,p=>program.error(N.red(p)));i.stop(`Fetched manifest from ${N.cyan(e)}`),Tt(d,g,n.cwd);let h=[],w=[];if(g.configFiles){let{prettierOptions:p,biomeOptions:u}=await bt({formatter:o,cwd:n.cwd});for(let b of g.configFiles){if(b.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${b.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(h.push(...b.dependencies??[]),w.push(...b.devDependencies??[]),!r[b.name]){let x=await text({message:`Where is your ${b.name} file?`,defaultValue:b.expectedPath,initialValue:b.expectedPath,placeholder:b.expectedPath,validate(C){if(C.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[b.name]=x;}let m=Z.join(n.cwd,r[b.name]),S;if(pe.existsSync(m))S=pe.readFileSync(m).toString();else {let x=Z.dirname(m);if(pe.existsSync(x)){let C=qo(m);if(C){S=pe.readFileSync(C).toString();let j=Z.relative(n.cwd,C);log.warn(`Located ${N.bold(r[b.name])} at ${N.bold(j)}`),r[b.name]=j,m=Z.join(n.cwd,j);}}}i.start(`Fetching the ${N.cyan(b.name)} from ${N.cyan(e)}`);let R=(await at(d,b.path)).match(x=>x,x=>program.error(N.red(x))),f=await lr({file:{content:R,destPath:m},biomeOptions:u,prettierOptions:p,formatter:o});i.stop(`Fetched the ${N.cyan(b.name)} from ${N.cyan(e)}`);let v=n.yes||S===void 0;if(S){if(!n.yes){let x=c(d.url,b.name),C=await Pt({config:{biomeOptions:u,prettierOptions:p,formatter:o},current:{content:S,path:m},incoming:{content:f,path:x},options:{...n,loading:i,no:false}});C.applyChanges&&(v=true,S=C.updatedContent);}}else {let x=Z.dirname(m);pe.existsSync(x)||pe.mkdirSync(x,{recursive:true}),S=f;}v&&S&&(i.start(`Writing ${N.cyan(b.name)} to ${N.cyan(m)}`),pe.writeFileSync(m,S),i.stop(`Wrote ${N.cyan(b.name)} to ${N.cyan(m)}`));}}if(!n.yes){let p=await multiselect({message:"Which category paths would you like to configure?",options:g.categories.map(u=>({label:u.name,value:u.name})),required:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p.length>0)for(let u of p){let b=t[u],m=await text({message:`Where should ${u} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:b||`./src/${u}`,defaultValue:b,initialValue:b});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),t[u]=m;}}return {paths:t,configFiles:r,dependencies:h,devDependencies:w}}var $a=async e=>{let t=spinner(),r=Z.join(e.cwd,"package.json");pe.existsSync(r)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let o=It(e.cwd).match(p=>p,p=>program.error(N.red(p)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:false}),o.$schema=`https://unpkg.com/jsrepo@${He.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let u=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),!u)break}let p=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(p);}let n=JSON.parse(pe.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let p=await confirm({message:`Configure to publish to ${Be}?`,initialValue:true});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),i=p;}if(i){if(!o.name){let p=await text({message:"What's the name of your registry?",placeholder:"@ieedan/std",validate:u=>{if(u.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.name=p;}o.version||(o.version="0.0.1"),e.publishScript=await qn(e.publishScript,n,e,"release:registry");}else e.buildScript=await qn(e.buildScript,n,e,"build:registry");let s=n.devDependencies&&n.devDependencies.jsrepo!==void 0,a=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="jsrepo build",l="jsrepo publish";n.scripts===void 0&&(n.scripts={}),i?n.scripts[e.publishScript]=l:n.scripts[e.buildScript]=c;let d=[];d.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{pe.writeFileSync(r,JSON.stringify(n,null," "));}catch(p){program.error(N.red(`Error writing to \`${N.bold(r)}\`. Error: ${p}`));}}}),d.push({loadingMessage:`Writing config to \`${N.cyan(yt)}\``,completedMessage:`Wrote config to \`${N.cyan(yt)}\``,run:async()=>{let p=Z.join(e.cwd,yt);try{pe.writeFileSync(Z.join(p),JSON.stringify(o,null," "));}catch(u){program.error(N.red(`Error writing to \`${N.bold(p)}\`. Error: ${u}`));}}}),await Vo(d,{loading:t});let g=s;s||(g=(await Ye(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let h=[];if(!g){let p=resolveCommand$1(a,"add",["jsrepo","-D"]);h.push(`Install ${Ke} as a dev dependency \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\``);}if(h.push(`Add categories to \`${N.cyan(o.dirs.join(", "))}\`.`),i){let p=resolveCommand$1(a,"run",[e.publishScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to publish the registry.`);}else {let p=resolveCommand$1(a,"run",[e.buildScript]);h.push(`Run \`${N.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to build the registry.`);}h=h.map((p,u)=>`${u+1}. ${p}`);let w=dt(h);process.stdout.write(w);};async function qn(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${N.cyan(n)}\` already exists overwrite?`,initialValue:false});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),i)break;{let s=await text({message:"What would you like to call the script?",placeholder:o,validate:a=>{if(a.trim().length===0)return "Please provide a value!"}});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),n=s;}}return n}var ja=$.object({private:$.boolean(),dryRun:$.boolean(),name:$.optional($.string()),ver:$.optional($.string()),dirs:$.optional($.array($.string())),includeBlocks:$.optional($.array($.string())),includeCategories:$.optional($.array($.string())),excludeBlocks:$.optional($.array($.string())),excludeCategories:$.optional($.array($.string())),excludeDeps:$.optional($.array($.string())),listBlocks:$.optional($.array($.string())),listCategories:$.optional($.array($.string())),doNotListBlocks:$.optional($.array($.string())),doNotListCategories:$.optional($.array($.string())),allowSubdirectories:$.optional($.boolean()),verbose:$.boolean(),cwd:$.string()}),io=new Command("publish").description("Publish a registry to jsrepo.com.").option("--private","When publishing the first version of the registry make it private.",false).option("--dry-run","Test the publish but don't list on jsrepo.com.",false).option("--name <name>","The name of the registry. i.e. @ieedan/std").option("--ver <version>","The version of the registry. i.e. 0.0.1").option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=$.parse(ja,e);await ie(),await Pa(t),outro(N.green("All done!"));});async function Pa(e){let t=f=>{e.verbose&&console.info(`${je} ${f}`);},r=he({verbose:e.verbose?t:void 0}),o=It(e.cwd).match(f=>{if(f===null)return {$schema:"",access:"public",readme:"README.md",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories};let v=f;return e.private&&(v.access="private"),e.name&&(v.name=e.name),e.ver&&(v.version=e.ver),e.dirs&&(v.dirs=e.dirs),e.doNotListBlocks&&(v.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(v.doNotListCategories=e.doNotListCategories),e.listBlocks&&(v.listBlocks=e.listBlocks),e.listCategories&&(v.listCategories=e.listCategories),e.includeBlocks&&(v.includeBlocks=e.includeBlocks),e.includeCategories&&(v.includeCategories=e.includeCategories),e.excludeBlocks&&(v.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(v.excludeCategories=e.excludeCategories),e.excludeDeps&&(v.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(v.allowSubdirectories=e.allowSubdirectories),v.rules={...zt,...v.rules},v},f=>program.error(N.red(f)));if(e.dryRun&&log.warn(N.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[f,v$1,...x]=o.name.split("/");if(x.length>0)throw new Error;if(!f.startsWith("@"))throw new Error;if(!f.slice(1).match(v))throw new Error;if(!v$1.match(v))throw new Error}catch{program.error(N.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(N.red(`To publish to ${N.bold("jsrepo.com")} you need to provide the \`name\` field in the \`jsrepo-build-config.json\``));if(o.version!==void 0){if(o.version==="package"){let v=Z.join(e.cwd,"package.json");pe.existsSync(v)||program.error(N.red(`Couldn't find your ${N.bold("package.json")}!`));let{version:x}=JSON.parse(pe.readFileSync(v).toString());o.version=x;}Lo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(N.red(`To publish to ${N.bold("jsrepo.com")} you need to provide the \`version\` field in the \`jsrepo-build-config.json\``));let n=new le().get("jsrepo");n===void 0&&program.error(N.red(`Please authenticate with ${N.cyan("jsrepo auth")} to publish to ${Be}.`));let i=[],s=Qs();try{let f=pe.readFileSync(Z.join(e.cwd,".gitignore")).toString();s.add(f);}catch{}s.add(kr);for(let f of o.dirs){let v=Z.join(e.cwd,f);r.start(`Building ${N.cyan(v)}`);let x=hr(v,{cwd:e.cwd,ignore:s,config:o});for(let C of x){if(i.find(j=>j.name===C.name)!==void 0){console.warn(`${T} ${me} Skipped adding \`${N.cyan(`${f}/${C.name}`)}\` because a category with the same name already exists!`);continue}i.push(C);}r.stop(`Built ${N.cyan(v)}`);}let a=yr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:d}=gr(c,o,e.cwd,o.rules);r.stop("Completed checking manifest."),(l.length>0||d.length>0)&&console.log(T);for(let f of l)console.log(f);if(d.length>0){for(let f of d)console.log(f);program.error(N.red(`Completed checking manifest with ${N.bold(`${d.length} error(s)`)} and ${N.bold(`${l.length} warning(s)`)}`));}let[g,h]=vr(c.categories);c.categories=g,h>0&&log.step(`Removed ${h} unused block${h>1?"s":""}.`),r.start(`Packaging ${N.cyan(c.name)}...`);let w$1=Z.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${w$1}`),pe.mkdirSync(w$1,{recursive:true}),t("Writing manifest to temp dir"),pe.writeFileSync(Z.resolve(w$1,"jsrepo-manifest.json"),JSON.stringify(c));let p$1=Z.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),pe.copyFileSync(p$1,Z.join(w$1,"README.md")),t("Copied readme");}catch{t("No readme found.");}if(c.configFiles){t("Copying config files");for(let f of c.configFiles){let v=Z.join(e.cwd,f.path),x=Z.join(w$1,f.path),C=Z.join(x,"../");pe.existsSync(C)||pe.mkdirSync(C,{recursive:true}),pe.copyFileSync(v,x);}t("Copied config files");}t("Copying registry files");for(let f of c.categories)for(let v of f.blocks){let x=Z.join(e.cwd,v.directory),C=Z.join(w$1,v.directory);for(let j of v.files){let Q=Z.join(C,j,"../");pe.existsSync(Q)||pe.mkdirSync(Q,{recursive:true}),pe.copyFileSync(Z.join(x,j),Z.join(C,j));}}t("Copied registry files");let u=Z.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),b=pe.readdirSync(w$1);t("Creating archive file"),await Xn.create({z:true,cwd:w$1,file:u},b),t("Created archive file"),t("Removing temp directory"),pe.rmSync(w$1,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${N.cyan(u)}...`);let m=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${N.cyan(m)}`),r.start(`Publishing ${N.bold(c.name)} to ${Be}...`);let S=pe.readFileSync(u);t("Removing archive file"),pe.rmSync(u,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let R=await Ne(`${w}/api/publish`,{body:S,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":m},method:"POST"});if(r.stop(`Got response from ${Be}.`),R.ok){let f=await R.json();f.status==="dry-run"?log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${N.hex("#f7df1e").bold("[jsrepo.com]")} published ${N.greenBright(`@${f.scope}`)}/${f.registry}${N.greenBright(`@${f.version}`)}!`);}else {let f=await R.json();program.error(N.red(`${N.bold("[jsrepo.com]")} ${N.bold(R.status)} ${f.message}`));}}var Ma=$.object({repo:$.optional($.string()),allow:$.boolean(),debug:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),so=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(Ma,t);await ie(),await Wa(e,r),outro(N.green("All done!"));});async function Wa(e,t){let r=m=>{t.verbose&&console.info(`${je} ${m}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Oe(t.cwd).match(m=>m,m=>program.error(N.red(m))),n=he({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let m=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(m)||!m)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await ct(i,{noCache:!t.cache})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed to get info for ${N.cyan(m)}`),program.error(N.red(S));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Yt(s,{verbose:t.verbose?r:void 0})).match(m=>m,({repo:m,message:S})=>{n.stop(`Failed fetching blocks from ${N.cyan(m)}`),program.error(N.red(S));});r(`Retrieved blocks from ${N.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`);let c$1=Z.resolve(Z.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${N.bold(c$1)}.`),pe.mkdirSync(c$1,{recursive:true});let l=()=>{pe.rmSync(c$1,{recursive:true,force:true});},d=wt(a,o,t.cwd).map(m=>m.specifier),g=e;e.length===0&&(g=d),g.length===0&&(l(),program.error(N.red("There were no blocks found in your project!")));let h=[];for(let m of g){let S,R=z(m);if(R){let{url:f}=R.parse(m,{fullyQualified:true}),v=(await qt(f)).match(C=>C,C=>program.error(N.red(C))),x=(await Yt([v])).match(C=>C,C=>program.error(N.red(C)));for(let[C,j]of x)a.set(C,j);S=a.get(m);}else for(let f of i){let v=z(f);if(!v)continue;let{url:x,specifier:C}=v.parse(c(f,m),{fullyQualified:true}),j=a.get(c(x,C));if(j!==void 0){S=j;break}}S||program.error(N.red(`Invalid block! ${N.bold(m)} does not exist!`)),h.push({name:m,block:S});}let w=We(o.paths,t.cwd).match(m=>m,m=>program.error(N.red(m)));for(let{block:m}of h){let S=m.sourceRepo,R=c(m.sourceRepo.url,m.category,m.name);if(t.verbose||n.start(`Setting up test file for ${N.cyan(R)}`),!m.tests){n.stop(`No tests found for ${N.cyan(R)}`);continue}let f=Ht(m,w,t.cwd);f=Z.relative(c$1,f);let v=async C=>{let j=await at(S,C);return j.isErr()&&(n.stop(N.red(`Error fetching ${N.bold(C)}`)),program.error(N.red(`There was an error trying to get ${R}`))),j.unwrap()};r(`Downloading and copying test files for ${R}`);let x=[];for(let C of m.files.filter(j=>st(j))){let j=await v(Z.join(m.directory,C)),Q=Z.join(c$1,C);pe.writeFileSync(Q,j),x.push(Q);}for(let C of x){r(`Opening test file ${C}`);let j=pe.readFileSync(C).toString(),Q=is.parseSync(C,j);for(let oe of Q.module.staticImports){let q=oe.moduleRequest.value,k;if(q.startsWith(".")&&(m.subdirectory?k=Z.join(f,m.name,q):k=Z.join(f,q)),k){let A=new RegExp(`(['"])${Qi(q)}\\1`,"g");j=j.replaceAll(A,`$1${k}$1`);}}pe.writeFileSync(C,j);}r(`Completed ${N.cyan.bold(R)} test file`),t.verbose||n.stop(`Completed setup for ${N.bold(R)}`);}r("Beginning testing");let p=await detect({cwd:t.cwd});p==null&&program.error(N.red("Could not detect package manager"));let u=resolveCommand(p.agent,"execute",["vitest","run",c$1]);u==null&&program.error(N.red(`Could not resolve add command for '${p.agent}'.`));let b=`${u.command} ${u.args.join(" ")}`;r(`Running ${N.cyan(b)} on ${N.cyan(t.cwd)}`);try{let m=x(u.command,u.args,{nodeOptions:{cwd:t.cwd}});for await(let S of m)process.stdout.write(`${S}
|
|
79
97
|
`);l();}catch(m){t.debug?console.info(`${N.bold("--debug")} flag provided. Skipping cleanup. Run '${N.bold(b)}' to retry tests.
|
|
80
|
-
`):l(),program.error(N.red(`Tests failed! Error ${m}`));}}var
|
|
98
|
+
`):l(),program.error(N.red(`Tests failed! Error ${m}`));}}var Ka=$.object({token:$.optional($.string()),logout:$.boolean(),cwd:$.string()}),Bt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),ao=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(Bt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=$.parse(Ka,t);await ie(),await Ha(e,r),outro(N.green("All done!"));});async function Ha(e,t){let r=Oe(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=Bt.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new le;if(t.logout){if(o!==void 0){if(o==="http"){await ei(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of Bt){if(s==="http"){await ei(n);continue}if(n.get(s)===void 0){log.step(N.gray(`Already logged out of ${N.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${N.bold(s)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(s);}return}if(o===void 0){let s=await select({message:"Which service do you want to authenticate to?",options:Bt.map(a=>({label:a,value:a})),initialValue:Bt[0]});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),o=s,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:Bt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let i=o;if(i.startsWith("http")&&(i=i.slice(5)),t.token===void 0){let s=await password({message:`Paste your token for ${N.bold(i)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(s)||!s)&&(cancel("Canceled!"),process.exit(0)),t.token=s;}n.set(o,t.token),log.success(`Logged into ${N.bold(i)}.`);}async function ei(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(N.gray(`Already logged out of ${N.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${N.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var ec=$.object({all:$.boolean(),expand:$.boolean(),maxUnchanged:$.number(),no:$.boolean(),repo:$.optional($.string()),allow:$.boolean(),yes:$.boolean(),cache:$.boolean(),verbose:$.boolean(),cwd:$.string()}),lo=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(ec,t);await ie(),await tc(e,r),outro(N.green("All done!"));});async function tc(e,t){let r=f=>{t.verbose&&console.info(`${je} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=he({verbose:t.verbose?r:void 0}),n=Oe(t.cwd).match(f=>f,f=>program.error(N.red(f))),i=n.repos;t.repo&&(i=[t.repo]);for(let f of e)y.find(v=>f.startsWith(v.name))&&program.error(N.red(`Invalid value provided for block names \`${N.bold(f)}\`. Block names are expected to be provided in the format of \`${N.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${N.cyan("jsrepo")} to download and run code from ${N.cyan(t.repo)}?`,initialValue:true});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${N.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${N.cyan(i.join(", "))}`);let s=(await ct(i,{noCache:!t.cache})).match(f=>f,({repo:f,message:v})=>{o.stop(`Failed to get info for ${N.cyan(f)}`),program.error(N.red(v));});r(`Resolved ${N.cyan(i.join(", "))}`),r(`Fetching blocks from ${N.cyan(i.join(", "))}`);let a=(await Cr(s)).match(f=>f,({repo:f,message:v})=>{o.stop(`Failed fetching blocks from ${N.cyan(f)}`),program.error(N.red(v));}),c$1=xr(a);t.verbose||o.stop(`Retrieved blocks from ${N.cyan(i.join(", "))}`),r(`Retrieved blocks from ${N.cyan(i.join(", "))}`);for(let f of a)Tt(f.state,f.manifest,t.cwd);let l=wt(c$1,n,t.cwd);l.length===0&&program.error(N.red(`You haven't installed any blocks yet. Did you mean to \`${N.bold("add")}\`?`));let d=e;if(t.all&&(d=l.map(f=>f.specifier)),d.length===0){let f=await multiselect({message:`Which blocks would you like to ${t.no?"diff":"update"}?`,options:l.filter(v=>v.block.list).map(v=>({label:`${N.cyan(v.block.category)}/${v.block.name}`,value:v.specifier})),required:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),d=f;}r(`Preparing to update ${N.cyan(d.join(", "))}`);let g=(await vt(d,c$1,s)).match(f=>f,program.error),h=new Set,w=new Set,{prettierOptions:p,biomeOptions:u}=await bt({formatter:n.formatter,cwd:t.cwd}),b=We(n.paths,t.cwd).match(f=>f,f=>program.error(N.red(f))),m=Sr(g,n);for(let f of m){let v=c(f.block.sourceRepo.url,f.block.category,f.block.name),x=Zt(f.block.sourceRepo.url);r(`Attempting to update ${v}`),n.includeTests&&f.block.tests&&(r("Trying to include tests"),h.add("vitest"));for(let j of f.block.devDependencies)h.add(j);for(let j of f.block.dependencies)w.add(j);let C=await f.files;process.stdout.write(`${T}
|
|
81
99
|
`),process.stdout.write(`${T} ${v}
|
|
82
|
-
`);for(let j of C){let Q=j.content.match(y=>y,y=>program.error(N.red(y))),oe=
|
|
100
|
+
`);for(let j of C){let Q=j.content.match(y=>y,y=>program.error(N.red(y))),oe=Xt(j.name,f.block,b,t.cwd),q=(await Gt({file:{content:Q,destPath:oe},biomeOptions:u,prettierOptions:p,config:n,imports:f.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(y=>y,y=>program.error(N.red(y))),k="";pe.existsSync(oe)&&(k=pe.readFileSync(oe).toString());let A=await Pt({config:{biomeOptions:u,prettierOptions:p,formatter:n.formatter},current:{path:oe,content:k},incoming:{path:c(v,j.name),content:q},options:{...t,loading:o,verbose:t.verbose?r:void 0}});A.applyChanges&&(o.start(`Writing changes to ${N.cyan(oe)}`),pe.writeFileSync(oe,A.updatedContent),o.stop(`Wrote changes to ${N.cyan(oe)}.`));}}let S=(await detect({cwd:t.cwd}))?.agent??"npm",R=await Ye(w,h,{yes:t.yes,no:t.no,cwd:t.cwd,pm:S});if(R.dependencies.size>0||R.devDependencies.size>0){let f=[];if(!R.installed){if(w.size>0){let x=resolveCommand(S,"add",[...w]);f.push(`Install dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(h.size>0){let x=resolveCommand(S,"add",[...h,"-D"]);f.push(`Install dev dependencies \`${N.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}f=f.map((x,C)=>`${C+1}. ${x}`),R.installed||f.push(""),f.push("Import and use the blocks!");let v=dt(f);process.stdout.write(v);}}var ii=program.name(St.name).description(St.description).version(St.version).addCommand(Hr).addCommand(Yr).addCommand(Qr).addCommand(eo).addCommand(to).addCommand(no).addCommand(io).addCommand(so).addCommand(ao).addCommand(lo);ii.parse();//# sourceMappingURL=index.js.map
|
|
83
101
|
//# sourceMappingURL=index.js.map
|