jsrepo 1.18.0 → 1.18.2
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 +43 -43
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Te from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import K from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,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
|
|
3
|
-
`)):
|
|
4
|
-
${
|
|
5
|
-
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await
|
|
6
|
-
`)):
|
|
7
|
-
${
|
|
8
|
-
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await
|
|
9
|
-
`)):
|
|
10
|
-
${
|
|
11
|
-
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await
|
|
12
|
-
${
|
|
13
|
-
-->`,format:async e=>e},
|
|
14
|
-
${o} references code not contained in ${x.bold(n.join(", "))} and cannot be resolved.`)}return
|
|
15
|
-
${e} references code not contained in ${
|
|
2
|
+
import Te from'node:fs';import {fileURLToPath}from'node:url';import {Command,program,Option,Argument}from'commander';import K from'pathe';import {outro,spinner,confirm,isCancel,cancel,multiselect,text,select,log,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 j from'valibot';import {getTsconfig,createPathsMatcher}from'get-tsconfig';import gt from'node-fetch';import {Octokit}from'octokit';import {builtinModules}from'node:module';import {Biome,Distribution}from'@biomejs/js-api';import*as Et from'@vue/compiler-sfc';import {walk}from'estree-walker';import*as tt from'prettier';import*as Er from'svelte/compiler';import {Project}from'ts-morph';import bo from'validate-npm-package-name';import fo from'node:os';import po from'ansi-regex';import To from'conf';import {execa}from'execa';import {detect as detect$1,resolveCommand as resolveCommand$1}from'package-manager-detector';import Bo from'escape-string-regexp';import {diffLines,diffChars}from'diff';var N=x.gray("\u2502"),Bt=x.gray("\u2500"),lr=x.gray("\u2510"),dr=x.gray("\u2518"),Ft=x.gray("\u251C");x.gray("\u250C");x.gray("\u2514");var ye=x.bgRgb(245,149,66).black(" WARN "),et=x.bgBlueBright.white(" INFO "),bt=x.bgRedBright.white(" ERROR "),xe=x.hex("#f7df1e")("jsrepo");var kt=class{_result;constructor(t){this._result=t;}match(t,r){return this._result.ok?t(this._result.val):r(this._result.err)}map(t){return this.match(r=>I(t(r)),r=>P(r))}mapOr(t,r){return this.match(o=>r(o),o=>t)}mapOrElse(t,r){return this.match(o=>r(o),o=>t(o))}mapErr(t){return this.match(r=>I(r),r=>P(t(r)))}mapErrOr(t,r){return this.match(o=>t,o=>r(o))}mapErrOrElse(t,r){return this.match(o=>t(o),o=>r(o))}isOk(){return this.match(()=>!0,()=>!1)}isErr(){return this.match(()=>!1,()=>!0)}unwrap(){return this.match(t=>t,()=>{throw new Error("Attempted to call `.unwrap()` on a non `Ok` value.")})}unwrapErr(){return this.match(()=>{throw new Error("Attempted to call `.unwrapErr()` on a non `Err` value.")},t=>t)}unwrapOr(t){return this.match(r=>r,r=>t)}unwrapErrOr(t){return this.match(()=>t,r=>r)}unwrapOrElse(t){return this.match(r=>r,r=>t(r))}unwrapErrOrElse(t){return this.match(r=>t(r),r=>r)}expect(t){return this.match(r=>r,()=>{throw new Error(t)})}expectErr(t){return this.match(()=>{throw new Error(t)},r=>r)}},I=e=>new kt({ok:!0,val:e}),P=e=>new kt({ok:!1,err:e});var pr=(e,t)=>{let r=[];for(let[o,n]of e)r.push(t(o,n));return r};var fr=j.union([j.literal("off"),j.literal("warn"),j.literal("error")]),so={"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("/"),s=t.find(l=>l.name.trim()===n.trim()),c=`${x.bold(`${e.category}/${e.name}`)} depends on local dependency ${x.bold(o)} which doesn't exist`;if(!s){r.push(c);continue}s.blocks.find(l=>l.name===i)===void 0&&r.push(c);}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 s=t.find(l=>l.name===n);!s||!s.blocks.find(l=>l.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=`${e.category}/${e.name}`,n=Rt(o,e,t);return n&&r.push(`There is a circular dependency in ${x.bold(o)}: ${x.bold(n.join(" -> "))}`),r.length>0?r:void 0}},"no-unused-block":{description:"Disallow unused blocks. (Not listed and not a dependency of another block)",check:(e,{categories:t})=>{if(e.list)return;let r=`${e.category}/${e.name}`,o=t.flatMap(n=>n.blocks).filter(n=>n.list);for(let n of o)if(Rt(r,n,t))return;return [`${x.bold(r)} is unused and will be ${x.bold.red("removed")}`]}}},io=j.union([j.literal("no-category-index-file-dependency"),j.literal("no-unpinned-dependency"),j.literal("require-local-dependency-exists"),j.literal("max-local-dependencies"),j.literal("no-circular-dependency"),j.literal("no-unused-block")]),mr=j.record(io,j.union([fr,j.tupleWithRest([fr,j.union([j.string(),j.number()])],j.union([j.string(),j.number()]))])),_t={"no-category-index-file-dependency":"warn","no-unpinned-dependency":"warn","require-local-dependency-exists":"error","max-local-dependencies":["warn",10],"no-circular-dependency":"error","no-unused-block":"warn"},ur=(e,t=_t)=>{let r=[],o=[];for(let n of e)for(let i of n.blocks)for(let[s,c]of Object.entries(so)){let l=t[s],a,p=[];if(Array.isArray(l)?(a=l[0],p.push(...l.slice(1))):a=l,a==="off")continue;let h=c.check(i,{categories:e,options:p});if(h){if(a==="error"){o.push(...h.map(u=>`${N} ${bt} ${x.red(u)} ${x.gray(s)}`));continue}r.push(...h.map(u=>`${N} ${ye} ${u} ${x.gray(s)}`));}}return {warnings:r,errors:o}},Rt=(e,t,r,o=[])=>{let n=[...o,`${t.category}/${t.name}`];for(let i of t.localDependencies){if(i===e)return n;let[s,c]=i.split("/"),l=r.find(p=>p.name===s)?.blocks.find(p=>p.name===c);if(!l)continue;let a=Rt(e,l,r,n);if(a)return [...a,e]}},gr=(e,t)=>{for(let r of t)for(let o of r.blocks){if(!o.list)continue;if(Rt(e,o,t))return !0}return !1};var Ue="jsrepo.json",Le="jsrepo-build-config.json",Wt=j.union([j.literal("prettier"),j.literal("biome")]),co=j.objectWithRest({"*":j.string()},j.string()),Vt=j.object({$schema:j.string(),repos:j.optional(j.array(j.string()),[]),includeTests:j.boolean(),paths:co,watermark:j.optional(j.boolean(),!0),formatter:j.optional(Wt)}),Ee=e=>{if(!Te.existsSync(K.join(e,Ue)))return P("Could not find your configuration file! Please run `init`.");let t=j.safeParse(Vt,JSON.parse(Te.readFileSync(K.join(e,Ue)).toString()));return t.success?I(t.output):P(`There was an error reading your \`${Ue}\` file!`)},lo=j.object({$schema:j.string(),dirs:j.array(j.string()),includeBlocks:j.optional(j.array(j.string()),[]),includeCategories:j.optional(j.array(j.string()),[]),doNotListBlocks:j.optional(j.array(j.string()),[]),doNotListCategories:j.optional(j.array(j.string()),[]),excludeDeps:j.optional(j.array(j.string()),[]),preview:j.optional(j.boolean()),rules:j.optional(mr)}),jt=e=>{if(!Te.existsSync(K.join(e,Le)))return I(null);let t=j.safeParse(lo,JSON.parse(Te.readFileSync(K.join(e,Le)).toString()));return t.success?I(t.output):P(`There was an error reading your \`${Le}\` file!`)},Ie=(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={"*":K.relative(t,K.join(K.resolve(t),e["*"]))};else {if(o===null)return P("Cannot resolve aliases because we couldn't find a tsconfig!");n={"*":yr(e["*"],o,t)};}for(let[i,s]of Object.entries(e))if(i!=="*"){if(s.startsWith(".")){n[i]=K.relative(t,K.join(K.resolve(t),s));continue}if(o===null)return P("Cannot resolve aliases because we couldn't find a tsconfig!");n[i]=yr(s,o,t);}return I(n)},yr=(e,t,r)=>{let o=t(e);return K.relative(r,o[0])};var ze=e=>e.replace(po(),"");var ut=(e,t,r=" ")=>{if(ze(e).length>t)throw new Error("String length is greater than the length provided.");return r.repeat(t-ze(e).length)+e},vr=(e,t,r=" ")=>e+r.repeat(t),wr=(e,t,r=" ")=>{if(ze(e).length>t)throw new Error("String length is greater than the length provided.");return e+r.repeat(t-ze(e).length)};var mo=/\n|\r\n/g,ae=e=>e.split(mo),re=(e,{lineNumbers:t=!1,prefix:r}={})=>{let o=e;if(t){let n=e.length.toString().length+1;o=o.map((i,s)=>`${ut(`${s+1}`,n)} ${i}`);}return r!==void 0&&(o=o.map((n,i)=>`${r(i,e.length)}${n}`)),o.join(fo.EOL)};var Jt=(e,t)=>{let r=K.join(e,"package.json");if(Te.existsSync(r))return r;if(e===t)return;let o=e.split(/[\/\\]/);return Jt(o.slice(0,o.length-1).join("/"),t)},uo=e=>{if(!Te.existsSync(e))return P(`${e} doesn't exist`);let t=Te.readFileSync(e).toString();return I(JSON.parse(t))},xt=(e,t,{cwd:r})=>{let o=e,n=t,i=uo(K.join(r,"package.json"));if(!i.isErr()){let s=i.unwrap();if(s.dependencies)for(let c of o){let[l,a]=c.split("@"),p=s.dependencies[l];a===void 0&&p||p&&p===a&&o.delete(c);}if(s.devDependencies)for(let c of n){let[l,a]=c.split("@"),p=s.devDependencies[l];a===void 0&&p||p&&p===a&&n.delete(c);}}return {dependencies:o,devDependencies:n}};var go=/^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/,ho=/^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/,kr=e=>{let t=go.exec(e)||ho.exec(e);return t?I({name:t[1]||"",version:t[2]||"latest",path:t[3]||""}):P(`invalid package name: ${e}`)};var ko={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 c=new Project().addSourceFileAtPath(e).getImportDeclarations().map(a=>a.getModuleSpecifierValue()),l=Ht({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:r});return l.isErr()?P(l.unwrapErr().map(a=>Gt(a)).join(`
|
|
3
|
+
`)):I(l.unwrap())},comment:e=>`/*
|
|
4
|
+
${re(ae(e),{prefix:()=>" "})}
|
|
5
|
+
*/`,format:async(e,{formatter:t,filePath:r,prettierOptions:o,biomeOptions:n})=>{if(!t)return e;if(t==="prettier")return await tt.format(e,{filepath:r,...o});let i=await Biome.create({distribution:Distribution.NODE});return n&&i.applyConfiguration(n),i.formatContent(e,{filePath:r}).content}},Ro={matches:e=>e.endsWith(".svelte"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Te.readFileSync(e).toString(),s=Er.parse(i,{modern:!0,filename:e});if(!s.instance)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let c=[];walk(s.instance,{enter:a=>{a.type==="ImportDeclaration"&&typeof a.source.value=="string"&&c.push(a.source.value);}});let l=Ht({moduleSpecifiers:c,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["svelte","@sveltejs/kit",...r]});return l.isErr()?P(l.unwrapErr().map(a=>Gt(a)).join(`
|
|
6
|
+
`)):I(l.unwrap())},comment:e=>`<!--
|
|
7
|
+
${re(ae(e),{prefix:()=>" "})}
|
|
8
|
+
-->`,format:async(e,{formatter:t,filePath:r,prettierOptions:o})=>t&&t==="prettier"&&o&&o.plugins?.find(n=>n==="prettier-plugin-svelte")?await tt.format(e,{filepath:r,...o}):e},Co={matches:e=>e.endsWith(".vue"),resolveDependencies:({filePath:e,isSubDir:t,excludeDeps:r,dirs:o,cwd:n})=>{let i=Te.readFileSync(e).toString(),s=Et.parse(i,{filename:e});if(!s.descriptor.script?.content&&!s.descriptor.scriptSetup?.content)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let c;try{c=Et.compileScript(s.descriptor,{id:"shut-it"});}catch(p){return P(`Compile error: ${p}`)}if(!c.imports)return I({dependencies:[],devDependencies:[],local:[],imports:{}});let l=Object.values(c.imports).map(p=>p.source),a=Ht({moduleSpecifiers:l,filePath:e,isSubDir:t,dirs:o,cwd:n,doNotInstall:["vue","nuxt",...r]});return a.isErr()?P(a.unwrapErr().map(p=>Gt(p)).join(`
|
|
9
|
+
`)):I(a.unwrap())},comment:e=>`<!--
|
|
10
|
+
${re(ae(e),{prefix:()=>" "})}
|
|
11
|
+
-->`,format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await tt.format(e,{parser:"vue",...r}):e},jo={matches:e=>e.endsWith(".yml")||e.endsWith(".yaml"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>re(ae(e),{prefix:()=>"# "}),format:async(e,{formatter:t,prettierOptions:r})=>t&&t==="prettier"?await tt.format(e,{parser:"yaml",...r}):e},xo={matches:e=>e.endsWith(".svg"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>`<!--
|
|
12
|
+
${re(ae(e),{prefix:()=>" "})}
|
|
13
|
+
-->`,format:async e=>e},zt={matches:e=>e.endsWith(".json"),resolveDependencies:()=>I({dependencies:[],local:[],devDependencies:[],imports:{}}),comment:e=>e,format:async(e,{formatter:t,prettierOptions:r,biomeOptions:o,filePath:n})=>{if(!t)return e;if(t==="prettier")return await tt.format(e,{filepath:n,...r});let i=await Biome.create({distribution:Distribution.NODE});return o&&i.applyConfiguration(o),i.formatContent(e,{filePath:n}).content}},Gt=e=>`${re(ae(e),{prefix:t=>t===0?`${N} ${bt} `:`${N} `})}`,Ht=({moduleSpecifiers:e,isSubDir:t,filePath:r,doNotInstall:o,dirs:n,cwd:i})=>{let s=[],c=new Set,l=new Set,a={};for(let u of e){if(u.startsWith(".")){let L=Ir(u,t,{filePath:r,dirs:n,cwd:i});if(L.isErr()){s.push(L.unwrapErr());continue}let f=L.unwrap();f&&(l.add(f.dependency),a[u]=f.template);continue}let w=Eo(u,t,{filePath:r,dirs:n,cwd:i});if(w.isErr()){s.push(w.unwrapErr());continue}let R=w.unwrap();R?(l.add(R.dependency),a[u]=R.template):c.add(u);}if(s.length>0)return P(s);let{devDependencies:p,dependencies:h}=So(Array.from(c),r,{doNotInstall:o||[]});return I({dependencies:h,devDependencies:p,local:Array.from(l),imports:a})},Ir=(e,t,{filePath:r,alias:o,dirs:n,cwd:i})=>{if(t&&(e.startsWith("./")||e==="."))return I(void 0);let s=t?K.join(r,"../../"):K.join(r,"../"),c=K.join(K.join(r,"../"),e),l=K.join(s,"../");if(c.startsWith(l))return I(Cr(c.slice(l.length)));if(o){for(let a of n){let p=K.resolve(K.join(i,a)),h=K.resolve(c);if(h.startsWith(p))return I(Cr(h.slice(p.length+1)))}return P(`${r}:
|
|
14
|
+
${o} references code not contained in ${x.bold(n.join(", "))} and cannot be resolved.`)}return P(`${r}:
|
|
15
|
+
${e} references code not contained in ${s} and cannot be resolved.`)},Cr=e=>{let[t,r,...o]=e.split("/");r===void 0&&(r="index");let n=r;n.includes(".")&&(n=n.slice(0,n.length-K.parse(n).ext.length));let i=`${t}/${n}`,s=`{{${i}}}`;return o.length===0?n.length!==r.length&&(s+=K.parse(r).ext):s+=`/${o.join("/")}`,{dependency:i,template:s}},Eo=(e,t,{filePath:r,dirs:o,cwd:n})=>{let i=getTsconfig(r,"tsconfig.json");if(!i&&(i=getTsconfig(r,"jsconfig.json"),!i))return I(void 0);let s=createPathsMatcher(i);if(s){let c=s(e);for(let l of c){let a=Io(l);if(!a)continue;let p=K.relative(K.resolve(K.join(r,"../")),a.path),h=Ir(p,t,{filePath:r,alias:e,dirs:o,cwd:n,modIsFile:a.type==="file"});if(h.isErr())return P(h.unwrapErr());if(h.unwrap())return I(h.unwrap());break}}return I(void 0)},Io=e=>{if(Te.existsSync(e))return {path:e,type:Te.statSync(e).isDirectory()?"directory":"file"};if(K.parse(e).ext===".js"){let n=`${e.slice(0,e.length-3)}.ts`;if(Te.existsSync(n))return {path:e,type:"file"}}let r=K.join(e,"../");if(!Te.existsSync(r))return;let o=Te.readdirSync(r);for(let n of o)if(K.parse(n).name===K.basename(e)){let s=K.join(r,n),c=s;return c.endsWith(".ts")&&(c=c.slice(0,c.length-3)),{path:c,type:Te.statSync(s).isDirectory()?"directory":"file"}}},So=(e,t,{doNotInstall:r}={doNotInstall:[]})=>{let o=new Set(r),n=e.filter(l=>!builtinModules.includes(l)&&!l.startsWith("node:")),i=Jt(K.dirname(t),""),s=new Set,c=new Set;if(i){let{devDependencies:l,dependencies:a}=JSON.parse(Te.readFileSync(i,"utf-8"));for(let p of n){let h=kr(p);if(h.isErr()){console.warn(`${N} ${ye} Skipped adding import \`${x.cyan(p)}\`. Reason: Couldn't parse package name`);continue}let u=h.unwrap();if(!bo(u.name).validForNewPackages){console.warn(`${N} ${ye} Skipped adding import \`${x.cyan(p)}\`. Reason: Not a valid package name`);continue}if(o.has(u.name))continue;let w;if(a!==void 0&&(w=a[u.name]),w!==void 0){s.add(`${u.name}@${w}`);continue}if(l!==void 0&&(w=l[u.name]),w!==void 0){c.add(`${u.name}@${w}`);continue}s.add(u.name);}}return {dependencies:Array.from(s),devDependencies:Array.from(c)}},Ge=[ko,Ro,Co,jo,zt,xo];var Po=j.object({name:j.string(),category:j.string(),localDependencies:j.array(j.string()),dependencies:j.array(j.string()),devDependencies:j.array(j.string()),tests:j.boolean(),list:j.optional(j.boolean(),!0),directory:j.string(),subdirectory:j.boolean(),files:j.array(j.string()),_imports_:j.record(j.string(),j.string())}),It=j.object({name:j.string(),blocks:j.array(Po)}),Sr=[".test.ts","_test.ts",".test.js","_test.js"],$e=e=>Sr.find(t=>e.endsWith(t))!==void 0,Pr=(e,{cwd:t,config:{excludeDeps:r,includeBlocks:o,includeCategories:n,dirs:i,doNotListBlocks:s,doNotListCategories:c}})=>{let l;try{l=Te.readdirSync(e);}catch{program.error(x.red(`Couldn't read the ${x.bold(e)} directory.`));}let a=[];for(let p of l){let h=K.join(e,p);if(Te.statSync(h).isFile())continue;let u=K.basename(p),w=c.findIndex(f=>f===u)===-1;if(n.length>0&&n.find(f=>f.trim()===u.trim())===void 0)continue;let R={name:u,blocks:[]},L=Te.readdirSync(h);for(let f of L){let $=K.join(h,f);if(Te.statSync($).isFile()){if($e(f))continue;let F=K.parse(K.basename(f)).name,D=s.findIndex(v=>v===F)===-1;if(o.length>0&&o.find(v=>v.trim()===F.trim())===void 0)continue;let B=Ge.find(v=>v.matches(f));if(!B){console.warn(`${N} ${ye} Skipped \`${x.bold($)}\` \`*${x.bold(K.parse(f).ext)}\` files are not currently supported!`);continue}let d=L.find(v=>Sr.find(m=>v===`${F}${m}`)),{dependencies:y,devDependencies:E,local:b,imports:W}=B.resolveDependencies({filePath:$,isSubDir:!1,excludeDeps:r,cwd:t,dirs:i}).match(v=>v,v=>{program.error(x.red(v));}),g={name:F,directory:K.relative(t,h),category:u,tests:d!==void 0,subdirectory:!1,list:w?D:!1,files:[f],localDependencies:b,_imports_:W,dependencies:y,devDependencies:E};d!==void 0&&g.files.push(d),R.blocks.push(g);}else {let F=f,D=s.findIndex(v=>v===F)===-1;if(o.length>0&&o.find(v=>v.trim()===F.trim())===void 0)continue;let B=Te.readdirSync($),d=B.findIndex(v=>$e(v))!==-1,y=new Set,E=new Set,b=new Set,W={};for(let v of B){if($e(v))continue;if(Te.statSync(K.join($,v)).isDirectory()){console.warn(`${N} ${ye} Skipped \`${x.bold(K.join($,v))}\` subdirectories are not currently supported!`);continue}let m=Ge.find(A=>A.matches(v));if(!m){console.warn(`${N} ${ye} Skipped \`${K.join($,v)}\` \`*${x.bold(K.parse(v).ext)}\` files are not currently supported!`);continue}let{local:k,dependencies:C,devDependencies:O,imports:T}=m.resolveDependencies({filePath:K.join($,v),isSubDir:!0,excludeDeps:r,cwd:t,dirs:i}).match(A=>A,A=>{program.error(x.red(A));});for(let A of k)A!==`${u}/${F}`&&y.add(A);for(let A of C)E.add(A);for(let A of O)b.add(A);for(let[A,ge]of Object.entries(T))W[A]=ge;}let g={name:F,directory:K.relative(t,$),category:u,tests:d,subdirectory:!0,list:w?D:!1,files:[...B],localDependencies:Array.from(y.keys()),dependencies:Array.from(E.keys()),devDependencies:Array.from(b.keys()),_imports_:W};R.blocks.push(g);}}a.push(R);}return a},Tr=e=>{let t=[];for(let o of e){let n=[];for(let i of o.blocks){let s=`${i.category}/${i.name}`;!i.list&&!gr(s,e)||n.push(i);}n.length>0&&t.push({name:o.name,blocks:n});}return [t,0]};var be="jsrepo-manifest.json";var le=()=>new To({projectName:"jsrepo"});var ot=(e,t,r)=>P(`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
|
-
`),
|
|
21
|
+
`),ne={name:()=>"github",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await ne.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 ne.info(e),n=await ne.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=le().get(`${ne.name()}-token`),s=new Headers;i!==void 0&&s.append("Authorization",`token ${i}`);let c=await gt(n,{headers:s});return r?.(`Got a response from ${n} ${c.status} ${c.statusText}`),c.ok?I(await c.text()):ot(o,t,ne.defaultBranch())}catch(i){return r?.(`erroring in response ${i} `),ot(o,t,ne.defaultBranch())}},fetchManifest:async e=>{let t=await ne.fetchRaw(e,be);if(t.isErr())return P(t.unwrapErr());let r=j.safeParse(j.array(It),JSON.parse(t.unwrap()));return r.success?I(r.output):P(`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=ne.defaultBranch(),s=le().get(`${ne.name()}-token`),c=new Octokit({auth:s});if(n[0]==="tree")i=n[1];else try{let{data:a}=await c.rest.repos.get({owner:r,repo:o});i=a.default_branch;}catch{}let l="heads";if(i!==ne.defaultBranch())try{let{data:a}=await c.rest.git.listMatchingRefs({owner:r,repo:o,ref:"tags"});a.some(p=>p.ref===`refs/tags/${i}`)&&(l="tags");}catch{l="heads";}return {refs:l,url:e,name:ne.name(),repoName:o,owner:r,ref:i,provider:ne}},matches:e=>e.toLowerCase().startsWith("https://github.com")||e.toLowerCase().startsWith("github")},ke={name:()=>"gitlab",defaultBranch:()=>"main",resolveRaw:async(e,t)=>{let r=await ke.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 ne.info(e),n=await ke.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=le().get(`${ke.name()}-token`),s=new Headers;i!==void 0&&s.append("PRIVATE-TOKEN",`${i}`);let c=await gt(n,{headers:s});return r?.(`Got a response from ${n} ${c.status} ${c.statusText}`),c.ok?I(await c.text()):ot(o,t,ke.defaultBranch())}catch{return ot(o,t,ke.defaultBranch())}},fetchManifest:async e=>{let t=await ke.fetchRaw(e,be);if(t.isErr())return P(t.unwrapErr());let r=j.safeParse(j.array(It),JSON.parse(t.unwrap()));return r.success?I(r.output):P(`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=ke.defaultBranch(),s="heads";if(n[0]==="-"&&n[1]==="tree")if(n[2].includes("?")){let[c,l]=n[2].split("?");i=c,l.startsWith("ref_type=")&&l.slice(10)==="tags"&&(s="tags");}else i=n[2];else try{let c=le().get(`${ke.name()}-token`),l=new Headers;c!==void 0&&l.append("Authorization",`Bearer ${c}`);let a=await gt(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${r}/${o}`)}`,{headers:l});a.ok&&(i=(await a.json()).default_branch);}catch{}return {refs:s,url:e,name:ke.name(),repoName:o,owner:r,ref:i,provider:ke}},matches:e=>e.toLowerCase().startsWith("https://gitlab.com")||e.toLowerCase().startsWith("gitlab")},fe={name:()=>"bitbucket",defaultBranch:()=>"master",resolveRaw:async(e,t)=>{let r=await fe.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 fe.info(e),n=await fe.resolveRaw(o,t);r?.(`Trying to fetch from ${n}`);try{let i=le().get(`${fe.name()}-token`),s=new Headers;i!==void 0&&s.append("Authorization",`Bearer ${i}`);let c=await gt(n,{headers:s});return r?.(`Got a response from ${n} ${c.status} ${c.statusText}`),c.ok?I(await c.text()):ot(o,t,fe.defaultBranch())}catch{return ot(o,t,fe.defaultBranch())}},fetchManifest:async e=>{let t=await fe.fetchRaw(e,be);if(t.isErr())return P(t.unwrapErr());let r=j.safeParse(j.array(It),JSON.parse(t.unwrap()));return r.success?I(r.output):P(`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",s=fe.defaultBranch();if(n[0]==="src")s=n[1];else try{let c=le().get(`${fe.name()}-token`),l=new Headers;c!==void 0&&l.append("Authorization",`Bearer ${c}`);let a=await gt(`https://api.bitbucket.org/2.0/repositories/${r}/${o}`,{headers:l});a.ok&&(s=(await a.json()).mainbranch.name);}catch{}return {refs:i,url:e,name:fe.name(),repoName:o,owner:r,ref:s,provider:fe}},matches:e=>e.toLowerCase().startsWith("https://bitbucket.org")||e.toLowerCase().startsWith("bitbucket")},q=[ne,ke,fe],qe=async e=>{let t=q.find(r=>r.matches(e));return t?I(await t.info(e)):P(`Only ${q.map((r,o)=>`${o===q.length-1?"and":""}${x.cyan(r.name())}`).join(", ")} repositories are supported at this time!`)},nt=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 P({message:n.unwrapErr(),repo:r});let i=n.unwrap();for(let s of i)for(let c of s.blocks)t.set(`${o.name}/${o.owner}/${o.repoName}/${s.name}/${c.name}`,{...c,sourceRepo:o});}return I(t)},st=async(...e)=>{let t=[];for(let r of e){let o=await qe(r);if(o.isErr())return P({message:o.unwrapErr(),repo:r});let n=o.unwrap();t.push({path:r,info:n});}return I(t)};var yt=async(e,t,r,o=new Map)=>{let n=new Map;for(let i of e){let s;if(q.find(l=>i.startsWith(l.name()))){let[l,a,p,...h]=i.split("/");s=t.get(`${l}/${a}/${p}/${h.slice(h.length-2).join("/")}`);}else {if(r.length===0)return P(x.red(`If your config doesn't repos then you must provide the repo in the block specifier ex: \`${x.bold(`github/<owner>/<name>/${i}`)}\`!`));for(let{info:l}of r){let a=t.get(`${l.name}/${l.owner}/${l.repoName}/${i}`);if(a!==void 0){s=a;break}}}if(!s)return P(`Invalid block! ${x.bold(i)} does not exist!`);let c=`${s.category}/${s.name}`;if(n.set(c,{name:s.name,subDependency:!1,block:s}),s.localDependencies&&s.localDependencies.length>0){let l=await yt(s.localDependencies.filter(a=>!n.has(a)&&!o.has(a)),t,r,n);if(l.isErr())return P(l.unwrapErr());for(let a of l.unwrap())n.set(`${a.block.category}/${a.block.name}`,a);}}return I(pr(n,(i,s)=>s))},_e=(e,t,r)=>{let o=[],n=Ie(t.paths,r);n.isErr()&&program.error(x.red(n.unwrapErr()));let i=n.unwrap();for(let[s,c]of e){let l;i[c.category]!==void 0?l=K.join(r,i[c.category]):l=K.join(r,i["*"],c.category);let a=K.join(l,c.files[0]);c.subdirectory&&(a=K.join(l,c.name)),Te.existsSync(a)&&o.push({specifier:`${c.category}/${c.name}`,path:a,block:c});}return o};var We=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 P(x.red(`Could not resolve add command for '${e}'.`));try{return await execa(n.command,[...n.args],{cwd:o}),I(t)}catch{return P(x.red(`Failed to install ${x.bold(t.join(", "))}! Failed while running '${x.bold(`${n.command} ${n.args.join(" ")}`)}'`))}},Lo=/\{\{([^\/]+)\/([^\}]+)\}\}/g,Nr=({template:e,config:t,destPath:r,cwd:o})=>{let n=K.join(r,"../");return e.replace(Lo,(i,s,c)=>{if(t.paths[s]===void 0){if(t.paths["*"].startsWith(".")){let l=K.relative(n,K.join(o,t.paths["*"],s,c));return l.startsWith(".")?l:`./${l}`}return K.join(t.paths["*"],s,c)}if(t.paths[s].startsWith(".")){let l=K.relative(n,K.join(o,t.paths[s],c));return l.startsWith(".")?l:`./${l}`}return K.join(t.paths[s],c)})};var Nt=async({file:e,config:t,imports:r,watermark:o,prettierOptions:n,biomeOptions:i,cwd:s,verbose:c})=>{let l=Ge.find(p=>p.matches(e.destPath)),a=e.content;if(l){t.watermark&&(a=`${l.comment(o)}
|
|
22
22
|
|
|
23
|
-
${a}`),c?.(`Formatting ${x.bold(e.destPath)}`);try{a=await l.format(a,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:
|
|
23
|
+
${a}`),c?.(`Formatting ${x.bold(e.destPath)}`);try{a=await l.format(a,{filePath:e.destPath,formatter:t.formatter,prettierOptions:n,biomeOptions:i});}catch(p){return P(`Error formatting ${x.bold(e.destPath)} ${p}`)}}for(let[p,h]of Object.entries(r)){let u=Nr({template:h,config:t,destPath:e.destPath,cwd:s}),w=new RegExp(`(['"])${Bo(p)}\\1`,"g");a=a.replaceAll(w,`$1${u}$1`);}return I(a)};var it=async({formatter:e,cwd:t})=>{let r=null;e==="prettier"&&(r=await tt.resolveConfig(K.join(t,".prettierrc")));let o=null;if(e==="biome"){let n=K.join(t,"biome.json");Te.existsSync(n)&&(o=JSON.parse(Te.readFileSync(n).toString()));}return {biomeOptions:o,prettierOptions:r}};var at=(e,t)=>`jsrepo ${e}
|
|
24
24
|
Installed from ${t}
|
|
25
|
-
${new Date().toLocaleDateString().replaceAll("/","-")}`;var
|
|
26
|
-
`;return o+=`${
|
|
25
|
+
${new Date().toLocaleDateString().replaceAll("/","-")}`;var vt=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);}},Wr=async({tasks:e,startMessage:t,stopMessage:r,verbose:o})=>{let n=spinner(),i=s=>{o?o(s):n.message(s);};o?o(t):n.start(t),await Promise.all([...e.map(s=>s.run({message:i}))]),o?o(r):n.stop(r);},ct=e=>{let t=20;e.map(n=>{let i=vr(ze(n),4);i.length>t&&(t=i.length);});let r="Next Steps",o=`${N}
|
|
26
|
+
`;return o+=`${Ft} ${r} ${Bt.repeat(t-r.length-1)}${lr}
|
|
27
27
|
`,o+=`${N} ${" ".repeat(t)} ${N}
|
|
28
|
-
`,e.map(n=>{o+=`${N} ${
|
|
28
|
+
`,e.map(n=>{o+=`${N} ${wr(n,t-1)} ${N}
|
|
29
29
|
`;}),o+=`${N} ${" ".repeat(t)} ${N}
|
|
30
|
-
`,o+=`${
|
|
31
|
-
`,o},
|
|
30
|
+
`,o+=`${Ft}${Bt.repeat(t+2)}${dr}
|
|
31
|
+
`,o},Vr=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},se=e=>intro(`${x.bgHex("#f7df1e").black(" jsrepo ")}${x.gray(` v${e} `)}`);var Ho=j.object({repo:j.optional(j.string()),allow:j.boolean(),yes:j.boolean(),verbose:j.boolean(),cwd:j.string()}),Kt=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=j.parse(Ho,t);se(Y.package.version),await qo(e,r),outro(x.green("All done!"));}),qo=async(e,t)=>{let r=g=>{t.verbose&&console.info(`${et} ${g}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=Ee(t.cwd),i=n.isErr(),s;if(n.isErr()){let g=await confirm({message:`You don't have ${xe} initialized in your project. Do you want to continue?`,initialValue:!1});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0)),s={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else s=n.unwrap();let c=s.repos;t.repo&&(c=[t.repo]);for(let g of e){if(!q.find(T=>g.startsWith(T.name())))continue;let[v,m,k,...C]=g.split("/"),O;if(C.length>2?O=`${v}/${m}/${k}/${C.slice(0,C.length-2).join("/")}`:O=`${v}/${m}/${k}`,!c.find(T=>T===O)){if(!t.allow){let T=await confirm({message:`Allow ${xe} to download and run code from ${x.cyan(O)}?`,initialValue:!0});(isCancel(T)||!T)&&(cancel("Canceled!"),process.exit(0));}c.push(O);}}if(!t.allow&&t.repo){let g=await confirm({message:`Allow ${xe} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(g)||!g)&&(cancel("Canceled!"),process.exit(0));}c.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(c.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${x.cyan(c.join(", "))}`);let l=(await st(...c)).match(g=>g,({repo:g,message:v})=>{o.stop(`Failed to get info for ${x.cyan(g)}`),program.error(x.red(v));});r(`Resolved ${x.cyan(c.join(", "))}`),r(`Fetching blocks from ${x.cyan(c.join(", "))}`);let a=(await nt(...l)).match(g=>g,({repo:g,message:v})=>{o.stop(`Failed fetching blocks from ${x.cyan(g)}`),program.error(x.red(v));});t.verbose||o.stop(`Retrieved blocks from ${x.cyan(c.join(", "))}`),r(`Retrieved blocks from ${x.cyan(c.join(", "))}`);let p=_e(a,s,t.cwd).map(g=>g.specifier),h=e;if(h.length===0){let g=await multiselect({message:"Select which blocks to add.",options:Array.from(a.entries()).filter(([v,m])=>m.list).map(([v,m])=>{let k=`${m.category}/${m.name}`,C=p.findIndex(T=>T===k)!==-1,O;return c.length>1?O=`${x.cyan(`${m.sourceRepo.name}/${m.sourceRepo.owner}/${m.sourceRepo.repoName}/${m.category}`)}/${m.name}`:O=`${x.cyan(m.category)}/${m.name}`,{label:C?x.gray(O):O,value:v,hint:C?"Installed":void 0}}),required:!0});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),h=g;}r(`Installing blocks ${x.cyan(h.join(", "))}`),t.verbose&&console.log("Blocks map: ",a);let u=(await yt(h,a,l)).match(g=>g,g=>program.error(g)),w=(await detect({cwd:t.cwd}))?.agent??"npm",R=[],L=new Set,f=new Set,$=le();if(i){let g=`${t.cwd}-zero-config`,v=j.safeParse(Vt,$.get(g)),m=v.success?v.output:s,k=u.map(T=>T.block.category);for(let T of k){let A=await text({message:`Where would you like to add ${x.cyan(T)}?`,placeholder:m?m.paths[T]:`./src/${T}`,initialValue:m?m.paths[T]:`./src/${T}`,defaultValue:m?m.paths[T]:`./src/${T}`,validate(ge){if(ge.trim()==="")return "Please provide a value"}});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),s.paths[T]=A;}if(!t.yes){let T=await confirm({message:"Include tests?",initialValue:m.includeTests});isCancel(T)&&(cancel("Canceled!"),process.exit(0)),s.includeTests=T;let A=await confirm({message:"Add watermark?",initialValue:m.watermark});isCancel(A)&&(cancel("Canceled!"),process.exit(0)),s.watermark=A;}let C="none";Te.existsSync(K.join(t.cwd,".prettierrc"))&&(C="prettier"),Te.existsSync(K.join(t.cwd,"biome.json"))&&(C="biome");let O=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(T=>({value:T.toLowerCase(),label:T})),initialValue:C==="none"?m.formatter?m.formatter:"none":C});isCancel(O)&&(cancel("Canceled!"),process.exit(0)),O!=="none"&&(s.formatter=O),$.set(g,s);}let{prettierOptions:F,biomeOptions:D}=await it({formatter:s.formatter,cwd:t.cwd}),B=Ie(s.paths,t.cwd);B.isErr()&&program.error(x.red(B.unwrapErr()));let d=B.unwrap(),y=[],E;for(let{block:g}of u){let v=`${g.sourceRepo.url}/${g.category}/${g.name}`,m=`${g.category}/${g.name}`,k=at(Y.package.version,g.sourceRepo.url),C=g.sourceRepo;r(`Setting up ${v}`);let O;if(d[g.category]!==void 0?O=K.join(t.cwd,d[g.category]):O=K.join(t.cwd,d["*"],g.category),p.find(A=>m===A)&&!t.yes&&!E){if(E===void 0){let A=u.map(De=>`${De.block.category}/${De.block.name}`).filter(De=>p.find(G=>G===De));log.warn(`The following components ${x.bold.yellow("already exist")}: ${x.cyan(Vr(A))}`);let ge=await confirm({message:`Would you like to ${x.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ge)&&(cancel("Canceled!"),process.exit(0)),E=ge;}if(!E){let A=await confirm({message:`${x.cyan(m)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(A)&&(cancel("Canceled!"),process.exit(0)),!A)continue}}y.push(m),R.push({run:async({message:A})=>{A(`Adding ${x.cyan(v)}`),r(`Creating directory ${x.bold(O)}`),Te.mkdirSync(O,{recursive:!0}),r(`Created directory ${x.bold(O)}`);let ge=[],De=async G=>{let X=await C.provider.fetchRaw(C,G,{verbose:r});return X.isErr()&&(o.stop(x.red(`Error fetching ${x.bold(G)}`)),program.error(x.red(`There was an error trying to get ${v}`))),X.unwrap()};for(let G of g.files){if(!s.includeTests&&$e(G))continue;let X=K.join(g.directory,G),Pe;g.subdirectory?Pe=K.join(O,g.name,G):Pe=K.join(O,G),r(`Adding ${x.bold(X)}`);let mt=await De(X),Qe=Pe.slice(0,Pe.length-G.length);r(`Creating directory ${x.bold(Qe)}`),Te.mkdirSync(Qe,{recursive:!0}),r(`Created directory ${x.bold(Qe)}`),ge.push({content:mt,destPath:Pe}),r(`Got ${x.bold(X)}`);}for(let G of ge){let X=await Nt({file:G,biomeOptions:D,prettierOptions:F,config:s,imports:g._imports_,watermark:k,verbose:r,cwd:t.cwd});X.isErr()&&program.error(x.red(X.unwrapErr())),r(`Writing to ${x.bold(G.destPath)}`),Te.writeFileSync(G.destPath,X.unwrap());}if(s.includeTests&&g.tests){r("Trying to include tests");let{devDependencies:G}=JSON.parse(Te.readFileSync(K.join(t.cwd,"package.json")).toString());(G===void 0||G.vitest===void 0)&&L.add("vitest");}for(let G of g.devDependencies)L.add(G);for(let G of g.dependencies)f.add(G);}});}await Wr({startMessage:"Adding blocks",stopMessage:`Added ${x.cyan(y.join(", "))}`,tasks:R,verbose:t.verbose?r:void 0});let b=xt(f,L,{cwd:t.cwd});if(f=b.dependencies,L=b.devDependencies,f.size>0||L.size>0){let g=t.yes;if(!t.yes){let k=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(k)&&(cancel("Canceled!"),process.exit(0)),g=k;}g&&(f.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(w)}`),(await We({pm:w,deps:Array.from(f),dev:!1,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${x.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dependencies"),program.error(k);})),L.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(w)}`),(await We({pm:w,deps:Array.from(L),dev:!0,cwd:t.cwd})).match(k=>{t.verbose||o.stop(`Installed ${x.cyan(k.join(", "))}`);},k=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(k);})));let v=[];if(!g){if(f.size>0){let k=resolveCommand(w,"install",[...f]);v.push(`Install dependencies \`${x.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}if(L.size>0){let k=resolveCommand(w,"install",[...L,"-D"]);v.push(`Install dev dependencies \`${x.cyan(`${k?.command} ${k?.args.join(" ")}`)}\``);}}v=v.map((k,C)=>`${C+1}. ${k}`),g||v.push(""),v.push("Import and use the blocks!");let m=ct(v);process.stdout.write(m);}};var tn=j.object({token:j.optional(j.string()),provider:j.optional(j.string()),logout:j.boolean(),cwd:j.string()}),Zt=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=j.parse(tn,e);se(Y.package.version),await rn(t),outro(x.green("All done!"));}),rn=async e=>{let t=le();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${N}
|
|
32
32
|
`),process.stdout.write(x.gray(`${N} 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(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var an=
|
|
34
|
-
`)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},
|
|
35
|
-
`,
|
|
36
|
-
`),
|
|
37
|
-
`;}
|
|
38
|
-
`),
|
|
39
|
-
`,
|
|
40
|
-
`,$.removed||(
|
|
41
|
-
`,$.removed||(
|
|
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(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var an=j.object({dirs:j.optional(j.array(j.string())),includeBlocks:j.optional(j.array(j.string())),includeCategories:j.optional(j.array(j.string())),excludeDeps:j.optional(j.array(j.string())),doNotListBlocks:j.optional(j.array(j.string())),doNotListCategories:j.optional(j.array(j.string())),preview:j.optional(j.boolean()),output:j.boolean(),verbose:j.boolean(),cwd:j.string()}),er=new Command("build").description(`Builds the provided --dirs in the project root into a \`${be}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--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("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${be}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=j.parse(an,e);se(Y.package.version),await cn(t),outro(x.green("All done!"));}),cn=async e=>{let t=spinner(),r=[],o=jt(e.cwd).match(a=>{if(a===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],preview:e.preview};let p=a;return e.dirs&&(p.dirs=e.dirs),e.doNotListBlocks&&(p.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(p.doNotListCategories=e.doNotListCategories),e.includeBlocks&&(p.includeBlocks=e.includeBlocks),e.includeCategories&&(p.includeCategories=e.includeCategories),e.excludeDeps&&(p.excludeDeps=e.excludeDeps),e.preview!==void 0&&(p.preview=e.preview),p.rules={..._t,...p.rules},p},a=>program.error(x.red(a))),n=K.join(e.cwd,be);for(let a of o.dirs){let p=K.join(e.cwd,a);t.start(`Building ${x.cyan(p)}`),e.output&&Te.existsSync(n)&&Te.rmSync(n);let h=Pr(p,{cwd:e.cwd,config:o});for(let u of h){if(r.find(w=>w.name===u.name)!==void 0){console.warn(`${N} ${ye} Skipped adding \`${x.cyan(`${a}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${x.cyan(p)}`);}t.start("Checking manifest");let{warnings:i,errors:s}=ur(r,o.rules);t.stop("Completed checking manifest."),(i.length>0||s.length>0)&&console.log(N);for(let a of i)console.log(a);if(s.length>0){for(let a of s)console.log(a);program.error(x.red(`Completed checking manifest with ${x.bold(`${s.length} error(s)`)} and ${x.bold(`${i.length} warning(s)`)}`));}let[c,l]=Tr(r);if(r=c,l>0&&log.step(`Removed ${l} unused block${l>1?"s":""}.`),o.preview){let a=r.flatMap(p=>p.blocks.filter(h=>h.list).map(h=>`${x.cyan(h.category)}/${h.name}`));log.message(`${x.yellow("Preview")}:`);for(let p of a)console.log(`${N} \u25FB ${p}`);}e.output&&(t.start(`Writing output to \`${x.cyan(n)}\``),Te.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${x.cyan(n)}\``));};var Hr=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var qr=e=>/^\s+$/g.test(e),dt=e=>{let t=e.length-1;for(;qr(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},At=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:i=x.red,colorAdded:s=x.green,colorCharsRemoved:c=x.bgRed,colorCharsAdded:l=x.bgGreen,prefix:a,onUnchanged:p,intro:h})=>{let u="",w=Hr(r,f=>f.count??0).toString().length+1,R=0;if(r.length===1&&!r[0].added&&!r[0].removed)return p({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:a,onUnchanged:p,intro:h});u+=h({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:s,colorRemoved:i,prefix:a,onUnchanged:p,intro:h});let L=f=>x.gray(`${a?.()??""}${ut(`${f+1+R} `,w)} `);for(let f=0;f<r.length;f++){let $=r[f],F=r[f-1]?.added||r[f-1]?.removed,D=r[f+1]?.added||r[f+1]?.removed;if(!$.added&&!$.removed){if(!o&&$.count!==void 0&&$.count>n){let y=R,E=ae(dt($.value)),b=0;if(D&&(b+=n),F&&(b+=n),b>=E.length){u+=`${re(E,{prefix:L})}
|
|
35
|
+
`,R+=E.length;continue}if(F&&(u+=`${re(E.slice(0,n),{prefix:L})}
|
|
36
|
+
`),E.length>b){let W=E.length-b;u+=`${re(ae(x.gray(`+ ${W} more unchanged (${x.italic("-E to expand")})`)),{prefix:()=>`${a?.()??""}${ut(" ",w)} `})}
|
|
37
|
+
`;}D&&(R=R+E.length-n,u+=`${re(E.slice(E.length-n),{prefix:L})}
|
|
38
|
+
`),R=y+$.count;continue}u+=`${re(ae(dt($.value)),{prefix:L})}
|
|
39
|
+
`,R+=$.count??0;continue}let B=y=>y.added?s(dt(y.value)):y.removed?i(dt(y.value)):y.value,d=y=>y.added?l(dt(y.value)):y.removed?c(dt(y.value)):y.value;if($.removed&&$.count===1&&r[f+1]?.added&&r[f+1]?.count===1){let E=diffChars($.value,r[f+1].value).map(b=>d(b)).join("");u+=`${L(0)}${E}`,R+=1,f++;}else qr($.value)?(u+=`${re(ae(d($)),{prefix:y=>`${L(y)}${d({removed:!0,value:" ",added:!1})}`})}
|
|
40
|
+
`,$.removed||(R+=$.count??0)):(u+=`${re(ae(B($)),{prefix:L})}
|
|
41
|
+
`,$.removed||(R+=$.count??0));}return u};var yn=j.object({expand:j.boolean(),maxUnchanged:j.number(),repo:j.optional(j.string()),allow:j.boolean(),cwd:j.string()}),tr=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=j.parse(yn,e);se(Y.package.version),await vn(t),outro(x.green("All done!"));}),vn=async e=>{let t=spinner(),r=Ee(e.cwd).match(a=>a,a=>program.error(x.red(a))),o=r.repos;if(e.repo&&(o=[e.repo]),!e.allow&&e.repo){let a=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(e.repo)}?`,initialValue:!0});(isCancel(a)||!a)&&(cancel("Canceled!"),process.exit(0));}t.start(`Fetching blocks from ${x.cyan(o.join(", "))}`);let n=(await st(...o)).match(a=>a,({repo:a,message:p})=>{t.stop(`Failed to get info for ${x.cyan(a)}`),program.error(x.red(p));}),i=(await nt(...n)).match(a=>a,({repo:a,message:p})=>{t.stop(`Failed fetching blocks from ${x.cyan(a)}`),program.error(x.red(p));});t.stop(`Retrieved blocks from ${x.cyan(o.join(", "))}`);let s=_e(i,r,e.cwd),c=Ie(r.paths,e.cwd);c.isErr()&&program.error(x.red(c.unwrapErr()));let l=c.unwrap();for(let a of s){let p=!1;for(let h of o){let u=(await qe(h)).unwrap(),w=`${u.name}/${u.owner}/${u.repoName}/${a.specifier}`,R=i.get(w);if(R===void 0)continue;let L=at(Y.package.version,h);p=!0,process.stdout.write(`${N}
|
|
42
42
|
`),process.stdout.write(`${N} ${w}
|
|
43
|
-
`);for(let f of
|
|
44
|
-
`);let $=K.join(
|
|
43
|
+
`);for(let f of R.files){if(!r.includeTests&&$e(f))continue;process.stdout.write(`${N}
|
|
44
|
+
`);let $=K.join(R.directory,f),F=await u.provider.fetchRaw(u,$);F.isErr()&&program.error(x.red(`There was an error trying to get ${w}`));let D=F.unwrap(),B,d;l[R.category]!==void 0?(d=l[R.category],B=K.join(e.cwd,l[R.category])):(d=K.join(l["*"],R.category),B=K.join(e.cwd,l["*"],R.category));let y=K.join(B,f),E=K.join(d,f);R.subdirectory&&(y=K.join(B,R.name,f),E=K.join(d,R.name,f));let b="";if(Te.existsSync(y)&&(b=Te.readFileSync(y).toString()),r.watermark){let m=Ge.find(k=>k.matches($));m&&(D=`${m.comment(L)}
|
|
45
45
|
|
|
46
|
-
${
|
|
47
|
-
`,intro:({from:m,to:
|
|
48
|
-
${
|
|
49
|
-
`}});process.stdout.write(v);}break}p||program.error(x.red(`Invalid block! ${x.bold(a)} does not exist!`));}};var jn=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(Ft),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),tr=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(jn,e);if(oe(Y.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 En(t):await xn(t),outro(x.green("All done!"));}),xn=async e=>{let t=be(),r=Ie(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let g=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(!q.find(D=>D.matches(O)))return `Invalid provider! Valid providers (${q.map(D=>D.name()).join(", ")})`}});isCancel(g)&&(cancel("Canceled!"),process.exit(0));let w=q.find(O=>O.matches(g));w||program.error(x.red("Invalid provider!"));let k=`${w.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(d){if(d.trim()==="")return "Please provide a value"}});isCancel(D)&&(cancel("Canceled!"),process.exit(0)),t.set(k,D);}}o.start(`Fetching categories from ${x.cyan(g)}`);let f=await w.fetchManifest(g);o.stop(`Fetched categories from ${x.cyan(g)}`),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(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],d=await text({message:`Where should ${O} be added in your project?`,validate(h){if(h.trim()==="")return "Please provide a value"},placeholder:D||`./src/${O}`,defaultValue:D,initialValue:D});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),n[O]=d;}e.repos.push(g);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Te.existsSync(K.join(e.cwd,".prettierrc"))&&(y="prettier"),Te.existsSync(K.join(e.cwd,"biome.json"))&&(y="biome");let g=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(w=>({value:w.toLowerCase(),label:w})),initialValue:y});isCancel(g)&&(cancel("Canceled!"),process.exit(0)),g!=="none"&&(e.formatter=g);}let i={$schema:`https://unpkg.com/jsrepo@${Y.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 \`${Ue}\``);let{prettierOptions:c,biomeOptions:l}=await it({formatter:i.formatter,cwd:e.cwd}),a=K.join(e.cwd,Ue),p=await Mt.format(JSON.stringify(i,null," "),{biomeOptions:l,prettierOptions:c,filePath:a,formatter:i.formatter});Te.writeFileSync(a,p),o.stop(`Wrote config to \`${Ue}\`.`);},En=async e=>{let t=spinner(),r=K.join(e.cwd,"package.json");Te.existsSync(r)||program.error(x.red(`Couldn't find your ${x.bold("package.json")}!`));let o=Ct(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@${Y.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 s=JSON.parse(Te.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.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 i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,c=e.yes||i;if(!e.yes&&!i){let f=await confirm({message:`Add ${Ee} as a dev dependency?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let l=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${x.cyan(De)}\` file?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),l=f;}let a=(await detect$1({cwd:"cwd"}))?.agent??"npm",p="";if(c)p+="jsrepo build";else {let f=resolveCommand$1(a,"execute",["jsrepo","build"]);f||program.error(x.red(`Error resolving execute command for ${a}`)),p+=`${f.command} ${f.args.join(" ")} `;}l||(p+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=p;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{Te.writeFileSync(r,JSON.stringify(s,null," "));}catch(f){program.error(x.red(`Error writing to \`${x.bold(r)}\`. Error: ${f}`));}}}),l&&y.push({loadingMessage:`Writing config to \`${x.cyan(De)}\``,completedMessage:`Wrote config to \`${x.cyan(De)}\``,run:async()=>{let f=K.join(e.cwd,De);try{Te.writeFileSync(K.join(f),JSON.stringify(o,null," "));}catch($){program.error(x.red(`Error writing to \`${x.bold(f)}\`. Error: ${$}`));}}}),await yt(y,{});let g=i;if(c&&!i){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 ${Ee}`),(await _e({pm:a,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${Ee}.`),L=>{t.stop(`Failed to install ${Ee}.`),program.error(L);}),g=!0);}let w=[];if(!g&&c){let f=resolveCommand$1(a,"install",["jsrepo","-D"]);w.push(`Install ${Ee} 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(a,"run",[e.script]);w.push(`Run \`${x.cyan(`${k?.command} ${k?.args.join(" ")}`)}\` to build the registry.`),w=w.map((f,$)=>`${$+1}. ${f}`);let A=at(w);process.stdout.write(A);};var _n=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),or=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(_n,t);oe(Y.package.version),await Wn(e,r),outro(x.green("All done!"));}),Wn=async(e,t)=>{let r=d=>{t.verbose&&console.info(`${Qe} ${d}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ie(t.cwd).match(d=>d,d=>program.error(x.red(d))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let d=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${x.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${x.cyan(i.join(", "))}`);for(let d of i){let h=(await qe(d)).match(u=>u,u=>program.error(x.red(u))),I=await h.provider.fetchManifest(h);r(`Got info for provider ${x.cyan(h.name)}`),I.isErr()&&(t.verbose||n.stop(`Error fetching ${x.cyan(d)}`),program.error(x.red(`There was an error fetching the \`${$e}\` from the repository ${x.cyan(d)} make sure the target repository has a \`${$e}\` in its root?`)));let b=I.unwrap();for(let u of b)for(let j of u.blocks)s.set(`${h.name}/${h.owner}/${h.repoName}/${u.name}/${j.name}`,{...j,sourceRepo:h});}r(`Retrieved blocks from ${x.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${x.cyan(i.join(", "))}`);let c=K.resolve(K.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${x.bold(c)}.`),Te.mkdirSync(c,{recursive:!0});let l=()=>{Te.rmSync(c,{recursive:!0,force:!0});},a=Fe(s,o,t.cwd).map(d=>d.specifier),p=e;e.length===0&&(p=a),p.length===0&&(l(),program.error(x.red("There were no blocks found in your project!")));let y=[];for(let d of p){let h;if(q.find(I=>d.startsWith(I.name()))){if(i.length===0){let[I,b,u,...j]=d.split("/"),v;j.length>2?v=`${I}/${b}/${u}/${j.slice(0,j.length-2).join("/")}`:v=`${I}/${b}/${u}`;let m=(await qe(v)).match(R=>R,R=>program.error(x.red(R))),S=(await m.provider.fetchManifest(m)).match(R=>R,R=>program.error(x.red(R)));for(let R of S)for(let V of R.blocks)s.set(`${m.name}/${m.owner}/${m.repoName}/${R.name}/${V.name}`,{...V,sourceRepo:m});}h=s.get(d);}else for(let I of i){let b=(await qe(I)).unwrap(),u=s.get(`${b.name}/${b.owner}/${b.repoName}/${d}`);if(u!==void 0){h=u;break}}h||program.error(x.red(`Invalid block! ${x.bold(d)} does not exist!`)),y.push({name:d,block:h});}let g=Se(o.paths,t.cwd);g.isErr()&&program.error(x.red(g.unwrapErr()));let w=g.unwrap();for(let{block:d}of y){let h=d.sourceRepo,I=`${d.sourceRepo.url}/${d.category}/${d.name}`;if(t.verbose||n.start(`Setting up test file for ${x.cyan(I)}`),!d.tests){n.stop(`No tests found for ${x.cyan(I)}`);continue}let b;w[d.category]!==void 0?b=K.join(t.cwd,w[d.category]):b=K.join(t.cwd,w["*"],d.category),b=K.relative(c,b);let u=async m=>{let S=await h.provider.fetchRaw(h,m);return S.isErr()&&(n.stop(x.red(`Error fetching ${x.bold(m)}`)),program.error(x.red(`There was an error trying to get ${I}`))),S.unwrap()};r(`Downloading and copying test files for ${I}`);let j=[];for(let m of d.files.filter(S=>we(S))){let S=await u(K.join(d.directory,m)),R=K.join(c,m);Te.writeFileSync(R,S),j.push(R);}let v=new Project;for(let m of j){r(`Opening test file ${m}`);let S=v.addSourceFileAtPath(m);for(let R of S.getImportDeclarations()){let V=R.getModuleSpecifierValue(),H;V.startsWith(".")&&(d.subdirectory?H=K.join(b,d.name,V):H=K.join(b,V)),H&&R.setModuleSpecifier(H.replaceAll(/\\/g,"/"));}}v.saveSync(),r(`Completed ${x.cyan.bold(I)} test file`),t.verbose||n.stop(`Completed setup for ${x.bold(I)}`);}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",c]);A==null&&program.error(x.red(`Could not resolve add command for '${k.agent}'.`));let{command:f,args:$}=A,L=`${f} ${$.join(" ")}`,O=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${L}`,D=d=>console.info(d.toString());O.stdout.on("data",D),O.stderr.on("data",D);try{await O,l();}catch(d){t.debug?console.info(`${x.bold("--debug")} flag provided. Skipping cleanup. Run '${x.bold(L)}' to retry tests.
|
|
50
|
-
`):l(),program.error(x.red(`Tests failed! Error ${d}`));}};var Hn=
|
|
51
|
-
`),process.stdout.write(`${N} ${
|
|
52
|
-
`);for(let m of
|
|
53
|
-
`);let
|
|
54
|
-
`,intro:({from:
|
|
55
|
-
${
|
|
56
|
-
`}});if(process.stdout.write(
|
|
46
|
+
${D}`);}let W=diffLines(b,D),g=K.join(`${u.name}/${u.owner}/${u.repoName}`,$),v=At({from:g,to:E,changes:W,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:x.greenBright,colorRemoved:x.redBright,colorCharsAdded:x.bgGreenBright,colorCharsRemoved:x.bgRedBright,prefix:()=>`${N} `,onUnchanged:({from:m,to:k,prefix:C})=>`${C?.()??""}${x.cyan(m)} \u2192 ${x.gray(k)} ${x.gray("(unchanged)")}
|
|
47
|
+
`,intro:({from:m,to:k,changes:C,prefix:O})=>{let T=C.filter(A=>A.added).length;return `${O?.()??""}${x.cyan(m)} \u2192 ${x.gray(k)} (${T} change${T===1?"":"s"})
|
|
48
|
+
${O?.()??""}
|
|
49
|
+
`}});process.stdout.write(v);}break}p||program.error(x.red(`Invalid block! ${x.bold(a)} does not exist!`));}};var jn=j.object({path:j.optional(j.string()),repos:j.optional(j.array(j.string())),watermark:j.boolean(),tests:j.optional(j.boolean()),formatter:j.optional(Wt),project:j.optional(j.boolean()),registry:j.optional(j.boolean()),script:j.string(),yes:j.boolean(),cwd:j.string()}),or=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=j.parse(jn,e);if(se(Y.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 En(t):await xn(t),outro(x.green("All done!"));}),xn=async e=>{let t=le(),r=Ee(e.cwd),o=spinner(),n,i=await text({message:"Please enter a default path to install the blocks",validate(h){if(h.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(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 h=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(h)&&(cancel("Canceled!"),process.exit(0)),!h)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:D=>{if(D.trim().length===0)return "Please provide a value";if(!q.find(B=>B.matches(D)))return `Invalid provider! Valid providers (${q.map(B=>B.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let w=q.find(D=>D.matches(u));w||program.error(x.red("Invalid provider!"));let R=`${w.name()}-token`;if(!t.get(R)){let D=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(D)&&(cancel("Canceled!"),process.exit(0)),D){let B=await password({message:"Paste your token",validate(d){if(d.trim()==="")return "Please provide a value"}});isCancel(B)&&(cancel("Canceled!"),process.exit(0)),t.set(R,B);}}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(),F=await multiselect({message:"Which category paths would you like to configure?",options:$.map(D=>({label:D.name,value:D.name})),required:!1});if(isCancel(F)&&(cancel("Canceled!"),process.exit(0)),F.length>0)for(let D of F){let B=n[D],d=await text({message:`Where should ${D} be added in your project?`,validate(y){if(y.trim()==="")return "Please provide a value"},placeholder:B||`./src/${D}`,defaultValue:B,initialValue:B});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),n[D]=d;}e.repos.push(u);}if(!e.formatter){let h=r.isErr()?"none":r.unwrap().formatter??"none";Te.existsSync(K.join(e.cwd,".prettierrc"))&&(h="prettier"),Te.existsSync(K.join(e.cwd,"biome.json"))&&(h="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:h});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let s={$schema:`https://unpkg.com/jsrepo@${Y.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 \`${Ue}\``);let{prettierOptions:c,biomeOptions:l}=await it({formatter:s.formatter,cwd:e.cwd}),a=K.join(e.cwd,Ue),p=await zt.format(JSON.stringify(s,null," "),{biomeOptions:l,prettierOptions:c,filePath:a,formatter:s.formatter});Te.writeFileSync(a,p),o.stop(`Wrote config to \`${Ue}\`.`);},En=async e=>{let t=spinner(),r=K.join(e.cwd,"package.json");Te.existsSync(r)||program.error(x.red(`Couldn't find your ${x.bold("package.json")}!`));let o=jt(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@${Y.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(Te.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:F=>{if(F.trim().length===0)return "Please provide a value!"}});isCancel($)&&(cancel("Canceled!"),process.exit(0)),e.script=$;}}let s=i.devDependencies&&i.devDependencies.jsrepo!==void 0,c=e.yes||s;if(!e.yes&&!s){let f=await confirm({message:`Add ${xe} as a dev dependency?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}let l=!n;if(!e.yes&&n){let f=await confirm({message:`Create a \`${x.cyan(Le)}\` file?`,initialValue:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),l=f;}let a=(await detect$1({cwd:"cwd"}))?.agent??"npm",p="";if(c)p+="jsrepo build";else {let f=resolveCommand$1(a,"execute",["jsrepo","build"]);f||program.error(x.red(`Error resolving execute command for ${a}`)),p+=`${f.command} ${f.args.join(" ")} `;}l||(p+=` --dirs ${o.dirs.join(" ")} `),i.scripts===void 0&&(i.scripts={}),i.scripts[e.script]=p;let h=[];h.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{Te.writeFileSync(r,JSON.stringify(i,null," "));}catch(f){program.error(x.red(`Error writing to \`${x.bold(r)}\`. Error: ${f}`));}}}),l&&h.push({loadingMessage:`Writing config to \`${x.cyan(Le)}\``,completedMessage:`Wrote config to \`${x.cyan(Le)}\``,run:async()=>{let f=K.join(e.cwd,Le);try{Te.writeFileSync(K.join(f),JSON.stringify(o,null," "));}catch($){program.error(x.red(`Error writing to \`${x.bold(f)}\`. Error: ${$}`));}}}),await vt(h,{});let u=s;if(c&&!s){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 ${xe}`),(await We({pm:a,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${xe}.`),F=>{t.stop(`Failed to install ${xe}.`),program.error(F);}),u=!0);}let w=[];if(!u&&c){let f=resolveCommand$1(a,"install",["jsrepo","-D"]);w.push(`Install ${xe} as a dev dependency \`${x.cyan(`${f?.command} ${f?.args.join(" ")}`)}\``);}w.push(`Add categories to \`${x.cyan(o.dirs.join(", "))}\`.`);let R=resolveCommand$1(a,"run",[e.script]);w.push(`Run \`${x.cyan(`${R?.command} ${R?.args.join(" ")}`)}\` to build the registry.`),w=w.map((f,$)=>`${$+1}. ${f}`);let L=ct(w);process.stdout.write(L);};var _n=j.object({repo:j.optional(j.string()),allow:j.boolean(),debug:j.boolean(),verbose:j.boolean(),cwd:j.string()}),sr=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=j.parse(_n,t);se(Y.package.version),await Wn(e,r),outro(x.green("All done!"));}),Wn=async(e,t)=>{let r=d=>{t.verbose&&console.info(`${et} ${d}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=Ee(t.cwd).match(d=>d,d=>program.error(x.red(d))),n=spinner(),i=new Map,s=o.repos;if(t.repo&&(s=[t.repo]),!t.allow&&t.repo){let d=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${x.cyan(s.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${x.cyan(s.join(", "))}`);for(let d of s){let y=(await qe(d)).match(W=>W,W=>program.error(x.red(W))),E=await y.provider.fetchManifest(y);r(`Got info for provider ${x.cyan(y.name)}`),E.isErr()&&(t.verbose||n.stop(`Error fetching ${x.cyan(d)}`),program.error(x.red(`There was an error fetching the \`${be}\` from the repository ${x.cyan(d)} make sure the target repository has a \`${be}\` in its root?`)));let b=E.unwrap();for(let W of b)for(let g of W.blocks)i.set(`${y.name}/${y.owner}/${y.repoName}/${W.name}/${g.name}`,{...g,sourceRepo:y});}r(`Retrieved blocks from ${x.cyan(s.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${x.cyan(s.join(", "))}`);let c=K.resolve(K.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${x.bold(c)}.`),Te.mkdirSync(c,{recursive:!0});let l=()=>{Te.rmSync(c,{recursive:!0,force:!0});},a=_e(i,o,t.cwd).map(d=>d.specifier),p=e;e.length===0&&(p=a),p.length===0&&(l(),program.error(x.red("There were no blocks found in your project!")));let h=[];for(let d of p){let y;if(q.find(E=>d.startsWith(E.name()))){if(s.length===0){let[E,b,W,...g]=d.split("/"),v;g.length>2?v=`${E}/${b}/${W}/${g.slice(0,g.length-2).join("/")}`:v=`${E}/${b}/${W}`;let m=(await qe(v)).match(C=>C,C=>program.error(x.red(C))),k=(await m.provider.fetchManifest(m)).match(C=>C,C=>program.error(x.red(C)));for(let C of k)for(let O of C.blocks)i.set(`${m.name}/${m.owner}/${m.repoName}/${C.name}/${O.name}`,{...O,sourceRepo:m});}y=i.get(d);}else for(let E of s){let b=(await qe(E)).unwrap(),W=i.get(`${b.name}/${b.owner}/${b.repoName}/${d}`);if(W!==void 0){y=W;break}}y||program.error(x.red(`Invalid block! ${x.bold(d)} does not exist!`)),h.push({name:d,block:y});}let u=Ie(o.paths,t.cwd);u.isErr()&&program.error(x.red(u.unwrapErr()));let w=u.unwrap();for(let{block:d}of h){let y=d.sourceRepo,E=`${d.sourceRepo.url}/${d.category}/${d.name}`;if(t.verbose||n.start(`Setting up test file for ${x.cyan(E)}`),!d.tests){n.stop(`No tests found for ${x.cyan(E)}`);continue}let b;w[d.category]!==void 0?b=K.join(t.cwd,w[d.category]):b=K.join(t.cwd,w["*"],d.category),b=K.relative(c,b);let W=async m=>{let k=await y.provider.fetchRaw(y,m);return k.isErr()&&(n.stop(x.red(`Error fetching ${x.bold(m)}`)),program.error(x.red(`There was an error trying to get ${E}`))),k.unwrap()};r(`Downloading and copying test files for ${E}`);let g=[];for(let m of d.files.filter(k=>$e(k))){let k=await W(K.join(d.directory,m)),C=K.join(c,m);Te.writeFileSync(C,k),g.push(C);}let v=new Project;for(let m of g){r(`Opening test file ${m}`);let k=v.addSourceFileAtPath(m);for(let C of k.getImportDeclarations()){let O=C.getModuleSpecifierValue(),T;O.startsWith(".")&&(d.subdirectory?T=K.join(b,d.name,O):T=K.join(b,O)),T&&C.setModuleSpecifier(T.replaceAll(/\\/g,"/"));}}v.saveSync(),r(`Completed ${x.cyan.bold(E)} test file`),t.verbose||n.stop(`Completed setup for ${x.bold(E)}`);}r("Beginning testing");let R=await detect({cwd:t.cwd});R==null&&program.error(x.red("Could not detect package manager"));let L=resolveCommand(R.agent,"execute",["vitest","run",c]);L==null&&program.error(x.red(`Could not resolve add command for '${R.agent}'.`));let{command:f,args:$}=L,F=`${f} ${$.join(" ")}`,D=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${F}`,B=d=>console.info(d.toString());D.stdout.on("data",B),D.stderr.on("data",B);try{await D,l();}catch(d){t.debug?console.info(`${x.bold("--debug")} flag provided. Skipping cleanup. Run '${x.bold(F)}' to retry tests.
|
|
50
|
+
`):l(),program.error(x.red(`Tests failed! Error ${d}`));}};var Hn=j.object({all:j.boolean(),expand:j.boolean(),maxUnchanged:j.number(),repo:j.optional(j.string()),allow:j.boolean(),yes:j.boolean(),verbose:j.boolean(),cwd:j.string()}),ar=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=j.parse(Hn,t);se(Y.package.version),await qn(e,r),outro(x.green("All done!"));}),qn=async(e,t)=>{let r=d=>{t.verbose&&console.info(`${et} ${d}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=Ee(t.cwd).match(d=>d,d=>program.error(x.red(d))),i=n.repos;t.repo&&(i=[t.repo]);for(let d of e)q.find(y=>d.startsWith(y.name()))&&program.error(x.red(`Invalid value provided for block names \`${x.bold(d)}\`. Block names are expected to be provided in the format of \`${x.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${x.cyan("jsrepo")} to download and run code from ${x.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${x.cyan(i.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${x.cyan(i.join(", "))}`);let s=(await st(...i)).match(d=>d,({repo:d,message:y})=>{o.stop(`Failed to get info for ${x.cyan(d)}`),program.error(x.red(y));});r(`Resolved ${x.cyan(i.join(", "))}`),r(`Fetching blocks from ${x.cyan(i.join(", "))}`);let c=(await nt(...s)).match(d=>d,({repo:d,message:y})=>{o.stop(`Failed fetching blocks from ${x.cyan(d)}`),program.error(x.red(y));});t.verbose||o.stop(`Retrieved blocks from ${x.cyan(i.join(", "))}`),r(`Retrieved blocks from ${x.cyan(i.join(", "))}`);let l=_e(c,n,t.cwd);l.length===0&&program.error(x.red(`You haven't installed any blocks yet. Did you mean to \`${x.bold("add")}\`?`));let a=e;if(t.all&&(a=l.map(d=>d.specifier)),a.length===0){let d=await multiselect({message:"Which blocks would you like to update?",options:l.map(y=>({label:`${x.cyan(y.block.category)}/${y.block.name}`,value:y.specifier})),required:!0});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),a=d;}r(`Preparing to update ${x.cyan(a.join(", "))}`);let p=(await yt(a,c,s)).match(d=>d,program.error),h=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],w=new Set,R=new Set,{prettierOptions:L,biomeOptions:f}=await it({formatter:n.formatter,cwd:t.cwd}),$=Ie(n.paths,t.cwd);$.isErr()&&program.error(x.red($.unwrapErr()));let F=$.unwrap();for(let{block:d}of p){let y=`${d.sourceRepo.url}/${d.category}/${d.name}`,E=at(Y.package.version,d.sourceRepo.url),b=d.sourceRepo;r(`Attempting to add ${y}`);let W;F[d.category]!==void 0?W=K.join(t.cwd,F[d.category]):W=K.join(t.cwd,F["*"],d.category);let g=[],v=async m=>{let k=await b.provider.fetchRaw(b,m,{verbose:r});return k.isErr()&&(o.stop(x.red(`Error fetching ${x.bold(m)}`)),program.error(x.red(`There was an error trying to get ${y}`))),k.unwrap()};for(let m of d.files){if(!n.includeTests&&$e(m))continue;let k=K.join(d.directory,m),C;d.subdirectory?C=K.join(W,d.name,m):C=K.join(W,m);let O=await v(k);Te.mkdirSync(C.slice(0,C.length-m.length),{recursive:!0}),g.push({content:O,destPath:C,fileName:m});}process.stdout.write(`${N}
|
|
51
|
+
`),process.stdout.write(`${N} ${y}
|
|
52
|
+
`);for(let m of g){let k=await Nt({file:m,biomeOptions:f,prettierOptions:L,config:n,imports:d._imports_,watermark:E,verbose:r,cwd:t.cwd});k.isErr()&&program.error(x.red(k.unwrapErr()));let C=k.unwrap(),O=t.yes;if(!t.yes){process.stdout.write(`${N}
|
|
53
|
+
`);let T="";Te.existsSync(m.destPath)&&(T=Te.readFileSync(m.destPath).toString());let A=diffLines(T,C),ge=K.join(`${b.name}/${b.owner}/${b.repoName}`,m.fileName),De=K.relative(t.cwd,m.destPath),G=At({from:ge,to:De,changes:A,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:x.greenBright,colorRemoved:x.redBright,colorCharsAdded:x.bgGreenBright,colorCharsRemoved:x.bgRedBright,prefix:()=>`${N} `,onUnchanged:({from:X,to:Pe,prefix:mt})=>`${mt?.()??""}${x.cyan(X)} \u2192 ${x.gray(Pe)} ${x.gray("(unchanged)")}
|
|
54
|
+
`,intro:({from:X,to:Pe,changes:mt,prefix:Qe})=>{let cr=mt.filter(no=>no.added).length;return `${Qe?.()??""}${x.cyan(X)} \u2192 ${x.gray(Pe)} (${cr} change${cr===1?"":"s"})
|
|
55
|
+
${Qe?.()??""}
|
|
56
|
+
`}});if(process.stdout.write(G),A.length>1||T===""){let X=await confirm({message:"Accept changes?",initialValue:!0});isCancel(X)&&(cancel("Canceled!"),process.exit(0)),O=X;}}O&&await vt([{loadingMessage:`Writing changes to ${x.cyan(m.destPath)}`,completedMessage:`Wrote changes to ${x.cyan(m.destPath)}.`,run:async()=>Te.writeFileSync(m.destPath,C)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&d.tests){r("Trying to include tests");let{devDependencies:m}=JSON.parse(Te.readFileSync(K.join(t.cwd,"package.json")).toString());(m===void 0||m.vitest===void 0)&&w.add("vitest");}for(let m of d.devDependencies)w.add(m);for(let m of d.dependencies)R.add(m);}await vt(u,{verbose:t.verbose?r:void 0});let D=xt(R,w,{cwd:t.cwd});if(R=D.dependencies,w=D.devDependencies,R.size>0||w.size>0){let d=t.yes;if(!t.yes){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),d=b;}d&&(R.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(h)}`),(await We({pm:h,deps:Array.from(R),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${x.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),w.size>0&&(t.verbose||o.start(`Installing dependencies with ${x.cyan(h)}`),(await We({pm:h,deps:Array.from(w),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${x.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let y=[];if(!d){if(R.size>0){let b=resolveCommand(h,"install",[...R]);y.push(`Install dependencies \`${x.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(w.size>0){let b=resolveCommand(h,"install",[...w,"-D"]);y.push(`Install dev dependencies \`${x.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}y=y.map((b,W)=>`${W+1}. ${b}`),d||y.push(""),y.push("Import and use the blocks!");let E=ct(y);process.stdout.write(E);}};var eo=e=>{let t=fileURLToPath(import.meta.url);return K.join(t,"../..",e)},{version:to,name:ro,description:oo,repository:Qn}=JSON.parse(Te.readFileSync(eo("package.json"),"utf-8")),Y={package:{name:ro,description:oo,version:to,repository:Qn},resolveRelativeToRoot:eo};console.clear();program.name(ro).description(oo).version(to).addCommand(Kt).addCommand(Zt).addCommand(or).addCommand(sr).addCommand(er).addCommand(ar).addCommand(tr);program.parse();export{Y as context};
|