jsrepo 2.4.9 → 2.5.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 +56 -56
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/schemas/registry-config.json +7 -0
package/dist/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {h,g,f,j,z,c,w,m,o,p,x as x$1,y,a,v,u,b,l,B,A}from'./chunk-2Y5JPVGF.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import me from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import
|
|
2
|
+
import {h,g,f,j,z,c,w,m,o,p,x as x$1,y,a,v,u,b,l,B,A as A$1}from'./chunk-2Y5JPVGF.js';import {Command,Option,program,Argument,InvalidArgumentError}from'commander';import me from'fs';import {outro,confirm,isCancel,cancel,multiselect,text,select,log,spinner,password,intro}from'@clack/prompts';import A from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import ne from'pathe';import*as k from'valibot';import yi from'is-unicode-supported';import {stripVTControlCharacters}from'util';import Hi from'ignore';import {builtinModules}from'module';import un from'validate-npm-package-name';import ki from'os';import Bo from'semver';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import {Biome,Distribution}from'@biomejs/js-api';import*as Jo from'css-dependency';import*as Uo from'prettier';import*as zo from'parse5';import Ni from'oxc-parser';import {walk}from'estree-walker';import*as sn from'svelte/compiler';import*as dn from'vue/compiler-sfc';import rs from'make-fetch-happen';import ns from'conf';import Ws from'escape-string-regexp';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import {x}from'tinyexec';import Fn from'boxen';import {diffLines,diffChars}from'diff';import {cursor,erase}from'sisteransi';import ms from'@anthropic-ai/sdk';import ys from'ollama';import vs from'openai';import oa from'node-machine-id';import {ValibotJsonSchemaAdapter}from'@tmcp/adapter-valibot';import {StdioTransport}from'@tmcp/transport-stdio';import {McpServer}from'tmcp';import*as ai from'tar';var Ft={name:"jsrepo",description:"A CLI to add shared code from remote repositories.",version:"2.5.0"};var vi=yi(),pe=(e,t)=>vi?e:t,jo=pe("\u25C6","*"),Po=pe("\u25C6","*"),Eo=pe("\u25A0","x"),T=A.gray(pe("\u2502","|")),Yt=A.gray(pe("\u2500","-")),Oo=A.gray(pe("\u2510","+")),Io=A.gray(pe("\u2518","+")),Qt=A.gray(pe("\u251C","+")),Do=A.gray(pe("\u252C","+"));A.gray(pe("\u250C","T"));var To=A.gray(pe("\u2514","-")),le=A.bgRgb(245,149,66).black(" WARN "),Oe=A.bgBlueBright.white(" INFO "),Xt=A.bgRedBright.white(" ERROR "),Ze=A.hex("#f7df1e")("jsrepo"),Ve=A.hex("#f7df1e").bold("jsrepo.com");function gr(e,t){let r=[];for(let[o,n]of e)r.push(t(o,n));return r}function No(e,t){let r=0;for(let o of e)r=r+t(o);return r}function Ao(e){let t=0;for(let r of e){let o=stripVTControlCharacters(r);o.length>t&&(t=o.length);}return t}function Zt(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 Lo(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 $i=/\n|\r\n/g;function K(e){return e.split($i)}function H(e,{lineNumbers:t=false,prefix:r}={}){let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${Zt(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(ki.EOL)}var xi=/^(@[^/]+\/[^@/]+)(?:@([^/]+))?(\/.*)?$/,Ci=/^([^@/]+)(?:@([^/]+))?(\/.*)?$/;function et(e){let t=xi.exec(e)||Ci.exec(e);return t?a({name:t[1]||"",version:t[2]||void 0,path:t[3]||""}):b(`invalid package name: ${e}`)}function Mr(e,t){let r=ne.join(e,"package.json");if(me.existsSync(r))return r;if(e===t)return;let o=e.split(/[/\\]/);return Mr(o.slice(0,o.length-1).join("/"),t)}function Wr(e){if(!me.existsSync(e))return b(`${e} doesn't exist`);let t=me.readFileSync(e).toString();try{return a(JSON.parse(t))}catch(r){return b(`Error reading package.json: ${r}`)}}function yr(e){return e[0]==="^"?e.slice(1):e}function Mo(e,t,{cwd:r}){let o=e,n=t,i=Wr(ne.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let a of o){let{name:c,version:l}=et(a).unwrap(),d=s.dependencies[c];if(l===void 0&&d){o.delete(a);continue}d&&Bo.satisfies(yr(d),l)&&o.delete(a);}if(s.devDependencies)for(let a of n){let{name:c,version:l}=et(a).unwrap(),d=s.devDependencies[c];if(l===void 0&&d){n.delete(a);continue}d&&Bo.satisfies(yr(d),l)&&n.delete(a);}}return {dependencies:o,devDependencies:n}}function mt(e,t){let r;try{if(r=getTsconfig(e,t),!r&&(r=getTsconfig(e,t),!r))return a(null)}catch(o){return b(`Error while trying to get ${A.bold(t||"tsconfig.json")}: ${o}`)}return a(r)}function ut(e,{cwd:t}){let r=createPathsMatcher(e);if(!e.config.references)return r;let o=r?[r]:[];for(let n of e.config.references){let i=ne.join(t,n.path);if(!me.existsSync(i))continue;let s,a="tsconfig.json";me.statSync(i).isFile()?(s=ne.dirname(i),a=ne.basename(i)):s=i;let c=mt(s,a).unwrapOr(null);if(c===null)continue;let l=ut(c,{cwd:s});l&&o.push(l);}return o.length===0?null:n=>o.flatMap(i=>i(n))}var Go={matches:e=>e.endsWith(".css"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=Jo.parse(s,{allowTailwindDirectives:true});if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Te({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=>De(d)).join(`
|
|
3
3
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
4
4
|
${H(K(e),{prefix:()=>" "})}
|
|
5
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n,cwd:i})=>{if(!t)return e;if(t==="prettier")return await Uo.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE}),{projectKey:a}=s.openProject(i);return o&&s.applyConfiguration(a,o),s.formatContent(a,e,{filePath:n}).content}};var Ho={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=zo.parse(s),c=[],l=(m,u)=>{if(m&&(u(m),m.childNodes&&m.childNodes.length>0))for(let w of m.childNodes)l(w,u);};for(let m of a$1.childNodes)l(m,u=>{if(u.tagName==="script")for(let w of u.attrs)w.name==="src"&&c.push(w.value);if(u.tagName==="link"&&u.attrs.find(w=>w.name==="rel"&&w.value==="stylesheet"))for(let w of u.attrs)w.name==="href"&&!w.value.startsWith("http")&&c.push(w.value);});let
|
|
6
|
-
`)):a(
|
|
5
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n,cwd:i})=>{if(!t)return e;if(t==="prettier")return await Uo.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE}),{projectKey:a}=s.openProject(i);return o&&s.applyConfiguration(a,o),s.formatContent(a,e,{filePath:n}).content}};var Ho={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=zo.parse(s),c=[],l=(m,u)=>{if(m&&(u(m),m.childNodes&&m.childNodes.length>0))for(let w of m.childNodes)l(w,u);};for(let m of a$1.childNodes)l(m,u=>{if(u.tagName==="script")for(let w of u.attrs)w.name==="src"&&c.push(w.value);if(u.tagName==="link"&&u.attrs.find(w=>w.name==="rel"&&w.value==="stylesheet"))for(let w of u.attrs)w.name==="href"&&!w.value.startsWith("http")&&c.push(w.value);});let d=Te({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(m=>De(m)).join(`
|
|
6
|
+
`)):a(d.unwrap())},comment:e=>`<!--
|
|
7
7
|
${H(K(e),{prefix:()=>" "})}
|
|
8
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"html",...r}):e};function vr(e,t){
|
|
8
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"html",...r}):e};function vr(e,t){let r=Ni.parseSync(e,t),o=[];for(let n of r.module.staticImports)o.push(n.moduleRequest.value);for(let n of r.module.dynamicImports){let i=t.slice(n.moduleRequest.start+1,n.moduleRequest.end-1);o.push(i);}for(let n of r.module.staticExports)for(let i of n.entries)i.moduleRequest&&o.push(i.moduleRequest.value);return o}var Yo={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=vr(e,s),c=Te({moduleSpecifiers:a$1,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:r});return c.isErr()?b(c.unwrapErr().map(l=>De(l)).join(`
|
|
9
9
|
`)):a(c.unwrap())},comment:e=>`/*
|
|
10
10
|
${H(K(e),{prefix:()=>" "})}
|
|
11
|
-
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n,cwd:i})=>{if(!t)return e;if(t==="prettier")return await Uo.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE}),{projectKey:a}=s.openProject(i);return n&&s.applyConfiguration(a,n),s.formatContent(a,e,{filePath:r}).content}};var
|
|
11
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n,cwd:i})=>{if(!t)return e;if(t==="prettier")return await Uo.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE}),{projectKey:a}=s.openProject(i);return n&&s.applyConfiguration(a,n),s.formatContent(a,e,{filePath:r}).content}};var Xo=async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n,cwd:i})=>{if(!t)return e;if(t==="prettier")return await Uo.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE}),{projectKey:a}=s.openProject(i);return o&&s.applyConfiguration(a,{...o,json:{parser:{allowComments:true}}}),s.formatContent(a,e,{filePath:n}).content},wr={matches:e=>e.endsWith(".json"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>"",format:Xo},Zo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
|
|
12
12
|
${H(K(e),{prefix:()=>" "})}
|
|
13
|
-
*/`,format:
|
|
13
|
+
*/`,format:Xo};var rn={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=Jo.parse(s);if(a$1.isErr())return b(a$1.unwrapErr().message);let c=a$1.unwrap(),l=Te({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=>De(d)).join(`
|
|
14
14
|
`)):a(l.unwrap())},comment:e=>`/*
|
|
15
15
|
${H(K(e),{prefix:()=>" "})}
|
|
16
|
-
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"scss",...r}):e};var
|
|
17
|
-
`)):a(
|
|
16
|
+
*/`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"scss",...r}):e};var an={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=sn.parse(s,{modern:true,filename:e});if(!a$1.instance&&!a$1.module)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[],l=m=>{(m.type==="ImportDeclaration"||m.type==="ExportAllDeclaration"||m.type==="ExportNamedDeclaration")&&typeof m.source?.value=="string"&&c.push(m.source.value),m.type==="ImportExpression"&&m.source.type==="Literal"&&typeof m.source.value=="string"&&c.push(m.source.value);};a$1.instance&&walk(a$1.instance,{enter:l}),a$1.module&&walk(a$1.module,{enter:l});let d=Te({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["svelte","@sveltejs/kit",...r]});return d.isErr()?b(d.unwrapErr().map(m=>De(m)).join(`
|
|
17
|
+
`)):a(d.unwrap())},comment:e=>`<!--
|
|
18
18
|
${H(K(e),{prefix:()=>" "})}
|
|
19
|
-
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Uo.format(e,{filepath:r,...o}):e};var
|
|
19
|
+
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Uo.format(e,{filepath:r,...o}):e};var cn={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
20
20
|
${H(K(e),{prefix:()=>" "})}
|
|
21
|
-
-->`,format:async e=>e};var
|
|
21
|
+
-->`,format:async e=>e};var pn={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n,containingDir:i})=>{let s=me.readFileSync(e).toString(),a$1=dn.parse(s,{filename:e}),c=[];if(a$1.descriptor.script?.content){let d=vr("noop.ts",a$1.descriptor.script.content);c.push(...d);}if(a$1.descriptor.scriptSetup?.content){let d=vr("noop.ts",a$1.descriptor.scriptSetup.content);c.push(...d);}if(c.length===0)return a({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Te({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,containingDir:i,doNotInstall:["vue","nuxt",...r]});return l.isErr()?b(l.unwrapErr().map(d=>De(d)).join(`
|
|
22
22
|
`)):a(l.unwrap())},comment:e=>`<!--
|
|
23
23
|
${H(K(e),{prefix:()=>" "})}
|
|
24
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"vue",...r}):e};var
|
|
25
|
-
${i||e} references code not contained in ${F.bold(s.join(", "))} and cannot be resolved.`)}function Wi(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-ne.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=ne.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function Vi(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=ft(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=mt(a$1,{cwd:n});if(c){let l=c(e);for(let f of l){let m=Ui(f);if(!m)continue;let u=ne.relative(ne.resolve(ne.join(r,"../")),m.prettyPath),w=Ji(m.prettyPath,m.path,[".js",".ts"]),p=hn(u,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:m.type==="file"});if(p.isErr())return b(p.unwrapErr());if(p.unwrap())return a(p.unwrap());break}}return a(void 0)}function Ji(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=ne.parse(e),n=ne.parse(t),i=ne.join(o.dir,o.name),s=ne.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function Ui(e){if(me.existsSync(e))return {path:e,prettyPath:e,type:me.statSync(e).isDirectory()?"directory":"file"};let t=ne.join(e,"../");if(!me.existsSync(t))return;let r=ne.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(me.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=me.readdirSync(t);for(let n of o){let i=ne.parse(n);if(i.name===r.base){let s=ne.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:me.statSync(s).isDirectory()?"directory":"file"}}}}function Gi(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Mr(ne.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(me.readFileSync(n,"utf-8"));for(let l of e){let f=et(l);if(f.isErr()){console.warn(`${T} ${le} Skipped adding import \`${F.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let m=f.unwrap();if(!gn(m.name).validForNewPackages){console.warn(`${T} ${le} Skipped adding import \`${F.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(m.name))continue;let u;if(c!==void 0&&(u=c[m.name]),u!==void 0){i.add(`${m.name}@${u}`);continue}if(a!==void 0&&(u=a[m.name]),u!==void 0){s.add(`${m.name}@${u}`);continue}i.add(m.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var gt=[Go,Ho,wr,en,on,cn,ln,Qo,fn,un];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=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),Ki=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),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 ${F.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=`${F.bold(`${e.category}/${e.name}`)} depends on local dependency ${F.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(`${F.bold(`${e.category}/${e.name}`)} depends on ${F.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(`${F.bold(`${e.category}/${e.name}`)} has too many local dependencies (${F.bold(e.localDependencies.length)}) limit (${F.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=kr(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${F.bold(o)}: ${F.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(kr(r,n,t.categories))return;return [`${F.bold(r)} is unused and will be ${F.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=>et(o).unwrap().name).filter(o=>vn.has(o));if(r.length>0)for(let o of r)t.push(`${F.bold(`${e.category}/${e.name}`)} depends on ${F.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)me.existsSync(ne.join(t,o.path))||r.push(`The ${F.bold(o.name)} config file doesn't exist at ${F.bold(ne.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=>et(n).unwrap().name).filter(n=>vn.has(n));if(o.length>0)for(let n of o)t.push(`${F.bold(r.name)} depends on ${F.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 ${F.bold(o)}`);return t.length>0?t:void 0}}}},kn=k.record(Ki,k.union([wn,k.tupleWithRest([wn,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),er={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"};function $r(e,t,r,o=er){let n=[],i=[];for(let[s,a]of Object.entries(bn)){if(a.scope==="block")continue;let c=o[s],l,f=[];if(Array.isArray(c)?(l=c[0],f.push(...c.slice(1))):l=c,l==="off")continue;let m=a.check({manifest:e,options:f,cwd:r,config:t});if(m){if(l==="error"){i.push(...m.map(u=>`${T} ${Xt} ${F.red(u)} ${F.gray(s)}`));continue}n.push(...m.map(u=>`${T} ${le} ${u} ${F.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 f=o[c],m,u=[];if(Array.isArray(f)?(m=f[0],u.push(...f.slice(1))):m=f,m==="off")continue;let w=l.check(a,{manifest:e,options:u,cwd:r,config:t});if(w){if(m==="error"){i.push(...w.map(p=>`${T} ${Xt} ${F.red(p)} ${F.gray(c)}`));continue}n.push(...w.map(p=>`${T} ${le} ${p} ${F.gray(c)}`));}}return {warnings:n,errors:i}}function kr(e,t,r,o=[]){let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;if(o.includes(i))return;let[s,a]=i.split("/"),c=r.find(f=>f.name===s)?.blocks.find(f=>f.name===a);if(!c)continue;let l=kr(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(kr(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"],jn=[".mdx",".md"];function ct(e){return l(e,Sn)!==void 0}function xr(e){return l(e,jn)!==void 0}function Cr(e,{cwd:t,ignore:r,config:o}){let n;try{n=me.readdirSync(e);}catch{program.error(F.red(`Couldn't read the ${F.bold(e)} directory.`));}let i=[];for(let s of n){let a=ne.join(e,s);if(me.statSync(a).isFile())continue;let c=`${ne.relative(t,a)}/`;if(r.ignores(c))continue;let l=ne.basename(s);if(!qi(l,o))continue;let f=Hi(l,o),m={name:l,blocks:[]},u=me.readdirSync(a);for(let w of u){let p=ne.join(a,w),h=ne.relative(t,p);if(!r.ignores(h))if(me.statSync(p).isFile()){if(ct(w))continue;if(xr(w)){o.includeDocs||console.warn(`${T} ${le} Documentation files (*.md, *.mdx) are not included by default include them with ${F.bold("--include-docs")}!`);continue}let y=Yi(w),g=xn(y,o);if(!Cn(y,o))continue;let S=gt.find(U=>U.matches(w));if(!S){console.warn(`${T} ${le} Skipped \`${F.bold(p)}\` \`*${F.bold(ne.parse(w).ext)}\` files are not currently supported!`);continue}let C=u.find(U=>Sn.find(Z=>U===`${y}${Z}`)),d=u.find(U=>jn.find(Z=>U===`${y}${Z}`)),{dependencies:b,devDependencies:x,local:R,imports:E}=S.resolveDependencies({filePath:p,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(U=>U,U=>{program.error(F.red(U));}),Y={name:y,directory:ne.relative(t,a),category:l,tests:C!==void 0,docs:d!==void 0,subdirectory:false,list:f?g:false,files:[w],localDependencies:R,_imports_:E,dependencies:b,devDependencies:x};C!==void 0&&Y.files.push(C),d!==void 0&&Y.files.push(d),m.blocks.push(Y);}else {let y=w,g=xn(y,o);if(!Cn(y,o))continue;let S=new Set,C=new Set,d=new Set,b={},x=false,R=false,E=[],Y=(Z,$)=>{for(let A of $){let v=ne.join(Z,A),V=v.slice(p.length+1);if(ct(A)){x=true,E.push(V);continue}if(xr(A)){o.includeDocs||console.warn(`${T} ${le} Documentation files (*.md, *.mdx) are not included by default include them with ${F.bold("--include-docs")}!`),R=true,E.push(V);continue}if(me.statSync(v).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${le} Skipped \`${F.bold(ne.join(p,A))}\` subdirectories are not allowed! Allow them with ${F.bold("--allow-subdirectories")}!`);continue}let z=me.readdirSync(v);Y(v,z);continue}let j=gt.find(z=>z.matches(A));if(!j){console.warn(`${T} ${le} Skipped \`${v}\` \`*${F.bold(ne.parse(A).ext)}\` files are not currently supported!`);continue}let{local:G,dependencies:oe,devDependencies:ve,imports:it}=j.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:p,filePath:v,cwd:t}).match(z=>z,z=>{program.error(F.red(z));});for(let z of G)z!==`${l}/${y}`&&S.add(z);for(let z of oe)C.add(z);for(let z of ve)d.add(z);for(let[z,ee]of Object.entries(it))b[z]=ee;E.push(V);}};Y(p,me.readdirSync(p));let U={name:y,directory:ne.relative(t,p),category:l,tests:x,docs:R,subdirectory:true,list:f?g:false,files:E,localDependencies:Array.from(S.keys()),dependencies:Array.from(C.keys()),devDependencies:Array.from(d.keys()),_imports_:b};m.blocks.push(U);}}i.push(m);}return i}function Rr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=gt.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:ne.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(F.red(c));});a.length>0&&program.error(F.red(`${F.bold(o.name)} ${F.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 Hi(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function qi(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function Yi(e){return ne.parse(ne.basename(e)).name}function Sr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!$n(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var Er=[".git","node_modules",".DS_Store"],yt="jsrepo.json",vt="jsrepo-build-config.json",Jr=k.union([k.literal("prettier"),k.literal("biome")]),Qi=k.objectWithRest({"*":k.string()},k.string()),Ur=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),includeDocs:k.optional(k.boolean(),false),paths:Qi,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(Jr)});function be(e){if(!me.existsSync(ne.join(e,yt)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse(Ur,JSON.parse(me.readFileSync(ne.join(e,yt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${yt}\` file!`)}var Xi=k.object({$schema:k.string(),name:k.optional(k.string()),version:k.optional(k.string()),readme:k.optional(k.string(),"README.md"),access:k.optional(j),meta:k.optional(f),defaultPaths:k.optional(k.record(k.string(),k.string())),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string()),[]),includeCategories:k.optional(k.array(k.string()),[]),excludeBlocks:k.optional(k.array(k.string()),[]),excludeCategories:k.optional(k.array(k.string()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean(),false),rules:k.optional(kn)});function Ft(e){if(!me.existsSync(ne.join(e,vt)))return a(null);let t=k.safeParse(Xi,JSON.parse(me.readFileSync(ne.join(e,vt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${vt}\` file!`)}function Ue(e,t){let r=ft(t).unwrapOr(null),o=r?mt(r,{cwd:t}):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=ne.relative(t,ne.join(ne.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${F.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 ${F.bold("`./`")}.`);let a=Zi(s,o,t);if(!a)return b(`Cannot resolve ${F.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 ${F.bold("`./`")}.`);n[i]=a;}return a(n)}function Zi(e,t,r){let o=t(e);return o.length>0?ne.relative(r,o[0]):void 0}function rr(e,t,r){let o;return t[e.category]!==void 0?o=ne.join(r,t[e.category]):o=ne.join(r,t["*"],e.category),o}var Se=es.defaults({cachePath:ne.join(import.meta.dirname,"cache")});function Ge(){return new rs({projectName:"jsrepo"})}var Gr="http-registries-w-tokens",fe=class{#e;constructor(t){this.#e=t??Ge();}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(Gr,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(Gr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Gr);return t||[]}};async function ze(e,t,{verbose:r}={}){return await A(e,t,{verbose:r,fetch:Se,token:zr(e.provider,e.url)})}async function Lt(e,{verbose:t}={}){return await B(e,{verbose:t,fetch:Se,token:zr(e.provider,e.url)})}function zr(e,t){let r=new fe;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function lt(e,{noCache:t=false}={}){let r=z(e);if(r){let o=Ge();if(r.name!==u.name)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:zr(r,n.url),fetch:Se});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 ":""}${F.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function Ke(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await lt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function bt(e,{verbose:t}={}){let r=new Map,n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();for(let c$1 of a.categories)for(let l of c$1.blocks)r.set(c(i.url,`${l.category}/${l.name}`),{...l,sourceRepo:i});}))).find(i=>i!==void 0);return n||a(r)}function Bt(e){let t=new Map;for(let r of e)for(let o of r.manifest.categories)for(let n of o.blocks)t.set(c(r.state.url,`${n.category}/${n.name}`),{...n,sourceRepo:r.state});return t}async function _t(e,{verbose:t}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await Lt(i,{verbose:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i.url});let a=s.unwrap();r.push({state:i,manifest:a});}))).find(i=>i!==void 0);return n||a(r)}async function $t(e,t,r,o=new Map,n=new Set){let i=new Map;for(let s of e){let a,c$1=z(s);if(c$1){let{url:f,specifier:m}=c$1.parse(s,{fullyQualified:true});a=t.get(c(f,m));}else {if(r.length===0)return b(F.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${F.bold(`github/ieedan/std/${s}`)}\`!`));for(let f of r){let{url:m,specifier:u}=f.provider.parse(c(f.url,s),{fullyQualified:true}),w=t.get(c(m,u));if(w!==void 0){a=w;break}}}if(!a)return b(`Invalid block! ${F.bold(s)} does not exist!`);let l=`${a.category}/${a.name}`;if(!(n.has(l)||o.has(l))&&(n.add(l),i.set(l,a),a.localDependencies&&a.localDependencies.length>0)){let f=a.localDependencies.filter(m=>!n.has(m)&&!o.has(m));if(f.length>0){let m=await $t(f,t,r,o,n);if(m.isErr())return b(m.unwrapErr());for(let u of m.unwrap()){let w=`${u.category}/${u.name}`;n.has(w)||n.add(w),i.set(w,u);}}}}return a(gr(i,(s,a)=>a))}function xt(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(F.red(i)));for(let[i,s]of e){let a=rr(s,n,r),c=ne.join(a,s.files[0]);s.subdirectory&&(c=ne.join(a,s.name)),me.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function Mt(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>!(ct(s)&&!t.includeTests||xr(s)&&!t.includeDocs)),i=Promise.all(n.map(async s=>{let a=await ze(o.sourceRepo,ne.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function ir(e,t,r,o){let n=rr(t,r,o);return t.subdirectory?ne.join(n,t.name,e):ne.join(n,e)}function sr(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))}var cs={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},ls={"install-as-dev-dependency":"-D"},ps={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},En={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},On={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Kr={bun:cs,npm:ps,pnpm:En,deno:ls,yarn:On,"yarn@berry":On,"pnpm@6":En};var Yr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await In("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Hr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
|
|
26
|
-
${JSON.stringify(a,null," ")}`);let c=await
|
|
27
|
-
${JSON.stringify(a,null," ")}`);let c=await
|
|
28
|
-
${JSON.stringify(s,null," ")}`);let a=await
|
|
24
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"vue",...r}):e};var mn={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>a({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>H(K(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Uo.format(e,{parser:"yaml",...r}):e};function De(e){return `${H(K(e),{prefix:t=>t===0?`${T} ${Xt} `:`${T} `})}`}function Te({moduleSpecifiers:e,isSubDir:t,filePath:r,containingDir:o,doNotInstall:n,dirs:i,cwd:s}){let a$1=[],c=new Set,l=new Set,d={};for(let w of e){if(builtinModules.includes(w)||w.startsWith("node:"))continue;if(w.startsWith(".")){let y=gn(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(y.isErr()){a$1.push(y.unwrapErr());continue}let h=y.unwrap();h&&(l.add(h.dependency),d[w]=h.template);continue}let p=Vi(w,t,{filePath:r,containingDir:o,dirs:i,cwd:s});if(!p.isErr()){let y=p.unwrap();if(y){l.add(y.dependency),d[w]=y.template;continue}}let g=et(w);if(!g.isErr()){let y=g.unwrap();if(un(y.name).validForNewPackages){c.add(w);continue}}console.warn(`${T} ${le} Skipped adding import \`${A.cyan(w)}\` from ${r}. Reason: Not a valid package name or path alias.`);}if(a$1.length>0)return b(a$1);let{devDependencies:m,dependencies:u}=Gi(Array.from(c),r,{doNotInstall:n||[]});return a({dependencies:u,devDependencies:m,local:Array.from(l),imports:d})}function gn(e,t,{filePath:r,containingDir:o,dropExtension:n=true,alias:i,dirs:s,cwd:a$1}){if(t&&(e.startsWith("./")||e==="."))return a(void 0);let c=ne.join(ne.join(r,"../"),e);if(o&&c.startsWith(o))return a(void 0);let l=ne.resolve(c),d=null;for(let m of s){let u=ne.resolve(ne.join(a$1,m));l.startsWith(u)&&(d===null||d.length<u.length)&&(d=u);}return d!==null?a(Wi(l.slice(d.length+1),n)):b(`${r}:
|
|
25
|
+
${i||e} references code not contained in ${A.bold(s.join(", "))} and cannot be resolved.`)}function Wi(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-ne.parse(i).ext.length));let s=`${r}/${i}`,a=`{{${s}}}`;return n.length===0?i.length!==o.length&&(a+=ne.parse(o).ext):a+=`/${n.join("/")}`,{dependency:s,template:a}}function Vi(e,t,{filePath:r,dirs:o,cwd:n,containingDir:i}){let s=mt(r);if(s.isErr())return b(s.unwrapErr());let a$1=s.unwrap();if(a$1===null)return a(void 0);let c=ut(a$1,{cwd:n});if(c){let l=c(e);for(let d of l){let m=Ui(d);if(!m)continue;let u=ne.relative(ne.resolve(ne.join(r,"../")),m.prettyPath),w=Ji(m.prettyPath,m.path,[".js",".ts"]),p=gn(u,t,{filePath:r,containingDir:i,alias:e,dropExtension:w,dirs:o,cwd:n,modIsFile:m.type==="file"});if(p.isErr())return b(p.unwrapErr());if(p.unwrap())return a(p.unwrap());break}}return a(void 0)}function Ji(e,t,r=[".ts",".js",""]){if(e===t)return true;let o=ne.parse(e),n=ne.parse(t),i=ne.join(o.dir,o.name),s=ne.join(n.dir,n.name);return i!==s?false:!!(r.includes(o.ext)&&r.includes(n.ext))}function Ui(e){if(me.existsSync(e))return {path:e,prettyPath:e,type:me.statSync(e).isDirectory()?"directory":"file"};let t=ne.join(e,"../");if(!me.existsSync(t))return;let r=ne.parse(e);if(r.ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(me.existsSync(n))return {path:n,prettyPath:e,type:"file"}}let o=me.readdirSync(t);for(let n of o){let i=ne.parse(n);if(i.name===r.base){let s=ne.join(t,n),a=s.slice(0,s.length-i.ext.length);return {path:s,prettyPath:a,type:me.statSync(s).isDirectory()?"directory":"file"}}}}function Gi(e,t,{doNotInstall:r}={doNotInstall:[]}){let o=new Set(r),n=Mr(ne.dirname(t),""),i=new Set,s=new Set;if(n){let{devDependencies:a,dependencies:c}=JSON.parse(me.readFileSync(n,"utf-8"));for(let l of e){let d=et(l);if(d.isErr()){console.warn(`${T} ${le} Skipped adding import \`${A.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let m=d.unwrap();if(!un(m.name).validForNewPackages){console.warn(`${T} ${le} Skipped adding import \`${A.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(m.name))continue;let u;if(c!==void 0&&(u=c[m.name]),u!==void 0){i.add(`${m.name}@${u}`);continue}if(a!==void 0&&(u=a[m.name]),u!==void 0){s.add(`${m.name}@${u}`);continue}i.add(m.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(s)}}var ht=[Go,Ho,wr,Zo,rn,an,cn,Yo,pn,mn];var yn=new Set(["svelte","@sveltejs/kit","vue","nuxt","react","react-dom","next","@remix-run/react","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router","@builder.io/qwik","astro","solid-js"]),vn=k.union([k.literal("off"),k.literal("warn"),k.literal("error")]),Ki=k.union([k.literal("no-category-index-file-dependency"),k.literal("no-unpinned-dependency"),k.literal("require-local-dependency-exists"),k.literal("max-local-dependencies"),k.literal("no-circular-dependency"),k.literal("no-unused-block"),k.literal("no-framework-dependency"),k.literal("require-config-file-exists"),k.literal("no-config-file-framework-dependency"),k.literal("no-config-file-unpinned-dependency")]),wn={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",scope:"block",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${A.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/"),s=t.categories.find(c=>c.name.trim()===n.trim()),a=`${A.bold(`${e.category}/${e.name}`)} depends on local dependency ${A.bold(o)} which doesn't exist`;if(!s){r.push(a);continue}s.blocks.find(c=>c.name===i)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",scope:"block",check:(e,{manifest:t})=>{let r=[];for(let o of e.localDependencies){let[n,i]=o.split("/");if(i!=="index")continue;let s=t.categories.find(c=>c.name===n);!s||!s.blocks.find(c=>c.name===i)||r.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(`${n}/${i}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",scope:"block",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${A.bold(`${e.category}/${e.name}`)} has too many local dependencies (${A.bold(e.localDependencies.length)}) limit (${A.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",scope:"block",check:(e,{manifest:t})=>{let r=[],o=`${e.category}/${e.name}`,n=kr(o,e,t.categories);return n&&r.push(`There is a circular dependency in ${A.bold(o)}: ${A.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",scope:"block",check:(e,{manifest:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.categories.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(kr(r,n,t.categories))return;return [`${A.bold(r)} is unused and will be ${A.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",scope:"block",check:e=>{let t=[],r=[...e.devDependencies,...e.dependencies].map(o=>et(o).unwrap().name).filter(o=>yn.has(o));if(r.length>0)for(let o of r)t.push(`${A.bold(`${e.category}/${e.name}`)} depends on ${A.bold(o)} causing it to be installed when added`);return t.length>0?t:void 0}},"require-config-file-exists":{description:"Require all of the paths listed in `configFiles` to exist.",scope:"global",check:({manifest:e,cwd:t})=>{let r=[];if(e.configFiles!==void 0){for(let o of e.configFiles)me.existsSync(ne.join(t,o.path))||r.push(`The ${A.bold(o.name)} config file doesn't exist at ${A.bold(ne.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=>et(n).unwrap().name).filter(n=>yn.has(n));if(o.length>0)for(let n of o)t.push(`${A.bold(r.name)} depends on ${A.bold(n)} causing it to be installed when added`);}return t.length>0?t:void 0}}},"no-config-file-unpinned-dependency":{description:"Require all dependencies of config files to have a pinned version.",scope:"global",check:({manifest:e})=>{let t=[];if(e.configFiles){for(let r of e.configFiles)for(let o of [...r.dependencies??[],...r.devDependencies??[]])o.includes("@")||t.push(`Couldn't find a version to use for ${A.bold(o)}`);return t.length>0?t:void 0}}}},bn=k.record(Ki,k.union([vn,k.tupleWithRest([vn,k.union([k.string(),k.number()])],k.union([k.string(),k.number()]))])),er={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn","require-config-file-exists":"error","no-config-file-framework-dependency":"warn","no-config-file-unpinned-dependency":"warn"};function $r(e,t,r,o=er){let n=[],i=[];for(let[s,a]of Object.entries(wn)){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 m=a.check({manifest:e,options:d,cwd:r,config:t});if(m){if(l==="error"){i.push(...m.map(u=>`${T} ${Xt} ${A.red(u)} ${A.gray(s)}`));continue}n.push(...m.map(u=>`${T} ${le} ${u} ${A.gray(s)}`));}}for(let s of e.categories)for(let a of s.blocks)for(let[c,l]of Object.entries(wn)){if(l.scope==="global")continue;let d=o[c],m,u=[];if(Array.isArray(d)?(m=d[0],u.push(...d.slice(1))):m=d,m==="off")continue;let w=l.check(a,{manifest:e,options:u,cwd:r,config:t});if(w){if(m==="error"){i.push(...w.map(p=>`${T} ${Xt} ${A.red(p)} ${A.gray(c)}`));continue}n.push(...w.map(p=>`${T} ${le} ${p} ${A.gray(c)}`));}}return {warnings:n,errors:i}}function kr(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=kr(e,c,r,n);if(l)return [...l,e]}}function kn(e,t){for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(kr(e,o,t))return true}return false}var Rn=[".test.ts","_test.ts",".test.js","_test.js",".spec.ts","_spec.ts",".spec.js","_spec.js",".stories.jsx","_stories.jsx",".stories.tsx","_stories.tsx"],Sn=[".mdx",".md"];function ct(e){return l(e,Rn)!==void 0}function xr(e){return l(e,Sn)!==void 0}function Cr(e,{cwd:t,ignore:r,config:o}){let n;try{n=me.readdirSync(e);}catch{program.error(A.red(`Couldn't read the ${A.bold(e)} directory.`));}let i=[];for(let s of n){let a=ne.join(e,s);if(me.statSync(a).isFile())continue;let c=`${ne.relative(t,a)}/`;if(r.ignores(c))continue;let l=ne.basename(s);if(!Yi(l,o))continue;let d=qi(l,o),m={name:l,blocks:[]},u=me.readdirSync(a);for(let w of u){let p=ne.join(a,w),g=ne.relative(t,p);if(!r.ignores(g))if(me.statSync(p).isFile()){if(ct(w))continue;if(xr(w)){o.includeDocs||console.warn(`${T} ${le} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`);continue}let y=Xi(w),h=$n(y,o);if(!xn(y,o))continue;let j=ht.find(J=>J.matches(w));if(!j){console.warn(`${T} ${le} Skipped \`${A.bold(p)}\` \`*${A.bold(ne.parse(w).ext)}\` files are not currently supported!`);continue}let C=u.find(J=>Rn.find(Z=>J===`${y}${Z}`)),f=u.find(J=>Sn.find(Z=>J===`${y}${Z}`)),{dependencies:b,devDependencies:x,local:R,imports:P}=j.resolveDependencies({filePath:p,isSubDir:false,excludeDeps:o.excludeDeps,dirs:o.dirs,cwd:t}).match(J=>J,J=>{program.error(A.red(J));}),X={name:y,directory:ne.relative(t,a),category:l,tests:C!==void 0,docs:f!==void 0,subdirectory:false,list:d?h:false,files:[w],localDependencies:R,_imports_:P,dependencies:b,devDependencies:x};C!==void 0&&X.files.push(C),f!==void 0&&X.files.push(f),m.blocks.push(X);}else {let y=w,h=$n(y,o);if(!xn(y,o))continue;let j=new Set,C=new Set,f=new Set,b={},x=false,R=false,P=[],X=Qi(o),J=($,L)=>{for(let v of L){let _=ne.join($,v),S=_.slice(p.length+1),G=_.replace(t,"").replace("/","");if(ct(v)){x=true,P.push(S);continue}if(xr(v)){o.includeDocs||console.warn(`${T} ${le} Documentation files (*.md, *.mdx) are not included by default include them with ${A.bold("--include-docs")}!`),R=true,P.push(S);continue}if(X(G)){P.push(S);continue}if(me.statSync(_).isDirectory()){if(!o.allowSubdirectories){console.warn(`${T} ${le} Skipped \`${A.bold(ne.join(p,v))}\` subdirectories are not allowed! Allow them with ${A.bold("--allow-subdirectories")}!`);continue}let z=me.readdirSync(_);J(_,z);continue}let oe=ht.find(z=>z.matches(v));if(!oe){console.warn(`${T} ${le} Skipped \`${_}\` \`*${A.bold(ne.parse(v).ext)}\` files are not currently supported!`);continue}let{local:ve,dependencies:it,devDependencies:we,imports:ee}=oe.resolveDependencies({isSubDir:true,excludeDeps:o.excludeDeps,dirs:o.dirs,containingDir:p,filePath:_,cwd:t}).match(z=>z,z=>{program.error(A.red(z));});for(let z of ve)z!==`${l}/${y}`&&j.add(z);for(let z of it)C.add(z);for(let z of we)f.add(z);for(let[z,ft]of Object.entries(ee))b[z]=ft;P.push(S);}};J(p,me.readdirSync(p));let Z={name:y,directory:ne.relative(t,p),category:l,tests:x,docs:R,subdirectory:true,list:d?h:false,files:P,localDependencies:Array.from(j.keys()),dependencies:Array.from(C.keys()),devDependencies:Array.from(f.keys()),_imports_:b};m.blocks.push(Z);}}i.push(m);}return i}function Rr(e,{cwd:t}){if(!e.configFiles)return;let r=[];for(let o of e.configFiles){let n=ht.find(c=>c.matches(o.path));if(!n){r.push(o);continue}let{dependencies:i,devDependencies:s,local:a}=n.resolveDependencies({filePath:ne.join(t,o.path),isSubDir:false,excludeDeps:e.excludeDeps,dirs:e.dirs,cwd:t}).match(c=>c,c=>{program.error(A.red(c));});a.length>0&&program.error(A.red(`${A.bold(o.name)} ${A.bold(o.path)} Config files cannot have local dependencies!`)),r.push({...o,dependencies:i,devDependencies:s});}return r}function $n(e,t){return t.doNotListBlocks.length>0&&t.doNotListBlocks.includes(e)?false:t.listBlocks.length>0?t.listBlocks.includes(e):true}function xn(e,t){return t.excludeBlocks.length>0&&t.excludeBlocks.includes(e)?false:t.includeBlocks.length>0?t.includeBlocks.includes(e):true}function qi(e,t){return t.doNotListCategories.length>0&&t.doNotListCategories.includes(e)?false:t.listCategories.length>0?t.listCategories.includes(e):true}function Yi(e,t){return t.excludeCategories.length>0&&t.excludeCategories.includes(e)?false:t.includeCategories.length>0?t.includeCategories.includes(e):true}function Qi(e){if(e.includeFiles.length===0)return ()=>false;let t=Hi().add(e.includeFiles.map(r=>r.replace(/^(\.\/|\/)/,"")));return r=>t.ignores(r)}function Xi(e){return ne.parse(ne.basename(e)).name}function Sr(e){let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!kn(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]}var Er=[".git","node_modules",".DS_Store"],vt="jsrepo.json",wt="jsrepo-build-config.json",Jr=k.union([k.literal("prettier"),k.literal("biome")]),Zi=k.objectWithRest({"*":k.string()},k.string()),Ur=k.object({$schema:k.string(),repos:k.optional(k.array(k.string()),[]),includeTests:k.boolean(),includeDocs:k.optional(k.boolean(),false),paths:Zi,configFiles:k.optional(k.record(k.string(),k.string())),watermark:k.optional(k.boolean(),true),formatter:k.optional(Jr)});function ke(e){if(!me.existsSync(ne.join(e,vt)))return b("Could not find your configuration file! Please run `init`.");let t=k.safeParse(Ur,JSON.parse(me.readFileSync(ne.join(e,vt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${vt}\` file!`)}var es=k.object({$schema:k.string(),name:k.optional(k.string()),version:k.optional(k.string()),readme:k.optional(k.string(),"README.md"),access:k.optional(j),meta:k.optional(f),defaultPaths:k.optional(k.record(k.string(),k.string())),peerDependencies:k.optional(g),configFiles:k.optional(k.array(h)),dirs:k.array(k.string()),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string()),[]),includeCategories:k.optional(k.array(k.string()),[]),includeFiles:k.optional(k.array(k.string()),[]),excludeBlocks:k.optional(k.array(k.string()),[]),excludeCategories:k.optional(k.array(k.string()),[]),doNotListBlocks:k.optional(k.array(k.string()),[]),doNotListCategories:k.optional(k.array(k.string()),[]),listBlocks:k.optional(k.array(k.string()),[]),listCategories:k.optional(k.array(k.string()),[]),excludeDeps:k.optional(k.array(k.string()),[]),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean(),false),rules:k.optional(bn)});function Lt(e){if(!me.existsSync(ne.join(e,wt)))return a(null);let t=k.safeParse(es,JSON.parse(me.readFileSync(ne.join(e,wt)).toString()));return t.success?a(t.output):b(`There was an error reading your \`${wt}\` file!`)}function Ue(e,t){let r=mt(t).unwrapOr(null),o=r?ut(r,{cwd:t}):null,n={"*":""};for(let[i,s]of Object.entries(e)){if(s.startsWith("./")){n[i]=ne.relative(t,ne.join(ne.resolve(t),s));continue}if(o===null)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a tsconfig! If you intended to use a relative path ensure that your path starts with ${A.bold("`./`")}.`);let a=ts(s,o,t);if(!a)return b(`Cannot resolve ${A.bold(`\`"${i}": "${s}"\``)} from paths because we couldn't find a matching alias in the tsconfig. If you intended to use a relative path ensure that your path starts with ${A.bold("`./`")}.`);n[i]=a;}return a(n)}function ts(e,t,r){let o=t(e);return o.length>0?ne.relative(r,o[0]):void 0}function rr(e,t,r){let o;return t[e.category]!==void 0?o=ne.join(r,t[e.category]):o=ne.join(r,t["*"],e.category),o}var je=rs.defaults({cachePath:ne.join(import.meta.dirname,"cache")});function Ge(){return new ns({projectName:"jsrepo"})}var Gr="http-registries-w-tokens",fe=class{#e;constructor(t){this.#e=t??Ge();}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(Gr,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(Gr,o);}let r=this.getKey(t);this.#e.delete(r);}getHttpRegistriesWithTokens(){let t=this.#e.get(Gr);return t||[]}};async function ze(e,t,{verbose:r}={}){return await A$1(e,t,{verbose:r,fetch:je,token:zr(e.provider,e.url)})}async function Bt(e,{verbose:t,noCache:r}={}){return await B(e,{verbose:t,fetch:(o,n)=>je(o,{...n,cache:r?"reload":void 0}),token:zr(e.provider,e.url)})}function zr(e,t){let r=new fe;return e.name==="http"?r.get(`http-${new URL(t).origin}`):r.get(e.name)}async function lt(e,{noCache:t=false}={}){let r=z(e);if(r){let o=Ge();if(r.name!==u.name)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:zr(r,n.url),fetch:je});return r.name!==u.name&&!t&&o.set(`${e}-state`,i),a(i)}return b(`Only ${y.map((o,n)=>`${n===y.length-1?"and ":""}${A.bold(o.name)}`).join(", ")} registries are supported at this time!`)}async function Ke(e,{noCache:t=false}={}){let r=[],n=(await Promise.all(e.map(async i=>{let s=await lt(i,{noCache:t});if(s.isErr())return b({message:s.unwrapErr(),repo:i});let a=s.unwrap();r.push(a);}))).find(i=>i!==void 0);return n||a(r)}async function kt(e,{verbose:t,noCache:r}={}){let o=new Map,i=(await Promise.all(e.map(async s=>{let a=await Bt(s,{verbose:t,noCache:r});if(a.isErr())return b({message:a.unwrapErr(),repo:s.url});let c$1=a.unwrap();for(let l of c$1.categories)for(let d of l.blocks)o.set(c(s.url,`${d.category}/${d.name}`),{...d,sourceRepo:s});}))).find(s=>s!==void 0);return i||a(o)}function _t(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 Mt(e,{verbose:t,noCache:r}={}){let o=[],i=(await Promise.all(e.map(async s=>{let a=await Bt(s,{verbose:t,noCache:r});if(a.isErr())return b({message:a.unwrapErr(),repo:s.url});let c=a.unwrap();o.push({state:s,manifest:c});}))).find(s=>s!==void 0);return i||a(o)}async function xt(e,t,r,o=new Map,n=new Set){let i=new Map;for(let s of e){let a,c$1=z(s);if(c$1){let{url:d,specifier:m}=c$1.parse(s,{fullyQualified:true});a=t.get(c(d,m));}else {if(r.length===0)return b(A.red(`If your config doesn't contain repos then you must provide the repo in the block specifier ex: \`${A.bold(`github/ieedan/std/${s}`)}\`!`));for(let d of r){let{url:m,specifier:u}=d.provider.parse(c(d.url,s),{fullyQualified:true}),w=t.get(c(m,u));if(w!==void 0){a=w;break}}}if(!a)return b(`Invalid block! ${A.bold(s)} does not exist!`);let l=`${a.category}/${a.name}`;if(!(n.has(l)||o.has(l))&&(n.add(l),i.set(l,a),a.localDependencies&&a.localDependencies.length>0)){let d=a.localDependencies.filter(m=>!n.has(m)&&!o.has(m));if(d.length>0){let m=await xt(d,t,r,o,n);if(m.isErr())return b(m.unwrapErr());for(let u of m.unwrap()){let w=`${u.category}/${u.name}`;n.has(w)||n.add(w),i.set(w,u);}}}}return a(gr(i,(s,a)=>a))}function Ct(e,t,r){let o=[],n=Ue(t.paths,r).match(i=>i,i=>program.error(A.red(i)));for(let[i,s]of e){let a=rr(s,n,r),c=ne.join(a,s.files[0]);s.subdirectory&&(c=ne.join(a,s.name)),me.existsSync(c)&&o.push({specifier:`${s.category}/${s.name}`,path:c,block:s});}return o}function Wt(e,t){let r=[];for(let o of e){let n=o.files.filter(s=>!(ct(s)&&!t.includeTests||xr(s)&&!t.includeDocs)),i=Promise.all(n.map(async s=>{let a=await ze(o.sourceRepo,ne.join(o.directory,s));return {name:s,content:a}}));r.push({block:o,files:i});}return r}function ir(e,t,r,o){let n=rr(t,r,o);return t.subdirectory?ne.join(n,t.name,e):ne.join(n,e)}function sr(e){if(e===void 0)return;let t={};for(let r of e.split(",")){let[o,n]=r.split("=");if(o===void 0||n===void 0)throw new InvalidArgumentError("Expected map to be provided in the following format: `--option key=value,key=value`");t[o]=n;}return t}function jn(e){return new Promise(t=>t(e))}var ds={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},ps={"install-as-dev-dependency":"-D"},fs={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Pn={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},En={"no-workspace":"--focus","install-as-dev-dependency":"-D"},Kr={bun:ds,npm:fs,pnpm:Pn,deno:ps,yarn:En,"yarn@berry":En,"pnpm@6":Pn};var Yr={"Claude 3.7 Sonnet":{updateFile:async({originalFile:e,newFile:t,loading:r,verbose:o,additionalInstructions:n,messages:i})=>{let s=await On("Anthropic");o||r.start("Asking Claude 3.7 Sonnet");let a=Hr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Claude 3.7 Sonnet with:
|
|
26
|
+
${JSON.stringify(a,null," ")}`);let c=await bs({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:qr(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 On("OpenAI");o||r.start("Asking OpenAI o3-mini");let a=Hr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting OpenAI o3-mini with:
|
|
27
|
+
${JSON.stringify(a,null," ")}`);let c=await ws({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:qr(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=Hr({originalFile:e,newFile:t,additionalInstructions:n,rePrompt:i!==void 0&&i.length>0});o?.(`Prompting Phi4 with:
|
|
28
|
+
${JSON.stringify(s,null," ")}`);let a=await ks({model:"phi4",prompt:s,messages:i});return o||r.stop("Phi4 updated the file"),a?{content:qr(a),prompt:s.message}:{content:t.content,prompt:s.message}}}};async function ws({prompt:e,maxTokens:t,model:r,apiKey:o,messages:n}){let a=(await new vs({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 bs({prompt:e,messages:t,maxTokens:r,model:o,apiKey:n}){let i=new ms({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 ks({prompt:e,messages:t,model:r}){return (await ys.chat({model:r,messages:[{role:"system",content:e.system},...t??[],{role:"user",content:e.message}]})).message.content}function Hr({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??"":`
|
|
29
29
|
This is my current file ${e.path}:
|
|
30
30
|
<code>
|
|
31
31
|
${e.content}
|
|
@@ -37,63 +37,63 @@ ${t.content}
|
|
|
37
37
|
</code>${r?`<additional-instructions>${r}</additional-instructions>`:""}
|
|
38
38
|
`}}function qr(e){let t=e.trim();if(t.startsWith("```")&&(t=K(t).slice(1).join(`
|
|
39
39
|
`).trim()),t.endsWith("```")){let r=K(t);t=r.slice(0,r.length-1).join(`
|
|
40
|
-
`).trim();}return t}async function
|
|
41
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function
|
|
42
|
-
`,p+=R.length;continue}if(
|
|
43
|
-
`),R.length>
|
|
44
|
-
`;}C&&(p=p+R.length-n,u+=`${H(R.slice(R.length-n),{prefix:
|
|
45
|
-
`),p=x+
|
|
46
|
-
`,p+=
|
|
47
|
-
`,
|
|
48
|
-
`,
|
|
40
|
+
`).trim();}return t}async function On(e){let t=new fe,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 Le=Ft;function In(e){return /^\s+$/g.test(e)}function Vt(e){let t=e.length-1;for(;In(e[t])&&t>=0;){if(e[t]===`
|
|
41
|
+
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e}function Dn({from:e,to:t,changes:r,expand:o=false,maxUnchanged:n=5,colorRemoved:i=A.redBright,colorAdded:s=A.greenBright,colorCharsRemoved:a=A.bgRedBright,colorCharsAdded:c=A.bgGreenBright,prefix:l,onUnchanged:d,intro:m}){let u="",w=No(r,y=>y.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:m});u+=m({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:l,onUnchanged:d,intro:m});let g=y=>A.gray(`${l?.()??""}${Zt(`${y+1+p} `,w)} `);for(let y=0;y<r.length;y++){let h=r[y],j=r[y-1]?.added||r[y-1]?.removed,C=r[y+1]?.added||r[y+1]?.removed;if(!h.added&&!h.removed){if(!o&&h.count!==void 0&&h.count>n){let x=p,R=K(Vt(h.value)),P=0;if(C&&(P+=n),j&&(P+=n),P>=R.length){u+=`${H(R,{prefix:g})}
|
|
42
|
+
`,p+=R.length;continue}if(j&&(u+=`${H(R.slice(0,n),{prefix:g})}
|
|
43
|
+
`),R.length>P){let X=R.length-P;u+=`${H(K(A.gray(`+ ${X} more unchanged (${A.italic("-E to expand")})`)),{prefix:()=>`${l?.()??""}${Zt(" ",w)} `})}
|
|
44
|
+
`;}C&&(p=p+R.length-n,u+=`${H(R.slice(R.length-n),{prefix:g})}
|
|
45
|
+
`),p=x+h.count;continue}u+=`${H(K(Vt(h.value)),{prefix:g})}
|
|
46
|
+
`,p+=h.count??0;continue}let f=x=>x.added?s(Vt(x.value)):x.removed?i(Vt(x.value)):x.value,b=x=>x.added?c(Vt(x.value)):x.removed?a(Vt(x.value)):x.value;if(h.removed&&h.count===1&&r[y+1]?.added&&r[y+1]?.count===1){let R=diffChars(h.value,r[y+1].value).map(P=>b(P)).join("");u+=`${g(0)}${R}`,p+=1,y++;}else In(h.value)?(u+=`${H(K(b(h)),{prefix:x=>`${g(x)}${b({removed:true,value:" ",added:false})}`})}
|
|
47
|
+
`,h.removed||(p+=h.count??0)):(u+=`${H(K(f(h)),{prefix:g})}
|
|
48
|
+
`,h.removed||(p+=h.count??0));}return u.endsWith(`
|
|
49
49
|
`)||(u=u+=`
|
|
50
|
-
`),u}var Qr="latest-version",
|
|
50
|
+
`),u}var Qr="latest-version",xs=3600*1e3;async function Tn({noCache:e=false}={}){try{let t=Ge(),r;if(!e){let i=t.get(Qr);if(i){if(i.expiration>Date.now())return r=i.version,a(r);t.delete(Qr);}}let o=await je("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(Qr,{expiration:Date.now()+xs,version:r}),a(r)}catch(t){return b(`Error getting version: ${t}`)}}async function Ln(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 Bn({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 $e({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 St(e){let t=Fn(e.join(`
|
|
51
51
|
`),{title:"Next Steps",textAlignment:"left",padding:1,borderColor:"gray",borderStyle:{topLeft:stripVTControlCharacters(Qt),bottomLeft:stripVTControlCharacters(Qt),topRight:stripVTControlCharacters(Oo),top:stripVTControlCharacters(Yt),bottom:stripVTControlCharacters(Yt),bottomRight:stripVTControlCharacters(Io),left:stripVTControlCharacters(T),right:stripVTControlCharacters(T)}});return `${T}
|
|
52
52
|
${t}
|
|
53
|
-
`}function
|
|
54
|
-
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function se(){console.clear();let e=await
|
|
55
|
-
`);let i=false,s=e.content,a=n.get(
|
|
56
|
-
`,intro:({from:m,to:u,changes:w,prefix:p})=>{let
|
|
53
|
+
`}function _n(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 As(e,t,r){let o=(await detect$1({cwd:process.cwd()}))?.agent??"npm",n=resolveCommand$1(o,"global",["jsrepo@latest"]),i=[`Update available! ${A.redBright(t)} -> ${A.greenBright(r)}`,`${A.cyan("Changelog")}: https://github.com/jsrepojs/jsrepo/releases/tag/${e}@${r}`,`Run ${A.cyan(`${n?.command} ${n?.args.join(" ")}`)} to update!`,"",`${A.yellowBright("Star")} on GitHub for updates: https://github.com/jsrepojs/jsrepo`];return Fn(i.join(`
|
|
54
|
+
`),{borderColor:"gray",padding:1,margin:1,textAlignment:"center"})}async function se(){console.clear();let e=await Tn();e.isOk()&&Bo.lt(Le.version,e.unwrap())&&console.info(await As(Le.name,Le.version,e.unwrap())),intro(`${A.bgHex("#f7df1e").black(` ${Le.name} `)}${A.gray(` v${Le.version} `)}`);}var An="model-preference";async function Jt({incoming:e,current:t,config:r,options:o}){let n=Ge();process.stdout.write(`${T}
|
|
55
|
+
`);let i=false,s=e.content,a=n.get(An,"Claude 3.5 Sonnet"),c=[];for(;;){let l=diffLines(t.content,s),d=Dn({from:e.path,to:t.path,changes:l,expand:o.expand,maxUnchanged:o.maxUnchanged,prefix:()=>`${T} `,onUnchanged:({from:m,to:u,prefix:w})=>`${w?.()??""}${A.cyan(m)} \u2192 ${A.gray(u)} ${A.gray("(unchanged)")}
|
|
56
|
+
`,intro:({from:m,to:u,changes:w,prefix:p})=>{let g=w.filter(y=>y.added||y.removed).length;return `${p?.()??""}${A.cyan(m)} \u2192 ${A.gray(u)} (${g} change${g===1?"":"s"})
|
|
57
57
|
${p?.()??""}
|
|
58
|
-
`}});if(process.stdout.write(
|
|
58
|
+
`}});if(process.stdout.write(d),(l.length>1||t.content==="")&&(i=o.yes,!o.yes&&!o.no)){let m=[{label:"Accept",value:"accept"},{label:"Reject",value:"reject"}];c.length>0?m.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Iterate)")}`,value:"update-iterate"},{label:`\u2728 ${A.yellow("Update with AI")} \u2728 ${A.gray("(Start over)")}`,value:"update"}):m.push({label:`\u2728 ${A.yellow("Update with AI")} \u2728`,value:"update"});let u=await select({message:"Accept changes?",options:m});if(isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u==="update"||u==="update-iterate"){u==="update"&&(c=[]);let w=await select({message:"Select a model",options:Object.keys(Yr).map(g=>({label:g,value:g})),initialValue:a});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!==a&&n.set(An,w),a=w;let p=await text({message:"Additional instructions:",defaultValue:"None",validate:g=>{if(c.length!==0&&g.trim()==="")return "Please provide additional context so that I know how I can improve."}});isCancel(p)&&(cancel("Canceled!"),process.exit(0));try{let{content:g,prompt:y}=await Yr[a].updateFile({originalFile:t,newFile:{content:u==="update-iterate"?s:e.content,path:e.path},additionalInstructions:p!=="None"?p:void 0,loading:o.loading,verbose:o.verbose,messages:c});s=g,c.push({role:"user",content:y}),c.push({role:"assistant",content:g});}catch(g){o.loading.stop(),log.error(A.red(`Error getting completions: ${g}`)),process.stdout.write(`${T}
|
|
59
59
|
`);continue}s=await Tr({file:{content:s,destPath:t.path},biomeOptions:r.biomeOptions,prettierOptions:r.prettierOptions,formatter:r.formatter,cwd:o.cwd}),process.stdout.write(`${T}
|
|
60
|
-
`);continue}i=u==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function tt(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Mo(e,t,{cwd:n});if(a.size>0||c.size>0){let
|
|
60
|
+
`);continue}i=u==="accept";break}break}return i?{applyChanges:true,updatedContent:s}:{applyChanges:false}}async function tt(e,t,{yes:r,no:o=false,cwd:n,pm:i,ignoreWorkspace:s=false}){let{dependencies:a,devDependencies:c}=Mo(e,t,{cwd:n});if(a.size>0||c.size>0){let d=r;if(!r&&!o){let m=await confirm({message:"Would you like to install dependencies?",initialValue:true});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),d=m;}if(d)return a.size>0&&await Xr({pm:i,deps:Array.from(a),dev:false,cwd:n,ignoreWorkspace:s}),c.size>0&&await Xr({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 Mn(e){let t=A.dim(T),r=A.green(jo),o=A.green(Po),n=A.red(Eo);process.stdout.write(`${t}
|
|
61
61
|
`),process.stdout.write(`${r} ${e}
|
|
62
|
-
`);let i="",s="",a=(l=false)=>{if(!s)return;let
|
|
63
|
-
`).reduce((w,p)=>w+Math.ceil(p.length/
|
|
64
|
-
`).slice(-l);s="";for(let m of
|
|
65
|
-
`;process.stdout.write(
|
|
62
|
+
`);let i="",s="",a=(l=false)=>{if(!s)return;let d=process.stdout.columns,u=s.split(`
|
|
63
|
+
`).reduce((w,p)=>w+Math.ceil(p.length/d),0)+(l?1:0);process.stdout.write(cursor.up(u)),process.stdout.write(erase.down());},c=(l=0)=>{let d=i.split(`
|
|
64
|
+
`).slice(-l);s="";for(let m of d)s+=`${t} ${m}
|
|
65
|
+
`;process.stdout.write(A.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}
|
|
66
66
|
`),c();},success(l){a(true),process.stdout.write(`${o} ${l}
|
|
67
|
-
`);}}}async function Xr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Kr[e]["install-as-dev-dependency"]);let s=Kr[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(
|
|
68
|
-
`;c.success(`Installed ${
|
|
67
|
+
`);}}}async function Xr({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=false}){let i=[...t];r&&i.push(Kr[e]["install-as-dev-dependency"]);let s=Kr[e]["no-workspace"];n&&s&&i.push(s);let a=resolveCommand$1(e,"add",i);a==null&&program.error(A.red(`Could not resolve add command for '${e}'.`));let c=Mn(`Installing dependencies with ${e}...`);try{let l=x(a.command,[...a.args],{nodeOptions:{cwd:o}});for await(let d of l)c.text=`${d}
|
|
68
|
+
`;c.success(`Installed ${A.cyan(t.join(", "))}`);}catch{c.fail("Failed to install dependencies"),process.exit(2);}}var _s=/\{\{([^/]+)\/([^}]+)\}\}/g;function Vn({template:e,config:t,destPath:r,cwd:o}){let n=ne.join(r,"../");return e.replace(_s,(i,s,a)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let c=ne.relative(n,ne.join(o,t.paths["*"],s,a));return c.startsWith(".")?c:`./${c}`}return ne.join(t.paths["*"],s,a)}if(t.paths[s].startsWith(".")){let c=ne.relative(n,ne.join(o,t.paths[s],a));return c.startsWith(".")?c:`./${c}`}return ne.join(t.paths[s],a)})}async function ar({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:a$1}){let c=ht.find(d=>d.matches(e.destPath)),l=e.content;if(c){t.watermark&&(l=`${c.comment(o)}
|
|
69
69
|
|
|
70
|
-
${l}`),a$1?.(`Formatting ${
|
|
71
|
-
${
|
|
72
|
-
`);let s=i.map((a,c)=>{let l=i.length-1===c,
|
|
73
|
-
${T} ${l?"":T} ${
|
|
70
|
+
${l}`),a$1?.(`Formatting ${A.bold(e.destPath)}`);try{l=await c.format(l,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i,cwd:s});}catch(d){return b(`Error formatting ${A.bold(e.destPath)} ${d}`)}}for(let[d,m]of Object.entries(r)){let u=Vn({template:m,config:t,destPath:e.destPath,cwd:s}),w=new RegExp(`(['"])${Ws(d)}\\1`,"g");l=l.replaceAll(w,`$1${u}$1`);}return a(l)}async function Tr({file:e,formatter:t,prettierOptions:r,biomeOptions:o,cwd:n}){let i=ht.find(a=>a.matches(e.destPath)),s=e.content;if(i)try{s=await i.format(e.content,{filePath:e.destPath,formatter:t,prettierOptions:r,biomeOptions:o,cwd:n});}catch{return s}return s}function Un(e){let t=[".js",".ts",".cjs",".mjs"];if(!l(e,t))return;let r=ne.dirname(e),o=me.readdirSync(r),n=ne.parse(e);for(let i of o)if(l(i,t)&&ne.parse(i).name===n.name)return ne.join(r,i)}async function Pt({formatter:e,cwd:t}){let r=null;e==="prettier"&&(r=await Uo.resolveConfig(ne.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=ne.join(t,"biome.json");me.existsSync(n)&&(o=JSON.parse(me.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}}function cr(e){return `Installed from ${e}`}function Ut(e,t,r){if(!t.peerDependencies)return;let o=Wr(ne.join(r,"package.json")).match(s=>s,s=>{s.endsWith("doesn't exist")&&program.error(`Couldn't find your ${A.bold("package.json")}. Please create one.`),program.error(A.red(s));}),n={...o.dependencies,...o.devDependencies},i=[];for(let[s,a]of Object.entries(t.peerDependencies)){let c,l;typeof a=="string"?c=a:(c=a.version,l=a.message);let d=n[s];if(!d){i.push({name:s,expected:c,message:l,version:d,exists:false});continue}Bo.satisfies(yr(d),c)||i.push({name:s,expected:c,message:l,version:d,exists:true});}if(i.length>0){process.stdout.write(`${T}
|
|
71
|
+
${A.yellow("\u25B2")} ${Do} Issues with ${A.bold(e.url)} peer dependencies
|
|
72
|
+
`);let s=i.map((a,c)=>{let l=i.length-1===c,d;a.exists?d=`${A.yellowBright("x unmet peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)} >> found ${A.yellowBright.bold(a.version)}`:d=`${A.red("x missing peer")} need ${A.bold(`${a.name}@`)}${A.greenBright.bold(a.expected)}`;let m=`${T} ${l?To:Qt}${Yt} ${d}`;return a.message?`${m}
|
|
73
|
+
${T} ${l?"":T} ${A.gray(a.message)}`:m}).join(`
|
|
74
74
|
`);process.stdout.write(`${s}
|
|
75
|
-
`);}}var
|
|
76
|
-
`),process.stdout.write(`${T} ${
|
|
77
|
-
`);for(let G of j){let oe=G.content.match(Ee=>Ee,Ee=>program.error(F.red(Ee))),ve=ir(G.name,$.block,b,t.cwd),it=(await ar({file:{content:oe,destPath:ve},biomeOptions:d,prettierOptions:C,config:s,imports:$.block._imports_,watermark:cr($.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(Ee=>Ee,Ee=>program.error(F.red(Ee))),z="";me.existsSync(ve)&&(z=me.readFileSync(ve).toString());let ee=await Vt({config:{biomeOptions:d,prettierOptions:C,formatter:s.formatter},current:{path:ve,content:z},incoming:{path:c(A,G.name),content:it},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});ee.applyChanges&&(Y.push(Pn({destination:ve,content:ee.updatedContent,block:$.block})),x.add(v));}continue}}$.files.then(j=>{j.map(async G=>{let oe=G.content.match(z=>z,z=>program.error(F.red(z))),ve=ir(G.name,$.block,b,t.cwd),it=ar({file:{content:oe,destPath:ve},biomeOptions:d,prettierOptions:C,config:s,imports:$.block._imports_,watermark:cr($.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(z=>(z.isErr()&&program.error(F.red(z.unwrapErr())),{destination:ve,content:z.unwrap(),block:$.block}));Y.push(it);});}),x.add(v);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(E.map($=>$.files)),await Promise.all(Y.map(async $=>{let A=await $,v=ne.dirname(A.destination);me.existsSync(v)||(r(`Creating directory ${F.bold(v)}`),me.mkdirSync(v,{recursive:true})),r(`Writing to ${F.bold(A.destination)}`),me.writeFileSync(A.destination,A.content);})),o.stop(`Added blocks ${F.cyan(Array.from(x).join(", "))}`));let U=(await detect({cwd:t.cwd}))?.agent??"npm",Z=await tt(g,y,{yes:t.yes,cwd:t.cwd,pm:U});if(Z.dependencies.size>0||Z.devDependencies.size>0){let $=[];if(!Z.installed){if(g.size>0){let v=resolveCommand(U,"add",[...g]);$.push(`Install dependencies \`${F.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(y.size>0){let v=resolveCommand(U,"add",[...y,"-D"]);$.push(`Install dev dependencies \`${F.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}$=$.map((v,V)=>`${V+1}. ${v}`),Z.installed||$.push(""),$.push("Import and use the blocks!");let A=Rt($);process.stdout.write(A);}}function Xn(e){return new Promise(t=>setTimeout(t,e))}var ra=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),oo=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(ra,e);await se(),await oa(t),outro(F.green("All done!"));});async function oa(e){let t=new fe;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Ve}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Ve}!`);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=ta.machineIdSync(true),o;try{let a=await Se(`${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(F.red(a));}log.step(`Sign in at ${F.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=ke(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(F.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await Xn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await Se(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 ${Ve}!`);break}catch{}}}var aa=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),no=new Command("build").description(`Builds the provided --dirs in the project root into a \`${m}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--output-dir <dir>","The directory to output the registry to. (Copies jsrepo-manifest.json + all required files)").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--include-docs","Include docs files (*.mdx, *.md) in the registry.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(aa,e);await se(),await ca(t),outro(F.green("All done!"));});async function ca(e){let t=p=>{e.verbose&&console.info(`${Oe} ${p}`);},r=ke({verbose:e.verbose?t:void 0}),o$1=[],n=Ft(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,includeDocs:e.includeDocs??false};let h=p;return e.dirs&&(h.dirs=e.dirs),e.outputDir&&(h.outputDir=e.outputDir),e.doNotListBlocks&&(h.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(h.doNotListCategories=e.doNotListCategories),e.listBlocks&&(h.listBlocks=e.listBlocks),e.listCategories&&(h.listCategories=e.listCategories),e.includeBlocks&&(h.includeBlocks=e.includeBlocks),e.includeCategories&&(h.includeCategories=e.includeCategories),e.excludeBlocks&&(h.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(h.excludeCategories=e.excludeCategories),e.excludeDeps&&(h.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(h.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(h.preview=e.preview),e.includeDocs!==void 0&&(h.includeDocs=e.includeDocs),h.rules={...er,...h.rules},h},p=>program.error(F.red(p))),i;n.outputDir?i=ne.join(e.cwd,n.outputDir):i=e.cwd;let s=ne.join(i,m);if(e.output&&me.existsSync(s)){if(n.outputDir){let p=o(me.readFileSync(s).toString());if(p.isOk())for(let h of p.unwrap().categories)for(let y of h.blocks){let g=ne.join(i,y.directory);me.existsSync(g)&&me.rmSync(g,{recursive:true});}}me.rmSync(s);}let a=sa();try{let p=me.readFileSync(ne.join(e.cwd,".gitignore")).toString();a.add(p);}catch{}a.add(Er);for(let p of n.dirs){let h=ne.join(e.cwd,p);r.start(`Building ${F.cyan(h)}`);let y=Cr(h,{cwd:e.cwd,ignore:a,config:n});for(let g of y){if(o$1.find(S=>S.name===g.name)!==void 0){console.warn(`${T} ${le} Skipped adding \`${F.cyan(`${p}/${g.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(g);}r.stop(`Built ${F.cyan(h)}`);}let c=Rr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:f,errors:m$1}=$r(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(f.length>0||m$1.length>0)&&console.log(T);for(let p of f)console.log(p);if(m$1.length>0){for(let p of m$1)console.log(p);program.error(F.red(`Completed checking manifest with ${F.bold(`${m$1.length} error(s)`)} and ${F.bold(`${f.length} warning(s)`)}`));}let[u,w]=Sr(l.categories);if(l.categories=u,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n.preview){let p=l.categories.flatMap(h=>h.blocks.filter(y=>y.list).map(y=>`${F.cyan(y.category)}/${y.name}`));log.message(`${F.yellow("Preview")}:`);for(let h of p)console.log(`${T} \u25FB ${h}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${F.cyan(i)}\``),l.configFiles)for(let p of l.configFiles){let h=ne.join(e.cwd,p.path),y=ne.join(i,p.path),g=ne.join(y,"../");me.existsSync(g)||me.mkdirSync(g,{recursive:true}),me.copyFileSync(h,y);}for(let p of l.categories)for(let h of p.blocks){let y=ne.join(e.cwd,h.directory),g=ne.join(i,h.directory);for(let S of h.files){let C=ne.join(g,S,"../");me.existsSync(C)||me.mkdirSync(C,{recursive:true}),me.copyFileSync(ne.join(y,S),ne.join(g,S));}}r.stop(`Copied registry files to \`${F.cyan(i)}\``);}r.start(`Writing output to \`${F.cyan(s)}\``),me.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${F.cyan(s)}\``);}}var ga=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),ao=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(ga,t);await se(),await ha(e,o,r);});async function ha(e,t,r){let o=v=>{t.verbose&&console.info(`${Oe} ${v}`);},n=e,i=ke({verbose:t.verbose?o:void 0}),s=be(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let f=n?z(n):void 0;if(n&&f){let{url:v}=f.parse(n,{fullyQualified:true});if(!l.find(V=>V===v)){if(!t.allow){let V=await confirm({message:`Allow ${Ze} to download and run code from ${F.cyan(v)}?`,initialValue:true});(isCancel(V)||!V)&&(cancel("Canceled!"),process.exit(0));}l=[v];}}if(!t.allow&&t.repo){let v=await confirm({message:`Allow ${Ze} to download and run code from ${F.cyan(t.repo)}?`,initialValue:true});(isCancel(v)||!v)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(F.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${F.bold("--repo")}\` flag to specify a registry.`)),program.error(F.red(`There were no repos present in your config and you didn't provide the \`${F.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${F.cyan(l.join(", "))}`);let m=(await Ke(l,{noCache:!t.cache})).match(v=>v,({repo:v,message:V})=>{i.stop(`Failed to get info for ${F.cyan(v)}`),program.error(F.red(V));}),u=(await bt(m,{verbose:t.verbose?o:void 0})).match(v=>v,({repo:v,message:V})=>{i.stop(`Failed fetching scripts from ${F.cyan(v)}`),program.error(F.red(V));});if(i.stop(`Retrieved scripts from ${F.cyan(l.join(", "))}`),!n){let v=await select({message:"Select which script to run.",options:Array.from(u.entries()).filter(([V,j])=>j.list).map(([V,j])=>{let G;return l.length>1?G=`${F.cyan(c(j.sourceRepo.url,j.category))}/${j.name}`:G=`${F.cyan(j.category)}/${j.name}`,{label:G,value:V}})});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),n=v;}let w=(await $t([n],u,m)).match(v=>v,v=>program.error(v)),p="temp-jsrepo-exec",h=`./${p}/${encodeURIComponent(n)}`,y=ne.join(process.cwd(),h);c$1.paths["*"]=h,me.mkdirSync(y,{recursive:true});let g=(await detect({cwd:process.cwd()}))?.agent??"npm",S=[],C=new Set,d=new Set,b=Ue(c$1.paths,t.cwd);b.isErr()&&program.error(F.red(b.unwrapErr()));let x$1=b.unwrap(),R=[];for(let v of w){let V=`${v.sourceRepo.url}/${v.category}/${v.name}`,j=`${v.category}/${v.name}`,G=v.sourceRepo,oe=ne.join(t.cwd,x$1["*"],v.category);R.push(j),S.push({run:async({message:ve})=>{ve(`Adding ${F.cyan(V)}`),me.mkdirSync(oe,{recursive:true});let it=[],z=async ee=>{let Ee=await ze(G,ee);return Ee.isErr()&&(i.stop(F.red(`Error fetching ${F.bold(ee)}`)),program.error(F.red(`There was an error trying to get ${V}`))),Ee.unwrap()};for(let ee of v.files){if(!c$1.includeTests&&ct(ee))continue;let Ee=ne.join(v.directory,ee),qt;v.subdirectory?qt=ne.join(oe,v.name,ee):qt=ne.join(oe,ee);let gi=await z(Ee),hi=qt.slice(0,qt.length-ee.length);me.mkdirSync(hi,{recursive:true}),it.push({content:gi,destPath:qt});}for(let ee of it)me.writeFileSync(ee.destPath,ee.content);if(c$1.includeTests&&v.tests){let{devDependencies:ee}=JSON.parse(me.readFileSync(ne.join(t.cwd,"package.json")).toString());(ee===void 0||ee.vitest===void 0)&&C.add("vitest");}for(let ee of v.devDependencies)C.add(ee);for(let ee of v.dependencies)d.add(ee);}});}if(await _n({startMessage:"Adding blocks",stopMessage:`Added ${F.cyan(R.join(", "))}`,loading:i,tasks:S}),d.size>0||C.size>0){let v={name:"temp-package",type:"module",version:"0.0.1"},V=ne.join(y,"package.json");me.writeFileSync(V,JSON.stringify(v,null," "));}await tt(d,C,{yes:true,no:false,cwd:y,pm:g,ignoreWorkspace:true});let Y=r.parent.rawArgs.indexOf("--"),U=[];Y!==-1&&(U=r.parent.rawArgs.slice(Y+1)),o(`Passing args ${F.cyan(U.join(" "))}`),console.clear();let Z=w[0],$;Z.subdirectory?$=ne.join(y,`${Z.category}/${Z.name}/index.js`):$=ne.join(y,`${Z.category}/${Z.name}.js`);let A=resolveCommand(g,"execute",["tsx",$,...U]);A||program.error(F.red("Error resolving run command!"));try{let v=x(A.command,A.args,{nodeOptions:{cwd:process.cwd()}});for await(let V of v)process.stdout.write(`${V}
|
|
78
|
-
`);}finally{me.rmSync(ne.join(process.cwd(),p),{recursive:true,force:true});}}var
|
|
75
|
+
`);}}var Ys=k.object({watermark:k.optional(k.boolean()),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(k.union([k.literal("prettier"),k.literal("biome"),k.literal("none")])),paths:k.optional(k.record(k.string(),k.string())),expand:k.boolean(),maxUnchanged:k.number(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),eo=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").addOption(new Option("--formatter <choice>","The formatter to use when adding blocks.").choices(["prettier","biome","none"])).addOption(new Option("--watermark <choice>","Include a watermark at the top of added files.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--tests <choice>","Include tests when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).addOption(new Option("--docs <choice>","Include docs when adding blocks.").choices(["true","false"]).argParser(e=>e==="true")).option("--paths <category=path,category=path>","The paths where categories should be added to your project.",sr,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,10),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Ys,t);await se(),await Qs(e,r),outro(A.green("All done!"));});async function Qs(e,t){let r=$=>{t.verbose&&console.info(`${Oe} ${$}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=$e({verbose:t.verbose?r:void 0}),n=ke(t.cwd),i=n.isErr(),s;if(n.isErr()){let $=t.yes;if(!t.yes){let L=await confirm({message:`You don't have ${Ze} initialized in your project. Do you want to continue?`,initialValue:false});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),$=L;}$||(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./src/blocks"},repos:[]};}else s=n.unwrap();s.formatter=t.formatter!==void 0&&t.formatter!=="none"?t.formatter:s.formatter,s.watermark=t.watermark!==void 0?t.watermark:s.watermark,s.includeTests=t.tests!==void 0?t.tests:s.includeTests,s.includeDocs=t.docs!==void 0?t.docs:s.includeDocs,s.paths=t.paths!==void 0?{...s.paths,...t.paths}:s.paths;let a=s.repos,c$1=new Set,l=false;t.repo&&(a=[t.repo]);for(let $ of e){let L=z($);if(!L){l=true;continue}let{url:v}=L.parse($,{fullyQualified:true});if(!(!s.repos.find(S=>S===v)&&!c$1.has(v))){if(!t.allow){let S=await confirm({message:`Allow ${Ze} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(S)||!S)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}c$1.add(v);}if(!l&&e.length>0&&(a=Array.from(c$1)),!t.allow&&t.repo){let $=await confirm({message:`Allow ${Ze} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel($)||!$)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(i&&program.error(A.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${A.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(a.join(", "))}`);let d=(await Ke(a,{noCache:!t.cache})).match($=>$,({repo:$,message:L})=>{o.stop(`Failed to get info for ${A.cyan($)}`),program.error(A.red(L));});r(`Resolved ${A.cyan(a.join(", "))}`),r(`Fetching blocks from ${A.cyan(a.join(", "))}`);let m=(await Mt(d,{verbose:t.verbose?r:void 0,noCache:!t.cache})).match($=>$,({repo:$,message:L})=>{o.stop(`Failed fetching blocks from ${A.cyan($)}`),program.error(A.red(L));}),u=_t(m);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(a.join(", "))}`),r(`Retrieved blocks from ${A.cyan(a.join(", "))}`);for(let $ of m)Ut($.state,$.manifest,t.cwd);let w=Ct(u,s,t.cwd).map($=>$.specifier),p=e;if(p.length===0){let $=await multiselect({message:"Select which blocks to add.",options:Array.from(u.entries()).filter(([L,v])=>v.list).map(([L,v])=>{let _=`${v.category}/${v.name}`,S=w.indexOf(_)!==-1,G;return a.length>1?G=`${A.cyan(c(v.sourceRepo.url,v.category))}/${v.name}`:G=`${A.cyan(v.category)}/${v.name}`,{label:S?A.gray(G):G,value:L,hint:S?"Installed":void 0}}),required:true});isCancel($)&&(cancel("Canceled!"),process.exit(0)),p=$;}r(`Installing blocks ${A.cyan(p.join(", "))}`);let g=(await xt(p,u,d)).match($=>$,$=>program.error($)),y=new Set,h=new Set,j=Ge();if(i){let $=`${t.cwd}-zero-config`,L=k.safeParse(Ur,j.get($)),v=L.success?L.output:s,_=Array.from(new Set(g.map(S=>S.category)));if(t.paths===void 0)for(let S of _){let G=await text({message:`Where would you like to add ${A.cyan(S)}?`,placeholder:v?v.paths[S]:`./src/${S}`,initialValue:v?v.paths[S]:`./src/${S}`,defaultValue:v?v.paths[S]:`./src/${S}`,validate(oe){if(oe.trim()==="")return "Please provide a value"}});isCancel(G)&&(cancel("Canceled!"),process.exit(0)),s.paths[S]=G;}if(!t.yes&&t.tests===void 0){let S=await confirm({message:"Include tests?",initialValue:v.includeTests});isCancel(S)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=S;}if(!t.yes&&t.watermark===void 0){let S=await confirm({message:"Add watermark?",initialValue:v.watermark});isCancel(S)&&(cancel("Canceled!"),process.exit(0)),s.watermark=S;}if(t.formatter===void 0){let S="none";me.existsSync(ne.join(t.cwd,".prettierrc"))&&(S="prettier"),me.existsSync(ne.join(t.cwd,"biome.json"))&&(S="biome");let G=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(oe=>({value:oe.toLowerCase(),label:oe})),initialValue:S==="none"?v.formatter?v.formatter:"none":S});isCancel(G)&&(cancel("Canceled!"),process.exit(0)),G!=="none"&&(s.formatter=G);}j.set($,s),w=Ct(u,s,t.cwd).map(S=>S.specifier);}let{prettierOptions:C,biomeOptions:f}=await Pt({formatter:s.formatter,cwd:t.cwd}),b=Ue(s.paths,t.cwd).match($=>$,$=>program.error(A.red($))),x=new Set,R,P=Wt(g,s),X=[];for(let $ of P){let L=c($.block.sourceRepo.url,$.block.category,$.block.name),v=`${$.block.category}/${$.block.name}`;r(`Setting up ${L}`);let _=w.find(S=>v===S);s.includeTests&&$.block.tests&&(r("Trying to include tests"),y.add("vitest"));for(let S of $.block.devDependencies)y.add(S);for(let S of $.block.dependencies)h.add(S);if(_&&!t.yes&&!R){if(R===void 0){let S=g.map(oe=>`${oe.category}/${oe.name}`).filter(oe=>w.find(ve=>ve===oe));log.warn(`The following components ${A.bold.yellow("already exist")}: ${A.cyan(_n(S))}`);let G=await confirm({message:`Would you like to ${A.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:false});isCancel(G)&&(cancel("Canceled!"),process.exit(0)),R=G;}if(!R){let S=await $.files;process.stdout.write(`${T}
|
|
76
|
+
`),process.stdout.write(`${T} ${L}
|
|
77
|
+
`);for(let G of S){let oe=G.content.match(z=>z,z=>program.error(A.red(z))),ve=ir(G.name,$.block,b,t.cwd),it=(await ar({file:{content:oe,destPath:ve},biomeOptions:f,prettierOptions:C,config:s,imports:$.block._imports_,watermark:cr($.block.sourceRepo.url),verbose:r,cwd:t.cwd})).match(z=>z,z=>program.error(A.red(z))),we="";me.existsSync(ve)&&(we=me.readFileSync(ve).toString());let ee=await Jt({config:{biomeOptions:f,prettierOptions:C,formatter:s.formatter},current:{path:ve,content:we},incoming:{path:c(L,G.name),content:it},options:{...t,loading:o,no:false,verbose:t.verbose?r:void 0}});ee.applyChanges&&(X.push(jn({destination:ve,content:ee.updatedContent,block:$.block})),x.add(v));}continue}}$.files.then(S=>{S.map(async G=>{let oe=G.content.match(we=>we,we=>program.error(A.red(we))),ve=ir(G.name,$.block,b,t.cwd),it=ar({file:{content:oe,destPath:ve},biomeOptions:f,prettierOptions:C,config:s,imports:$.block._imports_,watermark:cr($.block.sourceRepo.url),verbose:r,cwd:t.cwd}).then(we=>(we.isErr()&&program.error(A.red(we.unwrapErr())),{destination:ve,content:we.unwrap(),block:$.block}));X.push(it);});}),x.add(v);}x.size===0?log.success("Nothing to update"):(o.start("Adding blocks"),await Promise.all(P.map($=>$.files)),await Promise.all(X.map(async $=>{let L=await $,v=ne.dirname(L.destination);me.existsSync(v)||(r(`Creating directory ${A.bold(v)}`),me.mkdirSync(v,{recursive:true})),r(`Writing to ${A.bold(L.destination)}`),me.writeFileSync(L.destination,L.content);})),o.stop(`Added blocks ${A.cyan(Array.from(x).join(", "))}`));let J=(await detect({cwd:t.cwd}))?.agent??"npm",Z=await tt(h,y,{yes:t.yes,cwd:t.cwd,pm:J});if(Z.dependencies.size>0||Z.devDependencies.size>0){let $=[];if(!Z.installed){if(h.size>0){let v=resolveCommand(J,"add",[...h]);$.push(`Install dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(y.size>0){let v=resolveCommand(J,"add",[...y,"-D"]);$.push(`Install dev dependencies \`${A.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}$=$.map((v,_)=>`${_+1}. ${v}`),Z.installed||$.push(""),$.push("Import and use the blocks!");let L=St($);process.stdout.write(L);}}function Qn(e){return new Promise(t=>setTimeout(t,e))}var na=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),oo=new Command("auth").description("Authenticate to jsrepo.com").option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(na,e);await se(),await ia(t),outro(A.green("All done!"));});async function ia(e){let t=new fe;if(e.logout){t.delete("jsrepo"),log.success(`Logged out of ${Ve}!`);return}if(e.token!==void 0){t.set("jsrepo",e.token),log.success(`Logged into ${Ve}!`);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=oa.machineIdSync(true),o;try{let a=await je(`${w}/api/login/device`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({hardwareId:r})});if(!a.ok)throw new Error("There was an error creating the session");o=(await a.json()).id;}catch(a){program.error(A.red(a));}log.step(`Sign in at ${A.cyan(`${w}/login/device/${o}`)}`);let n=1e3*60*60*15,i=$e(),s=setTimeout(()=>{i.stop("You never signed in."),program.error(A.red("Session timed out try again!"));},n);for(i.start("Waiting for you to sign in...");;){await Qn(5e3);let a=`${w}/api/login/device/${o}`;try{let c=await je(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 ${Ve}!`);break}catch{}}}var la=k.object({dirs:k.optional(k.array(k.string())),outputDir:k.optional(k.string()),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),includeFiles:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),preview:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),output:k.boolean(),verbose:k.boolean(),cwd:k.string()}),no=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("--include-files [filePatterns...]","Additional files to include in the manifest. (Supports glob patterns)").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--preview","Display a preview of the blocks list.").option("--include-docs","Include docs files (*.mdx, *.md) in the registry.").option("--no-output",`Do not output a \`${m}\` file.`).option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(la,e);await se(),await da(t),outro(A.green("All done!"));});async function da(e){let t=p=>{e.verbose&&console.info(`${Oe} ${p}`);},r=$e({verbose:e.verbose?t:void 0}),o$1=[],n=Lt(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??[],includeFiles:e.includeFiles??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,preview:e.preview,includeDocs:e.includeDocs??false};let g=p;return e.dirs&&(g.dirs=e.dirs),e.outputDir&&(g.outputDir=e.outputDir),e.doNotListBlocks&&(g.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(g.doNotListCategories=e.doNotListCategories),e.listBlocks&&(g.listBlocks=e.listBlocks),e.listCategories&&(g.listCategories=e.listCategories),e.includeBlocks&&(g.includeBlocks=e.includeBlocks),e.includeCategories&&(g.includeCategories=e.includeCategories),e.includeFiles&&(g.includeFiles=e.includeFiles),e.excludeBlocks&&(g.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(g.excludeCategories=e.excludeCategories),e.excludeDeps&&(g.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(g.allowSubdirectories=e.allowSubdirectories),e.preview!==void 0&&(g.preview=e.preview),e.includeDocs!==void 0&&(g.includeDocs=e.includeDocs),g.rules={...er,...g.rules},g},p=>program.error(A.red(p))),i;n.outputDir?i=ne.join(e.cwd,n.outputDir):i=e.cwd;let s=ne.join(i,m);if(e.output&&me.existsSync(s)){if(n.outputDir){let p=o(me.readFileSync(s).toString());if(p.isOk())for(let g of p.unwrap().categories)for(let y of g.blocks){let h=ne.join(i,y.directory);me.existsSync(h)&&me.rmSync(h,{recursive:true});}}me.rmSync(s);}let a=Hi();try{let p=me.readFileSync(ne.join(e.cwd,".gitignore")).toString();a.add(p);}catch{}a.add(Er);for(let p of n.dirs){let g=ne.join(e.cwd,p);r.start(`Building ${A.cyan(g)}`);let y=Cr(g,{cwd:e.cwd,ignore:a,config:n});for(let h of y){if(o$1.find(j=>j.name===h.name)!==void 0){console.warn(`${T} ${le} Skipped adding \`${A.cyan(`${p}/${h.name}`)}\` because a category with the same name already exists!`);continue}o$1.push(h);}r.stop(`Built ${A.cyan(g)}`);}let c=Rr(n,{cwd:e.cwd}),l=p(o$1,c,n);r.start("Checking manifest");let{warnings:d,errors:m$1}=$r(l,n,e.cwd,n.rules);r.stop("Completed checking manifest."),(d.length>0||m$1.length>0)&&console.log(T);for(let p of d)console.log(p);if(m$1.length>0){for(let p of m$1)console.log(p);program.error(A.red(`Completed checking manifest with ${A.bold(`${m$1.length} error(s)`)} and ${A.bold(`${d.length} warning(s)`)}`));}let[u,w]=Sr(l.categories);if(l.categories=u,w>0&&log.step(`Removed ${w} unused block${w>1?"s":""}.`),n.preview){let p=l.categories.flatMap(g=>g.blocks.filter(y=>y.list).map(y=>`${A.cyan(y.category)}/${y.name}`));log.message(`${A.yellow("Preview")}:`);for(let g of p)console.log(`${T} \u25FB ${g}`);}if(e.output){if(n.outputDir){if(r.start(`Copying registry files to \`${A.cyan(i)}\``),l.configFiles)for(let p of l.configFiles){let g=ne.join(e.cwd,p.path),y=ne.join(i,p.path),h=ne.join(y,"../");me.existsSync(h)||me.mkdirSync(h,{recursive:true}),me.copyFileSync(g,y);}for(let p of l.categories)for(let g of p.blocks){let y=ne.join(e.cwd,g.directory),h=ne.join(i,g.directory);for(let j of g.files){let C=ne.join(h,j,"../");me.existsSync(C)||me.mkdirSync(C,{recursive:true}),me.copyFileSync(ne.join(y,j),ne.join(h,j));}}r.stop(`Copied registry files to \`${A.cyan(i)}\``);}r.start(`Writing output to \`${A.cyan(s)}\``),me.writeFileSync(s,JSON.stringify(l,null," ")),r.stop(`Wrote output to \`${A.cyan(s)}\``);}}var ya=k.objectWithRest({repo:k.optional(k.string()),allow:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()},k.unknown()),ao=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=k.parse(ya,t);await se(),await va(e,o,r);});async function va(e,t,r){let o=v=>{t.verbose&&console.info(`${Oe} ${v}`);},n=e,i=$e({verbose:t.verbose?o:void 0}),s=ke(t.cwd),a=s.isErr(),c$1;s.isErr()?c$1={$schema:"",includeTests:false,includeDocs:false,watermark:true,paths:{"*":"./"},repos:[]}:c$1=s.unwrap();let l=c$1.repos;t.repo&&(l=[t.repo]);let d=n?z(n):void 0;if(n&&d){let{url:v}=d.parse(n,{fullyQualified:true});if(!l.find(_=>_===v)){if(!t.allow){let _=await confirm({message:`Allow ${Ze} to download and run code from ${A.cyan(v)}?`,initialValue:true});(isCancel(_)||!_)&&(cancel("Canceled!"),process.exit(0));}l=[v];}}if(!t.allow&&t.repo){let v=await confirm({message:`Allow ${Ze} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(v)||!v)&&(cancel("Canceled!"),process.exit(0));}l.length===0&&(a&&program.error(A.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${A.bold("--repo")}\` flag to specify a registry.`)),program.error(A.red(`There were no repos present in your config and you didn't provide the \`${A.bold("--repo")}\` flag with a repo.`))),i.start(`Fetching scripts from ${A.cyan(l.join(", "))}`);let m=(await Ke(l,{noCache:!t.cache})).match(v=>v,({repo:v,message:_})=>{i.stop(`Failed to get info for ${A.cyan(v)}`),program.error(A.red(_));}),u=(await kt(m,{verbose:t.verbose?o:void 0,noCache:!t.cache})).match(v=>v,({repo:v,message:_})=>{i.stop(`Failed fetching scripts from ${A.cyan(v)}`),program.error(A.red(_));});if(i.stop(`Retrieved scripts from ${A.cyan(l.join(", "))}`),!n){let v=await select({message:"Select which script to run.",options:Array.from(u.entries()).filter(([_,S])=>S.list).map(([_,S])=>{let G;return l.length>1?G=`${A.cyan(c(S.sourceRepo.url,S.category))}/${S.name}`:G=`${A.cyan(S.category)}/${S.name}`,{label:G,value:_}})});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),n=v;}let w=(await xt([n],u,m)).match(v=>v,v=>program.error(v)),p="temp-jsrepo-exec",g=`./${p}/${encodeURIComponent(n)}`,y=ne.join(process.cwd(),g);c$1.paths["*"]=g,me.mkdirSync(y,{recursive:true});let h=(await detect({cwd:process.cwd()}))?.agent??"npm",j=[],C=new Set,f=new Set,b=Ue(c$1.paths,t.cwd);b.isErr()&&program.error(A.red(b.unwrapErr()));let x$1=b.unwrap(),R=[];for(let v of w){let _=`${v.sourceRepo.url}/${v.category}/${v.name}`,S=`${v.category}/${v.name}`,G=v.sourceRepo,oe=ne.join(t.cwd,x$1["*"],v.category);R.push(S),j.push({run:async({message:ve})=>{ve(`Adding ${A.cyan(_)}`),me.mkdirSync(oe,{recursive:true});let it=[],we=async ee=>{let z=await ze(G,ee);return z.isErr()&&(i.stop(A.red(`Error fetching ${A.bold(ee)}`)),program.error(A.red(`There was an error trying to get ${_}`))),z.unwrap()};for(let ee of v.files){if(!c$1.includeTests&&ct(ee))continue;let z=ne.join(v.directory,ee),ft;v.subdirectory?ft=ne.join(oe,v.name,ee):ft=ne.join(oe,ee);let ui=await we(z),gi=ft.slice(0,ft.length-ee.length);me.mkdirSync(gi,{recursive:true}),it.push({content:ui,destPath:ft});}for(let ee of it)me.writeFileSync(ee.destPath,ee.content);if(c$1.includeTests&&v.tests){let{devDependencies:ee}=JSON.parse(me.readFileSync(ne.join(t.cwd,"package.json")).toString());(ee===void 0||ee.vitest===void 0)&&C.add("vitest");}for(let ee of v.devDependencies)C.add(ee);for(let ee of v.dependencies)f.add(ee);}});}if(await Bn({startMessage:"Adding blocks",stopMessage:`Added ${A.cyan(R.join(", "))}`,loading:i,tasks:j}),f.size>0||C.size>0){let v={name:"temp-package",type:"module",version:"0.0.1"},_=ne.join(y,"package.json");me.writeFileSync(_,JSON.stringify(v,null," "));}await tt(f,C,{yes:true,no:false,cwd:y,pm:h,ignoreWorkspace:true});let X=r.parent.rawArgs.indexOf("--"),J=[];X!==-1&&(J=r.parent.rawArgs.slice(X+1)),o(`Passing args ${A.cyan(J.join(" "))}`),console.clear();let Z=w[0],$;Z.subdirectory?$=ne.join(y,`${Z.category}/${Z.name}/index.js`):$=ne.join(y,`${Z.category}/${Z.name}.js`);let L=resolveCommand(h,"execute",["tsx",$,...J]);L||program.error(A.red("Error resolving run command!"));try{let v=x(L.command,L.args,{nodeOptions:{cwd:process.cwd()}});for await(let _ of v)process.stdout.write(`${_}
|
|
78
|
+
`);}finally{me.rmSync(ne.join(process.cwd(),p),{recursive:true,force:true});}}var ka=k.object({json:k.boolean()}),co=new Command("info").description("Get info about a registry on jsrepo.com").argument("registry","Name of the registry to get the info for i.e. @ieedan/std").option("--json","Output the response in formatted JSON.",false).action(async(e,t)=>{let r=k.parse(ka,t);await $a(e,r);});async function $a(e,t){let o=new fe().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 rs(i,{headers:n});s.ok||(s.status===404?program.error(A.red("Registry not found!")):program.error(A.red(`Error fetching registry! Error: ${s.status} - ${s.statusText}`)));let a=await s.json();if(t.json)return process.stdout.write(JSON.stringify(a,null," "));process.stdout.write(xa(a));}function xa(e){let t=`${A.cyan(`${e.name}@${e.version}`)} | versions: ${A.cyan(e.versions.length.toString())}
|
|
79
79
|
`;e.meta.description&&(t+=`${e.meta.description}
|
|
80
|
-
`),e.meta.homepage&&(t+=`${
|
|
80
|
+
`),e.meta.homepage&&(t+=`${A.blue(e.meta.homepage)}
|
|
81
81
|
`),t+=`
|
|
82
|
-
`,e.meta.tags&&(t+=`keywords: ${e.meta.tags.map(i=>
|
|
82
|
+
`,e.meta.tags&&(t+=`keywords: ${e.meta.tags.map(i=>A.cyan(i)).join(", ")}
|
|
83
83
|
|
|
84
|
-
`);let r=i=>i%3===0,o=e.categories.flatMap(i=>i.blocks).map(i=>i.list?
|
|
84
|
+
`);let r=i=>i%3===0,o=e.categories.flatMap(i=>i.blocks).map(i=>i.list?A.blue(`${i.category}/${i.name}`):A.dim(`${i.category}/${i.name}`)),n=Ao(o)+4;return t+=`blocks:
|
|
85
85
|
${o.map((i,s)=>{let a=r(s+1),c=s+1>=o.length;return a?`${i}
|
|
86
86
|
`:`${Lo(i,n," ")}${c?`
|
|
87
87
|
`:""}`}).join("")}
|
|
88
88
|
`,e.meta.authors&&(t+=`authors:
|
|
89
|
-
${e.meta.authors.map(i=>`- ${
|
|
89
|
+
${e.meta.authors.map(i=>`- ${A.blue(i)}`).join(`
|
|
90
90
|
`)}
|
|
91
91
|
|
|
92
92
|
`),t+=`tags:
|
|
93
|
-
${Object.entries(e.tags).map(([i,s])=>`${
|
|
93
|
+
${Object.entries(e.tags).map(([i,s])=>`${A.blue(i)}: ${s}`).join(`
|
|
94
94
|
`)}
|
|
95
95
|
|
|
96
|
-
`,t}var Sa=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(Jr),paths:k.optional(k.record(k.string(),k.string())),configFiles:k.optional(k.record(k.string(),k.string())),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),buildScript:k.string(),publishScript:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),mo=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").option("--docs","Will include docs with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).addOption(new Option("--paths <category=path>,<category=path>","The paths to install the blocks to.").argParser(sr).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(sr).default({})).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e,10),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Sa,t);if(await se(),r.registry!==void 0&&r.project!==void 0&&program.error(F.red(`You cannot provide both ${F.bold("--project")} and ${F.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${F.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${F.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 ja(e,r):await Ea(r),outro(F.green("All done!"));}),ja=async(e,t)=>{let r=be(t.cwd),o=spinner(),n,i={},s=ft(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(F.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let C=await text({message:"Please enter a default path to install the blocks",validate(d){if(d.trim()==="")return "Please provide a value";if(!d.startsWith("./")){let b="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return b;let x=mt(s,{cwd:t.cwd});if(x&&x(d).length===0)return b}},placeholder:"./src/blocks",initialValue:a});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),a=C;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";me.existsSync(ne.join(t.cwd,".prettierrc"))&&(C="prettier"),me.existsSync(ne.join(t.cwd,"biome.json"))&&(C="biome");let d=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(b=>({value:b.toLowerCase(),label:b})),initialValue:C});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),d!=="none"&&(t.formatter=d);}let c=Array.from(new Set([...e,...t.repos??[],...r.isOk()?r.unwrap().repos:[]])),l=new Set,f=new Set,m=async C=>{let d=await Pa({url:C,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let b of d.dependencies)l.add(b);for(let b of d.devDependencies)f.add(b);n=d.paths,i=d.configFiles;};if(c.length>0)for(let C of c){if(!e.find(d=>d===C)&&r.isOk()&&r.unwrap().repos.find(d=>d===C)){let d=await confirm({message:`Initialize ${C}?`,initialValue:t.yes});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)continue}log.info(`Initializing ${F.cyan(C)}`),await m(C);}for(;!t.yes;){{let d=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(d)&&(cancel("Canceled!"),process.exit(0)),!d)break}let C=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:d=>{if(d.trim().length===0)return "Please provide a value";if(!z(d))return `Invalid provider! Valid providers (${y.map(b=>b.name).join(", ")})`}});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),await m(C),c.push(C);}let u={$schema:`https://unpkg.com/jsrepo@${Le.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,includeDocs:r.isOk()&&t.docs===void 0?r.unwrap().includeDocs:t.docs??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${yt}\``);let{prettierOptions:w,biomeOptions:p}=await jt({formatter:u.formatter,cwd:t.cwd}),h=ne.join(t.cwd,yt),y$1=await wr.format(JSON.stringify(u,null," "),{biomeOptions:p,prettierOptions:w,filePath:h,formatter:u.formatter,cwd:t.cwd});me.existsSync(t.cwd)||me.mkdirSync(t.cwd,{recursive:true}),me.writeFileSync(h,y$1),o.stop(`Wrote config to \`${yt}\`.`);let g=(await detect$1({cwd:t.cwd}))?.agent??"npm",S=await tt(l,f,{yes:t.yes,cwd:t.cwd,pm:g});if(S.dependencies.size>0||S.devDependencies.size>0){let C=[];if(!S.installed){if(l.size>0){let b=resolveCommand$1(g,"add",[...l]);C.push(`Install dependencies \`${F.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(f.size>0){let b=resolveCommand$1(g,"add",[...f,"-D"]);C.push(`Install dev dependencies \`${F.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}C=C.map((b,x)=>`${x+1}. ${b}`),S.installed||C.push(""),C.push(`Add blocks with ${F.cyan("jsrepo add")}!`);let d=Rt(C);process.stdout.write(d);}};async function Pa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new fe,a=z(e);a||program.error(F.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 h=await password({message:"Paste your token",validate(y){if(y.trim()==="")return "Please provide a value"}});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,h);}}i.start(`Fetching manifest from ${F.cyan(e)}`);let f=(await lt(e,{noCache:!n.cache})).match(p=>p,p=>program.error(F.red(p))),m=(await Lt(f)).match(p=>p,p=>program.error(F.red(p)));i.stop(`Fetched manifest from ${F.cyan(e)}`),Jt(f,m,n.cwd);let u$1=[],w=[];if(m.configFiles){let{prettierOptions:p,biomeOptions:h}=await jt({formatter:o,cwd:n.cwd});for(let y of m.configFiles){if(y.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${y.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(u$1.push(...y.dependencies??[]),w.push(...y.devDependencies??[]),!r[y.name])if(n.configFiles?.[y.name])r[y.name]=n.configFiles[y.name];else if(n.yes)y.expectedPath||program.error(F.red(`You must provide a path for ${y.name} when using --yes!`)),r[y.name]=y.expectedPath;else {let x=await text({message:`Where is your ${y.name} file?`,defaultValue:y.expectedPath,initialValue:y.expectedPath,placeholder:y.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[y.name]=x;}let g=ne.join(n.cwd,r[y.name]),S;if(me.existsSync(g))S=me.readFileSync(g).toString();else {let x=ne.dirname(g);if(me.existsSync(x)){let R=Gn(g);if(R){S=me.readFileSync(R).toString();let E=ne.relative(n.cwd,R);log.warn(`Located ${F.bold(r[y.name])} at ${F.bold(E)}`),r[y.name]=E,g=ne.join(n.cwd,E);}}}i.start(`Fetching the ${F.cyan(y.name)} from ${F.cyan(e)}`);let C=(await ze(f,y.path)).match(x=>x,x=>program.error(F.red(x))),d=await Tr({file:{content:C,destPath:g},biomeOptions:h,prettierOptions:p,formatter:o,cwd:n.cwd});i.stop(`Fetched the ${F.cyan(y.name)} from ${F.cyan(e)}`);let b=n.yes||S===void 0;if(S){if(!n.yes){let x=c(f.url,y.name),R=await Vt({config:{biomeOptions:h,prettierOptions:p,formatter:o},current:{content:S,path:g},incoming:{content:d,path:x},options:{...n,loading:i,no:false}});R.applyChanges&&(b=true,S=R.updatedContent);}}else {let x=ne.dirname(g);me.existsSync(x)||me.mkdirSync(x,{recursive:true}),S=d;}b&&S&&(i.start(`Writing ${F.cyan(y.name)} to ${F.cyan(g)}`),me.writeFileSync(g,S),i.stop(`Wrote ${F.cyan(y.name)} to ${F.cyan(g)}`));}}if(!n.yes){let p=await multiselect({message:"Which category paths would you like to configure?",options:m.categories.map(h=>({label:h.name,value:h.name,hint:m.defaultPaths?.[h.name]?`Default: ${m.defaultPaths?.[h.name]}`:void 0})),required:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p.length>0)for(let h of p){let y=t[h]??m.defaultPaths?.[h],g=await text({message:`Where should ${h} be added in your project?`,validate(S){if(S.trim()==="")return "Please provide a value"},placeholder:y||`./src/${h}`,defaultValue:y,initialValue:y});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),t[h]=g;}}for(let p of m.categories){if(t[p.name]!==void 0)continue;let h=m.defaultPaths?.[p.name];h&&(t[p.name]=h);}return {paths:t,configFiles:r,dependencies:u$1,devDependencies:w}}var Ea=async e=>{let t=spinner(),r=ne.join(e.cwd,"package.json");me.existsSync(r)||program.error(F.red(`Couldn't find your ${F.bold("package.json")}!`));let o=Ft(e.cwd).match(p=>p,p=>program.error(F.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,includeDocs:false}),o.$schema=`https://unpkg.com/jsrepo@${Le.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let h=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)break}let p=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:h=>{if(h.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(p);}let n=JSON.parse(me.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let p=await confirm({message:`Configure to publish to ${Ve}?`,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:h=>{if(h.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 ni(e.publishScript,n,e,"release:registry");}else e.buildScript=await ni(e.buildScript,n,e,"build:registry");let s=n.devDependencies&&n.devDependencies.jsrepo!==void 0,a=(await detect$1({cwd:"cwd"}))?.agent??"npm",c="jsrepo build",l="jsrepo publish";n.scripts===void 0&&(n.scripts={}),i?n.scripts[e.publishScript]=l:n.scripts[e.buildScript]=c;let f=[];f.push({loadingMessage:"Adding script to package.json",completedMessage:"Added script to package.json",run:async()=>{try{me.writeFileSync(r,JSON.stringify(n,null," "));}catch(p){program.error(F.red(`Error writing to \`${F.bold(r)}\`. Error: ${p}`));}}}),f.push({loadingMessage:`Writing config to \`${F.cyan(vt)}\``,completedMessage:`Wrote config to \`${F.cyan(vt)}\``,run:async()=>{let p=ne.join(e.cwd,vt);try{me.writeFileSync(ne.join(p),JSON.stringify(o,null," "));}catch(h){program.error(F.red(`Error writing to \`${F.bold(p)}\`. Error: ${h}`));}}}),await Bn(f,{loading:t});let m=s;s||(m=(await tt(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let u=[];if(!m){let p=resolveCommand$1(a,"add",["jsrepo","-D"]);u.push(`Install ${Ze} as a dev dependency \`${F.cyan(`${p?.command} ${p?.args.join(" ")}`)}\``);}if(u.push(`Add categories to \`${F.cyan(o.dirs.join(", "))}\`.`),i){let p=resolveCommand$1(a,"run",[e.publishScript]);u.push(`Run \`${F.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to publish the registry.`);}else {let p=resolveCommand$1(a,"run",[e.buildScript]);u.push(`Run \`${F.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to build the registry.`);}u=u.map((p,h)=>`${h+1}. ${p}`);let w=Rt(u);process.stdout.write(w);};async function ni(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${F.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 Ta=new ValibotJsonSchemaAdapter,Na=k.object({registries:k.pipe(k.optional(k.array(k.string())),k.metadata({description:"Registries to list components from. If not provided will use the registries in the users jsrepo.json file."})),cwd:k.pipe(k.string(),k.metadata({description:"The current working directory of the users project."}))}),Aa=k.object({registry:k.pipe(k.string(),k.metadata({description:"Registry for the component."})),component:k.pipe(k.string(),k.metadata({description:"The component to get the code for. Format: <category>/<block>"})),includeTests:k.pipe(k.optional(k.boolean()),k.metadata({description:"Should tests be included with the component code."})),includeDocs:k.pipe(k.optional(k.boolean()),k.metadata({description:"Should docs be included with the component code."}))}),Fa=k.object({registry:k.pipe(k.string(),k.metadata({description:"Registry to list config files from."})),requiredOnly:k.pipe(k.optional(k.boolean()),k.metadata({description:"When true only returns the config files required for the registry to work properly."}))}),La=k.object({query:k.pipe(k.string(),k.metadata({description:"A term to search for the registries by."}))});async function Ba({registries:e,cwd:t}){if(!e){let n=be(t).match(i=>i,()=>{throw new Error("Could not find your configuration file! Please provide `registries`.")});if(n.repos.length===0)throw new Error("No registries (repos) in your configuration file! Please provide `registries`.");e=n.repos;}let r=(await Ke(e)).match(n=>n,n=>{throw new Error(`Error getting registry state for ${n.repo}: ${n.message}`)}),o=(await bt(r)).match(n=>n,n=>{throw new Error(`Error getting components for ${n.repo}: ${n.message}`)});return {components:gr(o,(n,i)=>i).map(n=>c(n.sourceRepo.url,`${n.category}/${n.name}`))}}async function _a({component:e,includeTests:t=false,includeDocs:r=false}){let o=z(e);if(!o)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let{url:n,specifier:i}=o.parse(e,{fullyQualified:true});if(!i)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let s=(await lt(n)).match(u=>u,u=>{throw new Error(`Error getting state for ${n}: ${u}`)}),a=(await _t([s])).match(u=>u,u=>{throw new Error(`Error getting manifest for ${n}: ${u}`)}),l=Bt(a).get(c(n,i));if(!l)throw new Error(`${i} does not exist in ${n}`);let f=Mt([l],{includeTests:t,includeDocs:r}),m=(await Promise.all(f.map(u=>u.files))).flatMap(u=>[...u.map(w=>({name:w.name,content:w.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:n,component:i,files:m,commands:{add:`jsrepo add ${e} -y -A`,addMultiple:`jsrepo add ${e} ... -y -A`,update:`jsrepo update ${e} -y -A`}}}async function Ma({registry:e,requiredOnly:t=false}){let r=(await lt(e)).match(i=>i,i=>{throw new Error(`Error getting state for ${e}: ${i}`)}),o=(await Lt(r)).match(i=>i,i=>{throw new Error(`Error getting manifest for ${e}: ${i}`)});return !o.configFiles||o.configFiles.length===0?[]:{configFiles:await Promise.all(o.configFiles.filter(i=>!t||!i.optional).map(async i=>{let s=(await ze(r,i.path)).unwrapOr("<FETCH ERROR>");return {...i,content:s}}))}}async function Wa({query:e}){let t=await Se(`${w}/api/registries?order_by=most_popular&q=${e}`);if(!t.ok)return [];let{data:r}=await t.json();return {registries:r.map(o=>{let n=`@${o.scope.name}/${o.name}`;return {name:n,description:o.metaDescription,repository:o.metaRepository,keywords:o.metaTags,homepage:o.metaHomepage,rating:o.rating,primaryLanguage:o.metaPrimaryLanguage,monthlyDownloads:o.monthlyFetches,latestVersion:o.latestVersion,access:o.access,commands:{init:`jsrepo init ${n}`}}})}}function Va(){return {name:Dt.name(),description:Dt.description(),version:Dt.version(),commands:Dt.commands.map(e=>({name:e.name(),description:e.description(),usage:e.usage(),options:e.options.map(t=>({flags:t.flags,description:t.description,defaultValue:t.defaultValue}))}))}}async function ai(e){let t=new McpServer({name:"jsrepo",version:Le.version,description:"The jsrepo MCP server."},{adapter:Ta,capabilities:{tools:{listChanged:true}}});t.tool({name:"list-components",description:"Lists all available components/utilities for the provided registries. If registries are not provided tries to use the registries in the users jsrepo.json file.",schema:Na},async({registries:o,cwd:n})=>{e&&(o=[e]);let i=await Ba({registries:o,cwd:n});return {content:[{type:"text",text:`Available components:
|
|
96
|
+
`,t}var Pa=k.object({repos:k.optional(k.array(k.string())),watermark:k.boolean(),tests:k.optional(k.boolean()),docs:k.optional(k.boolean()),formatter:k.optional(Jr),paths:k.optional(k.record(k.string(),k.string())),configFiles:k.optional(k.record(k.string(),k.string())),project:k.optional(k.boolean()),registry:k.optional(k.boolean()),buildScript:k.string(),publishScript:k.string(),expand:k.boolean(),maxUnchanged:k.number(),yes:k.boolean(),cache:k.boolean(),cwd:k.string()}),mo=new Command("init").description("Initializes your project with a configuration file.").argument("[registries...]","Registries to install the blocks from.",[]).option("--repos [repos...]","Repository to install the blocks from. (DEPRECATED)").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").option("--docs","Will include docs with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).addOption(new Option("--paths <category=path>,<category=path>","The paths to install the blocks to.").argParser(sr).default({})).addOption(new Option("--config-files <configFile=path>,<configFile=path>","The paths to install the config files to.").argParser(sr).default({})).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--build-script <name>","The name of the build script. (For Registry setup)","build:registry").option("--publish-script <name>","The name of the publish script. (For Registry setup)","release:registry").option("-E, --expand","Expands the diff so you see the entire file.",false).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e,10),3).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Pa,t);if(await se(),r.registry!==void 0&&r.project!==void 0&&program.error(A.red(`You cannot provide both ${A.bold("--project")} and ${A.bold("--registry")} at the same time.`)),r.repos!==void 0&&log.warn(`The ${A.gray("`--repos`")} flag is deprecated! Instead supply registries as arguments. ${A.cyan(`\`jsrepo init ${r.repos.join(" ")}\``)}`),r.registry===void 0&&r.project===void 0&&e.length===0){let o=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(o)&&(cancel("Canceled!"),process.exit(0)),r.project=o==="project";}r.project||e.length>0?await Ea(e,r):await Ia(r),outro(A.green("All done!"));}),Ea=async(e,t)=>{let r=ke(t.cwd),o=spinner(),n,i={},s=mt(t.cwd).unwrapOr(null),a=t.paths?.["*"]??(r.isOk()?r.unwrap().paths["*"]:void 0);if(t.yes&&a===void 0&&program.error(A.red("You must provide a default path to install the blocks when using --yes.")),a===void 0){let C=await text({message:"Please enter a default path to install the blocks",validate(f){if(f.trim()==="")return "Please provide a value";if(!f.startsWith("./")){let b="Invalid path alias! If you are intending to use a relative path make sure it starts with `./`";if(s===null)return b;let x=ut(s,{cwd:t.cwd});if(x&&x(f).length===0)return b}},placeholder:"./src/blocks",initialValue:a});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),a=C;}if(r.isOk()?(n={...r.unwrap().paths,"*":a},i=r.unwrap().configFiles??{}):n={"*":a},n={...n,...t.paths},!t.formatter){let C=r.isErr()?"none":r.unwrap().formatter??"none";me.existsSync(ne.join(t.cwd,".prettierrc"))&&(C="prettier"),me.existsSync(ne.join(t.cwd,"biome.json"))&&(C="biome");let f=await select({message:"Which formatter would you like to use?",options:["Prettier","Biome","None"].map(b=>({value:b.toLowerCase(),label:b})),initialValue:C});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,m=async C=>{let f=await Oa({url:C,paths:n,configFiles:i,options:t,formatter:t.formatter});for(let b of f.dependencies)l.add(b);for(let b of f.devDependencies)d.add(b);n=f.paths,i=f.configFiles;};if(c.length>0)for(let C of c){if(!e.find(f=>f===C)&&r.isOk()&&r.unwrap().repos.find(f=>f===C)){let f=await confirm({message:`Initialize ${C}?`,initialValue:t.yes});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)continue}log.info(`Initializing ${A.cyan(C)}`),await m(C);}for(;!t.yes;){{let f=await confirm({message:c.length>0?"Add another repo?":"Add a repo?",initialValue:c.length===0});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),!f)break}let C=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:f=>{if(f.trim().length===0)return "Please provide a value";if(!z(f))return `Invalid provider! Valid providers (${y.map(b=>b.name).join(", ")})`}});isCancel(C)&&(cancel("Canceled!"),process.exit(0)),await m(C),c.push(C);}let u={$schema:`https://unpkg.com/jsrepo@${Le.version}/schemas/project-config.json`,repos:c,includeTests:r.isOk()&&t.tests===void 0?r.unwrap().includeTests:t.tests??false,includeDocs:r.isOk()&&t.docs===void 0?r.unwrap().includeDocs:t.docs??false,watermark:t.watermark,formatter:t.formatter,configFiles:i,paths:n};o.start(`Writing config to \`${vt}\``);let{prettierOptions:w,biomeOptions:p}=await Pt({formatter:u.formatter,cwd:t.cwd}),g=ne.join(t.cwd,vt),y$1=await wr.format(JSON.stringify(u,null," "),{biomeOptions:p,prettierOptions:w,filePath:g,formatter:u.formatter,cwd:t.cwd});me.existsSync(t.cwd)||me.mkdirSync(t.cwd,{recursive:true}),me.writeFileSync(g,y$1),o.stop(`Wrote config to \`${vt}\`.`);let h=(await detect$1({cwd:t.cwd}))?.agent??"npm",j=await tt(l,d,{yes:t.yes,cwd:t.cwd,pm:h});if(j.dependencies.size>0||j.devDependencies.size>0){let C=[];if(!j.installed){if(l.size>0){let b=resolveCommand$1(h,"add",[...l]);C.push(`Install dependencies \`${A.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(d.size>0){let b=resolveCommand$1(h,"add",[...d,"-D"]);C.push(`Install dev dependencies \`${A.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}C=C.map((b,x)=>`${x+1}. ${b}`),j.installed||C.push(""),C.push(`Add blocks with ${A.cyan("jsrepo add")}!`);let f=St(C);process.stdout.write(f);}};async function Oa({url:e,paths:t,configFiles:r,formatter:o,options:n}){let i=spinner(),s=new fe,a=z(e);a||program.error(A.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 g=await password({message:"Paste your token",validate(y){if(y.trim()==="")return "Please provide a value"}});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),s.set(c$1,g);}}i.start(`Fetching manifest from ${A.cyan(e)}`);let d=(await lt(e,{noCache:!n.cache})).match(p=>p,p=>program.error(A.red(p))),m=(await Bt(d,{noCache:!n.cache})).match(p=>p,p=>program.error(A.red(p)));i.stop(`Fetched manifest from ${A.cyan(e)}`),Ut(d,m,n.cwd);let u$1=[],w=[];if(m.configFiles){let{prettierOptions:p,biomeOptions:g}=await Pt({formatter:o,cwd:n.cwd});for(let y of m.configFiles){if(y.optional&&!n.yes){let x=await confirm({message:`Would you like to add the ${y.name} file?`,initialValue:true});if(isCancel(x)&&(cancel("Canceled!"),process.exit(0)),!x)continue}if(u$1.push(...y.dependencies??[]),w.push(...y.devDependencies??[]),!r[y.name])if(n.configFiles?.[y.name])r[y.name]=n.configFiles[y.name];else if(n.yes)y.expectedPath||program.error(A.red(`You must provide a path for ${y.name} when using --yes!`)),r[y.name]=y.expectedPath;else {let x=await text({message:`Where is your ${y.name} file?`,defaultValue:y.expectedPath,initialValue:y.expectedPath,placeholder:y.expectedPath,validate(R){if(R.trim()==="")return "Please provide a value"}});isCancel(x)&&(cancel("Canceled!"),process.exit(0)),r[y.name]=x;}let h=ne.join(n.cwd,r[y.name]),j;if(me.existsSync(h))j=me.readFileSync(h).toString();else {let x=ne.dirname(h);if(me.existsSync(x)){let R=Un(h);if(R){j=me.readFileSync(R).toString();let P=ne.relative(n.cwd,R);log.warn(`Located ${A.bold(r[y.name])} at ${A.bold(P)}`),r[y.name]=P,h=ne.join(n.cwd,P);}}}i.start(`Fetching the ${A.cyan(y.name)} from ${A.cyan(e)}`);let C=(await ze(d,y.path)).match(x=>x,x=>program.error(A.red(x))),f=await Tr({file:{content:C,destPath:h},biomeOptions:g,prettierOptions:p,formatter:o,cwd:n.cwd});i.stop(`Fetched the ${A.cyan(y.name)} from ${A.cyan(e)}`);let b=n.yes||j===void 0;if(j){if(!n.yes){let x=c(d.url,y.name),R=await Jt({config:{biomeOptions:g,prettierOptions:p,formatter:o},current:{content:j,path:h},incoming:{content:f,path:x},options:{...n,loading:i,no:false}});R.applyChanges&&(b=true,j=R.updatedContent);}}else {let x=ne.dirname(h);me.existsSync(x)||me.mkdirSync(x,{recursive:true}),j=f;}b&&j&&(i.start(`Writing ${A.cyan(y.name)} to ${A.cyan(h)}`),me.writeFileSync(h,j),i.stop(`Wrote ${A.cyan(y.name)} to ${A.cyan(h)}`));}}if(!n.yes){let p=await multiselect({message:"Which category paths would you like to configure?",options:m.categories.map(g=>({label:g.name,value:g.name,hint:m.defaultPaths?.[g.name]?`Default: ${m.defaultPaths?.[g.name]}`:void 0})),required:false});if(isCancel(p)&&(cancel("Canceled!"),process.exit(0)),p.length>0)for(let g of p){let y=t[g]??m.defaultPaths?.[g],h=await text({message:`Where should ${g} be added in your project?`,validate(j){if(j.trim()==="")return "Please provide a value"},placeholder:y||`./src/${g}`,defaultValue:y,initialValue:y});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),t[g]=h;}}for(let p of m.categories){if(t[p.name]!==void 0)continue;let g=m.defaultPaths?.[p.name];g&&(t[p.name]=g);}return {paths:t,configFiles:r,dependencies:u$1,devDependencies:w}}var Ia=async e=>{let t=spinner(),r=ne.join(e.cwd,"package.json");me.existsSync(r)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let o=Lt(e.cwd).match(p=>p,p=>program.error(A.red(p)));for(o||(o={$schema:"",name:void 0,version:void 0,readme:"README.md",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],includeFiles:[],excludeBlocks:[],excludeCategories:[],preview:false,includeDocs:false}),o.$schema=`https://unpkg.com/jsrepo@${Le.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let g=await confirm({message:"Add another blocks directory?",initialValue:false});if(isCancel(g)&&(cancel("Canceled!"),process.exit(0)),!g)break}let p=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:g=>{if(g.trim().length===0)return "Please provide a value!"}});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(p);}let n=JSON.parse(me.readFileSync(r).toString()),i=!e.yes;if(!e.yes){let p=await confirm({message:`Configure to publish to ${Ve}?`,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:g=>{if(g.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 oi(e.publishScript,n,e,"release:registry");}else e.buildScript=await oi(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{me.writeFileSync(r,JSON.stringify(n,null," "));}catch(p){program.error(A.red(`Error writing to \`${A.bold(r)}\`. Error: ${p}`));}}}),d.push({loadingMessage:`Writing config to \`${A.cyan(wt)}\``,completedMessage:`Wrote config to \`${A.cyan(wt)}\``,run:async()=>{let p=ne.join(e.cwd,wt);try{me.writeFileSync(ne.join(p),JSON.stringify(o,null," "));}catch(g){program.error(A.red(`Error writing to \`${A.bold(p)}\`. Error: ${g}`));}}}),await Ln(d,{loading:t});let m=s;s||(m=(await tt(new Set,new Set(["jsrepo"]),{cwd:e.cwd,pm:a,yes:e.yes})).installed);let u=[];if(!m){let p=resolveCommand$1(a,"add",["jsrepo","-D"]);u.push(`Install ${Ze} as a dev dependency \`${A.cyan(`${p?.command} ${p?.args.join(" ")}`)}\``);}if(u.push(`Add categories to \`${A.cyan(o.dirs.join(", "))}\`.`),i){let p=resolveCommand$1(a,"run",[e.publishScript]);u.push(`Run \`${A.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to publish the registry.`);}else {let p=resolveCommand$1(a,"run",[e.buildScript]);u.push(`Run \`${A.cyan(`${p?.command} ${p?.args.join(" ")}`)}\` to build the registry.`);}u=u.map((p,g)=>`${g+1}. ${p}`);let w=St(u);process.stdout.write(w);};async function oi(e,t,r,o){let n=e;for(;!r.yes&&t.scripts&&t.scripts[n];){let i=await confirm({message:`The \`${A.cyan(n)}\` already exists overwrite?`,initialValue:false});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),i)break;{let s=await text({message:"What would you like to call the script?",placeholder:o,validate:a=>{if(a.trim().length===0)return "Please provide a value!"}});isCancel(s)&&(cancel("Canceled!"),process.exit(0)),n=s;}}return n}var Aa=new ValibotJsonSchemaAdapter,Fa=k.object({registries:k.pipe(k.optional(k.array(k.string())),k.metadata({description:"Registries to list components from. If not provided will use the registries in the users jsrepo.json file."})),cwd:k.pipe(k.string(),k.metadata({description:"The current working directory of the users project."}))}),La=k.object({registry:k.pipe(k.string(),k.metadata({description:"Registry for the component."})),component:k.pipe(k.string(),k.metadata({description:"The component to get the code for. Format: <category>/<block>"})),includeTests:k.pipe(k.optional(k.boolean()),k.metadata({description:"Should tests be included with the component code."})),includeDocs:k.pipe(k.optional(k.boolean()),k.metadata({description:"Should docs be included with the component code."}))}),Ba=k.object({registry:k.pipe(k.string(),k.metadata({description:"Registry to list config files from."})),requiredOnly:k.pipe(k.optional(k.boolean()),k.metadata({description:"When true only returns the config files required for the registry to work properly."}))}),_a=k.object({query:k.pipe(k.string(),k.metadata({description:"A term to search for the registries by."}))});async function Ma({registries:e,cwd:t}){if(!e){let n=ke(t).match(i=>i,()=>{throw new Error("Could not find your configuration file! Please provide `registries`.")});if(n.repos.length===0)throw new Error("No registries (repos) in your configuration file! Please provide `registries`.");e=n.repos;}let r=(await Ke(e)).match(n=>n,n=>{throw new Error(`Error getting registry state for ${n.repo}: ${n.message}`)}),o=(await kt(r)).match(n=>n,n=>{throw new Error(`Error getting components for ${n.repo}: ${n.message}`)});return {components:gr(o,(n,i)=>i).map(n=>c(n.sourceRepo.url,`${n.category}/${n.name}`))}}async function Wa({component:e,includeTests:t=false,includeDocs:r=false}){let o=z(e);if(!o)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let{url:n,specifier:i}=o.parse(e,{fullyQualified:true});if(!i)throw new Error(`${e} is not valid! Expected a category and block proceeded by the registry url i.e. @ieedan/std/<category>/<block>`);let s=(await lt(n)).match(u=>u,u=>{throw new Error(`Error getting state for ${n}: ${u}`)}),a=(await Mt([s])).match(u=>u,u=>{throw new Error(`Error getting manifest for ${n}: ${u}`)}),l=_t(a).get(c(n,i));if(!l)throw new Error(`${i} does not exist in ${n}`);let d=Wt([l],{includeTests:t,includeDocs:r}),m=(await Promise.all(d.map(u=>u.files))).flatMap(u=>[...u.map(w=>({name:w.name,content:w.content.unwrapOr("<FETCH ERROR>")}))]);return {registry:n,component:i,files:m,commands:{add:`jsrepo add ${e} -y -A`,addMultiple:`jsrepo add ${e} ... -y -A`,update:`jsrepo update ${e} -y -A`}}}async function Va({registry:e,requiredOnly:t=false}){let r=(await lt(e)).match(i=>i,i=>{throw new Error(`Error getting state for ${e}: ${i}`)}),o=(await Bt(r)).match(i=>i,i=>{throw new Error(`Error getting manifest for ${e}: ${i}`)});return !o.configFiles||o.configFiles.length===0?[]:{configFiles:await Promise.all(o.configFiles.filter(i=>!t||!i.optional).map(async i=>{let s=(await ze(r,i.path)).unwrapOr("<FETCH ERROR>");return {...i,content:s}}))}}async function Ja({query:e}){let t=await je(`${w}/api/registries?order_by=most_popular&q=${e}`);if(!t.ok)return [];let{data:r}=await t.json();return {registries:r.map(o=>{let n=`@${o.scope.name}/${o.name}`;return {name:n,description:o.metaDescription,repository:o.metaRepository,keywords:o.metaTags,homepage:o.metaHomepage,rating:o.rating,primaryLanguage:o.metaPrimaryLanguage,monthlyDownloads:o.monthlyFetches,latestVersion:o.latestVersion,access:o.access,commands:{init:`jsrepo init ${n}`}}})}}function Ua(){return {name:Tt.name(),description:Tt.description(),version:Tt.version(),commands:Tt.commands.map(e=>({name:e.name(),description:e.description(),usage:e.usage(),options:e.options.map(t=>({flags:t.flags,description:t.description,defaultValue:t.defaultValue}))}))}}async function si(e){let t=new McpServer({name:"jsrepo",version:Le.version,description:"The jsrepo MCP server."},{adapter:Aa,capabilities:{tools:{listChanged:true}}});t.tool({name:"list-components",description:"Lists all available components/utilities for the provided registries. If registries are not provided tries to use the registries in the users jsrepo.json file.",schema:Fa},async({registries:o,cwd:n})=>{e&&(o=[e]);let i=await Ma({registries:o,cwd:n});return {content:[{type:"text",text:`Available components:
|
|
97
97
|
${JSON.stringify(i.components)}
|
|
98
98
|
Add a component to your project with:
|
|
99
99
|
jsrepo add ${i.components[0]} -y -A
|
|
@@ -102,10 +102,10 @@ jsrepo add ${i.components[0]} ${i.components[1]??i.components[0]} ... -y -A
|
|
|
102
102
|
Update existing components with:
|
|
103
103
|
jsrepo update ${i.components[0]} -y -A
|
|
104
104
|
Update multiple components with:
|
|
105
|
-
jsrepo update ${i.components[0]} ${i.components[1]??i.components[0]} ... -y -A`}]}}),t.tool({name:"get-component-code",description:"Returns the associated code files for the provided component.",schema:
|
|
106
|
-
Please try again. If this persists please contact support at ${
|
|
107
|
-
`);l();}catch(
|
|
108
|
-
`):l(),program.error(
|
|
105
|
+
jsrepo update ${i.components[0]} ${i.components[1]??i.components[0]} ... -y -A`}]}}),t.tool({name:"get-component-code",description:"Returns the associated code files for the provided component.",schema:La},async({registry:o,component:n,includeTests:i,includeDocs:s})=>{e&&(o=e);let a=await Wa({component:n,includeTests:i,includeDocs:s});return {content:[{type:"text",text:JSON.stringify(a)}]}}),t.tool({name:"get-config-files",description:"Lists the config files for this registry. These are files that are either necessary for the registry to work or optional as marked by the `optional` boolean on each file.",schema:Ba},async({registry:o,requiredOnly:n})=>{e&&(o=e);let i=await Va({registry:o,requiredOnly:n});return {content:[{type:"text",text:JSON.stringify(i)}]}}),t.tool({name:"search-registries",description:"Search jsrepo.com for registries that could include components the user needs in their project.",schema:_a},async({query:o})=>{let n=await Ja({query:o});return {content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool({name:"cli-reference",description:"A reference for the usage of the jsrepo CLI."},async()=>{let o=Ua();return {content:[{type:"text",text:JSON.stringify(o)}]}}),new StdioTransport(t).listen(),console.error("Server connected");}var uo=new Command("mcp").description("Interact with jsrepo through an MCP server.").addArgument(new Argument("<registry>","The registry to use.").argOptional()).action(async e=>{await si(e).catch(t=>{console.error(t),process.exit(1);});});var Qa=k.object({private:k.boolean(),dryRun:k.boolean(),name:k.optional(k.string()),ver:k.optional(k.string()),dirs:k.optional(k.array(k.string())),includeBlocks:k.optional(k.array(k.string())),includeCategories:k.optional(k.array(k.string())),includeFiles:k.optional(k.array(k.string())),excludeBlocks:k.optional(k.array(k.string())),excludeCategories:k.optional(k.array(k.string())),excludeDeps:k.optional(k.array(k.string())),listBlocks:k.optional(k.array(k.string())),listCategories:k.optional(k.array(k.string())),doNotListBlocks:k.optional(k.array(k.string())),doNotListCategories:k.optional(k.array(k.string())),allowSubdirectories:k.optional(k.boolean()),includeDocs:k.optional(k.boolean()),verbose:k.boolean(),cwd:k.string()}),go=new Command("publish").description("Publish a registry to jsrepo.com.").option("--private","When publishing the first version of the registry make it private.",false).option("--dry-run","Test the publish but don't list on jsrepo.com.",false).option("--name <name>","The name of the registry. i.e. @ieedan/std").option("--ver <version>","The version of the registry. i.e. 0.0.1").option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--allow-subdirectories","Allow subdirectories to be built.").option("--include-docs","Include documentation files (*.md, *.mdx) in the registry.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=k.parse(Qa,e);await se(),await Xa(t),outro(A.green("All done!"));});async function Xa(e){let t=f=>{e.verbose&&console.info(`${Oe} ${f}`);},r=$e({verbose:e.verbose?t:void 0}),o=Lt(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??[],includeFiles:e.includeFiles??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],allowSubdirectories:e.allowSubdirectories,includeDocs:e.includeDocs??false};let b=f;return e.private&&(b.access="private"),e.name&&(b.name=e.name),e.ver&&(b.version=e.ver),e.dirs&&(b.dirs=e.dirs),e.doNotListBlocks&&(b.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(b.doNotListCategories=e.doNotListCategories),e.listBlocks&&(b.listBlocks=e.listBlocks),e.listCategories&&(b.listCategories=e.listCategories),e.includeBlocks&&(b.includeBlocks=e.includeBlocks),e.includeCategories&&(b.includeCategories=e.includeCategories),e.includeFiles&&(b.includeFiles=e.includeFiles),e.excludeBlocks&&(b.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(b.excludeCategories=e.excludeCategories),e.excludeDeps&&(b.excludeDeps=e.excludeDeps),e.allowSubdirectories!==void 0&&(b.allowSubdirectories=e.allowSubdirectories),e.includeDocs!==void 0&&(b.includeDocs=e.includeDocs),b.rules={...er,...b.rules},b},f=>program.error(A.red(f)));if(e.dryRun&&log.warn(A.bgYellow.black(" DRY RUN ")),o.name!==void 0)try{let[f,b,...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(!b.match(v))throw new Error}catch{program.error(A.red(`\`${o.name}\` is not a valid name. The name should be provided as \`@<scope>/<registry>\``));}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`name\` field in the \`jsrepo-build-config.json\``));if(o.version!==void 0){if(o.version==="package"){let b=ne.join(e.cwd,"package.json");me.existsSync(b)||program.error(A.red(`Couldn't find your ${A.bold("package.json")}!`));let{version:x}=JSON.parse(me.readFileSync(b).toString());o.version=x;}Bo.valid(o.version)||program.error(`\`${o.version}\` is not a valid semver version.`);}else program.error(A.red(`To publish to ${A.bold("jsrepo.com")} you need to provide the \`version\` field in the \`jsrepo-build-config.json\``));let n=new fe().get("jsrepo");n===void 0&&program.error(A.red(`Please authenticate with ${A.cyan("jsrepo auth")} to publish to ${Ve}.`));let i=[],s=Hi();try{let f=me.readFileSync(ne.join(e.cwd,".gitignore")).toString();s.add(f);}catch{}s.add(Er);for(let f of o.dirs){let b=ne.join(e.cwd,f);r.start(`Building ${A.cyan(b)}`);let x=Cr(b,{cwd:e.cwd,ignore:s,config:o});for(let R of x){if(i.find(P=>P.name===R.name)!==void 0){console.warn(`${T} ${le} Skipped adding \`${A.cyan(`${f}/${R.name}`)}\` because a category with the same name already exists!`);continue}i.push(R);}r.stop(`Built ${A.cyan(b)}`);}let a=Rr(o,{cwd:e.cwd}),c=p(i,a,o);r.start("Checking manifest");let{warnings:l,errors:d}=$r(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(A.red(`Completed checking manifest with ${A.bold(`${d.length} error(s)`)} and ${A.bold(`${l.length} warning(s)`)}`));}let[m,u]=Sr(c.categories);c.categories=m,u>0&&log.step(`Removed ${u} unused block${u>1?"s":""}.`),r.start(`Packaging ${A.cyan(c.name)}...`);let w$1=ne.resolve(e.cwd,`jsrepo-publish-temp-${Date.now()}`);t(`Creating temp dir: ${w$1}`),me.mkdirSync(w$1,{recursive:true}),t("Writing manifest to temp dir"),me.writeFileSync(ne.resolve(w$1,"jsrepo-manifest.json"),JSON.stringify(c));let p$1=ne.resolve(e.cwd,o.readme);try{t("Attempting to copy readme"),me.copyFileSync(p$1,ne.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 b=ne.join(e.cwd,f.path),x=ne.join(w$1,f.path),R=ne.join(x,"../");me.existsSync(R)||me.mkdirSync(R,{recursive:true}),me.copyFileSync(b,x);}t("Copied config files");}t("Copying registry files");for(let f of c.categories)for(let b of f.blocks){let x=ne.join(e.cwd,b.directory),R=ne.join(w$1,b.directory);for(let P of b.files){let X=ne.join(R,P,"../");me.existsSync(X)||me.mkdirSync(X,{recursive:true}),me.copyFileSync(ne.join(x,P),ne.join(R,P));}}t("Copied registry files");let g=ne.resolve(e.cwd,`${o.name.replace("/","_")}-package.tar.gz`),y=me.readdirSync(w$1);t("Creating archive file"),await ai.create({z:true,cwd:w$1,file:g},y),t("Created archive file"),t("Removing temp directory"),me.rmSync(w$1,{force:true,recursive:true}),t("Removed temp directory"),r.stop(`Created package ${A.cyan(g)}...`);let h=o.access??"public";log.info(`Publishing to jsrepo with the access set to ${A.cyan(h)}`),r.start(`Publishing ${A.bold(c.name)} to ${Ve}...`);let j=me.readFileSync(g);t("Removing archive file"),me.rmSync(g,{force:true,recursive:true}),t("Removed archive file"),t(`Publishing to ${`${w}/api/publish`}`);let C=await je(`${w}/api/publish`,{body:j,headers:{"content-type":"application/gzip","content-encoding":"gzip","x-api-key":n,"x-dry-run":e.dryRun?"1":"0","x-access":h},method:"POST"});if(r.stop(`Got response from ${Ve}.`),C.ok){let f=await C.json();f.status==="dry-run"?log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} Completed dry run!`):log.success(`${A.hex("#f7df1e").bold("[jsrepo.com]")} published ${A.greenBright(`@${f.scope}`)}/${f.registry}${A.greenBright(`@${f.version}`)}!`);}else {let f=await C.json();C.status===500&&program.error(`${A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${f.message}`)}
|
|
106
|
+
Please try again. If this persists please contact support at ${A.cyan("https://www.jsrepo.com/help")}`),program.error(A.red(`${A.bold("[jsrepo.com]")} ${A.bold(C.status)} ${f.message}`));}}var dc=k.object({repo:k.optional(k.string()),allow:k.boolean(),debug:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),ho=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("--debug","Leaves the temp test file around for debugging upon failure.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(dc,t);await se(),await pc(e,r),outro(A.green("All done!"));});async function pc(e,t){let r=h=>{t.verbose&&console.info(`${Oe} ${h}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=ke(t.cwd).match(h=>h,h=>program.error(A.red(h))),n=$e({verbose:t.verbose?r:void 0}),i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let h=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(h)||!h)&&(cancel("Canceled!"),process.exit(0));}t.verbose||n.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await Ke(i,{noCache:!t.cache})).match(h=>h,({repo:h,message:j})=>{n.stop(`Failed to get info for ${A.cyan(h)}`),program.error(A.red(j));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await kt(s,{verbose:t.verbose?r:void 0})).match(h=>h,({repo:h,message:j})=>{n.stop(`Failed fetching blocks from ${A.cyan(h)}`),program.error(A.red(j));});r(`Retrieved blocks from ${A.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`);let c$1=ne.resolve(ne.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${A.bold(c$1)}.`),me.mkdirSync(c$1,{recursive:true});let l=()=>{me.rmSync(c$1,{recursive:true,force:true});},d=Ct(a,o,t.cwd).map(h=>h.specifier),m=e;e.length===0&&(m=d),m.length===0&&(l(),program.error(A.red("There were no blocks found in your project!")));let u=[];for(let h of m){let j,C=z(h);if(C){let{url:f}=C.parse(h,{fullyQualified:true}),b=(await lt(f)).match(R=>R,R=>program.error(A.red(R))),x=(await kt([b])).match(R=>R,R=>program.error(A.red(R)));for(let[R,P]of x)a.set(R,P);j=a.get(h);}else for(let f of i){let b=z(f);if(!b)continue;let{url:x,specifier:R}=b.parse(c(f,h),{fullyQualified:true}),P=a.get(c(x,R));if(P!==void 0){j=P;break}}j||program.error(A.red(`Invalid block! ${A.bold(h)} does not exist!`)),u.push({name:h,block:j});}let w=Ue(o.paths,t.cwd).match(h=>h,h=>program.error(A.red(h)));for(let{block:h}of u){let j=h.sourceRepo,C=c(h.sourceRepo.url,h.category,h.name);if(t.verbose||n.start(`Setting up test file for ${A.cyan(C)}`),!h.tests){n.stop(`No tests found for ${A.cyan(C)}`);continue}let f=rr(h,w,t.cwd);f=ne.relative(c$1,f);let b=async R=>{let P=await ze(j,R);return P.isErr()&&(n.stop(A.red(`Error fetching ${A.bold(R)}`)),program.error(A.red(`There was an error trying to get ${C}`))),P.unwrap()};r(`Downloading and copying test files for ${C}`);let x=[];for(let R of h.files.filter(P=>ct(P))){let P=await b(ne.join(h.directory,R)),X=ne.join(c$1,R);me.writeFileSync(X,P),x.push(X);}for(let R of x){r(`Opening test file ${R}`);let P=me.readFileSync(R).toString(),X=Ni.parseSync(R,P);for(let J of X.module.staticImports){let Z=J.moduleRequest.value,$;if(Z.startsWith(".")&&(h.subdirectory?$=ne.join(f,h.name,Z):$=ne.join(f,Z)),$){let L=new RegExp(`(['"])${Ws(Z)}\\1`,"g");P=P.replaceAll(L,`$1${$}$1`);}}me.writeFileSync(R,P);}r(`Completed ${A.cyan.bold(C)} test file`),t.verbose||n.stop(`Completed setup for ${A.bold(C)}`);}r("Beginning testing");let p=await detect({cwd:t.cwd});p==null&&program.error(A.red("Could not detect package manager"));let g=resolveCommand(p.agent,"execute",["vitest","run",c$1]);g==null&&program.error(A.red(`Could not resolve add command for '${p.agent}'.`));let y=`${g.command} ${g.args.join(" ")}`;r(`Running ${A.cyan(y)} on ${A.cyan(t.cwd)}`);try{let h=x(g.command,g.args,{nodeOptions:{cwd:t.cwd}});for await(let j of h)process.stdout.write(`${j}
|
|
107
|
+
`);l();}catch(h){t.debug?console.info(`${A.bold("--debug")} flag provided. Skipping cleanup. Run '${A.bold(y)}' to retry tests.
|
|
108
|
+
`):l(),program.error(A.red(`Tests failed! Error ${h}`));}}var yc=k.object({token:k.optional(k.string()),logout:k.boolean(),cwd:k.string()}),qt=["Anthropic","Azure","BitBucket","GitHub","GitLab","OpenAI","http"].sort(),yo=new Command("tokens").description("Provide a token for access to private repositories.").addArgument(new Argument("service","The service you want to authenticate to.").choices(qt.map(e=>e.toLowerCase())).argOptional()).option("--logout","Execute the logout flow.",false).option("--token <token>","The token to use for authenticating to this service.").option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(yc,t);await se(),await vc(e,r),outro(A.green("All done!"));});async function vc(e,t){let r=ke(t.cwd).match(s=>s.repos.filter(u.matches),()=>[]),o=qt.find(s=>s.toLowerCase()===e?.toLowerCase()),n=new fe;if(t.logout){if(o!==void 0){if(o==="http"){await li(n);return}n.delete(o),log.success(`Logged out of ${o}.`);return}for(let s of qt){if(s==="http"){await li(n);continue}if(n.get(s)===void 0){log.step(A.gray(`Already logged out of ${A.bold(s)}.`));continue}let a=await confirm({message:`Logout of ${A.bold(s)}?`,initialValue:true});isCancel(a)&&(cancel("Canceled!"),process.exit(0)),a&&n.delete(s);}return}if(o===void 0){let s=await select({message:"Which service do you want to authenticate to?",options:qt.map(a=>({label:a,value:a})),initialValue:qt[0]});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),o=s,o==="http"){let a="Other";if(r.length>0){r.push("Other");let c=await select({message:"Which registry do you want to authenticate to?",options:r.map(l=>({label:l,value:l})),initialValue:qt[0]});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}if(a==="Other"){let c=await text({message:"Please enter the registry url you want to authenticate to:",placeholder:"https://example.com",validate(l){if(l.trim()==="")return "Please provide a value";try{new URL(l);}catch{return "Please provide a valid url"}}});isCancel(c)&&(cancel("Canceled!"),process.exit(0)),a=new URL(c).origin;}o=`http-${a}`;}}let i=o;if(i.startsWith("http")&&(i=i.slice(5)),t.token===void 0){let s=await password({message:`Paste your token for ${A.bold(i)}:`,validate(a){if(a.trim()==="")return "Please provide a value"}});(isCancel(s)||!s)&&(cancel("Canceled!"),process.exit(0)),t.token=s;}n.set(o,t.token),log.success(`Logged into ${A.bold(i)}.`);}async function li(e){let t=e.getHttpRegistriesWithTokens();t.length===0&&log.step(A.gray(`Already logged out of ${A.bold("http")}.`));for(let r of t){let o;try{o=new URL(r);}catch{continue}let n=await confirm({message:`Logout of ${A.bold(o.origin)}?`,initialValue:true});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&e.delete(`http-${o.origin}`);}}var Cc=k.object({all:k.boolean(),expand:k.boolean(),maxUnchanged:k.number(),no:k.boolean(),repo:k.optional(k.string()),allow:k.boolean(),yes:k.boolean(),cache:k.boolean(),verbose:k.boolean(),cwd:k.string()}),wo=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,10),3).option("-n, --no","Do update any blocks.",false).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",false).option("-y, --yes","Skip confirmation prompt.",false).option("--no-cache","Disable caching of resolved git urls.").option("--verbose","Include debug logs.",false).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=k.parse(Cc,t);await se(),await Rc(e,r),outro(A.green("All done!"));});async function Rc(e,t){let r=f=>{t.verbose&&console.info(`${Oe} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=$e({verbose:t.verbose?r:void 0}),n=ke(t.cwd).match(f=>f,f=>program.error(A.red(f))),i=n.repos;t.repo&&(i=[t.repo]);for(let f of e)y.find(b=>f.startsWith(b.name))&&program.error(A.red(`Invalid value provided for block names \`${A.bold(f)}\`. Block names are expected to be provided in the format of \`${A.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${A.cyan("jsrepo")} to download and run code from ${A.cyan(t.repo)}?`,initialValue:true});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${A.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${A.cyan(i.join(", "))}`);let s=(await Ke(i,{noCache:!t.cache})).match(f=>f,({repo:f,message:b})=>{o.stop(`Failed to get info for ${A.cyan(f)}`),program.error(A.red(b));});r(`Resolved ${A.cyan(i.join(", "))}`),r(`Fetching blocks from ${A.cyan(i.join(", "))}`);let a=(await Mt(s)).match(f=>f,({repo:f,message:b})=>{o.stop(`Failed fetching blocks from ${A.cyan(f)}`),program.error(A.red(b));}),c$1=_t(a);t.verbose||o.stop(`Retrieved blocks from ${A.cyan(i.join(", "))}`),r(`Retrieved blocks from ${A.cyan(i.join(", "))}`);for(let f of a)Ut(f.state,f.manifest,t.cwd);let l=Ct(c$1,n,t.cwd);l.length===0&&program.error(A.red(`You haven't installed any blocks yet. Did you mean to \`${A.bold("add")}\`?`));let 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(b=>b.block.list).map(b=>({label:`${A.cyan(b.block.category)}/${b.block.name}`,value:b.specifier})),required:true});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),d=f;}r(`Preparing to update ${A.cyan(d.join(", "))}`);let m=(await xt(d,c$1,s)).match(f=>f,program.error),u=new Set,w=new Set,{prettierOptions:p,biomeOptions:g}=await Pt({formatter:n.formatter,cwd:t.cwd}),y$1=Ue(n.paths,t.cwd).match(f=>f,f=>program.error(A.red(f))),h=Wt(m,n);for(let f of h){let b=c(f.block.sourceRepo.url,f.block.category,f.block.name),x=cr(f.block.sourceRepo.url);r(`Attempting to update ${b}`),n.includeTests&&f.block.tests&&(r("Trying to include tests"),u.add("vitest"));for(let P of f.block.devDependencies)u.add(P);for(let P of f.block.dependencies)w.add(P);let R=await f.files;process.stdout.write(`${T}
|
|
109
109
|
`),process.stdout.write(`${T} ${b}
|
|
110
|
-
`);for(let
|
|
110
|
+
`);for(let P of R){let X=P.content.match(v=>v,v=>program.error(A.red(v))),J=ir(P.name,f.block,y$1,t.cwd),Z=(await ar({file:{content:X,destPath:J},biomeOptions:g,prettierOptions:p,config:n,imports:f.block._imports_,watermark:x,verbose:r,cwd:t.cwd})).match(v=>v,v=>program.error(A.red(v))),$="";me.existsSync(J)&&($=me.readFileSync(J).toString());let L=await Jt({config:{biomeOptions:g,prettierOptions:p,formatter:n.formatter},current:{path:J,content:$},incoming:{path:c(b,P.name),content:Z},options:{...t,loading:o,verbose:t.verbose?r:void 0}});L.applyChanges&&(o.start(`Writing changes to ${A.cyan(J)}`),me.writeFileSync(J,L.updatedContent),o.stop(`Wrote changes to ${A.cyan(J)}.`));}}let j=(await detect({cwd:t.cwd}))?.agent??"npm",C=await tt(w,u,{yes:t.yes,no:t.no,cwd:t.cwd,pm:j});if(C.dependencies.size>0||C.devDependencies.size>0){let f=[];if(!C.installed){if(w.size>0){let x=resolveCommand(j,"add",[...w]);f.push(`Install dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}if(u.size>0){let x=resolveCommand(j,"add",[...u,"-D"]);f.push(`Install dev dependencies \`${A.cyan(`${x?.command} ${x?.args.join(" ")}`)}\``);}}f=f.map((x,R)=>`${R+1}. ${x}`),C.installed||f.push(""),f.push("Import and use the blocks!");let b=St(f);process.stdout.write(b);}}var Tt=program.name(Ft.name).description(Ft.description).version(Ft.version).addCommand(eo).addCommand(oo).addCommand(no).addCommand(ao).addCommand(co).addCommand(mo).addCommand(uo).addCommand(go).addCommand(ho).addCommand(yo).addCommand(wo);Tt.parse();//# sourceMappingURL=index.js.map
|
|
111
111
|
//# sourceMappingURL=index.js.map
|