jsrepo 1.22.2 → 1.23.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.
Files changed (2) hide show
  1. package/dist/index.js +59 -59
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,65 +1,65 @@
1
1
  #!/usr/bin/env node
2
- import Ne from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import X from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,password,intro}from'@clack/prompts';import I from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import*as b from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import st from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as Ot from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as Sr from'parse5';import*as Oe from'prettier';import*as Pr from'svelte/compiler';import {Project}from'ts-morph';import Ro from'validate-npm-package-name';import yo from'node:os';import ho from'ansi-regex';import Fo from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import zo from'escape-string-regexp';import {diffLines,diffChars}from'diff';var A=I.gray("\u2502"),zt=I.gray("\u2500"),mr=I.gray("\u2510"),ur=I.gray("\u2518"),Ut=I.gray("\u251C");I.gray("\u250C");I.gray("\u2514");var $e=I.bgRgb(245,149,66).black(" WARN "),ot=I.bgBlueBright.white(" INFO "),Rt=I.bgRedBright.white(" ERROR "),Se=I.hex("#f7df1e")("jsrepo");var Ct=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>j(t(r)),r=>S(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>j(r),r=>S(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>!0,()=>!1)}isErr(){return this.match(()=>!1,()=>!0)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},j=e=>new Ct({ok:!0,val:e}),S=e=>new Ct({ok:!1,err:e});var gr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var co=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,lo=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,xt=e=>{let t=co.exec(e)||lo.exec(e);return t?j({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):S(`invalid package name: ${e}`)};var hr=b.union([b.literal("off"),b.literal("warn"),b.literal("error")]),po={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${I.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.find(d=>d.name.trim()===n.trim()),a=`${I.bold(`${e.category}/${e.name}`)} depends on local dependency ${I.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(d=>d.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.find(d=>d.name===n);!i||!i.blocks.find(d=>d.name===s)||r.push(`${I.bold(`${e.category}/${e.name}`)} depends on ${I.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${I.bold(`${e.category}/${e.name}`)} has too many local dependencies (${I.bold(e.localDependencies.length)}) limit (${I.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",check:(e,{categories:t})=>{let r=[],o=`${e.category}/${e.name}`,n=jt(o,e,t);return n&&r.push(`There is a circular dependency in ${I.bold(o)}: ${I.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)",check:(e,{categories:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(jt(r,n,t))return;return [`${I.bold(r)} is unused and will be ${I.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",check:e=>{let t=[],r=new Set(["svelte","vue","nuxt","react","react-dom","next","@remix-run/react","@builder.io/qwik","astro","solid-js","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router"]),o=[...e.devDependencies,...e.dependencies].map(n=>xt(n).unwrap().name).filter(n=>r.has(n));if(o.length>0)for(let n of o)t.push(`${I.bold(`${e.category}/${e.name}`)} depends on ${I.bold(n)} causing it to be installed when added`);return t.length>0?t:void 0}}},fo=b.union([b.literal("no-category-index-file-dependency"),b.literal("no-unpinned-dependency"),b.literal("require-local-dependency-exists"),b.literal("max-local-dependencies"),b.literal("no-circular-dependency"),b.literal("no-unused-block"),b.literal("no-framework-dependency")]),yr=b.record(fo,b.union([hr,b.tupleWithRest([hr,b.union([b.string(),b.number()])],b.union([b.string(),b.number()]))])),Gt={"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"},vr=(e,t,r=Gt)=>{let o=[],n=[];for(let s of e)for(let i of s.blocks)for(let[a,d]of Object.entries(po)){let c=r[a],l,h=[];if(Array.isArray(c)?(l=c[0],h.push(...c.slice(1))):l=c,l==="off")continue;let u=d.check(i,{categories:e,options:h,config:t});if(u){if(l==="error"){n.push(...u.map(v=>`${A} ${Rt} ${I.red(v)} ${I.gray(a)}`));continue}o.push(...u.map(v=>`${A} ${$e} ${v} ${I.gray(a)}`));}}return {warnings:o,errors:n}},jt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),d=r.find(l=>l.name===i)?.blocks.find(l=>l.name===a);if(!d)continue;let c=jt(e,d,r,n);if(c)return [...c,e]}},wr=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(jt(e,o,t))return !0}return !1};var He="jsrepo.json",_e="jsrepo-build-config.json",Ht=b.union([b.literal("prettier"),b.literal("biome")]),uo=b.objectWithRest({"*":b.string()},b.string()),qt=b.object({$schema:b.string(),repos:b.optional(b.array(b.string()),[]),includeTests:b.boolean(),paths:uo,watermark:b.optional(b.boolean(),!0),formatter:b.optional(Ht)}),Pe=e=>{if(!Ne.existsSync(X.join(e,He)))return S("Could not find your configuration file! Please run `init`.");let t=b.safeParse(qt,JSON.parse(Ne.readFileSync(X.join(e,He)).toString()));return t.success?j(t.output):S(`There was an error reading your \`${He}\` file!`)},go=b.object({$schema:b.string(),dirs:b.array(b.string()),includeBlocks:b.optional(b.array(b.string()),[]),includeCategories:b.optional(b.array(b.string()),[]),excludeBlocks:b.optional(b.array(b.string()),[]),excludeCategories:b.optional(b.array(b.string()),[]),doNotListBlocks:b.optional(b.array(b.string()),[]),doNotListCategories:b.optional(b.array(b.string()),[]),listBlocks:b.optional(b.array(b.string()),[]),listCategories:b.optional(b.array(b.string()),[]),excludeDeps:b.optional(b.array(b.string()),[]),preview:b.optional(b.boolean()),rules:b.optional(yr)}),It=e=>{if(!Ne.existsSync(X.join(e,_e)))return j(null);let t=b.safeParse(go,JSON.parse(Ne.readFileSync(X.join(e,_e)).toString()));return t.success?j(t.output):S(`There was an error reading your \`${_e}\` file!`)},Te=(e,t)=>{let r=getTsconfig(t,"tsconfig.json"),o=null;r||(r=getTsconfig(t,"jsconfig.json")),r&&(o=createPathsMatcher(r));let n;if(e["*"].startsWith("."))n={"*":X.relative(t,X.join(X.resolve(t),e["*"]))};else {if(o===null)return S("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":br(e["*"],o,t)};}for(let[s,i]of Object.entries(e))if(s!=="*"){if(i.startsWith(".")){n[s]=X.relative(t,X.join(X.resolve(t),i));continue}if(o===null)return S("Cannot resolve aliases because we couldn't find a tsconfig!");n[s]=br(i,o,t);}return j(n)},br=(e,t,r)=>{let o=t(e);return X.relative(r,o[0])};var qe=e=>e.replace(ho(),"");var ht=(e,t,r=" ")=>{if(qe(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-qe(e).length)+e},kr=(e,t,r=" ")=>e+r.repeat(t),Rr=(e,t,r=" ")=>{if(qe(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-qe(e).length)};var vo=/\n|\r\n/g,ee=e=>e.split(vo),Y=(e,{lineNumbers:t=!1,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${ht(`${i+1}`,n)} ${s}`);}return r!==void 0&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(yo.EOL)};var Yt=(e,t)=>{let r=X.join(e,"package.json");if(Ne.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Yt(o.slice(0,o.length-1).join("/"),t)},wo=e=>{if(!Ne.existsSync(e))return S(`${e} doesn't exist`);let t=Ne.readFileSync(e).toString();return j(JSON.parse(t))},St=(e,t,{cwd:r})=>{let o=e,n=t,s=wo(X.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of o){let[d,c]=a.split("@"),l=i.dependencies[d];c===void 0&&l||l&&l===c&&o.delete(a);}if(i.devDependencies)for(let a of n){let[d,c]=a.split("@"),l=i.devDependencies[d];c===void 0&&l||l&&l===c&&n.delete(a);}}return {dependencies:o,devDependencies:n}};var Co={matches:e=>e.endsWith(".css"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
3
- ${Y(ee(e),{prefix:()=>" "})}
4
- */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Oe.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},xo={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ne.readFileSync(e).toString(),i=Sr.parse(s),a=[],d=(l,h)=>{if(l&&(h(l),l.childNodes&&l.childNodes.length>0))for(let u of l.childNodes)d(u,h);};for(let l of i.childNodes)d(l,h=>{if(h.tagName==="script")for(let u of h.attrs)u.name==="src"&&a.push(u.value);if(h.tagName==="link"&&h.attrs.find(u=>u.name==="rel"&&u.value==="stylesheet"))for(let u of h.attrs)u.name==="href"&&!u.value.startsWith("http")&&a.push(u.value);});let c=At({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return c.isErr()?S(c.unwrapErr().map(l=>Dt(l)).join(`
5
- `)):j(c.unwrap())},comment:e=>`<!--
6
- ${Y(ee(e),{prefix:()=>" "})}
7
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Oe.format(e,{parser:"html",...r}):e},Xt={matches:e=>e.endsWith(".json"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Oe.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},jo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
8
- ${Y(ee(e),{prefix:()=>" "})}
9
- */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Oe.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:!0}}}),s.formatContent(e,{filePath:n}).content}},Eo={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
10
- ${Y(ee(e),{prefix:()=>" "})}
11
- */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Oe.format(e,{parser:"scss",...r}):e},Io={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ne.readFileSync(e).toString(),i=Pr.parse(s,{modern:!0,filename:e});if(!i.instance&&!i.module)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let a=[],d=l=>{(l.type==="ImportDeclaration"||l.type==="ExportAllDeclaration"||l.type==="ExportNamedDeclaration")&&typeof l.source?.value=="string"&&a.push(l.source.value);};i.instance&&walk(i.instance,{enter:d}),i.module&&walk(i.module,{enter:d});let c=At({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return c.isErr()?S(c.unwrapErr().map(l=>Dt(l)).join(`
12
- `)):j(c.unwrap())},comment:e=>`<!--
13
- ${Y(ee(e),{prefix:()=>" "})}
14
- -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Oe.format(e,{filepath:r,...o}):e},So={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
15
- ${Y(ee(e),{prefix:()=>" "})}
16
- -->`,format:async e=>e},Po={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})=>{let i=new Project().addSourceFileAtPath(e),a=i.getImportDeclarations().map(l=>l.getModuleSpecifierValue()),d=i.getExportDeclarations().map(l=>l.getModuleSpecifierValue()).filter(l=>l!==void 0);a.push(...d);let c=At({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return c.isErr()?S(c.unwrapErr().map(l=>Dt(l)).join(`
17
- `)):j(c.unwrap())},comment:e=>`/*
18
- ${Y(ee(e),{prefix:()=>" "})}
19
- */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Oe.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},To={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ne.readFileSync(e).toString(),i=Ot.parse(s,{filename:e});if(!i.descriptor.script?.content&&!i.descriptor.scriptSetup?.content)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let a;try{a=Ot.compileScript(i.descriptor,{id:"shut-it"});}catch(l){return S(`Compile error: ${l}`)}if(!a.imports)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let d=Object.values(a.imports).map(l=>l.source),c=At({moduleSpecifiers:d,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return c.isErr()?S(c.unwrapErr().map(l=>Dt(l)).join(`
20
- `)):j(c.unwrap())},comment:e=>`<!--
21
- ${Y(ee(e),{prefix:()=>" "})}
22
- -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Oe.format(e,{parser:"vue",...r}):e},No={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>Y(ee(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Oe.format(e,{parser:"yaml",...r}):e},Dt=e=>`${Y(ee(e),{prefix:t=>t===0?`${A} ${Rt} `:`${A} `})}`,At=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:s})=>{let i=[],a=new Set,d=new Set,c={};for(let u of e){if(u.startsWith(".")){let L=Tr(u,t,{filePath:r,dirs:n,cwd:s});if(L.isErr()){i.push(L.unwrapErr());continue}let f=L.unwrap();f&&(d.add(f.dependency),c[u]=f.template);continue}let v=Oo(u,t,{filePath:r,dirs:n,cwd:s});if(v.isErr()){i.push(v.unwrapErr());continue}let C=v.unwrap();C?(d.add(C.dependency),c[u]=C.template):a.add(u);}if(i.length>0)return S(i);let{devDependencies:l,dependencies:h}=Ao(Array.from(a),r,{doNotInstall:o||[]});return j({dependencies:h,devDependencies:l,local:Array.from(d),imports:c})},Tr=(e,t,{filePath:r,alias:o,dirs:n,cwd:s})=>{if(t&&(e.startsWith("./")||e==="."))return j(void 0);let i=t?X.join(r,"../../"):X.join(r,"../"),a=X.join(X.join(r,"../"),e),d=X.join(i,"../");if(a.startsWith(d))return j(Ir(a.slice(d.length)));if(o){for(let c of n){let l=X.resolve(X.join(s,c)),h=X.resolve(a);if(h.startsWith(l))return j(Ir(h.slice(l.length+1)))}return S(`${r}:
23
- ${o} references code not contained in ${I.bold(n.join(", "))} and cannot be resolved.`)}return S(`${r}:
24
- ${e} references code not contained in ${i} and cannot be resolved.`)},Ir=e=>{let[t,r,...o]=e.split("/");r===void 0&&(r="index");let n=r;n.includes(".")&&(n=n.slice(0,n.length-X.parse(n).ext.length));let s=`${t}/${n}`,i=`{{${s}}}`;return o.length===0?n.length!==r.length&&(i+=X.parse(r).ext):i+=`/${o.join("/")}`,{dependency:s,template:i}},Oo=(e,t,{filePath:r,dirs:o,cwd:n})=>{let s;try{if(s=getTsconfig(r,"tsconfig.json"),!s&&(s=getTsconfig(r,"jsconfig.json"),!s))return j(void 0)}catch(a){return S(`Error while trying to get ${I.bold("tsconfig.json")}: ${a}`)}let i=createPathsMatcher(s);if(i){let a=i(e);for(let d of a){let c=Do(d);if(!c)continue;let l=X.relative(X.resolve(X.join(r,"../")),c.path),h=Tr(l,t,{filePath:r,alias:e,dirs:o,cwd:n,modIsFile:c.type==="file"});if(h.isErr())return S(h.unwrapErr());if(h.unwrap())return j(h.unwrap());break}}return j(void 0)},Do=e=>{if(Ne.existsSync(e))return {path:e,type:Ne.statSync(e).isDirectory()?"directory":"file"};if(X.parse(e).ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Ne.existsSync(n))return {path:e,type:"file"}}let r=X.join(e,"../");if(!Ne.existsSync(r))return;let o=Ne.readdirSync(r);for(let n of o)if(X.parse(n).name===X.basename(e)){let i=X.join(r,n),a=i;return a.endsWith(".ts")&&(a=a.slice(0,a.length-3)),{path:a,type:Ne.statSync(i).isDirectory()?"directory":"file"}}},Ao=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(d=>!builtinModules.includes(d)&&!d.startsWith("node:")),s=Yt(X.dirname(t),""),i=new Set,a=new Set;if(s){let{devDependencies:d,dependencies:c}=JSON.parse(Ne.readFileSync(s,"utf-8"));for(let l of n){let h=xt(l);if(h.isErr()){console.warn(`${A} ${$e} Skipped adding import \`${I.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let u=h.unwrap();if(!Ro(u.name).validForNewPackages){console.warn(`${A} ${$e} Skipped adding import \`${I.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let v;if(c!==void 0&&(v=c[u.name]),v!==void 0){i.add(`${u.name}@${v}`);continue}if(d!==void 0&&(v=d[u.name]),v!==void 0){a.add(`${u.name}@${v}`);continue}i.add(u.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(a)}},Ke=[Co,xo,Xt,jo,Eo,Io,So,Po,To,No];var Lo=b.object({name:b.string(),category:b.string(),localDependencies:b.array(b.string()),dependencies:b.array(b.string()),devDependencies:b.array(b.string()),tests:b.boolean(),list:b.optional(b.boolean(),!0),directory:b.string(),subdirectory:b.boolean(),files:b.array(b.string()),_imports_:b.record(b.string(),b.string())}),yt=b.object({name:b.string(),blocks:b.array(Lo)}),Nr=[".test.ts","_test.ts",".test.js","_test.js"],Re=e=>Nr.find(t=>e.endsWith(t))!==void 0,Or=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,excludeBlocks:s,excludeCategories:i,dirs:a,doNotListBlocks:d,doNotListCategories:c,listBlocks:l,listCategories:h}})=>{let u;try{u=Ne.readdirSync(e);}catch{program.error(I.red(`Couldn't read the ${I.bold(e)} directory.`));}let v=[];for(let C of u){let L=X.join(e,C);if(Ne.statSync(L).isFile())continue;let f=X.basename(C);if(i.length>0&&i.find(D=>D.trim()===f.trim())||n.length>0&&!n.find(D=>D.trim()===f.trim()))continue;let R=!0;c.includes(f)&&(R=!1),h.length>0&&!h.includes(f)&&(R=!1);let J={name:f,blocks:[]},B=Ne.readdirSync(L);for(let D of B){let p=X.join(L,D);if(Ne.statSync(p).isFile()){if(Re(D))continue;let g=Bo(D),E=!0;if(d.includes(g)&&(E=!1),l.length>0&&!l.includes(g)&&(E=!1),s.length>0&&s.find(w=>w.trim()===g.trim())||o.length>0&&!o.find(w=>w.trim()===g.trim()))continue;let $=Ke.find(w=>w.matches(D));if(!$){console.warn(`${A} ${$e} Skipped \`${I.bold(p)}\` \`*${I.bold(X.parse(D).ext)}\` files are not currently supported!`);continue}let _=B.find(w=>Nr.find(T=>w===`${g}${T}`)),{dependencies:y,devDependencies:P,local:m,imports:k}=$.resolveDependencies({filePath:p,isSubDir:!1,excludeDeps:r,cwd:t,dirs:a}).match(w=>w,w=>{program.error(I.red(w));}),x={name:g,directory:X.relative(t,L),category:f,tests:_!==void 0,subdirectory:!1,list:R?E:!1,files:[D],localDependencies:m,_imports_:k,dependencies:y,devDependencies:P};_!==void 0&&x.files.push(_),J.blocks.push(x);}else {let g=D,E=!0;if(d.includes(g)&&(E=!1),l.length>0&&!l.includes(g)&&(E=!1),s.length>0&&s.find(w=>w.trim()===g.trim())||o.length>0&&!o.find(w=>w.trim()===g.trim()))continue;let $=Ne.readdirSync(p),_=$.findIndex(w=>Re(w))!==-1,y=new Set,P=new Set,m=new Set,k={};for(let w of $){if(Re(w))continue;if(Ne.statSync(X.join(p,w)).isDirectory()){console.warn(`${A} ${$e} Skipped \`${I.bold(X.join(p,w))}\` subdirectories are not currently supported!`);continue}let T=Ke.find(F=>F.matches(w));if(!T){console.warn(`${A} ${$e} Skipped \`${X.join(p,w)}\` \`*${I.bold(X.parse(w).ext)}\` files are not currently supported!`);continue}let{local:K,dependencies:ye,devDependencies:Ie,imports:z}=T.resolveDependencies({filePath:X.join(p,w),isSubDir:!0,excludeDeps:r,cwd:t,dirs:a}).match(F=>F,F=>{program.error(I.red(F));});for(let F of K)F!==`${f}/${g}`&&y.add(F);for(let F of ye)P.add(F);for(let F of Ie)m.add(F);for(let[F,ve]of Object.entries(z))k[F]=ve;}let x={name:g,directory:X.relative(t,p),category:f,tests:_,subdirectory:!0,list:R?E:!1,files:[...$],localDependencies:Array.from(y.keys()),dependencies:Array.from(P.keys()),devDependencies:Array.from(m.keys()),_imports_:k};J.blocks.push(x);}}v.push(J);}return v},Bo=e=>X.parse(X.basename(e)).name,Dr=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!wr(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var fe="jsrepo-manifest.json";var se=()=>new Fo({projectName:"jsrepo"});var Ve=(e,t,r)=>S(`There was an error fetching the \`${I.bold(t)}\` from ${I.bold(e.url)}.
2
+ import Ae from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import Q from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,password,intro}from'@clack/prompts';import P from'chalk';import {resolveCommand}from'package-manager-detector/commands';import {detect}from'package-manager-detector/detect';import*as C from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import ut from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as Ft from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as _r from'parse5';import*as Le from'prettier';import*as Wr from'svelte/compiler';import {Project}from'ts-morph';import Do from'validate-npm-package-name';import Io from'node:os';import Eo from'ansi-regex';import Ko from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import sn from'escape-string-regexp';import {diffLines,diffChars}from'diff';var W=P.gray("\u2502"),Yt=P.gray("\u2500"),Rr=P.gray("\u2510"),Cr=P.gray("\u2518"),Xt=P.gray("\u251C");P.gray("\u250C");P.gray("\u2514");var Ie=P.bgRgb(245,149,66).black(" WARN "),ft=P.bgBlueBright.white(" INFO "),It=P.bgRedBright.white(" ERROR "),fe=P.hex("#f7df1e")("jsrepo");var St=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>I(t(r)),r=>T(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>I(r),r=>T(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>!0,()=>!1)}isErr(){return this.match(()=>!1,()=>!0)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},I=e=>new St({ok:!0,val:e}),T=e=>new St({ok:!1,err:e});var xr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var $o=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,ko=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,Pt=e=>{let t=$o.exec(e)||ko.exec(e);return t?I({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):T(`invalid package name: ${e}`)};var jr=C.union([C.literal("off"),C.literal("warn"),C.literal("error")]),bo={"no-unpinned-dependency":{description:"Require all dependencies to have a pinned version.",check:e=>{let t=[];for(let r of [...e.dependencies,...e.devDependencies])r.includes("@")||t.push(`Couldn't find a version to use for ${P.bold(r)}`);return t.length>0?t:void 0}},"require-local-dependency-exists":{description:"Require all local dependencies to exist.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/"),i=t.find(p=>p.name.trim()===n.trim()),a=`${P.bold(`${e.category}/${e.name}`)} depends on local dependency ${P.bold(o)} which doesn't exist`;if(!i){r.push(a);continue}i.blocks.find(p=>p.name===s)===void 0&&r.push(a);}return r.length>0?r:void 0}},"no-category-index-file-dependency":{description:"Disallow depending on the index file of a category.",check:(e,{categories:t})=>{let r=[];for(let o of e.localDependencies){let[n,s]=o.split("/");if(s!=="index")continue;let i=t.find(p=>p.name===n);!i||!i.blocks.find(p=>p.name===s)||r.push(`${P.bold(`${e.category}/${e.name}`)} depends on ${P.bold(`${n}/${s}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${P.bold(`${e.category}/${e.name}`)} has too many local dependencies (${P.bold(e.localDependencies.length)}) limit (${P.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",check:(e,{categories:t})=>{let r=[],o=`${e.category}/${e.name}`,n=Tt(o,e,t);return n&&r.push(`There is a circular dependency in ${P.bold(o)}: ${P.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)",check:(e,{categories:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Tt(r,n,t))return;return [`${P.bold(r)} is unused and will be ${P.bold.red("removed")}`]}},"no-framework-dependency":{description:"Disallow frameworks (Svelte, Vue, React) as dependencies.",check:e=>{let t=[],r=new Set(["svelte","vue","nuxt","react","react-dom","next","@remix-run/react","@builder.io/qwik","astro","solid-js","@angular/core","@angular/common","@angular/forms","@angular/platform-browser","@angular/platform-browser-dynamic","@angular/router"]),o=[...e.devDependencies,...e.dependencies].map(n=>Pt(n).unwrap().name).filter(n=>r.has(n));if(o.length>0)for(let n of o)t.push(`${P.bold(`${e.category}/${e.name}`)} depends on ${P.bold(n)} causing it to be installed when added`);return t.length>0?t:void 0}}},Ro=C.union([C.literal("no-category-index-file-dependency"),C.literal("no-unpinned-dependency"),C.literal("require-local-dependency-exists"),C.literal("max-local-dependencies"),C.literal("no-circular-dependency"),C.literal("no-unused-block"),C.literal("no-framework-dependency")]),Er=C.record(Ro,C.union([jr,C.tupleWithRest([jr,C.union([C.string(),C.number()])],C.union([C.string(),C.number()]))])),Zt={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn","no-framework-dependency":"warn"},Ir=(e,t,r=Zt)=>{let o=[],n=[];for(let s of e)for(let i of s.blocks)for(let[a,p]of Object.entries(bo)){let c=r[a],l,y=[];if(Array.isArray(c)?(l=c[0],y.push(...c.slice(1))):l=c,l==="off")continue;let u=p.check(i,{categories:e,options:y,config:t});if(u){if(l==="error"){n.push(...u.map(k=>`${W} ${It} ${P.red(k)} ${P.gray(a)}`));continue}o.push(...u.map(k=>`${W} ${Ie} ${k} ${P.gray(a)}`));}}return {warnings:o,errors:n}},Tt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let s of t.localDependencies){if(s===e)return n;if(o.includes(s))return;let[i,a]=s.split("/"),p=r.find(l=>l.name===i)?.blocks.find(l=>l.name===a);if(!p)continue;let c=Tt(e,p,r,n);if(c)return [...c,e]}},Sr=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Tt(e,o,t))return !0}return !1};var tt="jsrepo.json",Ue="jsrepo-build-config.json",Qt=C.union([C.literal("prettier"),C.literal("biome")]),xo=C.objectWithRest({"*":C.string()},C.string()),er=C.object({$schema:C.string(),repos:C.optional(C.array(C.string()),[]),includeTests:C.boolean(),paths:xo,watermark:C.optional(C.boolean(),!0),formatter:C.optional(Qt)}),$e=e=>{if(!Ae.existsSync(Q.join(e,tt)))return T("Could not find your configuration file! Please run `init`.");let t=C.safeParse(er,JSON.parse(Ae.readFileSync(Q.join(e,tt)).toString()));return t.success?I(t.output):T(`There was an error reading your \`${tt}\` file!`)},jo=C.object({$schema:C.string(),dirs:C.array(C.string()),includeBlocks:C.optional(C.array(C.string()),[]),includeCategories:C.optional(C.array(C.string()),[]),excludeBlocks:C.optional(C.array(C.string()),[]),excludeCategories:C.optional(C.array(C.string()),[]),doNotListBlocks:C.optional(C.array(C.string()),[]),doNotListCategories:C.optional(C.array(C.string()),[]),listBlocks:C.optional(C.array(C.string()),[]),listCategories:C.optional(C.array(C.string()),[]),excludeDeps:C.optional(C.array(C.string()),[]),preview:C.optional(C.boolean()),rules:C.optional(Er)}),Ot=e=>{if(!Ae.existsSync(Q.join(e,Ue)))return I(null);let t=C.safeParse(jo,JSON.parse(Ae.readFileSync(Q.join(e,Ue)).toString()));return t.success?I(t.output):T(`There was an error reading your \`${Ue}\` file!`)},ke=(e,t)=>{let r=getTsconfig(t,"tsconfig.json"),o=null;r||(r=getTsconfig(t,"jsconfig.json")),r&&(o=createPathsMatcher(r));let n;if(e["*"].startsWith("."))n={"*":Q.relative(t,Q.join(Q.resolve(t),e["*"]))};else {if(o===null)return T("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":Tr(e["*"],o,t)};}for(let[s,i]of Object.entries(e))if(s!=="*"){if(i.startsWith(".")){n[s]=Q.relative(t,Q.join(Q.resolve(t),i));continue}if(o===null)return T("Cannot resolve aliases because we couldn't find a tsconfig!");n[s]=Tr(i,o,t);}return I(n)},Tr=(e,t,r)=>{let o=t(e);return Q.relative(r,o[0])};var rt=e=>e.replace(Eo(),"");var Rt=(e,t,r=" ")=>{if(rt(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-rt(e).length)+e},Nr=(e,t,r=" ")=>e+r.repeat(t),Or=(e,t,r=" ")=>{if(rt(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-rt(e).length)};var So=/\n|\r\n/g,re=e=>e.split(So),Z=(e,{lineNumbers:t=!1,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((s,i)=>`${Rt(`${i+1}`,n)} ${s}`);}return r!==void 0&&(o=o.map((n,s)=>`${r(s,e.length)}${n}`)),o.join(Io.EOL)};var rr=(e,t)=>{let r=Q.join(e,"package.json");if(Ae.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return rr(o.slice(0,o.length-1).join("/"),t)},Po=e=>{if(!Ae.existsSync(e))return T(`${e} doesn't exist`);let t=Ae.readFileSync(e).toString();return I(JSON.parse(t))},Dt=(e,t,{cwd:r})=>{let o=e,n=t,s=Po(Q.join(r,"package.json"));if(!s.isErr()){let i=s.unwrap();if(i.dependencies)for(let a of o){let[p,c]=a.split("@"),l=i.dependencies[p];c===void 0&&l||l&&l===c&&o.delete(a);}if(i.devDependencies)for(let a of n){let[p,c]=a.split("@"),l=i.devDependencies[p];c===void 0&&l||l&&l===c&&n.delete(a);}}return {dependencies:o,devDependencies:n}};var Ao={matches:e=>e.endsWith(".css"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
3
+ ${Z(re(e),{prefix:()=>" "})}
4
+ */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},Lo={matches:e=>e.endsWith(".html"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=_r.parse(s),a=[],p=(l,y)=>{if(l&&(y(l),l.childNodes&&l.childNodes.length>0))for(let u of l.childNodes)p(u,y);};for(let l of i.childNodes)p(l,y=>{if(y.tagName==="script")for(let u of y.attrs)u.name==="src"&&a.push(u.value);if(y.tagName==="link"&&y.attrs.find(u=>u.name==="rel"&&u.value==="stylesheet"))for(let u of y.attrs)u.name==="href"&&!u.value.startsWith("http")&&a.push(u.value);});let c=Wt({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return c.isErr()?T(c.unwrapErr().map(l=>_t(l)).join(`
5
+ `)):I(c.unwrap())},comment:e=>`<!--
6
+ ${Z(re(e),{prefix:()=>" "})}
7
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"html",...r}):e},or={matches:e=>e.endsWith(".json"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration(o),s.formatContent(e,{filePath:n}).content}},Bo={matches:e=>e.endsWith(".jsonc"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
8
+ ${Z(re(e),{prefix:()=>" "})}
9
+ */`,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:n,...r});let s=await Biome.create({distribution:Distribution.NODE});return o&&s.applyConfiguration({...o,json:{parser:{allowComments:!0}}}),s.formatContent(e,{filePath:n}).content}},Fo={matches:e=>e.endsWith(".sass")||e.endsWith(".scss"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`/*
10
+ ${Z(re(e),{prefix:()=>" "})}
11
+ */`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"scss",...r}):e},_o={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=Wr.parse(s,{modern:!0,filename:e});if(!i.instance&&!i.module)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let a=[],p=l=>{(l.type==="ImportDeclaration"||l.type==="ExportAllDeclaration"||l.type==="ExportNamedDeclaration")&&typeof l.source?.value=="string"&&a.push(l.source.value);};i.instance&&walk(i.instance,{enter:p}),i.module&&walk(i.module,{enter:p});let c=Wt({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return c.isErr()?T(c.unwrapErr().map(l=>_t(l)).join(`
12
+ `)):I(c.unwrap())},comment:e=>`<!--
13
+ ${Z(re(e),{prefix:()=>" "})}
14
+ -->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await Le.format(e,{filepath:r,...o}):e},Wo={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
15
+ ${Z(re(e),{prefix:()=>" "})}
16
+ -->`,format:async e=>e},Vo={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})=>{let i=new Project().addSourceFileAtPath(e),a=i.getImportDeclarations().map(l=>l.getModuleSpecifierValue()),p=i.getExportDeclarations().map(l=>l.getModuleSpecifierValue()).filter(l=>l!==void 0);a.push(...p);let c=Wt({moduleSpecifiers:a,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return c.isErr()?T(c.unwrapErr().map(l=>_t(l)).join(`
17
+ `)):I(c.unwrap())},comment:e=>`/*
18
+ ${Z(re(e),{prefix:()=>" "})}
19
+ */`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await Le.format(e,{filepath:r,...o});let s=await Biome.create({distribution:Distribution.NODE});return n&&s.applyConfiguration(n),s.formatContent(e,{filePath:r}).content}},Mo={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=Ae.readFileSync(e).toString(),i=Ft.parse(s,{filename:e});if(!i.descriptor.script?.content&&!i.descriptor.scriptSetup?.content)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let a;try{a=Ft.compileScript(i.descriptor,{id:"shut-it"});}catch(l){return T(`Compile error: ${l}`)}if(!a.imports)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let p=Object.values(a.imports).map(l=>l.source),c=Wt({moduleSpecifiers:p,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return c.isErr()?T(c.unwrapErr().map(l=>_t(l)).join(`
20
+ `)):I(c.unwrap())},comment:e=>`<!--
21
+ ${Z(re(e),{prefix:()=>" "})}
22
+ -->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"vue",...r}):e},Jo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>Z(re(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await Le.format(e,{parser:"yaml",...r}):e},_t=e=>`${Z(re(e),{prefix:t=>t===0?`${W} ${It} `:`${W} `})}`,Wt=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:s})=>{let i=[],a=new Set,p=new Set,c={};for(let u of e){if(u.startsWith(".")){let A=Vr(u,t,{filePath:r,dirs:n,cwd:s});if(A.isErr()){i.push(A.unwrapErr());continue}let m=A.unwrap();m&&(p.add(m.dependency),c[u]=m.template);continue}let k=zo(u,t,{filePath:r,dirs:n,cwd:s});if(k.isErr()){i.push(k.unwrapErr());continue}let x=k.unwrap();x?(p.add(x.dependency),c[u]=x.template):a.add(u);}if(i.length>0)return T(i);let{devDependencies:l,dependencies:y}=Go(Array.from(a),r,{doNotInstall:o||[]});return I({dependencies:y,devDependencies:l,local:Array.from(p),imports:c})},Vr=(e,t,{filePath:r,alias:o,dirs:n,cwd:s})=>{if(t&&(e.startsWith("./")||e==="."))return I(void 0);let i=t?Q.join(r,"../../"):Q.join(r,"../"),a=Q.join(Q.join(r,"../"),e),p=Q.join(i,"../");if(a.startsWith(p))return I(Fr(a.slice(p.length)));if(o){for(let c of n){let l=Q.resolve(Q.join(s,c)),y=Q.resolve(a);if(y.startsWith(l))return I(Fr(y.slice(l.length+1)))}return T(`${r}:
23
+ ${o} references code not contained in ${P.bold(n.join(", "))} and cannot be resolved.`)}return T(`${r}:
24
+ ${e} references code not contained in ${i} and cannot be resolved.`)},Fr=e=>{let[t,r,...o]=e.split("/");r===void 0&&(r="index");let n=r;n.includes(".")&&(n=n.slice(0,n.length-Q.parse(n).ext.length));let s=`${t}/${n}`,i=`{{${s}}}`;return o.length===0?n.length!==r.length&&(i+=Q.parse(r).ext):i+=`/${o.join("/")}`,{dependency:s,template:i}},zo=(e,t,{filePath:r,dirs:o,cwd:n})=>{let s;try{if(s=getTsconfig(r,"tsconfig.json"),!s&&(s=getTsconfig(r,"jsconfig.json"),!s))return I(void 0)}catch(a){return T(`Error while trying to get ${P.bold("tsconfig.json")}: ${a}`)}let i=createPathsMatcher(s);if(i){let a=i(e);for(let p of a){let c=Uo(p);if(!c)continue;let l=Q.relative(Q.resolve(Q.join(r,"../")),c.path),y=Vr(l,t,{filePath:r,alias:e,dirs:o,cwd:n,modIsFile:c.type==="file"});if(y.isErr())return T(y.unwrapErr());if(y.unwrap())return I(y.unwrap());break}}return I(void 0)},Uo=e=>{if(Ae.existsSync(e))return {path:e,type:Ae.statSync(e).isDirectory()?"directory":"file"};if(Q.parse(e).ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Ae.existsSync(n))return {path:e,type:"file"}}let r=Q.join(e,"../");if(!Ae.existsSync(r))return;let o=Ae.readdirSync(r);for(let n of o)if(Q.parse(n).name===Q.basename(e)){let i=Q.join(r,n),a=i;return a.endsWith(".ts")&&(a=a.slice(0,a.length-3)),{path:a,type:Ae.statSync(i).isDirectory()?"directory":"file"}}},Go=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(p=>!builtinModules.includes(p)&&!p.startsWith("node:")),s=rr(Q.dirname(t),""),i=new Set,a=new Set;if(s){let{devDependencies:p,dependencies:c}=JSON.parse(Ae.readFileSync(s,"utf-8"));for(let l of n){let y=Pt(l);if(y.isErr()){console.warn(`${W} ${Ie} Skipped adding import \`${P.cyan(l)}\`. Reason: Couldn't parse package name`);continue}let u=y.unwrap();if(!Do(u.name).validForNewPackages){console.warn(`${W} ${Ie} Skipped adding import \`${P.cyan(l)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let k;if(c!==void 0&&(k=c[u.name]),k!==void 0){i.add(`${u.name}@${k}`);continue}if(p!==void 0&&(k=p[u.name]),k!==void 0){a.add(`${u.name}@${k}`);continue}i.add(u.name);}}return {dependencies:Array.from(i),devDependencies:Array.from(a)}},ot=[Ao,Lo,or,Bo,Fo,_o,Wo,Vo,Mo,Jo];var Ho=C.object({name:C.string(),category:C.string(),localDependencies:C.array(C.string()),dependencies:C.array(C.string()),devDependencies:C.array(C.string()),tests:C.boolean(),list:C.optional(C.boolean(),!0),directory:C.string(),subdirectory:C.boolean(),files:C.array(C.string()),_imports_:C.record(C.string(),C.string())}),Ct=C.object({name:C.string(),blocks:C.array(Ho)}),Mr=[".test.ts","_test.ts",".test.js","_test.js"],ue=e=>Mr.find(t=>e.endsWith(t))!==void 0,Jr=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,excludeBlocks:s,excludeCategories:i,dirs:a,doNotListBlocks:p,doNotListCategories:c,listBlocks:l,listCategories:y}})=>{let u;try{u=Ae.readdirSync(e);}catch{program.error(P.red(`Couldn't read the ${P.bold(e)} directory.`));}let k=[];for(let x of u){let A=Q.join(e,x);if(Ae.statSync(A).isFile())continue;let m=Q.basename(x);if(i.length>0&&i.find(L=>L.trim()===m.trim())||n.length>0&&!n.find(L=>L.trim()===m.trim()))continue;let R=!0;c.includes(m)&&(R=!1),y.length>0&&!y.includes(m)&&(R=!1);let M={name:m,blocks:[]},F=Ae.readdirSync(A);for(let L of F){let f=Q.join(A,L);if(Ae.statSync(f).isFile()){if(ue(L))continue;let g=qo(L),E=!0;if(p.includes(g)&&(E=!1),l.length>0&&!l.includes(g)&&(E=!1),s.length>0&&s.find(v=>v.trim()===g.trim())||o.length>0&&!o.find(v=>v.trim()===g.trim()))continue;let b=ot.find(v=>v.matches(L));if(!b){console.warn(`${W} ${Ie} Skipped \`${P.bold(f)}\` \`*${P.bold(Q.parse(L).ext)}\` files are not currently supported!`);continue}let _=F.find(v=>Mr.find(j=>v===`${g}${j}`)),{dependencies:h,devDependencies:S,local:d,imports:w}=b.resolveDependencies({filePath:f,isSubDir:!1,excludeDeps:r,cwd:t,dirs:a}).match(v=>v,v=>{program.error(P.red(v));}),$={name:g,directory:Q.relative(t,A),category:m,tests:_!==void 0,subdirectory:!1,list:R?E:!1,files:[L],localDependencies:d,_imports_:w,dependencies:h,devDependencies:S};_!==void 0&&$.files.push(_),M.blocks.push($);}else {let g=L,E=!0;if(p.includes(g)&&(E=!1),l.length>0&&!l.includes(g)&&(E=!1),s.length>0&&s.find(v=>v.trim()===g.trim())||o.length>0&&!o.find(v=>v.trim()===g.trim()))continue;let b=Ae.readdirSync(f),_=b.findIndex(v=>ue(v))!==-1,h=new Set,S=new Set,d=new Set,w={};for(let v of b){if(ue(v))continue;if(Ae.statSync(Q.join(f,v)).isDirectory()){console.warn(`${W} ${Ie} Skipped \`${P.bold(Q.join(f,v))}\` subdirectories are not currently supported!`);continue}let j=ot.find(B=>B.matches(v));if(!j){console.warn(`${W} ${Ie} Skipped \`${Q.join(f,v)}\` \`*${P.bold(Q.parse(v).ext)}\` files are not currently supported!`);continue}let{local:z,dependencies:ce,devDependencies:ve,imports:N}=j.resolveDependencies({filePath:Q.join(f,v),isSubDir:!0,excludeDeps:r,cwd:t,dirs:a}).match(B=>B,B=>{program.error(P.red(B));});for(let B of z)B!==`${m}/${g}`&&h.add(B);for(let B of ce)S.add(B);for(let B of ve)d.add(B);for(let[B,ee]of Object.entries(N))w[B]=ee;}let $={name:g,directory:Q.relative(t,f),category:m,tests:_,subdirectory:!0,list:R?E:!1,files:[...b],localDependencies:Array.from(h.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(d.keys()),_imports_:w};M.blocks.push($);}}k.push(M);}return k},qo=e=>Q.parse(Q.basename(e)).name,zr=e=>{let t=[];for(let o of e){let n=[];for(let s of o.blocks){let i=`${s.category}/${s.name}`;!s.list&&!Sr(i,e)||n.push(s);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var be="jsrepo-manifest.json";var le=()=>new Ko({projectName:"jsrepo"});var He=(e,t,r)=>T(`There was an error fetching the \`${P.bold(t)}\` from ${P.bold(e.url)}.
25
25
 
26
- ${I.bold("This may be for one of the following reasons:")}
27
- 1. The \`${I.bold(t)}\` or containing repository doesn't exist
28
- 2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than \`${I.bold(r)}\` must be specified \`${I.bold("github/<owner>/<name>/tree/<branch>")}\`
26
+ ${P.bold("This may be for one of the following reasons:")}
27
+ 1. The \`${P.bold(t)}\` or containing repository doesn't exist
28
+ 2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than \`${P.bold(r)}\` must be specified \`${P.bold("github/<owner>/<name>/tree/<branch>")}\`
29
29
  3. You are using an expired access token or a token that doesn't have access to this repository
30
- `),ie={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await ie.info(e);return new URL(t,`https://raw.githubusercontent.com/${r.owner}/${r.repoName}/refs/${r.refs}/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ie.info(e),n=await ie.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=se().get(`${ie.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await st(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ve(o,t,ie.defaultBranch())}catch(s){return r?.(`erroring in response ${s} `),Ve(o,t,ie.defaultBranch())}},fetchManifest:async e=>{let t=await ie.fetchRaw(e,fe);if(t.isErr())return S(t.unwrapErr());let r=b.safeParse(b.array(yt),JSON.parse(t.unwrap()));return r.success?j(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/github.com\/)|(github\/)/g,""),[r,o,...n]=t.split("/"),s=ie.defaultBranch(),i=se().get(`${ie.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:c}=await a.rest.repos.get({owner:r,repo:o});s=c.default_branch;}catch{}let d="heads";if(s!==ie.defaultBranch())try{let{data:c}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});c.some(l=>l.ref===`refs/tags/${s}`)&&(d="tags");}catch{d="heads";}return {refs:d,url:e,name:ie.name(),repoName:o,owner:r,ref:s,provider:ie}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Ce={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await Ce.info(e);return new URL(`${encodeURIComponent(t)}/raw?ref=${r.ref}`,`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r.owner}/${r.repoName}`)}/repository/files/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await ie.info(e),n=await Ce.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=se().get(`${Ce.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await st(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ve(o,t,Ce.defaultBranch())}catch{return Ve(o,t,Ce.defaultBranch())}},fetchManifest:async e=>{let t=await Ce.fetchRaw(e,fe);if(t.isErr())return S(t.unwrapErr());let r=b.safeParse(b.array(yt),JSON.parse(t.unwrap()));return r.success?j(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/gitlab.com\/)|(gitlab\/)/g,""),[r,o,...n]=t.split("/"),s=Ce.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,d]=n[2].split("?");s=a,d.startsWith("ref_type=")&&d.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=se().get(`${Ce.name()}-token`),d=new Headers;a!==void 0&&d.append("Authorization",`Bearer ${a}`);let c=await st(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:d});c.ok&&(s=(await c.json()).default_branch);}catch{}return {refs:i,url:e,name:Ce.name(),repoName:o,owner:r,ref:s,provider:Ce}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},me={name:()=>"bitbucket",defaultBranch:()=>"master",resolveRaw:async(e,t)=>{let r=await me.info(e);return new URL(t,`https://api.bitbucket.org/2.0/repositories/${r.owner}/${r.repoName}/src/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await me.info(e),n=await me.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=se().get(`${me.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await st(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ve(o,t,me.defaultBranch())}catch{return Ve(o,t,me.defaultBranch())}},fetchManifest:async e=>{let t=await me.fetchRaw(e,fe);if(t.isErr())return S(t.unwrapErr());let r=b.safeParse(b.array(yt),JSON.parse(t.unwrap()));return r.success?j(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/bitbucket.org\/)|(bitbucket\/)/g,""),[r,o,...n]=t.split("/"),s="heads",i=me.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=se().get(`${me.name()}-token`),d=new Headers;a!==void 0&&d.append("Authorization",`Bearer ${a}`);let c=await st(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:d});c.ok&&(i=(await c.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:me.name(),repoName:o,owner:r,ref:i,provider:me}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},xe={name:()=>"azure",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await xe.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await xe.info(e),n=await xe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=se().get(`${xe.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await st(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?j(await a.text()):Ve(o,t,xe.defaultBranch())}catch(s){return r?.(`erroring in response ${s} `),Ve(o,t,xe.defaultBranch())}},fetchManifest:async e=>{let t=await xe.fetchRaw(e,fe);if(t.isErr())return S(t.unwrapErr());let r=b.safeParse(b.array(yt),JSON.parse(t.unwrap()));return r.success?j(r.output):S(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=xe.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:xe.name(),projectName:o,repoName:n,owner:r,ref:i,provider:xe}},matches:e=>e.toLowerCase().startsWith("azure")},q=[ie,Ce,me,xe],Xe=async e=>{let t=q.find(r=>r.matches(e));return t?j(await t.info(e)):S(`Only ${q.map((r,o)=>`${o===q.length-1?"and":""}${I.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},it=async(...e)=>{let t=new Map;for(let{path:r,info:o}of e){let n=await o.provider.fetchManifest(o);if(n.isErr())return S({message:n.unwrapErr(),repo:r});let s=n.unwrap();for(let i of s)for(let a of i.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${i.name}/${a.name}`,{...a,sourceRepo:o});}return j(t)},at=async(...e)=>{let t=[];for(let r of e){let o=await Xe(r);if(o.isErr())return S({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return j(t)};var wt=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i;if(q.find(d=>s.startsWith(d.name()))){let[d,c,l,...h]=s.split("/");i=t.get(`${d}/${c}/${l}/${h.slice(h.length-2).join("/")}`);}else {if(r.length===0)return S(I.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${I.bold(`github/<owner>/<name>/${s}`)}\`!`));for(let{info:d}of r){let c=t.get(`${d.name}/${d.owner}/${d.repoName}/${s}`);if(c!==void 0){i=c;break}}}if(!i)return S(`Invalid block! ${I.bold(s)} does not exist!`);let a=`${i.category}/${i.name}`;if(n.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let d=await wt(i.localDependencies.filter(c=>!n.has(c)&&!o.has(c)),t,r,n);if(d.isErr())return S(d.unwrapErr());for(let c of d.unwrap())n.set(`${c.block.category}/${c.block.name}`,c);}}return j(gr(n,(s,i)=>i))},Me=(e,t,r)=>{let o=[],n=Te(t.paths,r);n.isErr()&&program.error(I.red(n.unwrapErr()));let s=n.unwrap();for(let[i,a]of e){let d;s[a.category]!==void 0?d=X.join(r,s[a.category]):d=X.join(r,s["*"],a.category);let c=X.join(d,a.files[0]);a.subdirectory&&(c=X.join(d,a.name)),Ne.existsSync(c)&&o.push({specifier:`${a.category}/${a.name}`,path:c,block:a});}return o};var Je=async({pm:e,deps:t,dev:r,cwd:o})=>{let n;if(r?n=resolveCommand$1(e,"install",[...t,"-D"]):n=resolveCommand$1(e,"install",[...t]),n==null)return S(I.red(`Could not resolve add command for '${e}'.`));try{return await execa(n.command,[...n.args],{cwd:o}),j(t)}catch{return S(I.red(`Failed to install ${I.bold(t.join(", "))}! Failed while running '${I.bold(`${n.command} ${n.args.join(" ")}`)}'`))}},Jo=/\{\{([^\/]+)\/([^\}]+)\}\}/g,Lr=({template:e,config:t,destPath:r,cwd:o})=>{let n=X.join(r,"../");return e.replace(Jo,(s,i,a)=>{if(t.paths[i]===void 0){if(t.paths["*"].startsWith(".")){let d=X.relative(n,X.join(o,t.paths["*"],i,a));return d.startsWith(".")?d:`./${d}`}return X.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let d=X.relative(n,X.join(o,t.paths[i],a));return d.startsWith(".")?d:`./${d}`}return X.join(t.paths[i],a)})};var Wt=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:s,cwd:i,verbose:a})=>{let d=Ke.find(l=>l.matches(e.destPath)),c=e.content;if(d){t.watermark&&(c=`${d.comment(o)}
30
+ `),de={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await de.info(e);return new URL(t,`https://raw.githubusercontent.com/${r.owner}/${r.repoName}/refs/${r.refs}/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await de.info(e),n=await de.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=le().get(`${de.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`token ${s}`);let a=await ut(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?I(await a.text()):He(o,t,de.defaultBranch())}catch(s){return r?.(`erroring in response ${s} `),He(o,t,de.defaultBranch())}},fetchManifest:async e=>{let t=await de.fetchRaw(e,be);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(Ct),JSON.parse(t.unwrap()));return r.success?I(r.output):T(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/github.com\/)|(github\/)/g,""),[r,o,...n]=t.split("/"),s=de.defaultBranch(),i=le().get(`${de.name()}-token`),a=new Octokit({auth:i});if(n[0]==="tree")s=n[1];else try{let{data:c}=await a.rest.repos.get({owner:r,repo:o});s=c.default_branch;}catch{}let p="heads";if(s!==de.defaultBranch())try{let{data:c}=await a.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});c.some(l=>l.ref===`refs/tags/${s}`)&&(p="tags");}catch{p="heads";}return {refs:p,url:e,name:de.name(),repoName:o,owner:r,ref:s,provider:de}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},Pe={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await Pe.info(e);return new URL(`${encodeURIComponent(t)}/raw?ref=${r.ref}`,`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r.owner}/${r.repoName}`)}/repository/files/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await de.info(e),n=await Pe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=le().get(`${Pe.name()}-token`),i=new Headers;s!==void 0&&i.append("PRIVATE-TOKEN",`${s}`);let a=await ut(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?I(await a.text()):He(o,t,Pe.defaultBranch())}catch{return He(o,t,Pe.defaultBranch())}},fetchManifest:async e=>{let t=await Pe.fetchRaw(e,be);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(Ct),JSON.parse(t.unwrap()));return r.success?I(r.output):T(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/gitlab.com\/)|(gitlab\/)/g,""),[r,o,...n]=t.split("/"),s=Pe.defaultBranch(),i="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[a,p]=n[2].split("?");s=a,p.startsWith("ref_type=")&&p.slice(10)==="tags"&&(i="tags");}else s=n[2];else try{let a=le().get(`${Pe.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let c=await ut(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:p});c.ok&&(s=(await c.json()).default_branch);}catch{}return {refs:i,url:e,name:Pe.name(),repoName:o,owner:r,ref:s,provider:Pe}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},Re={name:()=>"bitbucket",defaultBranch:()=>"master",resolveRaw:async(e,t)=>{let r=await Re.info(e);return new URL(t,`https://api.bitbucket.org/2.0/repositories/${r.owner}/${r.repoName}/src/${r.ref}/`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Re.info(e),n=await Re.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=le().get(`${Re.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ut(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?I(await a.text()):He(o,t,Re.defaultBranch())}catch{return He(o,t,Re.defaultBranch())}},fetchManifest:async e=>{let t=await Re.fetchRaw(e,be);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(Ct),JSON.parse(t.unwrap()));return r.success?I(r.output):T(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(https:\/\/bitbucket.org\/)|(bitbucket\/)/g,""),[r,o,...n]=t.split("/"),s="heads",i=Re.defaultBranch();if(n[0]==="src")i=n[1];else try{let a=le().get(`${Re.name()}-token`),p=new Headers;a!==void 0&&p.append("Authorization",`Bearer ${a}`);let c=await ut(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:p});c.ok&&(i=(await c.json()).mainbranch.name);}catch{}return {refs:s,url:e,name:Re.name(),repoName:o,owner:r,ref:i,provider:Re}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},Te={name:()=>"azure",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await Te.info(e),o=r.refs==="tags"?"tag":"branch";return new URL(`https://dev.azure.com/${r.owner}/${r.projectName}/_apis/git/repositories/${r.repoName}/items?path=${t}&api-version=7.2-preview.1&versionDescriptor.version=${r.ref}&versionDescriptor.versionType=${o}`)},fetchRaw:async(e,t,{verbose:r}={})=>{let o=await Te.info(e),n=await Te.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let s=le().get(`${Te.name()}-token`),i=new Headers;s!==void 0&&i.append("Authorization",`Bearer ${s}`);let a=await ut(n,{headers:i});return r?.(`Got a response from ${n} ${a.status} ${a.statusText}`),a.ok?I(await a.text()):He(o,t,Te.defaultBranch())}catch(s){return r?.(`erroring in response ${s} `),He(o,t,Te.defaultBranch())}},fetchManifest:async e=>{let t=await Te.fetchRaw(e,be);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(Ct),JSON.parse(t.unwrap()));return r.success?I(r.output):T(`Error parsing categories: ${r.issues}`)},info:async e=>{if(typeof e!="string")return e;let t=e.replaceAll(/(azure\/)/g,""),[r,o,n,...s]=t.split("/"),i=Te.defaultBranch(),a="heads";return ["tags","heads"].includes(s[0])&&(a=s[0],s[1]&&s[1]!==""&&(i=s[1])),{refs:a,url:e,name:Te.name(),projectName:o,repoName:n,owner:r,ref:i,provider:Te}},matches:e=>e.toLowerCase().startsWith("azure")},q=[de,Pe,Re,Te],st=async e=>{let t=q.find(r=>r.matches(e));return t?I(await t.info(e)):T(`Only ${q.map((r,o)=>`${o===q.length-1?"and":""}${P.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},qe=async(...e)=>{let t=new Map;for(let{path:r,info:o}of e){let n=await o.provider.fetchManifest(o);if(n.isErr())return T({message:n.unwrapErr(),repo:r});let s=n.unwrap();for(let i of s)for(let a of i.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${i.name}/${a.name}`,{...a,sourceRepo:o});}return I(t)},Ke=async(...e)=>{let t=[];for(let r of e){let o=await st(r);if(o.isErr())return T({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return I(t)};var it=async(e,t,r,o=new Map)=>{let n=new Map;for(let s of e){let i;if(q.find(p=>s.startsWith(p.name()))){let[p,c,l,...y]=s.split("/");i=t.get(`${p}/${c}/${l}/${y.slice(y.length-2).join("/")}`);}else {if(r.length===0)return T(P.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${P.bold(`github/<owner>/<name>/${s}`)}\`!`));for(let{info:p}of r){let c=t.get(`${p.name}/${p.owner}/${p.repoName}/${s}`);if(c!==void 0){i=c;break}}}if(!i)return T(`Invalid block! ${P.bold(s)} does not exist!`);let a=`${i.category}/${i.name}`;if(n.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let p=await it(i.localDependencies.filter(c=>!n.has(c)&&!o.has(c)),t,r,n);if(p.isErr())return T(p.unwrapErr());for(let c of p.unwrap())n.set(`${c.block.category}/${c.block.name}`,c);}}return I(xr(n,(s,i)=>i))},Ye=(e,t,r)=>{let o=[],n=ke(t.paths,r);n.isErr()&&program.error(P.red(n.unwrapErr()));let s=n.unwrap();for(let[i,a]of e){let p;s[a.category]!==void 0?p=Q.join(r,s[a.category]):p=Q.join(r,s["*"],a.category);let c=Q.join(p,a.files[0]);a.subdirectory&&(c=Q.join(p,a.name)),Ae.existsSync(c)&&o.push({specifier:`${a.category}/${a.name}`,path:c,block:a});}return o};var Qo={"no-workspace":"--no-workspace","install-as-dev-dependency":"-D"},en={"install-as-dev-dependency":"-D"},tn={"no-workspace":"--workspaces=false","install-as-dev-dependency":"-D"},Ur={"no-workspace":"--ignore-workspace","install-as-dev-dependency":"-D"},Gr={"no-workspace":"--focus","install-as-dev-dependency":"-D"},sr={bun:Qo,npm:tn,pnpm:Ur,deno:en,yarn:Gr,"yarn@berry":Gr,"pnpm@6":Ur};var Ne=async({pm:e,deps:t,dev:r,cwd:o,ignoreWorkspace:n=!1})=>{let s=[...t];r&&s.push(sr[e]["install-as-dev-dependency"]);let i=sr[e]["no-workspace"];n&&i&&s.push(i);let a=resolveCommand$1(e,"install",s);if(a==null)return T(P.red(`Could not resolve add command for '${e}'.`));try{return await execa(a.command,[...a.args],{cwd:o}),I(t)}catch{return T(P.red(`Failed to install ${P.bold(t.join(", "))}! Failed while running '${P.bold(`${a.command} ${a.args.join(" ")}`)}'`))}},nn=/\{\{([^\/]+)\/([^\}]+)\}\}/g,Hr=({template:e,config:t,destPath:r,cwd:o})=>{let n=Q.join(r,"../");return e.replace(nn,(s,i,a)=>{if(t.paths[i]===void 0){if(t.paths["*"].startsWith(".")){let p=Q.relative(n,Q.join(o,t.paths["*"],i,a));return p.startsWith(".")?p:`./${p}`}return Q.join(t.paths["*"],i,a)}if(t.paths[i].startsWith(".")){let p=Q.relative(n,Q.join(o,t.paths[i],a));return p.startsWith(".")?p:`./${p}`}return Q.join(t.paths[i],a)})};var Ut=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:s,cwd:i,verbose:a})=>{let p=ot.find(l=>l.matches(e.destPath)),c=e.content;if(p){t.watermark&&(c=`${p.comment(o)}
31
31
 
32
- ${c}`),a?.(`Formatting ${I.bold(e.destPath)}`);try{c=await d.format(c,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(l){return S(`Error formatting ${I.bold(e.destPath)} ${l}`)}}for(let[l,h]of Object.entries(r)){let u=Lr({template:h,config:t,destPath:e.destPath,cwd:i}),v=new RegExp(`(['"])${zo(l)}\\1`,"g");c=c.replaceAll(v,`$1${u}$1`);}return j(c)};var ct=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await Oe.resolveConfig(X.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=X.join(t,"biome.json");Ne.existsSync(n)&&(o=JSON.parse(Ne.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var lt=(e,t)=>`jsrepo ${e}
32
+ ${c}`),a?.(`Formatting ${P.bold(e.destPath)}`);try{c=await p.format(c,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:s});}catch(l){return T(`Error formatting ${P.bold(e.destPath)} ${l}`)}}for(let[l,y]of Object.entries(r)){let u=Hr({template:y,config:t,destPath:e.destPath,cwd:i}),k=new RegExp(`(['"])${sn(l)}\\1`,"g");c=c.replaceAll(k,`$1${u}$1`);}return I(c)};var ht=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await Le.resolveConfig(Q.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=Q.join(t,"biome.json");Ae.existsSync(n)&&(o=JSON.parse(Ae.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var yt=(e,t)=>`jsrepo ${e}
33
33
  Installed from ${t}
34
- ${new Date().toLocaleDateString().replaceAll("/","-")}`;var $t=async(e,{verbose:t=void 0})=>{let r=spinner();for(let o of e){t?t(o.loadingMessage):r.start(o.loadingMessage);try{await o.run();}catch(n){r.stop(`Error while ${o.loadingMessage}`),console.error(n);}t?t(o.completedMessage):r.stop(o.completedMessage);}},Jr=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),s=i=>{o?o(i):n.message(i);};o?o(t):n.start(t),await Promise.all([...e.map(i=>i.run({message:s}))]),o?o(r):n.stop(r);},dt=e=>{let t=20;e.map(n=>{let s=kr(qe(n),4);s.length>t&&(t=s.length);});let r="Next Steps",o=`${A}
35
- `;return o+=`${Ut} ${r} ${zt.repeat(t-r.length-1)}${mr}
36
- `,o+=`${A} ${" ".repeat(t)} ${A}
37
- `,e.map(n=>{o+=`${A} ${Rr(n,t-1)} ${A}
38
- `;}),o+=`${A} ${" ".repeat(t)} ${A}
39
- `,o+=`${Ut}${zt.repeat(t+2)}${ur}
40
- `,o},zr=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},ae=e=>intro(`${I.bgHex("#f7df1e").black(" jsrepo ")}${I.gray(` v${e} `)}`);var en=b.object({repo:b.optional(b.string()),allow:b.boolean(),yes:b.boolean(),verbose:b.boolean(),cwd:b.string()}),Qt=new Command("add").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(en,t);ae(Z.package.version),await tn(e,r),outro(I.green("All done!"));}),tn=async(e,t)=>{let r=y=>{t.verbose&&console.info(`${ot} ${y}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Pe(t.cwd),s=n.isErr(),i;if(n.isErr()){let y=t.yes;if(!t.yes){let P=await confirm({message:`You don't have ${Se} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(P)&&(cancel("Canceled!"),process.exit(0)),y=P;}y||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let y of e){if(!q.find(T=>y.startsWith(T.name())))continue;let[P,m,k,...x]=y.split("/"),w;if(x.length>2?w=`${P}/${m}/${k}/${x.slice(0,x.length-2).join("/")}`:w=`${P}/${m}/${k}`,!a.find(T=>T===w)){if(!t.allow){let T=await confirm({message:`Allow ${Se} to download and run code from ${I.cyan(w)}?`,initialValue:!0});(isCancel(T)||!T)&&(cancel("Canceled!"),process.exit(0));}a.push(w);}}if(!t.allow&&t.repo){let y=await confirm({message:`Allow ${Se} to download and run code from ${I.cyan(t.repo)}?`,initialValue:!0});(isCancel(y)||!y)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(I.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${I.bold("--repo")}\` flag to specify a registry.`)),program.error(I.red(`There were no repos present in your config and you didn't provide the \`${I.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${I.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${I.cyan(a.join(", "))}`);let d=(await at(...a)).match(y=>y,({repo:y,message:P})=>{o.stop(`Failed to get info for ${I.cyan(y)}`),program.error(I.red(P));});r(`Resolved ${I.cyan(a.join(", "))}`),r(`Fetching blocks from ${I.cyan(a.join(", "))}`);let c=(await it(...d)).match(y=>y,({repo:y,message:P})=>{o.stop(`Failed fetching blocks from ${I.cyan(y)}`),program.error(I.red(P));});t.verbose||o.stop(`Retrieved blocks from ${I.cyan(a.join(", "))}`),r(`Retrieved blocks from ${I.cyan(a.join(", "))}`);let l=Me(c,i,t.cwd).map(y=>y.specifier),h=e;if(h.length===0){let y=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([P,m])=>m.list).map(([P,m])=>{let k=`${m.category}/${m.name}`,x=l.findIndex(T=>T===k)!==-1,w;return a.length>1?w=`${I.cyan(`${m.sourceRepo.name}/${m.sourceRepo.owner}/${m.sourceRepo.repoName}/${m.category}`)}/${m.name}`:w=`${I.cyan(m.category)}/${m.name}`,{label:x?I.gray(w):w,value:P,hint:x?"Installed":void 0}}),required:!0});isCancel(y)&&(cancel("Canceled!"),process.exit(0)),h=y;}r(`Installing blocks ${I.cyan(h.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await wt(h,c,d)).match(y=>y,y=>program.error(y)),v=(await detect({cwd:t.cwd}))?.agent??"npm",C=[],L=new Set,f=new Set,R=se();if(s){let y=`${t.cwd}-zero-config`,P=b.safeParse(qt,R.get(y)),m=P.success?P.output:i,k=Array.from(new Set(u.map(T=>T.block.category)));for(let T of k){let K=await text({message:`Where would you like to add ${I.cyan(T)}?`,placeholder:m?m.paths[T]:`./src/${T}`,initialValue:m?m.paths[T]:`./src/${T}`,defaultValue:m?m.paths[T]:`./src/${T}`,validate(ye){if(ye.trim()==="")return "Please provide a value"}});isCancel(K)&&(cancel("Canceled!"),process.exit(0)),i.paths[T]=K;}if(!t.yes){let T=await confirm({message:"Include tests?",initialValue:m.includeTests});isCancel(T)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=T;let K=await confirm({message:"Add watermark?",initialValue:m.watermark});isCancel(K)&&(cancel("Canceled!"),process.exit(0)),i.watermark=K;}let x="none";Ne.existsSync(X.join(t.cwd,".prettierrc"))&&(x="prettier"),Ne.existsSync(X.join(t.cwd,"biome.json"))&&(x="biome");let w=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(T=>({value:T.toLowerCase(),label:T})),initialValue:x==="none"?m.formatter?m.formatter:"none":x});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),w!=="none"&&(i.formatter=w),R.set(y,i);}let{prettierOptions:J,biomeOptions:B}=await ct({formatter:i.formatter,cwd:t.cwd}),D=Te(i.paths,t.cwd);D.isErr()&&program.error(I.red(D.unwrapErr()));let p=D.unwrap(),g=[],E;for(let{block:y}of u){let P=`${y.sourceRepo.url}/${y.category}/${y.name}`,m=`${y.category}/${y.name}`,k=lt(Z.package.version,y.sourceRepo.url),x=y.sourceRepo;r(`Setting up ${P}`);let w;if(p[y.category]!==void 0?w=X.join(t.cwd,p[y.category]):w=X.join(t.cwd,p["*"],y.category),l.find(K=>m===K)&&!t.yes&&!E){if(E===void 0){let K=u.map(Ie=>`${Ie.block.category}/${Ie.block.name}`).filter(Ie=>l.find(z=>z===Ie));log.warn(`The following components ${I.bold.yellow("already exist")}: ${I.cyan(zr(K))}`);let ye=await confirm({message:`Would you like to ${I.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ye)&&(cancel("Canceled!"),process.exit(0)),E=ye;}if(!E){let K=await confirm({message:`${I.cyan(m)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(K)&&(cancel("Canceled!"),process.exit(0)),!K)continue}}g.push(m),C.push({run:async({message:K})=>{K(`Adding ${I.cyan(P)}`),r(`Creating directory ${I.bold(w)}`),Ne.mkdirSync(w,{recursive:!0}),r(`Created directory ${I.bold(w)}`);let ye=[],Ie=async z=>{let F=await x.provider.fetchRaw(x,z,{verbose:r});return F.isErr()&&(o.stop(I.red(`Error fetching ${I.bold(z)}`)),program.error(I.red(`There was an error trying to get ${P}`))),F.unwrap()};for(let z of y.files){if(!i.includeTests&&Re(z))continue;let F=X.join(y.directory,z),ve;y.subdirectory?ve=X.join(w,y.name,z):ve=X.join(w,z),r(`Adding ${I.bold(F)}`);let gt=await Ie(F),rt=ve.slice(0,ve.length-z.length);r(`Creating directory ${I.bold(rt)}`),Ne.mkdirSync(rt,{recursive:!0}),r(`Created directory ${I.bold(rt)}`),ye.push({content:gt,destPath:ve}),r(`Got ${I.bold(F)}`);}for(let z of ye){let F=await Wt({file:z,biomeOptions:B,prettierOptions:J,config:i,imports:y._imports_,watermark:k,verbose:r,cwd:t.cwd});F.isErr()&&program.error(I.red(F.unwrapErr())),r(`Writing to ${I.bold(z.destPath)}`),Ne.writeFileSync(z.destPath,F.unwrap());}if(i.includeTests&&y.tests){r("Trying to include tests");let{devDependencies:z}=JSON.parse(Ne.readFileSync(X.join(t.cwd,"package.json")).toString());(z===void 0||z.vitest===void 0)&&L.add("vitest");}for(let z of y.devDependencies)L.add(z);for(let z of y.dependencies)f.add(z);}});}await Jr({startMessage:"Adding blocks",stopMessage:`Added ${I.cyan(g.join(", "))}`,tasks:C,verbose:t.verbose?r:void 0});let $=St(f,L,{cwd:t.cwd});if(f=$.dependencies,L=$.devDependencies,f.size>0||L.size>0){let y=t.yes;if(!t.yes){let k=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),y=k;}y&&(f.size>0&&(t.verbose||o.start(`Installing dependencies with ${I.cyan(v)}`),(await Je({pm:v,deps:Array.from(f),dev:!1,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${I.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dependencies"),program.error(k);})),L.size>0&&(t.verbose||o.start(`Installing dependencies with ${I.cyan(v)}`),(await Je({pm:v,deps:Array.from(L),dev:!0,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${I.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(k);})));let P=[];if(!y){if(f.size>0){let k=resolveCommand(v,"install",[...f]);P.push(`Install dependencies \`${I.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(L.size>0){let k=resolveCommand(v,"install",[...L,"-D"]);P.push(`Install dev dependencies \`${I.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}P=P.map((k,x)=>`${x+1}. ${k}`),y||P.push(""),P.push("Import and use the blocks!");let m=dt(P);process.stdout.write(m);}};var ln=b.object({token:b.optional(b.string()),provider:b.optional(b.string()),logout:b.boolean(),cwd:b.string()}),rr=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(ln,e);ae(Z.package.version),await dn(t),outro(I.green("All done!"));}),dn=async e=>{let t=se();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${A}
41
- `),process.stdout.write(I.gray(`${A} Already logged out of ${r.name()}.
42
- `));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:!0});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var un=b.object({dirs:b.optional(b.array(b.string())),includeBlocks:b.optional(b.array(b.string())),includeCategories:b.optional(b.array(b.string())),excludeBlocks:b.optional(b.array(b.string())),excludeCategories:b.optional(b.array(b.string())),excludeDeps:b.optional(b.array(b.string())),listBlocks:b.optional(b.array(b.string())),listCategories:b.optional(b.array(b.string())),doNotListBlocks:b.optional(b.array(b.string())),doNotListCategories:b.optional(b.array(b.string())),preview:b.optional(b.boolean()),output:b.boolean(),verbose:b.boolean(),cwd:b.string()}),nr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${fe}\` file.`).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("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${fe}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(un,e);ae(Z.package.version),await gn(t),outro(I.green("All done!"));}),gn=async e=>{let t=spinner(),r=[],o=It(e.cwd).match(c=>{if(c===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],preview:e.preview};let l=c;return e.dirs&&(l.dirs=e.dirs),e.doNotListBlocks&&(l.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(l.doNotListCategories=e.doNotListCategories),e.listBlocks&&(l.listBlocks=e.listBlocks),e.listCategories&&(l.listCategories=e.listCategories),e.includeBlocks&&(l.includeBlocks=e.includeBlocks),e.includeCategories&&(l.includeCategories=e.includeCategories),e.excludeBlocks&&(l.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(l.excludeCategories=e.excludeCategories),e.excludeDeps&&(l.excludeDeps=e.excludeDeps),e.preview!==void 0&&(l.preview=e.preview),l.rules={...Gt,...l.rules},l},c=>program.error(I.red(c))),n=X.join(e.cwd,fe);for(let c of o.dirs){let l=X.join(e.cwd,c);t.start(`Building ${I.cyan(l)}`),e.output&&Ne.existsSync(n)&&Ne.rmSync(n);let h=Or(l,{cwd:e.cwd,config:o});for(let u of h){if(r.find(v=>v.name===u.name)!==void 0){console.warn(`${A} ${$e} Skipped adding \`${I.cyan(`${c}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${I.cyan(l)}`);}t.start("Checking manifest");let{warnings:s,errors:i}=vr(r,o,o.rules);t.stop("Completed checking manifest."),(s.length>0||i.length>0)&&console.log(A);for(let c of s)console.log(c);if(i.length>0){for(let c of i)console.log(c);program.error(I.red(`Completed checking manifest with ${I.bold(`${i.length} error(s)`)} and ${I.bold(`${s.length} warning(s)`)}`));}let[a,d]=Dr(r);if(r=a,d>0&&log.step(`Removed ${d} unused block${d>1?"s":""}.`),o.preview){let c=r.flatMap(l=>l.blocks.filter(h=>h.list).map(h=>`${I.cyan(h.category)}/${h.name}`));log.message(`${I.yellow("Preview")}:`);for(let l of c)console.log(`${A} \u25FB ${l}`);}e.output&&(t.start(`Writing output to \`${I.cyan(n)}\``),Ne.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${I.cyan(n)}\``));};var Yr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var Xr=e=>/^\s+$/g.test(e),ft=e=>{let t=e.length-1;for(;Xr(e[t])&&t>=0;){if(e[t]===`
43
- `)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Vt=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:s=I.red,colorAdded:i=I.green,colorCharsRemoved:a=I.bgRed,colorCharsAdded:d=I.bgGreen,prefix:c,onUnchanged:l,intro:h})=>{let u="",v=Yr(r,f=>f.count??0).toString().length+1,C=0;if(r.length===1&&!r[0].added&&!r[0].removed)return l({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:h});u+=h({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:h});let L=f=>I.gray(`${c?.()??""}${ht(`${f+1+C} `,v)} `);for(let f=0;f<r.length;f++){let R=r[f],J=r[f-1]?.added||r[f-1]?.removed,B=r[f+1]?.added||r[f+1]?.removed;if(!R.added&&!R.removed){if(!o&&R.count!==void 0&&R.count>n){let g=C,E=ee(ft(R.value)),$=0;if(B&&($+=n),J&&($+=n),$>=E.length){u+=`${Y(E,{prefix:L})}
44
- `,C+=E.length;continue}if(J&&(u+=`${Y(E.slice(0,n),{prefix:L})}
45
- `),E.length>$){let _=E.length-$;u+=`${Y(ee(I.gray(`+ ${_} more unchanged (${I.italic("-E to expand")})`)),{prefix:()=>`${c?.()??""}${ht(" ",v)} `})}
46
- `;}B&&(C=C+E.length-n,u+=`${Y(E.slice(E.length-n),{prefix:L})}
47
- `),C=g+R.count;continue}u+=`${Y(ee(ft(R.value)),{prefix:L})}
48
- `,C+=R.count??0;continue}let D=g=>g.added?i(ft(g.value)):g.removed?s(ft(g.value)):g.value,p=g=>g.added?d(ft(g.value)):g.removed?a(ft(g.value)):g.value;if(R.removed&&R.count===1&&r[f+1]?.added&&r[f+1]?.count===1){let E=diffChars(R.value,r[f+1].value).map($=>p($)).join("");u+=`${L(0)}${E}`,C+=1,f++;}else Xr(R.value)?(u+=`${Y(ee(p(R)),{prefix:g=>`${L(g)}${p({removed:!0,value:" ",added:!1})}`})}
49
- `,R.removed||(C+=R.count??0)):(u+=`${Y(ee(D(R)),{prefix:L})}
50
- `,R.removed||(C+=R.count??0));}return u};var Cn=b.object({expand:b.boolean(),maxUnchanged:b.number(),repo:b.optional(b.string()),allow:b.boolean(),cwd:b.string()}),sr=new Command("diff").description("Compares local blocks to the blocks in the provided repository.").option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(Cn,e);ae(Z.package.version),await xn(t),outro(I.green("All done!"));}),xn=async e=>{let t=spinner(),r=Pe(e.cwd).match(c=>c,c=>program.error(I.red(c))),o=r.repos;if(e.repo&&(o=[e.repo]),!e.allow&&e.repo){let c=await confirm({message:`Allow ${I.cyan("jsrepo")} to download and run code from ${I.cyan(e.repo)}?`,initialValue:!0});(isCancel(c)||!c)&&(cancel("Canceled!"),process.exit(0));}t.start(`Fetching blocks from ${I.cyan(o.join(", "))}`);let n=(await at(...o)).match(c=>c,({repo:c,message:l})=>{t.stop(`Failed to get info for ${I.cyan(c)}`),program.error(I.red(l));}),s=(await it(...n)).match(c=>c,({repo:c,message:l})=>{t.stop(`Failed fetching blocks from ${I.cyan(c)}`),program.error(I.red(l));});t.stop(`Retrieved blocks from ${I.cyan(o.join(", "))}`);let i=Me(s,r,e.cwd),a=Te(r.paths,e.cwd);a.isErr()&&program.error(I.red(a.unwrapErr()));let d=a.unwrap();for(let c of i){let l=!1;for(let h of o){let u=(await Xe(h)).unwrap(),v=`${u.name}/${u.owner}/${u.repoName}/${c.specifier}`,C=s.get(v);if(C===void 0)continue;let L=lt(Z.package.version,h);l=!0,process.stdout.write(`${A}
51
- `),process.stdout.write(`${A} ${v}
52
- `);for(let f of C.files){if(!r.includeTests&&Re(f))continue;process.stdout.write(`${A}
53
- `);let R=X.join(C.directory,f),J=await u.provider.fetchRaw(u,R);J.isErr()&&program.error(I.red(`There was an error trying to get ${v}`));let B=J.unwrap(),D,p;d[C.category]!==void 0?(p=d[C.category],D=X.join(e.cwd,d[C.category])):(p=X.join(d["*"],C.category),D=X.join(e.cwd,d["*"],C.category));let g=X.join(D,f),E=X.join(p,f);C.subdirectory&&(g=X.join(D,C.name,f),E=X.join(p,C.name,f));let $="";if(Ne.existsSync(g)&&($=Ne.readFileSync(g).toString()),r.watermark){let m=Ke.find(k=>k.matches(R));m&&(B=`${m.comment(L)}
34
+ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var xt=async(e,{verbose:t=void 0})=>{let r=spinner();for(let o of e){t?t(o.loadingMessage):r.start(o.loadingMessage);try{await o.run();}catch(n){r.stop(`Error while ${o.loadingMessage}`),console.error(n);}t?t(o.completedMessage):r.stop(o.completedMessage);}},Gt=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),s=i=>{o?o(i):n.message(i);};o?o(t):n.start(t),await Promise.all([...e.map(i=>i.run({message:s}))]),o?o(r):n.stop(r);},vt=e=>{let t=20;e.map(n=>{let s=Nr(rt(n),4);s.length>t&&(t=s.length);});let r="Next Steps",o=`${W}
35
+ `;return o+=`${Xt} ${r} ${Yt.repeat(t-r.length-1)}${Rr}
36
+ `,o+=`${W} ${" ".repeat(t)} ${W}
37
+ `,e.map(n=>{o+=`${W} ${Or(n,t-1)} ${W}
38
+ `;}),o+=`${W} ${" ".repeat(t)} ${W}
39
+ `,o+=`${Xt}${Yt.repeat(t+2)}${Cr}
40
+ `,o},eo=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},ne=e=>intro(`${P.bgHex("#f7df1e").black(" jsrepo ")}${P.gray(` v${e} `)}`);var hn=C.object({repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),ir=new Command("add").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hn,t);ne(X.package.version),await yn(e,r),outro(P.green("All done!"));}),yn=async(e,t)=>{let r=h=>{t.verbose&&console.info(`${ft} ${h}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=$e(t.cwd),s=n.isErr(),i;if(n.isErr()){let h=t.yes;if(!t.yes){let S=await confirm({message:`You don't have ${fe} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(S)&&(cancel("Canceled!"),process.exit(0)),h=S;}h||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let h of e){if(!q.find(j=>h.startsWith(j.name())))continue;let[S,d,w,...$]=h.split("/"),v;if($.length>2?v=`${S}/${d}/${w}/${$.slice(0,$.length-2).join("/")}`:v=`${S}/${d}/${w}`,!a.find(j=>j===v)){if(!t.allow){let j=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(v)}?`,initialValue:!0});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}}if(!t.allow&&t.repo){let h=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(h)||!h)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(P.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${P.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(a.join(", "))}`);let p=(await Ke(...a)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed to get info for ${P.cyan(h)}`),program.error(P.red(S));});r(`Resolved ${P.cyan(a.join(", "))}`),r(`Fetching blocks from ${P.cyan(a.join(", "))}`);let c=(await qe(...p)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed fetching blocks from ${P.cyan(h)}`),program.error(P.red(S));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(a.join(", "))}`),r(`Retrieved blocks from ${P.cyan(a.join(", "))}`);let l=Ye(c,i,t.cwd).map(h=>h.specifier),y=e;if(y.length===0){let h=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([S,d])=>d.list).map(([S,d])=>{let w=`${d.category}/${d.name}`,$=l.findIndex(j=>j===w)!==-1,v;return a.length>1?v=`${P.cyan(`${d.sourceRepo.name}/${d.sourceRepo.owner}/${d.sourceRepo.repoName}/${d.category}`)}/${d.name}`:v=`${P.cyan(d.category)}/${d.name}`,{label:$?P.gray(v):v,value:S,hint:$?"Installed":void 0}}),required:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),y=h;}r(`Installing blocks ${P.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await it(y,c,p)).match(h=>h,h=>program.error(h)),k=(await detect({cwd:t.cwd}))?.agent??"npm",x=[],A=new Set,m=new Set,R=le();if(s){let h=`${t.cwd}-zero-config`,S=C.safeParse(er,R.get(h)),d=S.success?S.output:i,w=Array.from(new Set(u.map(j=>j.block.category)));for(let j of w){let z=await text({message:`Where would you like to add ${P.cyan(j)}?`,placeholder:d?d.paths[j]:`./src/${j}`,initialValue:d?d.paths[j]:`./src/${j}`,defaultValue:d?d.paths[j]:`./src/${j}`,validate(ce){if(ce.trim()==="")return "Please provide a value"}});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.paths[j]=z;}if(!t.yes){let j=await confirm({message:"Include tests?",initialValue:d.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=j;let z=await confirm({message:"Add watermark?",initialValue:d.watermark});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.watermark=z;}let $="none";Ae.existsSync(Q.join(t.cwd,".prettierrc"))&&($="prettier"),Ae.existsSync(Q.join(t.cwd,"biome.json"))&&($="biome");let v=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(j=>({value:j.toLowerCase(),label:j})),initialValue:$==="none"?d.formatter?d.formatter:"none":$});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(i.formatter=v),R.set(h,i);}let{prettierOptions:M,biomeOptions:F}=await ht({formatter:i.formatter,cwd:t.cwd}),L=ke(i.paths,t.cwd);L.isErr()&&program.error(P.red(L.unwrapErr()));let f=L.unwrap(),g=[],E;for(let{block:h}of u){let S=`${h.sourceRepo.url}/${h.category}/${h.name}`,d=`${h.category}/${h.name}`,w=yt(X.package.version,h.sourceRepo.url),$=h.sourceRepo;r(`Setting up ${S}`);let v;if(f[h.category]!==void 0?v=Q.join(t.cwd,f[h.category]):v=Q.join(t.cwd,f["*"],h.category),l.find(z=>d===z)&&!t.yes&&!E){if(E===void 0){let z=u.map(ve=>`${ve.block.category}/${ve.block.name}`).filter(ve=>l.find(N=>N===ve));log.warn(`The following components ${P.bold.yellow("already exist")}: ${P.cyan(eo(z))}`);let ce=await confirm({message:`Would you like to ${P.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ce)&&(cancel("Canceled!"),process.exit(0)),E=ce;}if(!E){let z=await confirm({message:`${P.cyan(d)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(z)&&(cancel("Canceled!"),process.exit(0)),!z)continue}}g.push(d),x.push({run:async({message:z})=>{z(`Adding ${P.cyan(S)}`),r(`Creating directory ${P.bold(v)}`),Ae.mkdirSync(v,{recursive:!0}),r(`Created directory ${P.bold(v)}`);let ce=[],ve=async N=>{let B=await $.provider.fetchRaw($,N,{verbose:r});return B.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${S}`))),B.unwrap()};for(let N of h.files){if(!i.includeTests&&ue(N))continue;let B=Q.join(h.directory,N),ee;h.subdirectory?ee=Q.join(v,h.name,N):ee=Q.join(v,N),r(`Adding ${P.bold(B)}`);let et=await ve(B),ze=ee.slice(0,ee.length-N.length);r(`Creating directory ${P.bold(ze)}`),Ae.mkdirSync(ze,{recursive:!0}),r(`Created directory ${P.bold(ze)}`),ce.push({content:et,destPath:ee}),r(`Got ${P.bold(B)}`);}for(let N of ce){let B=await Ut({file:N,biomeOptions:F,prettierOptions:M,config:i,imports:h._imports_,watermark:w,verbose:r,cwd:t.cwd});B.isErr()&&program.error(P.red(B.unwrapErr())),r(`Writing to ${P.bold(N.destPath)}`),Ae.writeFileSync(N.destPath,B.unwrap());}if(i.includeTests&&h.tests){r("Trying to include tests");let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&A.add("vitest");}for(let N of h.devDependencies)A.add(N);for(let N of h.dependencies)m.add(N);}});}await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(g.join(", "))}`,tasks:x,verbose:t.verbose?r:void 0});let b=Dt(m,A,{cwd:t.cwd});if(m=b.dependencies,A=b.devDependencies,m.size>0||A.size>0){let h=t.yes;if(!t.yes){let w=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),h=w;}h&&(m.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(m),dev:!1,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dependencies"),program.error(w);})),A.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(A),dev:!0,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(w);})));let S=[];if(!h){if(m.size>0){let w=resolveCommand(k,"install",[...m]);S.push(`Install dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(A.size>0){let w=resolveCommand(k,"install",[...A,"-D"]);S.push(`Install dev dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}S=S.map((w,$)=>`${$+1}. ${w}`),h||S.push(""),S.push("Import and use the blocks!");let d=vt(S);process.stdout.write(d);}};var Cn=C.object({token:C.optional(C.string()),provider:C.optional(C.string()),logout:C.boolean(),cwd:C.string()}),lr=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(Cn,e);ne(X.package.version),await xn(t),outro(P.green("All done!"));}),xn=async e=>{let t=le();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${W}
41
+ `),process.stdout.write(P.gray(`${W} Already logged out of ${r.name()}.
42
+ `));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:!0});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var Sn=C.object({dirs:C.optional(C.array(C.string())),includeBlocks:C.optional(C.array(C.string())),includeCategories:C.optional(C.array(C.string())),excludeBlocks:C.optional(C.array(C.string())),excludeCategories:C.optional(C.array(C.string())),excludeDeps:C.optional(C.array(C.string())),listBlocks:C.optional(C.array(C.string())),listCategories:C.optional(C.array(C.string())),doNotListBlocks:C.optional(C.array(C.string())),doNotListCategories:C.optional(C.array(C.string())),preview:C.optional(C.boolean()),output:C.boolean(),verbose:C.boolean(),cwd:C.string()}),pr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${be}\` file.`).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("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${be}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(Sn,e);ne(X.package.version),await Pn(t),outro(P.green("All done!"));}),Pn=async e=>{let t=spinner(),r=[],o=Ot(e.cwd).match(c=>{if(c===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],preview:e.preview};let l=c;return e.dirs&&(l.dirs=e.dirs),e.doNotListBlocks&&(l.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(l.doNotListCategories=e.doNotListCategories),e.listBlocks&&(l.listBlocks=e.listBlocks),e.listCategories&&(l.listCategories=e.listCategories),e.includeBlocks&&(l.includeBlocks=e.includeBlocks),e.includeCategories&&(l.includeCategories=e.includeCategories),e.excludeBlocks&&(l.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(l.excludeCategories=e.excludeCategories),e.excludeDeps&&(l.excludeDeps=e.excludeDeps),e.preview!==void 0&&(l.preview=e.preview),l.rules={...Zt,...l.rules},l},c=>program.error(P.red(c))),n=Q.join(e.cwd,be);for(let c of o.dirs){let l=Q.join(e.cwd,c);t.start(`Building ${P.cyan(l)}`),e.output&&Ae.existsSync(n)&&Ae.rmSync(n);let y=Jr(l,{cwd:e.cwd,config:o});for(let u of y){if(r.find(k=>k.name===u.name)!==void 0){console.warn(`${W} ${Ie} Skipped adding \`${P.cyan(`${c}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${P.cyan(l)}`);}t.start("Checking manifest");let{warnings:s,errors:i}=Ir(r,o,o.rules);t.stop("Completed checking manifest."),(s.length>0||i.length>0)&&console.log(W);for(let c of s)console.log(c);if(i.length>0){for(let c of i)console.log(c);program.error(P.red(`Completed checking manifest with ${P.bold(`${i.length} error(s)`)} and ${P.bold(`${s.length} warning(s)`)}`));}let[a,p]=zr(r);if(r=a,p>0&&log.step(`Removed ${p} unused block${p>1?"s":""}.`),o.preview){let c=r.flatMap(l=>l.blocks.filter(y=>y.list).map(y=>`${P.cyan(y.category)}/${y.name}`));log.message(`${P.yellow("Preview")}:`);for(let l of c)console.log(`${W} \u25FB ${l}`);}e.output&&(t.start(`Writing output to \`${P.cyan(n)}\``),Ae.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${P.cyan(n)}\``));};var io=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var ao=e=>/^\s+$/g.test(e),$t=e=>{let t=e.length-1;for(;ao(e[t])&&t>=0;){if(e[t]===`
43
+ `)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Ht=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:s=P.red,colorAdded:i=P.green,colorCharsRemoved:a=P.bgRed,colorCharsAdded:p=P.bgGreen,prefix:c,onUnchanged:l,intro:y})=>{let u="",k=io(r,m=>m.count??0).toString().length+1,x=0;if(r.length===1&&!r[0].added&&!r[0].removed)return l({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:y});u+=y({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:y});let A=m=>P.gray(`${c?.()??""}${Rt(`${m+1+x} `,k)} `);for(let m=0;m<r.length;m++){let R=r[m],M=r[m-1]?.added||r[m-1]?.removed,F=r[m+1]?.added||r[m+1]?.removed;if(!R.added&&!R.removed){if(!o&&R.count!==void 0&&R.count>n){let g=x,E=re($t(R.value)),b=0;if(F&&(b+=n),M&&(b+=n),b>=E.length){u+=`${Z(E,{prefix:A})}
44
+ `,x+=E.length;continue}if(M&&(u+=`${Z(E.slice(0,n),{prefix:A})}
45
+ `),E.length>b){let _=E.length-b;u+=`${Z(re(P.gray(`+ ${_} more unchanged (${P.italic("-E to expand")})`)),{prefix:()=>`${c?.()??""}${Rt(" ",k)} `})}
46
+ `;}F&&(x=x+E.length-n,u+=`${Z(E.slice(E.length-n),{prefix:A})}
47
+ `),x=g+R.count;continue}u+=`${Z(re($t(R.value)),{prefix:A})}
48
+ `,x+=R.count??0;continue}let L=g=>g.added?i($t(g.value)):g.removed?s($t(g.value)):g.value,f=g=>g.added?p($t(g.value)):g.removed?a($t(g.value)):g.value;if(R.removed&&R.count===1&&r[m+1]?.added&&r[m+1]?.count===1){let E=diffChars(R.value,r[m+1].value).map(b=>f(b)).join("");u+=`${A(0)}${E}`,x+=1,m++;}else ao(R.value)?(u+=`${Z(re(f(R)),{prefix:g=>`${A(g)}${f({removed:!0,value:" ",added:!1})}`})}
49
+ `,R.removed||(x+=R.count??0)):(u+=`${Z(re(L(R)),{prefix:A})}
50
+ `,R.removed||(x+=R.count??0));}return u};var _n=C.object({expand:C.boolean(),maxUnchanged:C.number(),repo:C.optional(C.string()),allow:C.boolean(),cwd:C.string()}),fr=new Command("diff").description("Compares local blocks to the blocks in the provided repository.").option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(_n,e);ne(X.package.version),await Wn(t),outro(P.green("All done!"));}),Wn=async e=>{let t=spinner(),r=$e(e.cwd).match(c=>c,c=>program.error(P.red(c))),o=r.repos;if(e.repo&&(o=[e.repo]),!e.allow&&e.repo){let c=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(e.repo)}?`,initialValue:!0});(isCancel(c)||!c)&&(cancel("Canceled!"),process.exit(0));}t.start(`Fetching blocks from ${P.cyan(o.join(", "))}`);let n=(await Ke(...o)).match(c=>c,({repo:c,message:l})=>{t.stop(`Failed to get info for ${P.cyan(c)}`),program.error(P.red(l));}),s=(await qe(...n)).match(c=>c,({repo:c,message:l})=>{t.stop(`Failed fetching blocks from ${P.cyan(c)}`),program.error(P.red(l));});t.stop(`Retrieved blocks from ${P.cyan(o.join(", "))}`);let i=Ye(s,r,e.cwd),a=ke(r.paths,e.cwd);a.isErr()&&program.error(P.red(a.unwrapErr()));let p=a.unwrap();for(let c of i){let l=!1;for(let y of o){let u=(await st(y)).unwrap(),k=`${u.name}/${u.owner}/${u.repoName}/${c.specifier}`,x=s.get(k);if(x===void 0)continue;let A=yt(X.package.version,y);l=!0,process.stdout.write(`${W}
51
+ `),process.stdout.write(`${W} ${k}
52
+ `);for(let m of x.files){if(!r.includeTests&&ue(m))continue;process.stdout.write(`${W}
53
+ `);let R=Q.join(x.directory,m),M=await u.provider.fetchRaw(u,R);M.isErr()&&program.error(P.red(`There was an error trying to get ${k}`));let F=M.unwrap(),L,f;p[x.category]!==void 0?(f=p[x.category],L=Q.join(e.cwd,p[x.category])):(f=Q.join(p["*"],x.category),L=Q.join(e.cwd,p["*"],x.category));let g=Q.join(L,m),E=Q.join(f,m);x.subdirectory&&(g=Q.join(L,x.name,m),E=Q.join(f,x.name,m));let b="";if(Ae.existsSync(g)&&(b=Ae.readFileSync(g).toString()),r.watermark){let d=ot.find(w=>w.matches(R));d&&(F=`${d.comment(A)}
54
54
 
55
- ${B}`);}let _=diffLines($,B),y=X.join(`${u.name}/${u.owner}/${u.repoName}`,R),P=Vt({from:y,to:E,changes:_,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:I.greenBright,colorRemoved:I.redBright,colorCharsAdded:I.bgGreenBright,colorCharsRemoved:I.bgRedBright,prefix:()=>`${A} `,onUnchanged:({from:m,to:k,prefix:x})=>`${x?.()??""}${I.cyan(m)} \u2192 ${I.gray(k)} ${I.gray("(unchanged)")}
56
- `,intro:({from:m,to:k,changes:x,prefix:w})=>{let T=x.filter(K=>K.added).length;return `${w?.()??""}${I.cyan(m)} \u2192 ${I.gray(k)} (${T} change${T===1?"":"s"})
57
- ${w?.()??""}
58
- `}});process.stdout.write(P);}break}l||program.error(I.red(`Invalid block! ${I.bold(c)} does not exist!`));}};var Nn=b.object({path:b.optional(b.string()),repos:b.optional(b.array(b.string())),watermark:b.boolean(),tests:b.optional(b.boolean()),formatter:b.optional(Ht),project:b.optional(b.boolean()),registry:b.optional(b.boolean()),script:b.string(),yes:b.boolean(),cwd:b.string()}),ar=new Command("init").description("Initializes your project with a configuration file.").option("--path <path>","Path to install the blocks from.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=b.parse(Nn,e);if(ae(Z.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(I.red(`You cannot provide both ${I.bold("--project")} and ${I.bold("--registry")} at the same time.`)),t.registry===void 0&&t.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),t.registry=r==="registry";}t.registry?await Dn(t):await On(t),outro(I.green("All done!"));}),On=async e=>{let t=se(),r=Pe(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(h){if(h.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let h=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:B=>{if(B.trim().length===0)return "Please provide a value";if(!q.find(D=>D.matches(B)))return `Invalid provider! Valid providers (${q.map(D=>D.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let v=q.find(B=>B.matches(u));v||program.error(I.red("Invalid provider!"));let C=`${v.name()}-token`;if(!t.get(C)){let B=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(B)&&(cancel("Canceled!"),process.exit(0)),B){let D=await password({message:"Paste your token",validate(p){if(p.trim()==="")return "Please provide a value"}});isCancel(D)&&(cancel("Canceled!"),process.exit(0)),t.set(C,D);}}o.start(`Fetching categories from ${I.cyan(u)}`);let f=await v.fetchManifest(u);o.stop(`Fetched categories from ${I.cyan(u)}`),f.isErr()&&program.error(I.red(f.unwrapErr()));let R=f.unwrap(),J=await multiselect({message:"Which category paths would you like to configure?",options:R.map(B=>({label:B.name,value:B.name})),required:!1});if(isCancel(J)&&(cancel("Canceled!"),process.exit(0)),J.length>0)for(let B of J){let D=n[B],p=await text({message:`Where should ${B} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:D||`./src/${B}`,defaultValue:D,initialValue:D});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),n[B]=p;}e.repos.push(u);}if(!e.formatter){let h=r.isErr()?"none":r.unwrap().formatter??"none";Ne.existsSync(X.join(e.cwd,".prettierrc"))&&(h="prettier"),Ne.existsSync(X.join(e.cwd,"biome.json"))&&(h="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(v=>({value:v.toLowerCase(),label:v})),initialValue:h});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${Z.package.version}/schemas/project-config.json`,repos:e.repos,includeTests:r.isOk()&&e.tests===void 0?r.unwrap().includeTests:e.tests??!1,watermark:e.watermark,formatter:e.formatter,paths:n};o.start(`Writing config to \`${He}\``);let{prettierOptions:a,biomeOptions:d}=await ct({formatter:i.formatter,cwd:e.cwd}),c=X.join(e.cwd,He),l=await Xt.format(JSON.stringify(i,null," "),{biomeOptions:d,prettierOptions:a,filePath:c,formatter:i.formatter});Ne.writeFileSync(c,l),o.stop(`Wrote config to \`${He}\`.`);},Dn=async e=>{let t=spinner(),r=X.join(e.cwd,"package.json");Ne.existsSync(r)||program.error(I.red(`Couldn't find your ${I.bold("package.json")}!`));let o=It(e.cwd).match(f=>f,f=>program.error(I.red(f))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${Z.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let R=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break}let f=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:R=>{if(R.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(f);}let s=JSON.parse(Ne.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let f=await confirm({message:`The \`${I.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f)break;{let R=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:J=>{if(J.trim().length===0)return "Please provide a value!"}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),e.script=R;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let f=await confirm({message:`Add ${Se} as a dev dependency?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),a=f;}let d=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${I.cyan(_e)}\` file?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),d=f;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",l="";if(a)l+="jsrepo build";else {let f=resolveCommand$1(c,"execute",["jsrepo","build"]);f||program.error(I.red(`Error resolving execute command for ${c}`)),l+=`${f.command} ${f.args.join(" ")} `;}d||(l+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=l;let h=[];h.push({loadingMessage:`Adding \`${I.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${I.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ne.writeFileSync(r,JSON.stringify(s,null," "));}catch(f){program.error(I.red(`Error writing to \`${I.bold(r)}\`. Error: ${f}`));}}}),d&&h.push({loadingMessage:`Writing config to \`${I.cyan(_e)}\``,completedMessage:`Wrote config to \`${I.cyan(_e)}\``,run:async()=>{let f=X.join(e.cwd,_e);try{Ne.writeFileSync(X.join(f),JSON.stringify(o,null," "));}catch(R){program.error(I.red(`Error writing to \`${I.bold(f)}\`. Error: ${R}`));}}}),await $t(h,{});let u=i;if(a&&!i){let f=e.yes;if(!e.yes){let R=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),f=R;}f&&(t.start(`Installing ${Se}`),(await Je({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${Se}.`),J=>{t.stop(`Failed to install ${Se}.`),program.error(J);}),u=!0);}let v=[];if(!u&&a){let f=resolveCommand$1(c,"install",["jsrepo","-D"]);v.push(`Install ${Se} as a dev dependency \`${I.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}v.push(`Add categories to \`${I.cyan(o.dirs.join(", "))}\`.`);let C=resolveCommand$1(c,"run",[e.script]);v.push(`Run \`${I.cyan(`${C?.command} ${C?.args.join(" ")}`)}\` to build the registry.`),v=v.map((f,R)=>`${R+1}. ${f}`);let L=dt(v);process.stdout.write(L);};var Gn=b.object({repo:b.optional(b.string()),allow:b.boolean(),debug:b.boolean(),verbose:b.boolean(),cwd:b.string()}),lr=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.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(Gn,t);ae(Z.package.version),await Hn(e,r),outro(I.green("All done!"));}),Hn=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${ot} ${p}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Pe(t.cwd).match(p=>p,p=>program.error(I.red(p))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let p=await confirm({message:`Allow ${I.cyan("jsrepo")} to download and run code from ${I.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${I.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${I.cyan(i.join(", "))}`);for(let p of i){let g=(await Xe(p)).match(_=>_,_=>program.error(I.red(_))),E=await g.provider.fetchManifest(g);r(`Got info for provider ${I.cyan(g.name)}`),E.isErr()&&(t.verbose||n.stop(`Error fetching ${I.cyan(p)}`),program.error(I.red(`There was an error fetching the \`${fe}\` from the repository ${I.cyan(p)} make sure the target repository has a \`${fe}\` in its root?`)));let $=E.unwrap();for(let _ of $)for(let y of _.blocks)s.set(`${g.name}/${g.owner}/${g.repoName}/${_.name}/${y.name}`,{...y,sourceRepo:g});}r(`Retrieved blocks from ${I.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${I.cyan(i.join(", "))}`);let a=X.resolve(X.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${I.bold(a)}.`),Ne.mkdirSync(a,{recursive:!0});let d=()=>{Ne.rmSync(a,{recursive:!0,force:!0});},c=Me(s,o,t.cwd).map(p=>p.specifier),l=e;e.length===0&&(l=c),l.length===0&&(d(),program.error(I.red("There were no blocks found in your project!")));let h=[];for(let p of l){let g;if(q.find(E=>p.startsWith(E.name()))){if(i.length===0){let[E,$,_,...y]=p.split("/"),P;y.length>2?P=`${E}/${$}/${_}/${y.slice(0,y.length-2).join("/")}`:P=`${E}/${$}/${_}`;let m=(await Xe(P)).match(x=>x,x=>program.error(I.red(x))),k=(await m.provider.fetchManifest(m)).match(x=>x,x=>program.error(I.red(x)));for(let x of k)for(let w of x.blocks)s.set(`${m.name}/${m.owner}/${m.repoName}/${x.name}/${w.name}`,{...w,sourceRepo:m});}g=s.get(p);}else for(let E of i){let $=(await Xe(E)).unwrap(),_=s.get(`${$.name}/${$.owner}/${$.repoName}/${p}`);if(_!==void 0){g=_;break}}g||program.error(I.red(`Invalid block! ${I.bold(p)} does not exist!`)),h.push({name:p,block:g});}let u=Te(o.paths,t.cwd);u.isErr()&&program.error(I.red(u.unwrapErr()));let v=u.unwrap();for(let{block:p}of h){let g=p.sourceRepo,E=`${p.sourceRepo.url}/${p.category}/${p.name}`;if(t.verbose||n.start(`Setting up test file for ${I.cyan(E)}`),!p.tests){n.stop(`No tests found for ${I.cyan(E)}`);continue}let $;v[p.category]!==void 0?$=X.join(t.cwd,v[p.category]):$=X.join(t.cwd,v["*"],p.category),$=X.relative(a,$);let _=async m=>{let k=await g.provider.fetchRaw(g,m);return k.isErr()&&(n.stop(I.red(`Error fetching ${I.bold(m)}`)),program.error(I.red(`There was an error trying to get ${E}`))),k.unwrap()};r(`Downloading and copying test files for ${E}`);let y=[];for(let m of p.files.filter(k=>Re(k))){let k=await _(X.join(p.directory,m)),x=X.join(a,m);Ne.writeFileSync(x,k),y.push(x);}let P=new Project;for(let m of y){r(`Opening test file ${m}`);let k=P.addSourceFileAtPath(m);for(let x of k.getImportDeclarations()){let w=x.getModuleSpecifierValue(),T;w.startsWith(".")&&(p.subdirectory?T=X.join($,p.name,w):T=X.join($,w)),T&&x.setModuleSpecifier(T.replaceAll(/\\/g,"/"));}}P.saveSync(),r(`Completed ${I.cyan.bold(E)} test file`),t.verbose||n.stop(`Completed setup for ${I.bold(E)}`);}r("Beginning testing");let C=await detect({cwd:t.cwd});C==null&&program.error(I.red("Could not detect package manager"));let L=resolveCommand(C.agent,"execute",["vitest","run",a]);L==null&&program.error(I.red(`Could not resolve add command for '${C.agent}'.`));let{command:f,args:R}=L,J=`${f} ${R.join(" ")}`,B=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${J}`,D=p=>console.info(p.toString());B.stdout.on("data",D),B.stderr.on("data",D);try{await B,d();}catch(p){t.debug?console.info(`${I.bold("--debug")} flag provided. Skipping cleanup. Run '${I.bold(J)}' to retry tests.
59
- `):d(),program.error(I.red(`Tests failed! Error ${p}`));}};var es=b.object({all:b.boolean(),expand:b.boolean(),maxUnchanged:b.number(),repo:b.optional(b.string()),allow:b.boolean(),yes:b.boolean(),verbose:b.boolean(),cwd:b.string()}),pr=new Command("update").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",!1).option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=b.parse(es,t);ae(Z.package.version),await ts(e,r),outro(I.green("All done!"));}),ts=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${ot} ${p}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=Pe(t.cwd).match(p=>p,p=>program.error(I.red(p))),s=n.repos;t.repo&&(s=[t.repo]);for(let p of e)q.find(g=>p.startsWith(g.name()))&&program.error(I.red(`Invalid value provided for block names \`${I.bold(p)}\`. Block names are expected to be provided in the format of \`${I.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${I.cyan("jsrepo")} to download and run code from ${I.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${I.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${I.cyan(s.join(", "))}`);let i=(await at(...s)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed to get info for ${I.cyan(p)}`),program.error(I.red(g));});r(`Resolved ${I.cyan(s.join(", "))}`),r(`Fetching blocks from ${I.cyan(s.join(", "))}`);let a=(await it(...i)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed fetching blocks from ${I.cyan(p)}`),program.error(I.red(g));});t.verbose||o.stop(`Retrieved blocks from ${I.cyan(s.join(", "))}`),r(`Retrieved blocks from ${I.cyan(s.join(", "))}`);let d=Me(a,n,t.cwd);d.length===0&&program.error(I.red(`You haven't installed any blocks yet. Did you mean to \`${I.bold("add")}\`?`));let c=e;if(t.all&&(c=d.map(p=>p.specifier)),c.length===0){let p=await multiselect({message:"Which blocks would you like to update?",options:d.filter(g=>g.block.list).map(g=>({label:`${I.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),c=p;}r(`Preparing to update ${I.cyan(c.join(", "))}`);let l=(await wt(c,a,i)).match(p=>p,program.error),h=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],v=new Set,C=new Set,{prettierOptions:L,biomeOptions:f}=await ct({formatter:n.formatter,cwd:t.cwd}),R=Te(n.paths,t.cwd);R.isErr()&&program.error(I.red(R.unwrapErr()));let J=R.unwrap();for(let{block:p}of l){let g=`${p.sourceRepo.url}/${p.category}/${p.name}`,E=lt(Z.package.version,p.sourceRepo.url),$=p.sourceRepo;r(`Attempting to add ${g}`);let _;J[p.category]!==void 0?_=X.join(t.cwd,J[p.category]):_=X.join(t.cwd,J["*"],p.category);let y=[],P=async m=>{let k=await $.provider.fetchRaw($,m,{verbose:r});return k.isErr()&&(o.stop(I.red(`Error fetching ${I.bold(m)}`)),program.error(I.red(`There was an error trying to get ${g}`))),k.unwrap()};for(let m of p.files){if(!n.includeTests&&Re(m))continue;let k=X.join(p.directory,m),x;p.subdirectory?x=X.join(_,p.name,m):x=X.join(_,m);let w=await P(k);Ne.mkdirSync(x.slice(0,x.length-m.length),{recursive:!0}),y.push({content:w,destPath:x,fileName:m});}process.stdout.write(`${A}
60
- `),process.stdout.write(`${A} ${g}
61
- `);for(let m of y){let k=await Wt({file:m,biomeOptions:f,prettierOptions:L,config:n,imports:p._imports_,watermark:E,verbose:r,cwd:t.cwd});k.isErr()&&program.error(I.red(k.unwrapErr()));let x=k.unwrap(),w=t.yes;if(!t.yes){process.stdout.write(`${A}
62
- `);let T="";Ne.existsSync(m.destPath)&&(T=Ne.readFileSync(m.destPath).toString());let K=diffLines(T,x),ye=X.join(`${$.name}/${$.owner}/${$.repoName}`,m.fileName),Ie=X.relative(t.cwd,m.destPath),z=Vt({from:ye,to:Ie,changes:K,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:I.greenBright,colorRemoved:I.redBright,colorCharsAdded:I.bgGreenBright,colorCharsRemoved:I.bgRedBright,prefix:()=>`${A} `,onUnchanged:({from:F,to:ve,prefix:gt})=>`${gt?.()??""}${I.cyan(F)} \u2192 ${I.gray(ve)} ${I.gray("(unchanged)")}
63
- `,intro:({from:F,to:ve,changes:gt,prefix:rt})=>{let fr=gt.filter(ao=>ao.added).length;return `${rt?.()??""}${I.cyan(F)} \u2192 ${I.gray(ve)} (${fr} change${fr===1?"":"s"})
64
- ${rt?.()??""}
65
- `}});if(process.stdout.write(z),K.length>1||T===""){let F=await confirm({message:"Accept changes?",initialValue:!0});isCancel(F)&&(cancel("Canceled!"),process.exit(0)),w=F;}}w&&await $t([{loadingMessage:`Writing changes to ${I.cyan(m.destPath)}`,completedMessage:`Wrote changes to ${I.cyan(m.destPath)}.`,run:async()=>Ne.writeFileSync(m.destPath,x)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&p.tests){r("Trying to include tests");let{devDependencies:m}=JSON.parse(Ne.readFileSync(X.join(t.cwd,"package.json")).toString());(m===void 0||m.vitest===void 0)&&v.add("vitest");}for(let m of p.devDependencies)v.add(m);for(let m of p.dependencies)C.add(m);}await $t(u,{verbose:t.verbose?r:void 0});let B=St(C,v,{cwd:t.cwd});if(C=B.dependencies,v=B.devDependencies,C.size>0||v.size>0){let p=t.yes;if(!t.yes){let $=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel($)&&(cancel("Canceled!"),process.exit(0)),p=$;}p&&(C.size>0&&(t.verbose||o.start(`Installing dependencies with ${I.cyan(h)}`),(await Je({pm:h,deps:Array.from(C),dev:!1,cwd:t.cwd})).match($=>{t.verbose||o.stop(`Installed ${I.cyan($.join(", "))}`);},$=>{t.verbose||o.stop("Failed to install dependencies"),program.error($);})),v.size>0&&(t.verbose||o.start(`Installing dependencies with ${I.cyan(h)}`),(await Je({pm:h,deps:Array.from(v),dev:!0,cwd:t.cwd})).match($=>{t.verbose||o.stop(`Installed ${I.cyan($.join(", "))}`);},$=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error($);})));let g=[];if(!p){if(C.size>0){let $=resolveCommand(h,"install",[...C]);g.push(`Install dependencies \`${I.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}if(v.size>0){let $=resolveCommand(h,"install",[...v,"-D"]);g.push(`Install dev dependencies \`${I.cyan(`${$?.command} ${$?.args.join(" ")}`)}\``);}}g=g.map(($,_)=>`${_+1}. ${$}`),p||g.push(""),g.push("Import and use the blocks!");let E=dt(g);process.stdout.write(E);}};var oo=e=>{let t=fileURLToPath(import.meta.url);return X.join(t,"../..",e)},{version:no,name:so,description:io,repository:is}=JSON.parse(Ne.readFileSync(oo("package.json"),"utf-8")),Z={package:{name:so,description:io,version:no,repository:is},resolveRelativeToRoot:oo};console.clear();program.name(so).description(io).version(no).addCommand(Qt).addCommand(rr).addCommand(ar).addCommand(lr).addCommand(nr).addCommand(pr).addCommand(sr);program.parse();export{Z as context};
55
+ ${F}`);}let _=diffLines(b,F),h=Q.join(`${u.name}/${u.owner}/${u.repoName}`,R),S=Ht({from:h,to:E,changes:_,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:P.greenBright,colorRemoved:P.redBright,colorCharsAdded:P.bgGreenBright,colorCharsRemoved:P.bgRedBright,prefix:()=>`${W} `,onUnchanged:({from:d,to:w,prefix:$})=>`${$?.()??""}${P.cyan(d)} \u2192 ${P.gray(w)} ${P.gray("(unchanged)")}
56
+ `,intro:({from:d,to:w,changes:$,prefix:v})=>{let j=$.filter(z=>z.added).length;return `${v?.()??""}${P.cyan(d)} \u2192 ${P.gray(w)} (${j} change${j===1?"":"s"})
57
+ ${v?.()??""}
58
+ `}});process.stdout.write(S);}break}l||program.error(P.red(`Invalid block! ${P.bold(c)} does not exist!`));}};var qn=C.objectWithRest({repo:C.optional(C.string()),allow:C.boolean(),cwd:C.string()},C.unknown()),gr=new Command("exec").alias("x").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.",!1).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=C.parse(qn,t);ne(X.package.version),await Kn(e,o,r);}),Kn=async(e,t,r)=>{let o=e,n=spinner(),s=$e(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./"},repos:[]}:a=s.unwrap();let p=a.repos;if(t.repo&&(p=[t.repo]),o&&q.find(d=>o?.startsWith(d.name()))){let[d,w,$,...v]=o.split("/"),j;if(v.length>2?j=`${d}/${w}/${$}/${v.slice(0,v.length-2).join("/")}`:j=`${d}/${w}/${$}`,!p.find(z=>z===j)){if(!t.allow){let z=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(j)}?`,initialValue:!0});(isCancel(z)||!z)&&(cancel("Canceled!"),process.exit(0));}p=[j];}}if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}p.length===0&&(i&&program.error(P.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${P.cyan(p.join(", "))}`);let c=(await Ke(...p)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed to get info for ${P.cyan(d)}`),program.error(P.red(w));}),l=(await qe(...c)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed fetching scripts from ${P.cyan(d)}`),program.error(P.red(w));});if(n.stop(`Retrieved scripts from ${P.cyan(p.join(", "))}`),!o){let d=await select({message:"Select which script to run.",options:Array.from(l.entries()).filter(([w,$])=>$.list).map(([w,$])=>{let v;return p.length>1?v=`${P.cyan(`${$.sourceRepo.name}/${$.sourceRepo.owner}/${$.sourceRepo.repoName}/${$.category}`)}/${$.name}`:v=`${P.cyan($.category)}/${$.name}`,{label:v,value:w}})});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o=d;}let y=(await it([o],l,c)).match(d=>d,d=>program.error(d)),u="temp-jsrepo-exec",k=`./${u}/${encodeURIComponent(o)}`,x=Q.join(process.cwd(),k);a.paths["*"]=k,Ae.mkdirSync(x,{recursive:!0});let A=(await detect({cwd:process.cwd()}))?.agent??"npm",m=[],R=new Set,M=new Set,F=ke(a.paths,t.cwd);F.isErr()&&program.error(P.red(F.unwrapErr()));let L=F.unwrap(),f=[];for(let{block:d}of y){let w=`${d.sourceRepo.url}/${d.category}/${d.name}`,$=`${d.category}/${d.name}`,v=d.sourceRepo,j=Q.join(t.cwd,L["*"],d.category);f.push($),m.push({run:async({message:z})=>{z(`Adding ${P.cyan(w)}`),Ae.mkdirSync(j,{recursive:!0});let ce=[],ve=async N=>{let B=await v.provider.fetchRaw(v,N);return B.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${w}`))),B.unwrap()};for(let N of d.files){if(!a.includeTests&&ue(N))continue;let B=Q.join(d.directory,N),ee;d.subdirectory?ee=Q.join(j,d.name,N):ee=Q.join(j,N);let et=await ve(B),ze=ee.slice(0,ee.length-N.length);Ae.mkdirSync(ze,{recursive:!0}),ce.push({content:et,destPath:ee});}for(let N of ce)Ae.writeFileSync(N.destPath,N.content);if(a.includeTests&&d.tests){let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&R.add("vitest");}for(let N of d.devDependencies)R.add(N);for(let N of d.dependencies)M.add(N);}});}if(await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(f.join(", "))}`,tasks:m}),M.size>0||R.size>0){let d={name:"temp-package",type:"module",version:"0.0.1"},w=Q.join(x,"package.json");Ae.writeFileSync(w,JSON.stringify(d,null," ")),M.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(M),dev:!1,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dependencies"),program.error($);})),R.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(R),dev:!0,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error($);}));}let E=r.parent.rawArgs.findIndex(d=>d==="--"),b=[];E!==-1&&(b=r.parent.rawArgs.slice(E+1)),console.clear();let _=y[0],h;_.block.subdirectory?h=Q.join(x,`${_.block.category}/${_.block.name}/index.js`):h=Q.join(x,`${_.block.category}/${_.block.name}.js`);let S=resolveCommand(A,"execute",["tsx",h,...b]);S||program.error(P.red("Error resolving run command!"));try{await execa(S.command,S.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Ae.rmSync(Q.join(process.cwd(),u),{recursive:!0,force:!0});}};var rs=C.object({path:C.optional(C.string()),repos:C.optional(C.array(C.string())),watermark:C.boolean(),tests:C.optional(C.boolean()),formatter:C.optional(Qt),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),yr=new Command("init").description("Initializes your project with a configuration file.").option("--path <path>","Path to install the blocks from.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(rs,e);if(ne(X.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(P.red(`You cannot provide both ${P.bold("--project")} and ${P.bold("--registry")} at the same time.`)),t.registry===void 0&&t.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),t.registry=r==="registry";}t.registry?await ns(t):await os(t),outro(P.green("All done!"));}),os=async e=>{let t=le(),r=$e(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let u=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(!q.find(L=>L.matches(F)))return `Invalid provider! Valid providers (${q.map(L=>L.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let k=q.find(F=>F.matches(u));k||program.error(P.red("Invalid provider!"));let x=`${k.name()}-token`;if(!t.get(x)){let F=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(F)&&(cancel("Canceled!"),process.exit(0)),F){let L=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),t.set(x,L);}}o.start(`Fetching categories from ${P.cyan(u)}`);let m=await k.fetchManifest(u);o.stop(`Fetched categories from ${P.cyan(u)}`),m.isErr()&&program.error(P.red(m.unwrapErr()));let R=m.unwrap(),M=await multiselect({message:"Which category paths would you like to configure?",options:R.map(F=>({label:F.name,value:F.name})),required:!1});if(isCancel(M)&&(cancel("Canceled!"),process.exit(0)),M.length>0)for(let F of M){let L=n[F],f=await text({message:`Where should ${F} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:L||`./src/${F}`,defaultValue:L,initialValue:L});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),n[F]=f;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Ae.existsSync(Q.join(e.cwd,".prettierrc"))&&(y="prettier"),Ae.existsSync(Q.join(e.cwd,"biome.json"))&&(y="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(k=>({value:k.toLowerCase(),label:k})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${X.package.version}/schemas/project-config.json`,repos:e.repos,includeTests:r.isOk()&&e.tests===void 0?r.unwrap().includeTests:e.tests??!1,watermark:e.watermark,formatter:e.formatter,paths:n};o.start(`Writing config to \`${tt}\``);let{prettierOptions:a,biomeOptions:p}=await ht({formatter:i.formatter,cwd:e.cwd}),c=Q.join(e.cwd,tt),l=await or.format(JSON.stringify(i,null," "),{biomeOptions:p,prettierOptions:a,filePath:c,formatter:i.formatter});Ae.writeFileSync(c,l),o.stop(`Wrote config to \`${tt}\`.`);},ns=async e=>{let t=spinner(),r=Q.join(e.cwd,"package.json");Ae.existsSync(r)||program.error(P.red(`Couldn't find your ${P.bold("package.json")}!`));let o=Ot(e.cwd).match(m=>m,m=>program.error(P.red(m))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${X.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let R=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break}let m=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:R=>{if(R.trim().length===0)return "Please provide a value!"}});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(m);}let s=JSON.parse(Ae.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let m=await confirm({message:`The \`${P.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m)break;{let R=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:M=>{if(M.trim().length===0)return "Please provide a value!"}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),e.script=R;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let m=await confirm({message:`Add ${fe} as a dev dependency?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),a=m;}let p=!n;if(!e.yes&&n){let m=await confirm({message:`Create a \`${P.cyan(Ue)}\` file?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),p=m;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",l="";if(a)l+="jsrepo build";else {let m=resolveCommand$1(c,"execute",["jsrepo","build"]);m||program.error(P.red(`Error resolving execute command for ${c}`)),l+=`${m.command} ${m.args.join(" ")} `;}p||(l+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=l;let y=[];y.push({loadingMessage:`Adding \`${P.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${P.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ae.writeFileSync(r,JSON.stringify(s,null," "));}catch(m){program.error(P.red(`Error writing to \`${P.bold(r)}\`. Error: ${m}`));}}}),p&&y.push({loadingMessage:`Writing config to \`${P.cyan(Ue)}\``,completedMessage:`Wrote config to \`${P.cyan(Ue)}\``,run:async()=>{let m=Q.join(e.cwd,Ue);try{Ae.writeFileSync(Q.join(m),JSON.stringify(o,null," "));}catch(R){program.error(P.red(`Error writing to \`${P.bold(m)}\`. Error: ${R}`));}}}),await xt(y,{});let u=i;if(a&&!i){let m=e.yes;if(!e.yes){let R=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),m=R;}m&&(t.start(`Installing ${fe}`),(await Ne({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${fe}.`),M=>{t.stop(`Failed to install ${fe}.`),program.error(M);}),u=!0);}let k=[];if(!u&&a){let m=resolveCommand$1(c,"install",["jsrepo","-D"]);k.push(`Install ${fe} as a dev dependency \`${P.cyan(`${m?.command} ${m?.args.join(" ")}`)}\``);}k.push(`Add categories to \`${P.cyan(o.dirs.join(", "))}\`.`);let x=resolveCommand$1(c,"run",[e.script]);k.push(`Run \`${P.cyan(`${x?.command} ${x?.args.join(" ")}`)}\` to build the registry.`),k=k.map((m,R)=>`${R+1}. ${m}`);let A=vt(k);process.stdout.write(A);};var hs=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),wr=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.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hs,t);ne(X.package.version),await ys(e,r),outro(P.green("All done!"));}),ys=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=$e(t.cwd).match(f=>f,f=>program.error(P.red(f))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${P.cyan(i.join(", "))}`);for(let f of i){let g=(await st(f)).match(_=>_,_=>program.error(P.red(_))),E=await g.provider.fetchManifest(g);r(`Got info for provider ${P.cyan(g.name)}`),E.isErr()&&(t.verbose||n.stop(`Error fetching ${P.cyan(f)}`),program.error(P.red(`There was an error fetching the \`${be}\` from the repository ${P.cyan(f)} make sure the target repository has a \`${be}\` in its root?`)));let b=E.unwrap();for(let _ of b)for(let h of _.blocks)s.set(`${g.name}/${g.owner}/${g.repoName}/${_.name}/${h.name}`,{...h,sourceRepo:g});}r(`Retrieved blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${P.cyan(i.join(", "))}`);let a=Q.resolve(Q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${P.bold(a)}.`),Ae.mkdirSync(a,{recursive:!0});let p=()=>{Ae.rmSync(a,{recursive:!0,force:!0});},c=Ye(s,o,t.cwd).map(f=>f.specifier),l=e;e.length===0&&(l=c),l.length===0&&(p(),program.error(P.red("There were no blocks found in your project!")));let y=[];for(let f of l){let g;if(q.find(E=>f.startsWith(E.name()))){if(i.length===0){let[E,b,_,...h]=f.split("/"),S;h.length>2?S=`${E}/${b}/${_}/${h.slice(0,h.length-2).join("/")}`:S=`${E}/${b}/${_}`;let d=(await st(S)).match($=>$,$=>program.error(P.red($))),w=(await d.provider.fetchManifest(d)).match($=>$,$=>program.error(P.red($)));for(let $ of w)for(let v of $.blocks)s.set(`${d.name}/${d.owner}/${d.repoName}/${$.name}/${v.name}`,{...v,sourceRepo:d});}g=s.get(f);}else for(let E of i){let b=(await st(E)).unwrap(),_=s.get(`${b.name}/${b.owner}/${b.repoName}/${f}`);if(_!==void 0){g=_;break}}g||program.error(P.red(`Invalid block! ${P.bold(f)} does not exist!`)),y.push({name:f,block:g});}let u=ke(o.paths,t.cwd);u.isErr()&&program.error(P.red(u.unwrapErr()));let k=u.unwrap();for(let{block:f}of y){let g=f.sourceRepo,E=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(t.verbose||n.start(`Setting up test file for ${P.cyan(E)}`),!f.tests){n.stop(`No tests found for ${P.cyan(E)}`);continue}let b;k[f.category]!==void 0?b=Q.join(t.cwd,k[f.category]):b=Q.join(t.cwd,k["*"],f.category),b=Q.relative(a,b);let _=async d=>{let w=await g.provider.fetchRaw(g,d);return w.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${E}`))),w.unwrap()};r(`Downloading and copying test files for ${E}`);let h=[];for(let d of f.files.filter(w=>ue(w))){let w=await _(Q.join(f.directory,d)),$=Q.join(a,d);Ae.writeFileSync($,w),h.push($);}let S=new Project;for(let d of h){r(`Opening test file ${d}`);let w=S.addSourceFileAtPath(d);for(let $ of w.getImportDeclarations()){let v=$.getModuleSpecifierValue(),j;v.startsWith(".")&&(f.subdirectory?j=Q.join(b,f.name,v):j=Q.join(b,v)),j&&$.setModuleSpecifier(j.replaceAll(/\\/g,"/"));}}S.saveSync(),r(`Completed ${P.cyan.bold(E)} test file`),t.verbose||n.stop(`Completed setup for ${P.bold(E)}`);}r("Beginning testing");let x=await detect({cwd:t.cwd});x==null&&program.error(P.red("Could not detect package manager"));let A=resolveCommand(x.agent,"execute",["vitest","run",a]);A==null&&program.error(P.red(`Could not resolve add command for '${x.agent}'.`));let{command:m,args:R}=A,M=`${m} ${R.join(" ")}`,F=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${M}`,L=f=>console.info(f.toString());F.stdout.on("data",L),F.stderr.on("data",L);try{await F,p();}catch(f){t.debug?console.info(`${P.bold("--debug")} flag provided. Skipping cleanup. Run '${P.bold(M)}' to retry tests.
59
+ `):p(),program.error(P.red(`Tests failed! Error ${f}`));}};var Cs=C.object({all:C.boolean(),expand:C.boolean(),maxUnchanged:C.number(),repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),kr=new Command("update").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",!1).option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(Cs,t);ne(X.package.version),await xs(e,r),outro(P.green("All done!"));}),xs=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=$e(t.cwd).match(f=>f,f=>program.error(P.red(f))),s=n.repos;t.repo&&(s=[t.repo]);for(let f of e)q.find(g=>f.startsWith(g.name()))&&program.error(P.red(`Invalid value provided for block names \`${P.bold(f)}\`. Block names are expected to be provided in the format of \`${P.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${P.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(s.join(", "))}`);let i=(await Ke(...s)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed to get info for ${P.cyan(f)}`),program.error(P.red(g));});r(`Resolved ${P.cyan(s.join(", "))}`),r(`Fetching blocks from ${P.cyan(s.join(", "))}`);let a=(await qe(...i)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed fetching blocks from ${P.cyan(f)}`),program.error(P.red(g));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(s.join(", "))}`),r(`Retrieved blocks from ${P.cyan(s.join(", "))}`);let p=Ye(a,n,t.cwd);p.length===0&&program.error(P.red(`You haven't installed any blocks yet. Did you mean to \`${P.bold("add")}\`?`));let c=e;if(t.all&&(c=p.map(f=>f.specifier)),c.length===0){let f=await multiselect({message:"Which blocks would you like to update?",options:p.filter(g=>g.block.list).map(g=>({label:`${P.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}r(`Preparing to update ${P.cyan(c.join(", "))}`);let l=(await it(c,a,i)).match(f=>f,program.error),y=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],k=new Set,x=new Set,{prettierOptions:A,biomeOptions:m}=await ht({formatter:n.formatter,cwd:t.cwd}),R=ke(n.paths,t.cwd);R.isErr()&&program.error(P.red(R.unwrapErr()));let M=R.unwrap();for(let{block:f}of l){let g=`${f.sourceRepo.url}/${f.category}/${f.name}`,E=yt(X.package.version,f.sourceRepo.url),b=f.sourceRepo;r(`Attempting to add ${g}`);let _;M[f.category]!==void 0?_=Q.join(t.cwd,M[f.category]):_=Q.join(t.cwd,M["*"],f.category);let h=[],S=async d=>{let w=await b.provider.fetchRaw(b,d,{verbose:r});return w.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${g}`))),w.unwrap()};for(let d of f.files){if(!n.includeTests&&ue(d))continue;let w=Q.join(f.directory,d),$;f.subdirectory?$=Q.join(_,f.name,d):$=Q.join(_,d);let v=await S(w);Ae.mkdirSync($.slice(0,$.length-d.length),{recursive:!0}),h.push({content:v,destPath:$,fileName:d});}process.stdout.write(`${W}
60
+ `),process.stdout.write(`${W} ${g}
61
+ `);for(let d of h){let w=await Ut({file:d,biomeOptions:m,prettierOptions:A,config:n,imports:f._imports_,watermark:E,verbose:r,cwd:t.cwd});w.isErr()&&program.error(P.red(w.unwrapErr()));let $=w.unwrap(),v=t.yes;if(!t.yes){process.stdout.write(`${W}
62
+ `);let j="";Ae.existsSync(d.destPath)&&(j=Ae.readFileSync(d.destPath).toString());let z=diffLines(j,$),ce=Q.join(`${b.name}/${b.owner}/${b.repoName}`,d.fileName),ve=Q.relative(t.cwd,d.destPath),N=Ht({from:ce,to:ve,changes:z,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:P.greenBright,colorRemoved:P.redBright,colorCharsAdded:P.bgGreenBright,colorCharsRemoved:P.bgRedBright,prefix:()=>`${W} `,onUnchanged:({from:B,to:ee,prefix:et})=>`${et?.()??""}${P.cyan(B)} \u2192 ${P.gray(ee)} ${P.gray("(unchanged)")}
63
+ `,intro:({from:B,to:ee,changes:et,prefix:ze})=>{let br=et.filter(wo=>wo.added).length;return `${ze?.()??""}${P.cyan(B)} \u2192 ${P.gray(ee)} (${br} change${br===1?"":"s"})
64
+ ${ze?.()??""}
65
+ `}});if(process.stdout.write(N),z.length>1||j===""){let B=await confirm({message:"Accept changes?",initialValue:!0});isCancel(B)&&(cancel("Canceled!"),process.exit(0)),v=B;}}v&&await xt([{loadingMessage:`Writing changes to ${P.cyan(d.destPath)}`,completedMessage:`Wrote changes to ${P.cyan(d.destPath)}.`,run:async()=>Ae.writeFileSync(d.destPath,$)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&f.tests){r("Trying to include tests");let{devDependencies:d}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(d===void 0||d.vitest===void 0)&&k.add("vitest");}for(let d of f.devDependencies)k.add(d);for(let d of f.dependencies)x.add(d);}await xt(u,{verbose:t.verbose?r:void 0});let F=Dt(x,k,{cwd:t.cwd});if(x=F.dependencies,k=F.devDependencies,x.size>0||k.size>0){let f=t.yes;if(!t.yes){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),f=b;}f&&(x.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(x),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),k.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(k),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let g=[];if(!f){if(x.size>0){let b=resolveCommand(y,"install",[...x]);g.push(`Install dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(k.size>0){let b=resolveCommand(y,"install",[...k,"-D"]);g.push(`Install dev dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}g=g.map((b,_)=>`${_+1}. ${b}`),f||g.push(""),g.push("Import and use the blocks!");let E=vt(g);process.stdout.write(E);}};var go=e=>{let t=fileURLToPath(import.meta.url);return Q.join(t,"../..",e)},{version:ho,name:yo,description:vo,repository:Ps}=JSON.parse(Ae.readFileSync(go("package.json"),"utf-8")),X={package:{name:yo,description:vo,version:ho,repository:Ps},resolveRelativeToRoot:go};console.clear();program.name(yo).description(vo).version(ho).addCommand(ir).addCommand(lr).addCommand(pr).addCommand(fr).addCommand(gr).addCommand(yr).addCommand(wr).addCommand(kr);program.parse();export{X as context};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "jsrepo",
3
3
  "description": "A CLI to add shared code from remote repositories.",
4
- "version": "1.22.2",
4
+ "version": "1.23.0",
5
5
  "license": "MIT",
6
6
  "homepage": "https://jsrepo.dev",
7
7
  "author": {
@@ -48,7 +48,7 @@
48
48
  "@clack/prompts": "^0.8.2",
49
49
  "@vue/compiler-sfc": "^3.5.13",
50
50
  "ansi-regex": "^6.1.0",
51
- "chalk": "^5.3.0",
51
+ "chalk": "^5.4.1",
52
52
  "commander": "^12.1.0",
53
53
  "conf": "^13.1.0",
54
54
  "diff": "^7.0.0",