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