jsrepo 1.17.2 → 1.17.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +35 -35
- package/package.json +1 -1
- package/schemas/registry-config.json +8 -1
package/dist/index.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Ee 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,password,intro}from'@clack/prompts';import x 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 mt from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as Ct from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as et from'prettier';import*as Cr from'svelte/compiler';import {Project}from'ts-morph';import ho from'validate-npm-package-name';import io from'node:os';import so from'ansi-regex';import xo from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import Oo from'escape-string-regexp';import {diffLines,diffChars}from'diff';var
|
|
2
|
+
import Ee 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,password,intro}from'@clack/prompts';import x 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 mt from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as Ct from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as et from'prettier';import*as Cr from'svelte/compiler';import {Project}from'ts-morph';import ho from'validate-npm-package-name';import io from'node:os';import so from'ansi-regex';import xo from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import Oo from'escape-string-regexp';import {diffLines,diffChars}from'diff';var A=x.gray("\u2502"),At=x.gray("\u2500"),ar=x.gray("\u2510"),cr=x.gray("\u2518"),Dt=x.gray("\u251C");x.gray("\u250C");x.gray("\u2514");var ue=x.bgRgb(245,149,66).black(" WARN "),Qe=x.bgBlueBright.white(" INFO "),wt=x.bgRedBright.white(" ERROR "),ke=x.hex("#f7df1e")("jsrepo");var $t=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=>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=>j(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)}},j=e=>new $t({ok:!0,val:e}),T=e=>new $t({ok:!1,err:e});var lr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var dr=C.union([C.literal("off"),C.literal("warn"),C.literal("error")]),Qr={"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 ${x.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,i]=o.split("/"),a=t.find(c=>c.name.trim()===n.trim()),s=`${x.bold(`${e.category}/${e.name}`)} depends on local dependency ${x.bold(o)} which doesn't exist`;if(!a){r.push(s);continue}a.blocks.find(c=>c.name===i)===void 0&&r.push(s);}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,i]=o.split("/");if(i!=="index")continue;let a=t.find(c=>c.name===n);!a||!a.blocks.find(c=>c.name===i)||r.push(`${x.bold(`${e.category}/${e.name}`)} depends on ${x.bold(`${n}/${i}`)}`);}return r.length>0?r:void 0}},"max-local-dependencies":{description:"Enforces a limit on the amount of local dependencies a block can have.",check:(e,{options:t})=>{let r=[],o;return typeof t[0]!="number"?o=5:o=t[0],e.localDependencies.length>o&&r.push(`${x.bold(`${e.category}/${e.name}`)} has too many local dependencies (${x.bold(e.localDependencies.length)}) limit (${x.bold(o)})`),r.length>0?r:void 0}},"no-circular-dependency":{description:"Disallow circular dependencies.",check:(e,{categories:t})=>{let r=[],o=(a,s,c)=>{let d=[...c,`${s.category}/${s.name}`];for(let m of s.localDependencies){if(m===a)return d;let[y,u]=m.split("/"),w=t.find(O=>O.name===y)?.blocks.find(O=>O.name===u);if(!w)continue;let k=o(a,w,d);if(k)return [...k,a]}},n=`${e.category}/${e.name}`,i=o(n,e,[]);return i&&r.push(`There is a circular dependency in ${x.bold(n)}: ${x.bold(i.join(" -> "))}`),r.length>0?r:void 0}}},eo=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")]),pr=C.record(eo,C.union([dr,C.tupleWithRest([dr,C.union([C.string(),C.number()])],C.union([C.string(),C.number()]))])),Lt={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error"},fr=(e,t=Lt)=>{let r=[],o=[];for(let n of e)for(let i of n.blocks)for(let[a,s]of Object.entries(Qr)){let c=t[a],d,m=[];if(Array.isArray(c)?(d=c[0],m.push(...c.slice(1))):d=c,d==="off")continue;let y=s.check(i,{categories:e,options:m});if(y){if(d==="error"){o.push(...y.map(u=>`${A} ${wt} ${x.red(u)} ${x.gray(a)}`));continue}r.push(...y.map(u=>`${A} ${ue} ${u} ${x.gray(a)}`));}}return {warnings:r,errors:o}};var Je="jsrepo.json",Ae="jsrepo-build-config.json",Bt=C.union([C.literal("prettier"),C.literal("biome")]),ro=C.objectWithRest({"*":C.string()},C.string()),oo=C.object({$schema:C.string(),repos:C.optional(C.array(C.string()),[]),includeTests:C.boolean(),paths:ro,watermark:C.optional(C.boolean(),!0),formatter:C.optional(Bt)}),Re=e=>{if(!Ee.existsSync(q.join(e,Je)))return T("Could not find your configuration file! Please run `init`.");let t=C.safeParse(oo,JSON.parse(Ee.readFileSync(q.join(e,Je)).toString()));return t.success?j(t.output):T(`There was an error reading your \`${Je}\` file!`)},no=C.object({$schema:C.string(),dirs:C.array(C.string()),includeBlocks:C.optional(C.array(C.string()),[]),includeCategories:C.optional(C.array(C.string()),[]),doNotListBlocks:C.optional(C.array(C.string()),[]),doNotListCategories:C.optional(C.array(C.string()),[]),excludeDeps:C.optional(C.array(C.string()),[]),rules:C.optional(pr)}),kt=e=>{if(!Ee.existsSync(q.join(e,Ae)))return j(null);let t=C.safeParse(no,JSON.parse(Ee.readFileSync(q.join(e,Ae)).toString()));return t.success?j(t.output):T(`There was an error reading your \`${Ae}\` file!`)},Ce=(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={"*":ur(e["*"],o,t)};}for(let[i,a]of Object.entries(e))if(i!=="*"){if(a.startsWith(".")){n[i]=q.relative(t,q.join(q.resolve(t),a));continue}if(o===null)return T("Cannot resolve aliases because we couldn't find a tsconfig!");n[i]=ur(a,o,t);}return j(n)},ur=(e,t,r)=>{let o=t(e);return q.relative(r,o[0])};var Ue=e=>e.replace(so(),"");var ft=(e,t,r=" ")=>{if(Ue(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-Ue(e).length)+e},gr=(e,t,r=" ")=>e+r.repeat(t),hr=(e,t,r=" ")=>{if(Ue(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-Ue(e).length)};var ao=/\n|\r\n/g,se=e=>e.split(ao),ee=(e,{lineNumbers:t=!1,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,a)=>`${ft(`${a+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(io.EOL)};var _t=(e,t)=>{let r=q.join(e,"package.json");if(Ee.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return _t(o.slice(0,o.length-1).join("/"),t)},co=e=>{if(!Ee.existsSync(e))return T(`${e} doesn't exist`);let t=Ee.readFileSync(e).toString();return j(JSON.parse(t))},Rt=(e,t,{cwd:r})=>{let o=e,n=t,i=co(q.join(r,"package.json"));if(!i.isErr()){let a=i.unwrap();if(a.dependencies)for(let s of o){let[c,d]=s.split("@"),m=a.dependencies[c];d===void 0&&m||m&&m===d&&o.delete(s);}if(a.devDependencies)for(let s of n){let[c,d]=s.split("@"),m=a.devDependencies[c];d===void 0&&m||m&&m===d&&n.delete(s);}}return {dependencies:o,devDependencies:n}};var lo=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,po=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,wr=e=>{let t=lo.exec(e)||po.exec(e);return t?j({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):T(`invalid package name: ${e}`)};var yo={matches:e=>e.endsWith(".ts")||e.endsWith(".js")||e.endsWith(".tsx")||e.endsWith(".jsx"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let s=new Project().addSourceFileAtPath(e).getImportDeclarations().map(d=>d.getModuleSpecifierValue()),c=Jt({moduleSpecifiers:s,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return c.isErr()?T(c.unwrapErr().map(d=>Mt(d)).join(`
|
|
3
3
|
`)):j(c.unwrap())},comment:e=>`/*
|
|
4
|
-
${ee(
|
|
4
|
+
${ee(se(e),{prefix:()=>" "})}
|
|
5
5
|
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await et.format(e,{filepath:r,...o});let i=await Biome.create({distribution:Distribution.NODE});return n&&i.applyConfiguration(n),i.formatContent(e,{filePath:r}).content}},vo={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Ee.readFileSync(e).toString(),a=Cr.parse(i,{modern:!0,filename:e});if(!a.instance)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let s=[];walk(a.instance,{enter:d=>{d.type==="ImportDeclaration"&&typeof d.source.value=="string"&&s.push(d.source.value);}});let c=Jt({moduleSpecifiers:s,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return c.isErr()?T(c.unwrapErr().map(d=>Mt(d)).join(`
|
|
6
6
|
`)):j(c.unwrap())},comment:e=>`<!--
|
|
7
|
-
${ee(
|
|
7
|
+
${ee(se(e),{prefix:()=>" "})}
|
|
8
8
|
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await et.format(e,{filepath:r,...o}):e},wo={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Ee.readFileSync(e).toString(),a=Ct.parse(i,{filename:e});if(!a.descriptor.script?.content&&!a.descriptor.scriptSetup?.content)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let s;try{s=Ct.compileScript(a.descriptor,{id:"shut-it"});}catch(m){return T(`Compile error: ${m}`)}if(!s.imports)return j({dependencies:[],devDependencies:[],local:[],imports:{}});let c=Object.values(s.imports).map(m=>m.source),d=Jt({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return d.isErr()?T(d.unwrapErr().map(m=>Mt(m)).join(`
|
|
9
9
|
`)):j(d.unwrap())},comment:e=>`<!--
|
|
10
|
-
${ee(
|
|
11
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await et.format(e,{parser:"vue",...r}):e},$o={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>ee(
|
|
12
|
-
${ee(
|
|
13
|
-
-->`,format:async e=>e},Vt={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 et.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}},Mt=e=>`${ee(
|
|
10
|
+
${ee(se(e),{prefix:()=>" "})}
|
|
11
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await et.format(e,{parser:"vue",...r}):e},$o={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>ee(se(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await et.format(e,{parser:"yaml",...r}):e},bo={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>j({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
12
|
+
${ee(se(e),{prefix:()=>" "})}
|
|
13
|
+
-->`,format:async e=>e},Vt={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 et.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}},Mt=e=>`${ee(se(e),{prefix:t=>t===0?`${A} ${wt} `:`${A} `})}`,Jt=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:i})=>{let a=[],s=new Set,c=new Set,d={};for(let u of e){if(u.startsWith(".")){let O=jr(u,t,{filePath:r,dirs:n,cwd:i});if(O.isErr()){a.push(O.unwrapErr());continue}let f=O.unwrap();f&&(c.add(f.dependency),d[u]=f.template);continue}let w=ko(u,t,{filePath:r,dirs:n,cwd:i});if(w.isErr()){a.push(w.unwrapErr());continue}let k=w.unwrap();k?(c.add(k.dependency),d[u]=k.template):s.add(u);}if(a.length>0)return T(a);let{devDependencies:m,dependencies:y}=Co(Array.from(s),r,{doNotInstall:o||[]});return j({dependencies:y,devDependencies:m,local:Array.from(c),imports:d})},jr=(e,t,{filePath:r,alias:o,dirs:n,cwd:i})=>{if(t&&(e.startsWith("./")||e==="."))return j(void 0);let a=t?q.join(r,"../../"):q.join(r,"../"),s=q.join(q.join(r,"../"),e),c=q.join(a,"../");if(s.startsWith(c))return j(br(s.slice(c.length)));if(o){for(let d of n){let m=q.resolve(q.join(i,d)),y=q.resolve(s);if(y.startsWith(m))return j(br(y.slice(m.length+1)))}return T(`${r}:
|
|
14
14
|
${o} references code not contained in ${x.bold(n.join(", "))} and cannot be resolved.`)}return T(`${r}:
|
|
15
|
-
${e} references code not contained in ${a} and cannot be resolved.`)},br=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 i=`${t}/${n}`,a=`{{${i}}}`;return o.length===0?n.length!==r.length&&(a+=q.parse(r).ext):a+=`/${o.join("/")}`,{dependency:i,template:a}},ko=(e,t,{filePath:r,dirs:o,cwd:n})=>{let i=getTsconfig(r,"tsconfig.json");if(!i&&(i=getTsconfig(r,"jsconfig.json"),!i))return j(void 0);let a=createPathsMatcher(i);if(a){let s=a(e);for(let c of s){let d=Ro(c);if(!d)continue;let m=q.relative(q.resolve(q.join(r,"../")),d.path),
|
|
15
|
+
${e} references code not contained in ${a} and cannot be resolved.`)},br=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 i=`${t}/${n}`,a=`{{${i}}}`;return o.length===0?n.length!==r.length&&(a+=q.parse(r).ext):a+=`/${o.join("/")}`,{dependency:i,template:a}},ko=(e,t,{filePath:r,dirs:o,cwd:n})=>{let i=getTsconfig(r,"tsconfig.json");if(!i&&(i=getTsconfig(r,"jsconfig.json"),!i))return j(void 0);let a=createPathsMatcher(i);if(a){let s=a(e);for(let c of s){let d=Ro(c);if(!d)continue;let m=q.relative(q.resolve(q.join(r,"../")),d.path),y=jr(m,t,{filePath:r,alias:e,dirs:o,cwd:n,modIsFile:d.type==="file"});if(y.isErr())return T(y.unwrapErr());if(y.unwrap())return j(y.unwrap());break}}return j(void 0)},Ro=e=>{if(Ee.existsSync(e))return {path:e,type:Ee.statSync(e).isDirectory()?"directory":"file"};if(q.parse(e).ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Ee.existsSync(n))return {path:e,type:"file"}}let r=q.join(e,"../");if(!Ee.existsSync(r))return;let o=Ee.readdirSync(r);for(let n of o)if(q.parse(n).name===q.basename(e)){let a=q.join(r,n),s=a;return s.endsWith(".ts")&&(s=s.slice(0,s.length-3)),{path:s,type:Ee.statSync(a).isDirectory()?"directory":"file"}}},Co=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(c=>!builtinModules.includes(c)&&!c.startsWith("node:")),i=_t(q.dirname(t),""),a=new Set,s=new Set;if(i){let{devDependencies:c,dependencies:d}=JSON.parse(Ee.readFileSync(i,"utf-8"));for(let m of n){let y=wr(m);if(y.isErr()){console.warn(`${A} ${ue} Skipped adding import \`${x.cyan(m)}\`. Reason: Couldn't parse package name`);continue}let u=y.unwrap();if(!ho(u.name).validForNewPackages){console.warn(`${A} ${ue} Skipped adding import \`${x.cyan(m)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let w;if(d!==void 0&&(w=d[u.name]),w!==void 0){a.add(`${u.name}@${w}`);continue}if(c!==void 0&&(w=c[u.name]),w!==void 0){s.add(`${u.name}@${w}`);continue}a.add(u.name);}}return {dependencies:Array.from(a),devDependencies:Array.from(s)}},Ge=[yo,vo,wo,$o,Vt,bo];var jo=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())}),jt=C.object({name:C.string(),blocks:C.array(jo)}),xr=[".test.ts","_test.ts",".test.js","_test.js"],ye=e=>xr.find(t=>e.endsWith(t))!==void 0,Er=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,dirs:i,doNotListBlocks:a,doNotListCategories:s}})=>{let c;try{c=Ee.readdirSync(e);}catch{program.error(x.red(`Couldn't read the ${x.bold(e)} directory.`));}let d=[];for(let m of c){let y=q.join(e,m);if(Ee.statSync(y).isFile())continue;let u=q.basename(m),w=s.findIndex(f=>f===u)===-1;if(n.length>0&&n.find(f=>f.trim()===u.trim())===void 0)continue;let k={name:u,blocks:[]},O=Ee.readdirSync(y);for(let f of O){let $=q.join(y,f);if(Ee.statSync($).isFile()){if(ye(f))continue;let L=q.parse(q.basename(f)).name,N=a.findIndex(v=>v===L)===-1;if(o.length>0&&o.find(v=>v.trim()===L.trim())===void 0)continue;let D=Ge.find(v=>v.matches(f));if(!D){console.warn(`${A} ${ue} Skipped \`${x.bold($)}\` \`*${x.bold(q.parse(f).ext)}\` files are not currently supported!`);continue}let p=O.find(v=>xr.find(h=>v===`${L}${h}`)),{dependencies:g,devDependencies:S,local:l,imports:b}=D.resolveDependencies({filePath:$,isSubDir:!1,excludeDeps:r,cwd:t,dirs:i}).match(v=>v,v=>{program.error(x.red(v));}),E={name:L,directory:q.relative(t,y),category:u,tests:p!==void 0,subdirectory:!1,list:w?N:!1,files:[f],localDependencies:l,_imports_:b,dependencies:g,devDependencies:S};p!==void 0&&E.files.push(p),k.blocks.push(E);}else {let L=f,N=a.findIndex(v=>v===L)===-1;if(o.length>0&&o.find(v=>v.trim()===L.trim())===void 0)continue;let D=Ee.readdirSync($),p=D.findIndex(v=>ye(v))!==-1,g=new Set,S=new Set,l=new Set,b={};for(let v of D){if(ye(v))continue;if(Ee.statSync(q.join($,v)).isDirectory()){console.warn(`${A} ${ue} Skipped \`${x.bold(q.join($,v))}\` subdirectories are not currently supported!`);continue}let h=Ge.find(J=>J.matches(v));if(!h){console.warn(`${A} ${ue} Skipped \`${q.join($,v)}\` \`*${x.bold(q.parse(v).ext)}\` files are not currently supported!`);continue}let{local:R,dependencies:P,devDependencies:H,imports:X}=h.resolveDependencies({filePath:q.join($,v),isSubDir:!0,excludeDeps:r,cwd:t,dirs:i}).match(J=>J,J=>{program.error(x.red(J));});for(let J of R)J!==`${u}/${L}`&&g.add(J);for(let J of P)S.add(J);for(let J of H)l.add(J);for(let[J,U]of Object.entries(X))b[J]=U;}let E={name:L,directory:q.relative(t,$),category:u,tests:p,subdirectory:!0,list:w?N:!1,files:[...D],localDependencies:Array.from(g.keys()),dependencies:Array.from(S.keys()),devDependencies:Array.from(l.keys()),_imports_:b};k.blocks.push(E);}}d.push(k);}return d};var ve="jsrepo-manifest.json";var we=()=>new xo({projectName:"jsrepo"});var rt=(e,t,r)=>T(`There was an error fetching the \`${x.bold(t)}\` from ${x.bold(e.url)}.
|
|
16
16
|
|
|
17
17
|
${x.bold("This may be for one of the following reasons:")}
|
|
18
18
|
1. The \`${x.bold(t)}\` or containing repository doesn't exist
|
|
19
19
|
2. Your repository path is incorrect (wrong branch, wrong tag) default branches other than \`${x.bold(r)}\` must be specified \`${x.bold("github/<owner>/<name>/tree/<branch>")}\`
|
|
20
20
|
3. You are using an expired access token or a token that doesn't have access to this repository
|
|
21
|
-
`),te={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await te.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 te.info(e),n=await te.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=we().get(`${te.name()}-token`),a=new Headers;i!==void 0&&a.append("Authorization",`token ${i}`);let s=await mt(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):rt(o,t,te.defaultBranch())}catch(i){return r?.(`erroring in response ${i} `),rt(o,t,te.defaultBranch())}},fetchManifest:async e=>{let t=await te.fetchRaw(e,ve);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(jt),JSON.parse(t.unwrap()));return r.success?j(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("/"),i=te.defaultBranch(),a=we().get(`${te.name()}-token`),s=new Octokit({auth:a});if(n[0]==="tree")i=n[1];else try{let{data:d}=await s.rest.repos.get({owner:r,repo:o});i=d.default_branch;}catch{}let c="heads";if(i!==te.defaultBranch())try{let{data:d}=await s.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});d.some(m=>m.ref===`refs/tags/${i}`)&&(c="tags");}catch{c="heads";}return {refs:c,url:e,name:te.name(),repoName:o,owner:r,ref:i,provider:te}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},$e={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await $e.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 te.info(e),n=await $e.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=we().get(`${$e.name()}-token`),a=new Headers;i!==void 0&&a.append("PRIVATE-TOKEN",`${i}`);let s=await mt(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):rt(o,t,$e.defaultBranch())}catch{return rt(o,t,$e.defaultBranch())}},fetchManifest:async e=>{let t=await $e.fetchRaw(e,ve);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(jt),JSON.parse(t.unwrap()));return r.success?j(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("/"),i=$e.defaultBranch(),a="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[s,c]=n[2].split("?");i=s,c.startsWith("ref_type=")&&c.slice(10)==="tags"&&(a="tags");}else i=n[2];else try{let s=we().get(`${$e.name()}-token`),c=new Headers;s!==void 0&&c.append("Authorization",`Bearer ${s}`);let d=await mt(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:c});d.ok&&(i=(await d.json()).default_branch);}catch{}return {refs:a,url:e,name:$e.name(),repoName:o,owner:r,ref:i,provider:$e}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},
|
|
21
|
+
`),te={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await te.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 te.info(e),n=await te.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=we().get(`${te.name()}-token`),a=new Headers;i!==void 0&&a.append("Authorization",`token ${i}`);let s=await mt(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):rt(o,t,te.defaultBranch())}catch(i){return r?.(`erroring in response ${i} `),rt(o,t,te.defaultBranch())}},fetchManifest:async e=>{let t=await te.fetchRaw(e,ve);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(jt),JSON.parse(t.unwrap()));return r.success?j(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("/"),i=te.defaultBranch(),a=we().get(`${te.name()}-token`),s=new Octokit({auth:a});if(n[0]==="tree")i=n[1];else try{let{data:d}=await s.rest.repos.get({owner:r,repo:o});i=d.default_branch;}catch{}let c="heads";if(i!==te.defaultBranch())try{let{data:d}=await s.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});d.some(m=>m.ref===`refs/tags/${i}`)&&(c="tags");}catch{c="heads";}return {refs:c,url:e,name:te.name(),repoName:o,owner:r,ref:i,provider:te}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},$e={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await $e.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 te.info(e),n=await $e.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=we().get(`${$e.name()}-token`),a=new Headers;i!==void 0&&a.append("PRIVATE-TOKEN",`${i}`);let s=await mt(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):rt(o,t,$e.defaultBranch())}catch{return rt(o,t,$e.defaultBranch())}},fetchManifest:async e=>{let t=await $e.fetchRaw(e,ve);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(jt),JSON.parse(t.unwrap()));return r.success?j(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("/"),i=$e.defaultBranch(),a="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[s,c]=n[2].split("?");i=s,c.startsWith("ref_type=")&&c.slice(10)==="tags"&&(a="tags");}else i=n[2];else try{let s=we().get(`${$e.name()}-token`),c=new Headers;s!==void 0&&c.append("Authorization",`Bearer ${s}`);let d=await mt(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:c});d.ok&&(i=(await d.json()).default_branch);}catch{}return {refs:a,url:e,name:$e.name(),repoName:o,owner:r,ref:i,provider:$e}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},pe={name:()=>"bitbucket",defaultBranch:()=>"master",resolveRaw:async(e,t)=>{let r=await pe.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 pe.info(e),n=await pe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=we().get(`${pe.name()}-token`),a=new Headers;i!==void 0&&a.append("Authorization",`Bearer ${i}`);let s=await mt(n,{headers:a});return r?.(`Got a response from ${n} ${s.status} ${s.statusText}`),s.ok?j(await s.text()):rt(o,t,pe.defaultBranch())}catch{return rt(o,t,pe.defaultBranch())}},fetchManifest:async e=>{let t=await pe.fetchRaw(e,ve);if(t.isErr())return T(t.unwrapErr());let r=C.safeParse(C.array(jt),JSON.parse(t.unwrap()));return r.success?j(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("/"),i="heads",a=pe.defaultBranch();if(n[0]==="src")a=n[1];else try{let s=we().get(`${pe.name()}-token`),c=new Headers;s!==void 0&&c.append("Authorization",`Bearer ${s}`);let d=await mt(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:c});d.ok&&(a=(await d.json()).mainbranch.name);}catch{}return {refs:i,url:e,name:pe.name(),repoName:o,owner:r,ref:a,provider:pe}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},z=[te,$e,pe],He=async e=>{let t=z.find(r=>r.matches(e));return t?j(await t.info(e)):T(`Only ${z.map((r,o)=>`${o===z.length-1?"and":""}${x.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},ot=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 i=n.unwrap();for(let a of i)for(let s of a.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${a.name}/${s.name}`,{...s,sourceRepo:o});}return j(t)},nt=async(...e)=>{let t=[];for(let r of e){let o=await He(r);if(o.isErr())return T({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return j(t)};var gt=async(e,t,r)=>{let o=new Map;for(let n of e){let i;if(z.find(s=>n.startsWith(s.name()))){let[s,c,d,...m]=n.split("/");i=t.get(`${s}/${c}/${d}/${m.slice(m.length-2).join("/")}`);}else {if(r.length===0)return T(x.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${x.bold(`github/<owner>/<name>/${n}`)}\`!`));for(let{info:s}of r){let c=t.get(`${s.name}/${s.owner}/${s.repoName}/${n}`);if(c!==void 0){i=c;break}}}if(!i)return T(`Invalid block! ${x.bold(n)} does not exist!`);let a=`${i.category}/${i.name}`;if(o.set(a,{name:i.name,subDependency:!1,block:i}),i.localDependencies&&i.localDependencies.length>0){let s=await gt(i.localDependencies.filter(c=>!o.has(c)),t,r);if(s.isErr())return T(s.unwrapErr());for(let c of s.unwrap())o.set(`${c.block.category}/${c.block.name}`,c);}}return j(lr(o,(n,i)=>i))},Be=(e,t,r)=>{let o=[],n=Ce(t.paths,r);n.isErr()&&program.error(x.red(n.unwrapErr()));let i=n.unwrap();for(let[a,s]of e){let c;i[s.category]!==void 0?c=q.join(r,i[s.category]):c=q.join(r,i["*"],s.category);let d=q.join(c,s.files[0]);s.subdirectory&&(d=q.join(c,s.name)),Ee.existsSync(d)&&o.push({specifier:`${s.category}/${s.name}`,path:d,block:s});}return o};var Fe=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 T(x.red(`Could not resolve add command for '${e}'.`));try{return await execa(n.command,[...n.args],{cwd:o}),j(t)}catch{return T(x.red(`Failed to install ${x.bold(t.join(", "))}! Failed while running '${x.bold(`${n.command} ${n.args.join(" ")}`)}'`))}},To=/\{\{([^\/]+)\/([^\}]+)\}\}/g,Sr=({template:e,config:t,destPath:r,cwd:o})=>{let n=q.join(r,"../");return e.replace(To,(i,a,s)=>{if(t.paths[a]===void 0){if(t.paths["*"].startsWith(".")){let c=q.relative(n,q.join(o,t.paths["*"],a,s));return c.startsWith(".")?c:`./${c}`}return q.join(t.paths["*"],a,s)}if(t.paths[a].startsWith(".")){let c=q.relative(n,q.join(o,t.paths[a],s));return c.startsWith(".")?c:`./${c}`}return q.join(t.paths[a],s)})};var St=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:a,verbose:s})=>{let c=Ge.find(m=>m.matches(e.destPath)),d=e.content;if(c){t.watermark&&(d=`${c.comment(o)}
|
|
22
22
|
|
|
23
|
-
${d}`),s?.(`Formatting ${x.bold(e.destPath)}`);try{d=await c.format(d,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(m){return T(`Error formatting ${x.bold(e.destPath)} ${m}`)}}for(let[m,
|
|
23
|
+
${d}`),s?.(`Formatting ${x.bold(e.destPath)}`);try{d=await c.format(d,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(m){return T(`Error formatting ${x.bold(e.destPath)} ${m}`)}}for(let[m,y]of Object.entries(r)){let u=Sr({template:y,config:t,destPath:e.destPath,cwd:a}),w=new RegExp(`(['"])${Oo(m)}\\1`,"g");d=d.replaceAll(w,`$1${u}$1`);}return j(d)};var st=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await et.resolveConfig(q.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=q.join(t,"biome.json");Ee.existsSync(n)&&(o=JSON.parse(Ee.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var it=(e,t)=>`jsrepo ${e}
|
|
24
24
|
Installed from ${t}
|
|
25
|
-
${new Date().toLocaleDateString().replaceAll("/","-")}`;var ht=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);}},Lr=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),i=a=>{o?o(a):n.message(a);};o?o(t):n.start(t),await Promise.all([...e.map(a=>a.run({message:i}))]),o?o(r):n.stop(r);},at=e=>{let t=20;e.map(n=>{let i=gr(Ue(n),4);i.length>t&&(t=i.length);});let r="Next Steps",o=`${
|
|
25
|
+
${new Date().toLocaleDateString().replaceAll("/","-")}`;var ht=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);}},Lr=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),i=a=>{o?o(a):n.message(a);};o?o(t):n.start(t),await Promise.all([...e.map(a=>a.run({message:i}))]),o?o(r):n.stop(r);},at=e=>{let t=20;e.map(n=>{let i=gr(Ue(n),4);i.length>t&&(t=i.length);});let r="Next Steps",o=`${A}
|
|
26
26
|
`;return o+=`${Dt} ${r} ${At.repeat(t-r.length-1)}${ar}
|
|
27
|
-
`,o+=`${
|
|
28
|
-
`,e.map(n=>{o+=`${
|
|
29
|
-
`;}),o+=`${
|
|
27
|
+
`,o+=`${A} ${" ".repeat(t)} ${A}
|
|
28
|
+
`,e.map(n=>{o+=`${A} ${hr(n,t-1)} ${A}
|
|
29
|
+
`;}),o+=`${A} ${" ".repeat(t)} ${A}
|
|
30
30
|
`,o+=`${Dt}${At.repeat(t+2)}${cr}
|
|
31
|
-
`,o},re=e=>intro(`${x.bgHex("#f7df1e").black(" jsrepo ")}${x.gray(` v${e} `)}`);var Wo=C.object({repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),zt=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(Wo,t);re(K.package.version),await Vo(e,r),outro(x.green("All done!"));}),Vo=async(e,t)=>{let r=l=>{t.verbose&&console.info(`${Qe} ${l}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Re(t.cwd),i=n.isErr(),a;if(n.isErr()){let l=await confirm({message:`You don't have ${ke} initialized in your project. Do you want to continue?`,initialValue:!1});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0)),a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else a=n.unwrap();let s=a.repos;t.repo&&(s=[t.repo]);for(let l of e){if(!z.find(P=>l.startsWith(P.name())))continue;let[b,E,
|
|
32
|
-
`),process.stdout.write(x.gray(`${
|
|
33
|
-
`));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(z.length>1){let r=await select({message:"Which provider is this token for?",options:z.map(o=>({label:o.name(),value:o.name()})),initialValue:z[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=z[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 Qo=C.object({dirs:C.optional(C.array(C.string())),includeBlocks:C.optional(C.array(C.string())),includeCategories:C.optional(C.array(C.string())),excludeDeps:C.optional(C.array(C.string())),doNotListBlocks:C.optional(C.array(C.string())),doNotListCategories:C.optional(C.array(C.string())),output:C.boolean(),verbose:C.boolean(),cwd:C.string()}),Xt=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ve}\` 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("--do-not-list-blocks [blockNames...]","The names of blocks that shouldn't be listed when the user runs add.").option("--do-not-list-categories [categoryNames...]","The names of categories that shouldn't be listed when the user runs add.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--no-output",`Do not output a \`${ve}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(Qo,e);re(K.package.version),await en(t),outro(x.green("All done!"));}),en=async e=>{let t=spinner(),r=[],o=kt(e.cwd).match(s=>{if(s===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[]};let c=s;return e.dirs&&(c.dirs=e.dirs),e.doNotListBlocks&&(c.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(c.doNotListCategories=e.doNotListCategories),e.includeBlocks&&(c.includeBlocks=e.includeBlocks),e.includeCategories&&(c.includeCategories=e.includeCategories),e.excludeDeps&&(c.excludeDeps=e.excludeDeps),c.rules={...Lt,...c.rules},c},s=>program.error(x.red(s))),n=q.join(e.cwd,ve);for(let s of o.dirs){let c=q.join(e.cwd,s);t.start(`Building ${x.cyan(c)}`),e.output&&Ee.existsSync(n)&&Ee.rmSync(n);let d=Er(c,{cwd:e.cwd,config:o});for(let m of d){if(r.find(
|
|
34
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Pt=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:i=x.red,colorAdded:a=x.green,colorCharsRemoved:s=x.bgRed,colorCharsAdded:c=x.bgGreen,prefix:d,onUnchanged:m,intro:
|
|
35
|
-
`,k+=S.length;continue}if(L&&(u+=`${ee(S.slice(0,n),{prefix:
|
|
36
|
-
`),S.length>l){let b=S.length-l;u+=`${ee(
|
|
37
|
-
`;}
|
|
38
|
-
`),k=g
|
|
39
|
-
`,k
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
`),process.stdout.write(`${
|
|
43
|
-
`);for(let f of k.files){if(!r.includeTests&&ye(f))continue;process.stdout.write(`${
|
|
44
|
-
`);let
|
|
31
|
+
`,o},re=e=>intro(`${x.bgHex("#f7df1e").black(" jsrepo ")}${x.gray(` v${e} `)}`);var Wo=C.object({repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),zt=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(Wo,t);re(K.package.version),await Vo(e,r),outro(x.green("All done!"));}),Vo=async(e,t)=>{let r=l=>{t.verbose&&console.info(`${Qe} ${l}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Re(t.cwd),i=n.isErr(),a;if(n.isErr()){let l=await confirm({message:`You don't have ${ke} initialized in your project. Do you want to continue?`,initialValue:!1});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0)),a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else a=n.unwrap();let s=a.repos;t.repo&&(s=[t.repo]);for(let l of e){if(!z.find(P=>l.startsWith(P.name())))continue;let[b,E,v,...h]=l.split("/"),R;if(h.length>2?R=`${b}/${E}/${v}/${h.slice(0,h.length-2).join("/")}`:R=`${b}/${E}/${v}`,!s.find(P=>P===R)){if(!t.allow){let P=await confirm({message:`Allow ${ke} to download and run code from ${x.cyan(R)}?`,initialValue:!0});(isCancel(P)||!P)&&(cancel("Canceled!"),process.exit(0));}s.push(R);}}if(!t.allow&&t.repo){let l=await confirm({message:`Allow ${ke} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(l)||!l)&&(cancel("Canceled!"),process.exit(0));}s.length===0&&(i&&program.error(x.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${x.bold("--repo")}\` flag to specify a registry.`)),program.error(x.red(`There were no repos present in your config and you didn't provide the \`${x.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${x.cyan(s.join(", "))}`);let c=(await nt(...s)).match(l=>l,({repo:l,message:b})=>{o.stop(`Failed to get info for ${x.cyan(l)}`),program.error(x.red(b));});r(`Resolved ${x.cyan(s.join(", "))}`),r(`Fetching blocks from ${x.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${x.cyan(s.join(", "))}`);let d=(await ot(...c)).match(l=>l,({repo:l,message:b})=>{o.stop(`Failed fetching blocks from ${x.cyan(l)}`),program.error(x.red(b));});t.verbose||o.stop(`Retrieved blocks from ${x.cyan(s.join(", "))}`),r(`Retrieved blocks from ${x.cyan(s.join(", "))}`);let m=Be(d,a,t.cwd).map(l=>l.specifier),y=e;if(y.length===0){let l=await multiselect({message:"Select which blocks to add.",options:Array.from(d.entries()).filter(([b,E])=>E.list).map(([b,E])=>{let v=`${E.category}/${E.name}`,h=m.findIndex(P=>P===v)!==-1,R;return s.length>1?R=`${x.cyan(`${E.sourceRepo.name}/${E.sourceRepo.owner}/${E.sourceRepo.repoName}/${E.category}`)}/${E.name}`:R=`${x.cyan(E.category)}/${E.name}`,{label:h?x.gray(R):R,value:b,hint:h?"Installed":void 0}}),required:!0});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),y=l;}r(`Installing blocks ${x.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",d);let u=(await gt(y,d,c)).match(l=>l,l=>program.error(l)),w=(await detect({cwd:t.cwd}))?.agent??"npm",k=[],O=new Set,f=new Set;if(i){let l=await text({message:"Where would you like to add the blocks?",initialValue:a.paths["*"],defaultValue:a.paths["*"],placeholder:a.paths["*"],validate(b){if(b.trim()==="")return "Please provide a value"}});if(isCancel(l)&&(cancel("Canceled!"),process.exit(0)),a.paths["*"]=l,!t.yes){let b=await confirm({message:"Include tests?",initialValue:a.includeTests});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),a.includeTests=b;let E=await confirm({message:"Add watermark?",initialValue:a.watermark});isCancel(E)&&(cancel("Canceled!"),process.exit(0)),a.watermark=E;}}let{prettierOptions:$,biomeOptions:L}=await st({formatter:a.formatter,cwd:t.cwd}),N=Ce(a.paths,t.cwd);N.isErr()&&program.error(x.red(N.unwrapErr()));let D=N.unwrap(),p=[];for(let{block:l}of u){let b=`${l.sourceRepo.url}/${l.category}/${l.name}`,E=`${l.category}/${l.name}`,v=it(K.package.version,l.sourceRepo.url),h=l.sourceRepo;r(`Setting up ${b}`);let R;if(D[l.category]!==void 0?R=q.join(t.cwd,D[l.category]):R=q.join(t.cwd,D["*"],l.category),(!l.subdirectory&&Ee.existsSync(q.join(R,l.files[0]))||l.subdirectory&&Ee.existsSync(q.join(R,l.name)))&&!t.yes){let H=await confirm({message:`${x.cyan(E)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(H)&&(cancel("Canceled!"),process.exit(0)),!H)continue}p.push(E),k.push({run:async({message:H})=>{H(`Adding ${x.cyan(b)}`),r(`Creating directory ${x.bold(R)}`),Ee.mkdirSync(R,{recursive:!0}),r(`Created directory ${x.bold(R)}`);let X=[],J=async U=>{let de=await h.provider.fetchRaw(h,U,{verbose:r});return de.isErr()&&(o.stop(x.red(`Error fetching ${x.bold(U)}`)),program.error(x.red(`There was an error trying to get ${b}`))),de.unwrap()};for(let U of l.files){if(!a.includeTests&&ye(U))continue;let de=q.join(l.directory,U),Ve;l.subdirectory?Ve=q.join(R,l.name,U):Ve=q.join(R,U),r(`Adding ${x.bold(de)}`);let Ne=await J(de),Me=Ve.slice(0,Ve.length-U.length);r(`Creating directory ${x.bold(Me)}`),Ee.mkdirSync(Me,{recursive:!0}),r(`Created directory ${x.bold(Me)}`),X.push({content:Ne,destPath:Ve}),r(`Got ${x.bold(de)}`);}for(let U of X){let de=await St({file:U,biomeOptions:L,prettierOptions:$,config:a,imports:l._imports_,watermark:v,verbose:r,cwd:t.cwd});de.isErr()&&program.error(x.red(de.unwrapErr())),r(`Writing to ${x.bold(U.destPath)}`),Ee.writeFileSync(U.destPath,de.unwrap());}if(a.includeTests&&l.tests){r("Trying to include tests");let{devDependencies:U}=JSON.parse(Ee.readFileSync(q.join(t.cwd,"package.json")).toString());(U===void 0||U.vitest===void 0)&&O.add("vitest");}for(let U of l.devDependencies)O.add(U);for(let U of l.dependencies)f.add(U);}});}await Lr({startMessage:"Adding blocks",stopMessage:`Added ${x.cyan(p.join(", "))}`,tasks:k,verbose:t.verbose?r:void 0});let g=Rt(f,O,{cwd:t.cwd});if(f=g.dependencies,O=g.devDependencies,f.size>0||O.size>0){let l=t.yes;if(!t.yes){let v=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),l=v;}l&&(f.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(w)}`),(await Fe({pm:w,deps:Array.from(f),dev:!1,cwd:t.cwd})).match(v=>{t.verbose||o.stop(`Installed ${x.cyan(v.join(", "))}`);},v=>{t.verbose||o.stop("Failed to install dependencies"),program.error(v);})),O.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(w)}`),(await Fe({pm:w,deps:Array.from(O),dev:!0,cwd:t.cwd})).match(v=>{t.verbose||o.stop(`Installed ${x.cyan(v.join(", "))}`);},v=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(v);})));let b=[];if(!l){if(f.size>0){let v=resolveCommand(w,"install",[...f]);b.push(`Install dependencies \`${x.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}if(O.size>0){let v=resolveCommand(w,"install",[...O,"-D"]);b.push(`Install dev dependencies \`${x.cyan(`${v?.command} ${v?.args.join(" ")}`)}\``);}}b=b.map((v,h)=>`${h+1}. ${v}`),l||b.push(""),b.push("Import and use the blocks!");let E=at(b);process.stdout.write(E);}};var qo=C.object({token:C.optional(C.string()),provider:C.optional(C.string()),logout:C.boolean(),cwd:C.string()}),Kt=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(z.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(qo,e);re(K.package.version),await Ko(t),outro(x.green("All done!"));}),Ko=async e=>{let t=we();if(e.logout){for(let r of z){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${A}
|
|
32
|
+
`),process.stdout.write(x.gray(`${A} Already logged out of ${r.name()}.
|
|
33
|
+
`));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(z.length>1){let r=await select({message:"Which provider is this token for?",options:z.map(o=>({label:o.name(),value:o.name()})),initialValue:z[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=z[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 Qo=C.object({dirs:C.optional(C.array(C.string())),includeBlocks:C.optional(C.array(C.string())),includeCategories:C.optional(C.array(C.string())),excludeDeps:C.optional(C.array(C.string())),doNotListBlocks:C.optional(C.array(C.string())),doNotListCategories:C.optional(C.array(C.string())),output:C.boolean(),verbose:C.boolean(),cwd:C.string()}),Xt=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ve}\` 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("--do-not-list-blocks [blockNames...]","The names of blocks that shouldn't be listed when the user runs add.").option("--do-not-list-categories [categoryNames...]","The names of categories that shouldn't be listed when the user runs add.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--no-output",`Do not output a \`${ve}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(Qo,e);re(K.package.version),await en(t),outro(x.green("All done!"));}),en=async e=>{let t=spinner(),r=[],o=kt(e.cwd).match(s=>{if(s===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[]};let c=s;return e.dirs&&(c.dirs=e.dirs),e.doNotListBlocks&&(c.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(c.doNotListCategories=e.doNotListCategories),e.includeBlocks&&(c.includeBlocks=e.includeBlocks),e.includeCategories&&(c.includeCategories=e.includeCategories),e.excludeDeps&&(c.excludeDeps=e.excludeDeps),c.rules={...Lt,...c.rules},c},s=>program.error(x.red(s))),n=q.join(e.cwd,ve);for(let s of o.dirs){let c=q.join(e.cwd,s);t.start(`Building ${x.cyan(c)}`),e.output&&Ee.existsSync(n)&&Ee.rmSync(n);let d=Er(c,{cwd:e.cwd,config:o});for(let m of d){if(r.find(y=>y.name===m.name)!==void 0){console.warn(`${A} ${ue} Skipped adding \`${x.cyan(`${s}/${m.name}`)}\` because a category with the same name already exists!`);continue}r.push(m);}t.stop(`Built ${x.cyan(c)}`);}t.start("Checking manifest");let{warnings:i,errors:a}=fr(r,o.rules);t.stop("Completed checking manifest."),(i.length>0||a.length>0)&&console.log(A);for(let s of i)console.log(s);if(a.length>0){for(let s of a)console.log(s);program.error(x.red(`Completed checking manifest with ${x.bold(`${a.length} error(s)`)} and ${x.bold(`${i.length} warning(s)`)}`));}e.output&&(t.start(`Writing output to \`${x.cyan(n)}\``),Ee.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${x.cyan(n)}\``));};var Vr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var Mr=e=>/^\s+$/g.test(e),lt=e=>{let t=e.length-1;for(;Mr(e[t])&&t>=0;){if(e[t]===`
|
|
34
|
+
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Pt=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:i=x.red,colorAdded:a=x.green,colorCharsRemoved:s=x.bgRed,colorCharsAdded:c=x.bgGreen,prefix:d,onUnchanged:m,intro:y})=>{let u="",w=Vr(r,f=>f.count??0).toString().length+1,k=0;if(r.length===1&&!r[0].added&&!r[0].removed)return m({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:a,colorRemoved:i,prefix:d,onUnchanged:m,intro:y});u+=y({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:a,colorRemoved:i,prefix:d,onUnchanged:m,intro:y});let O=f=>x.gray(`${d?.()??""}${ft(`${f+1+k} `,w)} `);for(let f=0;f<r.length;f++){let $=r[f],L=r[f-1]?.added||r[f-1]?.removed,N=r[f+1]?.added||r[f+1]?.removed;if(!$.added&&!$.removed){if(!o&&$.count!==void 0&&$.count>n){let g=k,S=se(lt($.value)),l=0;if(N&&(l+=n),L&&(l+=n),l>=S.length){u+=`${ee(S,{prefix:O})}
|
|
35
|
+
`,k+=S.length;continue}if(L&&(u+=`${ee(S.slice(0,n),{prefix:O})}
|
|
36
|
+
`),S.length>l){let b=S.length-l;u+=`${ee(se(x.gray(`+ ${b} more unchanged (${x.italic("-E to expand")})`)),{prefix:()=>`${d?.()??""}${ft(" ",w)} `})}
|
|
37
|
+
`;}N&&(k=k+S.length-n,u+=`${ee(S.slice(S.length-n),{prefix:O})}
|
|
38
|
+
`),k=g+$.count;continue}u+=`${ee(se(lt($.value)),{prefix:O})}
|
|
39
|
+
`,k+=$.count??0;continue}let D=g=>g.added?a(lt(g.value)):g.removed?i(lt(g.value)):g.value,p=g=>g.added?c(lt(g.value)):g.removed?s(lt(g.value)):g.value;if($.removed&&$.count===1&&r[f+1]?.added&&r[f+1]?.count===1){let S=diffChars($.value,r[f+1].value).map(l=>p(l)).join("");u+=`${O(0)}${S}`,k+=1,f++;}else Mr($.value)?(u+=`${ee(se(p($)),{prefix:g=>`${O(g)}${p({removed:!0,value:" ",added:!1})}`})}
|
|
40
|
+
`,$.removed||(k+=$.count??0)):(u+=`${ee(se(D($)),{prefix:O})}
|
|
41
|
+
`,$.removed||(k+=$.count??0));}return u};var dn=C.object({expand:C.boolean(),maxUnchanged:C.number(),repo:C.optional(C.string()),allow:C.boolean(),cwd:C.string()}),Zt=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(dn,e);re(K.package.version),await pn(t),outro(x.green("All done!"));}),pn=async e=>{let t=spinner(),r=Re(e.cwd).match(d=>d,d=>program.error(x.red(d))),o=r.repos;if(e.repo&&(o=[e.repo]),!e.allow&&e.repo){let d=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(e.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}let n=(await nt(...o)).match(d=>d,({repo:d,message:m})=>{t.stop(`Failed to get info for ${x.cyan(d)}`),program.error(x.red(m));});t.start(`Fetching blocks from ${x.cyan(o.join(", "))}`);let i=(await ot(...n)).match(d=>d,({repo:d,message:m})=>{t.stop(`Failed fetching blocks from ${x.cyan(d)}`),program.error(x.red(m));});t.stop(`Retrieved blocks from ${x.cyan(o.join(", "))}`);let a=Be(i,r,e.cwd),s=Ce(r.paths,e.cwd);s.isErr()&&program.error(x.red(s.unwrapErr()));let c=s.unwrap();for(let d of a){let m=!1;for(let y of o){let u=(await He(y)).unwrap(),w=`${u.name}/${u.owner}/${u.repoName}/${d.specifier}`,k=i.get(w);if(k===void 0)continue;let O=it(K.package.version,y);m=!0,process.stdout.write(`${A}
|
|
42
|
+
`),process.stdout.write(`${A} ${w}
|
|
43
|
+
`);for(let f of k.files){if(!r.includeTests&&ye(f))continue;process.stdout.write(`${A}
|
|
44
|
+
`);let $=q.join(k.directory,f),L=await u.provider.fetchRaw(u,$);L.isErr()&&program.error(x.red(`There was an error trying to get ${w}`));let N=L.unwrap(),D,p;c[k.category]!==void 0?(p=c[k.category],D=q.join(e.cwd,c[k.category])):(p=q.join(c["*"],k.category),D=q.join(e.cwd,c["*"],k.category));let g=q.join(D,f),S=q.join(p,f);k.subdirectory&&(g=q.join(D,k.name,f),S=q.join(p,k.name,f));let l="";if(Ee.existsSync(g)&&(l=Ee.readFileSync(g).toString()),r.watermark){let h=Ge.find(R=>R.matches($));h&&(N=`${h.comment(O)}
|
|
45
45
|
|
|
46
|
-
${
|
|
46
|
+
${N}`);}let b=diffLines(l,N),E=q.join(`${u.name}/${u.owner}/${u.repoName}`,$),v=Pt({from:E,to:S,changes:b,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:x.greenBright,colorRemoved:x.redBright,colorCharsAdded:x.bgGreenBright,colorCharsRemoved:x.bgRedBright,prefix:()=>`${A} `,onUnchanged:({from:h,to:R,prefix:P})=>`${P?.()??""}${x.cyan(h)} \u2192 ${x.gray(R)} ${x.gray("(unchanged)")}
|
|
47
47
|
`,intro:({from:h,to:R,changes:P,prefix:H})=>{let X=P.filter(J=>J.added).length;return `${H?.()??""}${x.cyan(h)} \u2192 ${x.gray(R)} (${X} change${X===1?"":"s"})
|
|
48
48
|
${H?.()??""}
|
|
49
|
-
`}});process.stdout.write(y);}break}m||program.error(x.red(`Invalid block! ${x.bold(d)} does not exist!`));}};var vn=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(Bt),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),er=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(vn,e);if(re(K.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(x.red(`You cannot provide both ${x.bold("--project")} and ${x.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 $n(t):await wn(t),outro(x.green("All done!"));}),wn=async e=>{let t=we(),r=Re(e.cwd),o=spinner(),n,i=await text({message:"Please enter a default path to install the blocks",validate(v){if(v.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(i)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":i}:n={"*":i},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let v=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(v)&&(cancel("Canceled!"),process.exit(0)),!v)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:O=>{if(O.trim().length===0)return "Please provide a value";if(!z.find(D=>D.matches(O)))return `Invalid provider! Valid providers (${z.map(D=>D.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let $=z.find(O=>O.matches(u));$||program.error(x.red("Invalid provider!"));let k=`${$.name()}-token`;if(!t.get(k)){let O=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(O)&&(cancel("Canceled!"),process.exit(0)),O){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(k,D);}}o.start(`Fetching categories from ${x.cyan(u)}`);let f=await $.fetchManifest(u);o.stop(`Fetched categories from ${x.cyan(u)}`),f.isErr()&&program.error(x.red(f.unwrapErr()));let w=f.unwrap(),L=await multiselect({message:"Which category paths would you like to configure?",options:w.map(O=>({label:O.name,value:O.name})),required:!1});if(isCancel(L)&&(cancel("Canceled!"),process.exit(0)),L.length>0)for(let O of L){let D=n[O],p=await text({message:`Where should ${O} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:D||`./src/${O}`,defaultValue:D,initialValue:D});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),n[O]=p;}e.repos.push(u);}if(!e.formatter){let v=r.isErr()?"none":r.unwrap().formatter??"none";Ee.existsSync(q.join(e.cwd,".prettierrc"))&&(v="prettier"),Ee.existsSync(q.join(e.cwd,"biome.json"))&&(v="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map($=>({value:$.toLowerCase(),label:$})),initialValue:v});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let a={$schema:`https://unpkg.com/jsrepo@${K.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 \`${Je}\``);let{prettierOptions:s,biomeOptions:c}=await st({formatter:a.formatter,cwd:e.cwd}),d=q.join(e.cwd,Je),m=await Vt.format(JSON.stringify(a,null," "),{biomeOptions:c,prettierOptions:s,filePath:d,formatter:a.formatter});Ee.writeFileSync(d,m),o.stop(`Wrote config to \`${Je}\`.`);},$n=async e=>{let t=spinner(),r=q.join(e.cwd,"package.json");Ee.existsSync(r)||program.error(x.red(`Couldn't find your ${x.bold("package.json")}!`));let o=kt(e.cwd).match(f=>f,f=>program.error(x.red(f))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[]}),o.$schema=`https://unpkg.com/jsrepo@${K.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let w=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(w)&&(cancel("Canceled!"),process.exit(0)),!w)break}let f=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:w=>{if(w.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(f);}let i=JSON.parse(Ee.readFileSync(r).toString());for(;!e.yes&&i.scripts&&i.scripts[e.script];){let f=await confirm({message:`The \`${x.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f)break;{let w=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:L=>{if(L.trim().length===0)return "Please provide a value!"}});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),e.script=w;}}let a=i.devDependencies&&i.devDependencies.jsrepo!==void 0,s=e.yes||a;if(!e.yes&&!a){let f=await confirm({message:`Add ${ke} as a dev dependency?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),s=f;}let c=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${x.cyan(Ae)}\` file?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let d=(await detect$1({cwd:"cwd"}))?.agent??"npm",m="";if(s)m+="jsrepo build";else {let f=resolveCommand$1(d,"execute",["jsrepo","build"]);f||program.error(x.red(`Error resolving execute command for ${d}`)),m+=`${f.command} ${f.args.join(" ")} `;}c||(m+=` --dirs ${o.dirs.join(" ")} `),i.scripts===void 0&&(i.scripts={}),i.scripts[e.script]=m;let v=[];v.push({loadingMessage:`Adding \`${x.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${x.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ee.writeFileSync(r,JSON.stringify(i,null," "));}catch(f){program.error(x.red(`Error writing to \`${x.bold(r)}\`. Error: ${f}`));}}}),c&&v.push({loadingMessage:`Writing config to \`${x.cyan(Ae)}\``,completedMessage:`Wrote config to \`${x.cyan(Ae)}\``,run:async()=>{let f=q.join(e.cwd,Ae);try{Ee.writeFileSync(q.join(f),JSON.stringify(o,null," "));}catch(w){program.error(x.red(`Error writing to \`${x.bold(f)}\`. Error: ${w}`));}}}),await ht(v,{});let u=a;if(s&&!a){let f=e.yes;if(!e.yes){let w=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),f=w;}f&&(t.start(`Installing ${ke}`),(await Fe({pm:d,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${ke}.`),L=>{t.stop(`Failed to install ${ke}.`),program.error(L);}),u=!0);}let $=[];if(!u&&s){let f=resolveCommand$1(d,"install",["jsrepo","-D"]);$.push(`Install ${ke} as a dev dependency \`${x.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}$.push(`Add categories to \`${x.cyan(o.dirs.join(", "))}\`.`);let k=resolveCommand$1(d,"run",[e.script]);$.push(`Run \`${x.cyan(`${k?.command} ${k?.args.join(" ")}`)}\` to build the registry.`),$=$.map((f,w)=>`${w+1}. ${f}`);let A=at($);process.stdout.write(A);};var On=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),rr=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(On,t);re(K.package.version),await Nn(e,r),outro(x.green("All done!"));}),Nn=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Qe} ${p}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Re(t.cwd).match(p=>p,p=>program.error(x.red(p))),n=spinner(),i=new Map,a=o.repos;if(t.repo&&(a=[t.repo]),!t.allow&&t.repo){let p=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${x.cyan(a.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${x.cyan(a.join(", "))}`);for(let p of a){let g=(await He(p)).match(b=>b,b=>program.error(x.red(b))),S=await g.provider.fetchManifest(g);r(`Got info for provider ${x.cyan(g.name)}`),S.isErr()&&(t.verbose||n.stop(`Error fetching ${x.cyan(p)}`),program.error(x.red(`There was an error fetching the \`${ve}\` from the repository ${x.cyan(p)} make sure the target repository has a \`${ve}\` in its root?`)));let l=S.unwrap();for(let b of l)for(let E of b.blocks)i.set(`${g.name}/${g.owner}/${g.repoName}/${b.name}/${E.name}`,{...E,sourceRepo:g});}r(`Retrieved blocks from ${x.cyan(a.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${x.cyan(a.join(", "))}`);let s=q.resolve(q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${x.bold(s)}.`),Ee.mkdirSync(s,{recursive:!0});let c=()=>{Ee.rmSync(s,{recursive:!0,force:!0});},d=Be(i,o,t.cwd).map(p=>p.specifier),m=e;e.length===0&&(m=d),m.length===0&&(c(),program.error(x.red("There were no blocks found in your project!")));let v=[];for(let p of m){let g;if(z.find(S=>p.startsWith(S.name()))){if(a.length===0){let[S,l,b,...E]=p.split("/"),y;E.length>2?y=`${S}/${l}/${b}/${E.slice(0,E.length-2).join("/")}`:y=`${S}/${l}/${b}`;let h=(await He(y)).match(P=>P,P=>program.error(x.red(P))),R=(await h.provider.fetchManifest(h)).match(P=>P,P=>program.error(x.red(P)));for(let P of R)for(let H of P.blocks)i.set(`${h.name}/${h.owner}/${h.repoName}/${P.name}/${H.name}`,{...H,sourceRepo:h});}g=i.get(p);}else for(let S of a){let l=(await He(S)).unwrap(),b=i.get(`${l.name}/${l.owner}/${l.repoName}/${p}`);if(b!==void 0){g=b;break}}g||program.error(x.red(`Invalid block! ${x.bold(p)} does not exist!`)),v.push({name:p,block:g});}let u=Ce(o.paths,t.cwd);u.isErr()&&program.error(x.red(u.unwrapErr()));let $=u.unwrap();for(let{block:p}of v){let g=p.sourceRepo,S=`${p.sourceRepo.url}/${p.category}/${p.name}`;if(t.verbose||n.start(`Setting up test file for ${x.cyan(S)}`),!p.tests){n.stop(`No tests found for ${x.cyan(S)}`);continue}let l;$[p.category]!==void 0?l=q.join(t.cwd,$[p.category]):l=q.join(t.cwd,$["*"],p.category),l=q.relative(s,l);let b=async h=>{let R=await g.provider.fetchRaw(g,h);return R.isErr()&&(n.stop(x.red(`Error fetching ${x.bold(h)}`)),program.error(x.red(`There was an error trying to get ${S}`))),R.unwrap()};r(`Downloading and copying test files for ${S}`);let E=[];for(let h of p.files.filter(R=>ye(R))){let R=await b(q.join(p.directory,h)),P=q.join(s,h);Ee.writeFileSync(P,R),E.push(P);}let y=new Project;for(let h of E){r(`Opening test file ${h}`);let R=y.addSourceFileAtPath(h);for(let P of R.getImportDeclarations()){let H=P.getModuleSpecifierValue(),X;H.startsWith(".")&&(p.subdirectory?X=q.join(l,p.name,H):X=q.join(l,H)),X&&P.setModuleSpecifier(X.replaceAll(/\\/g,"/"));}}y.saveSync(),r(`Completed ${x.cyan.bold(S)} test file`),t.verbose||n.stop(`Completed setup for ${x.bold(S)}`);}r("Beginning testing");let k=await detect({cwd:t.cwd});k==null&&program.error(x.red("Could not detect package manager"));let A=resolveCommand(k.agent,"execute",["vitest","run",s]);A==null&&program.error(x.red(`Could not resolve add command for '${k.agent}'.`));let{command:f,args:w}=A,L=`${f} ${w.join(" ")}`,O=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${L}`,D=p=>console.info(p.toString());O.stdout.on("data",D),O.stderr.on("data",D);try{await O,c();}catch(p){t.debug?console.info(`${x.bold("--debug")} flag provided. Skipping cleanup. Run '${x.bold(L)}' to retry tests.
|
|
50
|
-
`):c(),program.error(x.red(`Tests failed! Error ${p}`));}};var Wn=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()}),nr=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(Wn,t);re(K.package.version),await Vn(e,r),outro(x.green("All done!"));}),Vn=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Qe} ${p}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=Re(t.cwd).match(p=>p,p=>program.error(x.red(p))),i=n.repos;t.repo&&(i=[t.repo]);for(let p of e)z.find(g=>p.startsWith(g.name()))&&program.error(x.red(`Invalid value provided for block names \`${x.bold(p)}\`. Block names are expected to be provided in the format of \`${x.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${x.cyan(i.join(", "))}`);let a=(await nt(...i)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed to get info for ${x.cyan(p)}`),program.error(x.red(g));});r(`Resolved ${x.cyan(i.join(", "))}`),r(`Fetching blocks from ${x.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${x.cyan(i.join(", "))}`);let s=(await ot(...a)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed fetching blocks from ${x.cyan(p)}`),program.error(x.red(g));});t.verbose||o.stop(`Retrieved blocks from ${x.cyan(i.join(", "))}`),r(`Retrieved blocks from ${x.cyan(i.join(", "))}`);let c=Be(s,n,t.cwd);c.length===0&&program.error(x.red(`You haven't installed any blocks yet. Did you mean to \`${x.bold("add")}\`?`));let d=e;if(t.all&&(d=c.map(p=>p.specifier)),d.length===0){let p=await multiselect({message:"Which blocks would you like to update?",options:c.map(g=>({label:`${x.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),d=p;}r(`Preparing to update ${x.cyan(d.join(", "))}`);let m=(await gt(d,s,a)).match(p=>p,program.error),
|
|
51
|
-
`),process.stdout.write(`${
|
|
52
|
-
`);for(let h of E){let R=await St({file:h,biomeOptions:f,prettierOptions:
|
|
53
|
-
`);let X="";Ee.existsSync(h.destPath)&&(X=Ee.readFileSync(h.destPath).toString());let J=diffLines(X,P),U=q.join(`${l.name}/${l.owner}/${l.repoName}`,h.fileName),
|
|
49
|
+
`}});process.stdout.write(v);}break}m||program.error(x.red(`Invalid block! ${x.bold(d)} does not exist!`));}};var vn=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(Bt),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),er=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(vn,e);if(re(K.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(x.red(`You cannot provide both ${x.bold("--project")} and ${x.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 $n(t):await wn(t),outro(x.green("All done!"));}),wn=async e=>{let t=we(),r=Re(e.cwd),o=spinner(),n,i=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(i)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":i}:n={"*":i},!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:N=>{if(N.trim().length===0)return "Please provide a value";if(!z.find(D=>D.matches(N)))return `Invalid provider! Valid providers (${z.map(D=>D.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let w=z.find(N=>N.matches(u));w||program.error(x.red("Invalid provider!"));let k=`${w.name()}-token`;if(!t.get(k)){let N=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(N)&&(cancel("Canceled!"),process.exit(0)),N){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(k,D);}}o.start(`Fetching categories from ${x.cyan(u)}`);let f=await w.fetchManifest(u);o.stop(`Fetched categories from ${x.cyan(u)}`),f.isErr()&&program.error(x.red(f.unwrapErr()));let $=f.unwrap(),L=await multiselect({message:"Which category paths would you like to configure?",options:$.map(N=>({label:N.name,value:N.name})),required:!1});if(isCancel(L)&&(cancel("Canceled!"),process.exit(0)),L.length>0)for(let N of L){let D=n[N],p=await text({message:`Where should ${N} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:D||`./src/${N}`,defaultValue:D,initialValue:D});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),n[N]=p;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Ee.existsSync(q.join(e.cwd,".prettierrc"))&&(y="prettier"),Ee.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(w=>({value:w.toLowerCase(),label:w})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let a={$schema:`https://unpkg.com/jsrepo@${K.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 \`${Je}\``);let{prettierOptions:s,biomeOptions:c}=await st({formatter:a.formatter,cwd:e.cwd}),d=q.join(e.cwd,Je),m=await Vt.format(JSON.stringify(a,null," "),{biomeOptions:c,prettierOptions:s,filePath:d,formatter:a.formatter});Ee.writeFileSync(d,m),o.stop(`Wrote config to \`${Je}\`.`);},$n=async e=>{let t=spinner(),r=q.join(e.cwd,"package.json");Ee.existsSync(r)||program.error(x.red(`Couldn't find your ${x.bold("package.json")}!`));let o=kt(e.cwd).match(f=>f,f=>program.error(x.red(f))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[]}),o.$schema=`https://unpkg.com/jsrepo@${K.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let $=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel($)&&(cancel("Canceled!"),process.exit(0)),!$)break}let f=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:$=>{if($.trim().length===0)return "Please provide a value!"}});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(f);}let i=JSON.parse(Ee.readFileSync(r).toString());for(;!e.yes&&i.scripts&&i.scripts[e.script];){let f=await confirm({message:`The \`${x.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(f)&&(cancel("Canceled!"),process.exit(0)),f)break;{let $=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:L=>{if(L.trim().length===0)return "Please provide a value!"}});isCancel($)&&(cancel("Canceled!"),process.exit(0)),e.script=$;}}let a=i.devDependencies&&i.devDependencies.jsrepo!==void 0,s=e.yes||a;if(!e.yes&&!a){let f=await confirm({message:`Add ${ke} as a dev dependency?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),s=f;}let c=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${x.cyan(Ae)}\` file?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let d=(await detect$1({cwd:"cwd"}))?.agent??"npm",m="";if(s)m+="jsrepo build";else {let f=resolveCommand$1(d,"execute",["jsrepo","build"]);f||program.error(x.red(`Error resolving execute command for ${d}`)),m+=`${f.command} ${f.args.join(" ")} `;}c||(m+=` --dirs ${o.dirs.join(" ")} `),i.scripts===void 0&&(i.scripts={}),i.scripts[e.script]=m;let y=[];y.push({loadingMessage:`Adding \`${x.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${x.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ee.writeFileSync(r,JSON.stringify(i,null," "));}catch(f){program.error(x.red(`Error writing to \`${x.bold(r)}\`. Error: ${f}`));}}}),c&&y.push({loadingMessage:`Writing config to \`${x.cyan(Ae)}\``,completedMessage:`Wrote config to \`${x.cyan(Ae)}\``,run:async()=>{let f=q.join(e.cwd,Ae);try{Ee.writeFileSync(q.join(f),JSON.stringify(o,null," "));}catch($){program.error(x.red(`Error writing to \`${x.bold(f)}\`. Error: ${$}`));}}}),await ht(y,{});let u=a;if(s&&!a){let f=e.yes;if(!e.yes){let $=await confirm({message:"Install dependencies?",initialValue:!0});isCancel($)&&(cancel("Canceled!"),process.exit(0)),f=$;}f&&(t.start(`Installing ${ke}`),(await Fe({pm:d,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${ke}.`),L=>{t.stop(`Failed to install ${ke}.`),program.error(L);}),u=!0);}let w=[];if(!u&&s){let f=resolveCommand$1(d,"install",["jsrepo","-D"]);w.push(`Install ${ke} as a dev dependency \`${x.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}w.push(`Add categories to \`${x.cyan(o.dirs.join(", "))}\`.`);let k=resolveCommand$1(d,"run",[e.script]);w.push(`Run \`${x.cyan(`${k?.command} ${k?.args.join(" ")}`)}\` to build the registry.`),w=w.map((f,$)=>`${$+1}. ${f}`);let O=at(w);process.stdout.write(O);};var On=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),rr=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(On,t);re(K.package.version),await Nn(e,r),outro(x.green("All done!"));}),Nn=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Qe} ${p}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Re(t.cwd).match(p=>p,p=>program.error(x.red(p))),n=spinner(),i=new Map,a=o.repos;if(t.repo&&(a=[t.repo]),!t.allow&&t.repo){let p=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${x.cyan(a.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${x.cyan(a.join(", "))}`);for(let p of a){let g=(await He(p)).match(b=>b,b=>program.error(x.red(b))),S=await g.provider.fetchManifest(g);r(`Got info for provider ${x.cyan(g.name)}`),S.isErr()&&(t.verbose||n.stop(`Error fetching ${x.cyan(p)}`),program.error(x.red(`There was an error fetching the \`${ve}\` from the repository ${x.cyan(p)} make sure the target repository has a \`${ve}\` in its root?`)));let l=S.unwrap();for(let b of l)for(let E of b.blocks)i.set(`${g.name}/${g.owner}/${g.repoName}/${b.name}/${E.name}`,{...E,sourceRepo:g});}r(`Retrieved blocks from ${x.cyan(a.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${x.cyan(a.join(", "))}`);let s=q.resolve(q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${x.bold(s)}.`),Ee.mkdirSync(s,{recursive:!0});let c=()=>{Ee.rmSync(s,{recursive:!0,force:!0});},d=Be(i,o,t.cwd).map(p=>p.specifier),m=e;e.length===0&&(m=d),m.length===0&&(c(),program.error(x.red("There were no blocks found in your project!")));let y=[];for(let p of m){let g;if(z.find(S=>p.startsWith(S.name()))){if(a.length===0){let[S,l,b,...E]=p.split("/"),v;E.length>2?v=`${S}/${l}/${b}/${E.slice(0,E.length-2).join("/")}`:v=`${S}/${l}/${b}`;let h=(await He(v)).match(P=>P,P=>program.error(x.red(P))),R=(await h.provider.fetchManifest(h)).match(P=>P,P=>program.error(x.red(P)));for(let P of R)for(let H of P.blocks)i.set(`${h.name}/${h.owner}/${h.repoName}/${P.name}/${H.name}`,{...H,sourceRepo:h});}g=i.get(p);}else for(let S of a){let l=(await He(S)).unwrap(),b=i.get(`${l.name}/${l.owner}/${l.repoName}/${p}`);if(b!==void 0){g=b;break}}g||program.error(x.red(`Invalid block! ${x.bold(p)} does not exist!`)),y.push({name:p,block:g});}let u=Ce(o.paths,t.cwd);u.isErr()&&program.error(x.red(u.unwrapErr()));let w=u.unwrap();for(let{block:p}of y){let g=p.sourceRepo,S=`${p.sourceRepo.url}/${p.category}/${p.name}`;if(t.verbose||n.start(`Setting up test file for ${x.cyan(S)}`),!p.tests){n.stop(`No tests found for ${x.cyan(S)}`);continue}let l;w[p.category]!==void 0?l=q.join(t.cwd,w[p.category]):l=q.join(t.cwd,w["*"],p.category),l=q.relative(s,l);let b=async h=>{let R=await g.provider.fetchRaw(g,h);return R.isErr()&&(n.stop(x.red(`Error fetching ${x.bold(h)}`)),program.error(x.red(`There was an error trying to get ${S}`))),R.unwrap()};r(`Downloading and copying test files for ${S}`);let E=[];for(let h of p.files.filter(R=>ye(R))){let R=await b(q.join(p.directory,h)),P=q.join(s,h);Ee.writeFileSync(P,R),E.push(P);}let v=new Project;for(let h of E){r(`Opening test file ${h}`);let R=v.addSourceFileAtPath(h);for(let P of R.getImportDeclarations()){let H=P.getModuleSpecifierValue(),X;H.startsWith(".")&&(p.subdirectory?X=q.join(l,p.name,H):X=q.join(l,H)),X&&P.setModuleSpecifier(X.replaceAll(/\\/g,"/"));}}v.saveSync(),r(`Completed ${x.cyan.bold(S)} test file`),t.verbose||n.stop(`Completed setup for ${x.bold(S)}`);}r("Beginning testing");let k=await detect({cwd:t.cwd});k==null&&program.error(x.red("Could not detect package manager"));let O=resolveCommand(k.agent,"execute",["vitest","run",s]);O==null&&program.error(x.red(`Could not resolve add command for '${k.agent}'.`));let{command:f,args:$}=O,L=`${f} ${$.join(" ")}`,N=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${L}`,D=p=>console.info(p.toString());N.stdout.on("data",D),N.stderr.on("data",D);try{await N,c();}catch(p){t.debug?console.info(`${x.bold("--debug")} flag provided. Skipping cleanup. Run '${x.bold(L)}' to retry tests.
|
|
50
|
+
`):c(),program.error(x.red(`Tests failed! Error ${p}`));}};var Wn=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()}),nr=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(Wn,t);re(K.package.version),await Vn(e,r),outro(x.green("All done!"));}),Vn=async(e,t)=>{let r=p=>{t.verbose&&console.info(`${Qe} ${p}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=Re(t.cwd).match(p=>p,p=>program.error(x.red(p))),i=n.repos;t.repo&&(i=[t.repo]);for(let p of e)z.find(g=>p.startsWith(g.name()))&&program.error(x.red(`Invalid value provided for block names \`${x.bold(p)}\`. Block names are expected to be provided in the format of \`${x.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let p=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(p)||!p)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${x.cyan(i.join(", "))}`);let a=(await nt(...i)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed to get info for ${x.cyan(p)}`),program.error(x.red(g));});r(`Resolved ${x.cyan(i.join(", "))}`),r(`Fetching blocks from ${x.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${x.cyan(i.join(", "))}`);let s=(await ot(...a)).match(p=>p,({repo:p,message:g})=>{o.stop(`Failed fetching blocks from ${x.cyan(p)}`),program.error(x.red(g));});t.verbose||o.stop(`Retrieved blocks from ${x.cyan(i.join(", "))}`),r(`Retrieved blocks from ${x.cyan(i.join(", "))}`);let c=Be(s,n,t.cwd);c.length===0&&program.error(x.red(`You haven't installed any blocks yet. Did you mean to \`${x.bold("add")}\`?`));let d=e;if(t.all&&(d=c.map(p=>p.specifier)),d.length===0){let p=await multiselect({message:"Which blocks would you like to update?",options:c.map(g=>({label:`${x.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(p)&&(cancel("Canceled!"),process.exit(0)),d=p;}r(`Preparing to update ${x.cyan(d.join(", "))}`);let m=(await gt(d,s,a)).match(p=>p,program.error),y=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],w=new Set,k=new Set,{prettierOptions:O,biomeOptions:f}=await st({formatter:n.formatter,cwd:t.cwd}),$=Ce(n.paths,t.cwd);$.isErr()&&program.error(x.red($.unwrapErr()));let L=$.unwrap();for(let{block:p}of m){let g=`${p.sourceRepo.url}/${p.category}/${p.name}`,S=it(K.package.version,p.sourceRepo.url),l=p.sourceRepo;r(`Attempting to add ${g}`);let b;L[p.category]!==void 0?b=q.join(t.cwd,L[p.category]):b=q.join(t.cwd,L["*"],p.category);let E=[],v=async h=>{let R=await l.provider.fetchRaw(l,h,{verbose:r});return R.isErr()&&(o.stop(x.red(`Error fetching ${x.bold(h)}`)),program.error(x.red(`There was an error trying to get ${g}`))),R.unwrap()};for(let h of p.files){if(!n.includeTests&&ye(h))continue;let R=q.join(p.directory,h),P;p.subdirectory?P=q.join(b,p.name,h):P=q.join(b,h);let H=await v(R);Ee.mkdirSync(P.slice(0,P.length-h.length),{recursive:!0}),E.push({content:H,destPath:P,fileName:h});}process.stdout.write(`${A}
|
|
51
|
+
`),process.stdout.write(`${A} ${g}
|
|
52
|
+
`);for(let h of E){let R=await St({file:h,biomeOptions:f,prettierOptions:O,config:n,imports:p._imports_,watermark:S,verbose:r,cwd:t.cwd});R.isErr()&&program.error(x.red(R.unwrapErr()));let P=R.unwrap(),H=t.yes;if(!t.yes){process.stdout.write(`${A}
|
|
53
|
+
`);let X="";Ee.existsSync(h.destPath)&&(X=Ee.readFileSync(h.destPath).toString());let J=diffLines(X,P),U=q.join(`${l.name}/${l.owner}/${l.repoName}`,h.fileName),de=q.relative(t.cwd,h.destPath),Ve=Pt({from:U,to:de,changes:J,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:x.greenBright,colorRemoved:x.redBright,colorCharsAdded:x.bgGreenBright,colorCharsRemoved:x.bgRedBright,prefix:()=>`${A} `,onUnchanged:({from:Ne,to:Me,prefix:Nt})=>`${Nt?.()??""}${x.cyan(Ne)} \u2192 ${x.gray(Me)} ${x.gray("(unchanged)")}
|
|
54
54
|
`,intro:({from:Ne,to:Me,changes:Nt,prefix:sr})=>{let ir=Nt.filter(Zr=>Zr.added).length;return `${sr?.()??""}${x.cyan(Ne)} \u2192 ${x.gray(Me)} (${ir} change${ir===1?"":"s"})
|
|
55
55
|
${sr?.()??""}
|
|
56
|
-
`}});if(process.stdout.write(Ve),J.length>1||X===""){let Ne=await confirm({message:"Accept changes?",initialValue:!0});isCancel(Ne)&&(cancel("Canceled!"),process.exit(0)),H=Ne;}}H&&await ht([{loadingMessage:`Writing changes to ${x.cyan(h.destPath)}`,completedMessage:`Wrote changes to ${x.cyan(h.destPath)}.`,run:async()=>Ee.writeFileSync(h.destPath,P)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&p.tests){r("Trying to include tests");let{devDependencies:h}=JSON.parse(Ee.readFileSync(q.join(t.cwd,"package.json")).toString());(h===void 0||h.vitest===void 0)
|
|
56
|
+
`}});if(process.stdout.write(Ve),J.length>1||X===""){let Ne=await confirm({message:"Accept changes?",initialValue:!0});isCancel(Ne)&&(cancel("Canceled!"),process.exit(0)),H=Ne;}}H&&await ht([{loadingMessage:`Writing changes to ${x.cyan(h.destPath)}`,completedMessage:`Wrote changes to ${x.cyan(h.destPath)}.`,run:async()=>Ee.writeFileSync(h.destPath,P)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&p.tests){r("Trying to include tests");let{devDependencies:h}=JSON.parse(Ee.readFileSync(q.join(t.cwd,"package.json")).toString());(h===void 0||h.vitest===void 0)&&w.add("vitest");}for(let h of p.devDependencies)w.add(h);for(let h of p.dependencies)k.add(h);}await ht(u,{verbose:t.verbose?r:void 0});let N=Rt(k,w,{cwd:t.cwd});if(k=N.dependencies,w=N.devDependencies,k.size>0||w.size>0){let p=t.yes;if(!t.yes){let l=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(l)&&(cancel("Canceled!"),process.exit(0)),p=l;}p&&(k.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(y)}`),(await Fe({pm:y,deps:Array.from(k),dev:!1,cwd:t.cwd})).match(l=>{t.verbose||o.stop(`Installed ${x.cyan(l.join(", "))}`);},l=>{t.verbose||o.stop("Failed to install dependencies"),program.error(l);})),w.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(y)}`),(await Fe({pm:y,deps:Array.from(w),dev:!0,cwd:t.cwd})).match(l=>{t.verbose||o.stop(`Installed ${x.cyan(l.join(", "))}`);},l=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(l);})));let g=[];if(!p){if(k.size>0){let l=resolveCommand(y,"install",[...k]);g.push(`Install dependencies \`${x.cyan(`${l?.command} ${l?.args.join(" ")}`)}\``);}if(w.size>0){let l=resolveCommand(y,"install",[...w,"-D"]);g.push(`Install dev dependencies \`${x.cyan(`${l?.command} ${l?.args.join(" ")}`)}\``);}}g=g.map((l,b)=>`${b+1}. ${l}`),p||g.push(""),g.push("Import and use the blocks!");let S=at(g);process.stdout.write(S);}};var qr=e=>{let t=fileURLToPath(import.meta.url);return q.join(t,"../..",e)},{version:Kr,name:Yr,description:Xr,repository:zn}=JSON.parse(Ee.readFileSync(qr("package.json"),"utf-8")),K={package:{name:Yr,description:Xr,version:Kr,repository:zn},resolveRelativeToRoot:qr};console.clear();program.name(Yr).description(Xr).version(Kr).addCommand(zt).addCommand(Kt).addCommand(er).addCommand(rr).addCommand(Xt).addCommand(nr).addCommand(Zt);program.parse();export{K as context};
|
package/package.json
CHANGED
|
@@ -82,13 +82,20 @@
|
|
|
82
82
|
}
|
|
83
83
|
],
|
|
84
84
|
"default": ["warn", 10]
|
|
85
|
+
},
|
|
86
|
+
"no-circular-dependency": {
|
|
87
|
+
"description": "Disallow circular dependencies.",
|
|
88
|
+
"type": "string",
|
|
89
|
+
"enum": ["error", "warn", "off"],
|
|
90
|
+
"default": "error"
|
|
85
91
|
}
|
|
86
92
|
},
|
|
87
93
|
"default": {
|
|
88
94
|
"no-category-index-file-dependency": "warn",
|
|
89
95
|
"no-unpinned-dependency": "warn",
|
|
90
96
|
"require-local-dependency-exists": "error",
|
|
91
|
-
"max-local-dependencies": ["warn", 10]
|
|
97
|
+
"max-local-dependencies": ["warn", 10],
|
|
98
|
+
"no-circular-dependency": "error"
|
|
92
99
|
}
|
|
93
100
|
}
|
|
94
101
|
},
|