jsrepo 1.23.2 → 1.23.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.
Files changed (2) hide show
  1. package/dist/index.js +4 -4
  2. package/package.json +5 -4
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var xt=async(e,{verbose:
37
37
  `,e.map(n=>{o+=`${W} ${Or(n,t-1)} ${W}
38
38
  `;}),o+=`${W} ${" ".repeat(t)} ${W}
39
39
  `,o+=`${Xt}${Yt.repeat(t+2)}${Cr}
40
- `,o},eo=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},ne=e=>intro(`${P.bgHex("#f7df1e").black(" jsrepo ")}${P.gray(` v${e} `)}`);var hn=C.object({repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),ir=new Command("add").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hn,t);ne(X.package.version),await yn(e,r),outro(P.green("All done!"));}),yn=async(e,t)=>{let r=h=>{t.verbose&&console.info(`${ft} ${h}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=we(t.cwd),s=n.isErr(),i;if(n.isErr()){let h=t.yes;if(!t.yes){let S=await confirm({message:`You don't have ${fe} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(S)&&(cancel("Canceled!"),process.exit(0)),h=S;}h||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let h of e){if(!q.find(j=>h.startsWith(j.name())))continue;let[S,d,w,...$]=h.split("/"),v;if($.length>2?v=`${S}/${d}/${w}/${$.slice(0,$.length-2).join("/")}`:v=`${S}/${d}/${w}`,!a.find(j=>j===v)){if(!t.allow){let j=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(v)}?`,initialValue:!0});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}}if(!t.allow&&t.repo){let h=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(h)||!h)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(P.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${P.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(a.join(", "))}`);let p=(await Ke(...a)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed to get info for ${P.cyan(h)}`),program.error(P.red(S));});r(`Resolved ${P.cyan(a.join(", "))}`),r(`Fetching blocks from ${P.cyan(a.join(", "))}`);let c=(await qe(...p)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed fetching blocks from ${P.cyan(h)}`),program.error(P.red(S));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(a.join(", "))}`),r(`Retrieved blocks from ${P.cyan(a.join(", "))}`);let l=Ye(c,i,t.cwd).map(h=>h.specifier),y=e;if(y.length===0){let h=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([S,d])=>d.list).map(([S,d])=>{let w=`${d.category}/${d.name}`,$=l.findIndex(j=>j===w)!==-1,v;return a.length>1?v=`${P.cyan(`${d.sourceRepo.name}/${d.sourceRepo.owner}/${d.sourceRepo.repoName}/${d.category}`)}/${d.name}`:v=`${P.cyan(d.category)}/${d.name}`,{label:$?P.gray(v):v,value:S,hint:$?"Installed":void 0}}),required:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),y=h;}r(`Installing blocks ${P.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await it(y,c,p)).match(h=>h,h=>program.error(h)),k=(await detect({cwd:t.cwd}))?.agent??"npm",x=[],A=new Set,m=new Set,R=le();if(s){let h=`${t.cwd}-zero-config`,S=C.safeParse(er,R.get(h)),d=S.success?S.output:i,w=Array.from(new Set(u.map(j=>j.block.category)));for(let j of w){let z=await text({message:`Where would you like to add ${P.cyan(j)}?`,placeholder:d?d.paths[j]:`./src/${j}`,initialValue:d?d.paths[j]:`./src/${j}`,defaultValue:d?d.paths[j]:`./src/${j}`,validate(ce){if(ce.trim()==="")return "Please provide a value"}});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.paths[j]=z;}if(!t.yes){let j=await confirm({message:"Include tests?",initialValue:d.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=j;let z=await confirm({message:"Add watermark?",initialValue:d.watermark});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.watermark=z;}let $="none";Ae.existsSync(Q.join(t.cwd,".prettierrc"))&&($="prettier"),Ae.existsSync(Q.join(t.cwd,"biome.json"))&&($="biome");let v=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(j=>({value:j.toLowerCase(),label:j})),initialValue:$==="none"?d.formatter?d.formatter:"none":$});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(i.formatter=v),R.set(h,i);}let{prettierOptions:M,biomeOptions:F}=await ht({formatter:i.formatter,cwd:t.cwd}),L=$e(i.paths,t.cwd);L.isErr()&&program.error(P.red(L.unwrapErr()));let f=L.unwrap(),g=[],E;for(let{block:h}of u){let S=`${h.sourceRepo.url}/${h.category}/${h.name}`,d=`${h.category}/${h.name}`,w=yt(X.package.version,h.sourceRepo.url),$=h.sourceRepo;r(`Setting up ${S}`);let v;if(f[h.category]!==void 0?v=Q.join(t.cwd,f[h.category]):v=Q.join(t.cwd,f["*"],h.category),l.find(z=>d===z)&&!t.yes&&!E){if(E===void 0){let z=u.map(ye=>`${ye.block.category}/${ye.block.name}`).filter(ye=>l.find(N=>N===ye));log.warn(`The following components ${P.bold.yellow("already exist")}: ${P.cyan(eo(z))}`);let ce=await confirm({message:`Would you like to ${P.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ce)&&(cancel("Canceled!"),process.exit(0)),E=ce;}if(!E){let z=await confirm({message:`${P.cyan(d)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(z)&&(cancel("Canceled!"),process.exit(0)),!z)continue}}g.push(d),x.push({run:async({message:z})=>{z(`Adding ${P.cyan(S)}`),r(`Creating directory ${P.bold(v)}`),Ae.mkdirSync(v,{recursive:!0}),r(`Created directory ${P.bold(v)}`);let ce=[],ye=async N=>{let B=await $.provider.fetchRaw($,N,{verbose:r});return B.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${S}`))),B.unwrap()};for(let N of h.files){if(!i.includeTests&&ue(N))continue;let B=Q.join(h.directory,N),ee;h.subdirectory?ee=Q.join(v,h.name,N):ee=Q.join(v,N),r(`Adding ${P.bold(B)}`);let et=await ye(B),ze=ee.slice(0,ee.length-N.length);r(`Creating directory ${P.bold(ze)}`),Ae.mkdirSync(ze,{recursive:!0}),r(`Created directory ${P.bold(ze)}`),ce.push({content:et,destPath:ee}),r(`Got ${P.bold(B)}`);}for(let N of ce){let B=await Ut({file:N,biomeOptions:F,prettierOptions:M,config:i,imports:h._imports_,watermark:w,verbose:r,cwd:t.cwd});B.isErr()&&program.error(P.red(B.unwrapErr())),r(`Writing to ${P.bold(N.destPath)}`),Ae.writeFileSync(N.destPath,B.unwrap());}if(i.includeTests&&h.tests){r("Trying to include tests");let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&A.add("vitest");}for(let N of h.devDependencies)A.add(N);for(let N of h.dependencies)m.add(N);}});}await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(g.join(", "))}`,tasks:x,verbose:t.verbose?r:void 0});let b=Dt(m,A,{cwd:t.cwd});if(m=b.dependencies,A=b.devDependencies,m.size>0||A.size>0){let h=t.yes;if(!t.yes){let w=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),h=w;}h&&(m.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(m),dev:!1,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dependencies"),program.error(w);})),A.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(A),dev:!0,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(w);})));let S=[];if(!h){if(m.size>0){let w=resolveCommand(k,"install",[...m]);S.push(`Install dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(A.size>0){let w=resolveCommand(k,"install",[...A,"-D"]);S.push(`Install dev dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}S=S.map((w,$)=>`${$+1}. ${w}`),h||S.push(""),S.push("Import and use the blocks!");let d=vt(S);process.stdout.write(d);}};var Cn=C.object({token:C.optional(C.string()),provider:C.optional(C.string()),logout:C.boolean()}),lr=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).action(async e=>{let t=C.parse(Cn,e);ne(X.package.version),await xn(t),outro(P.green("All done!"));}),xn=async e=>{let t=le();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${W}
40
+ `,o},eo=(e,t=3)=>{let r=e.slice(0,t),o=e.length-r.length;return `${r.join(", ")}${o>0?` and ${o} other(s)`:""}`},ne=e=>intro(`${P.bgHex("#f7df1e").black(" jsrepo ")}${P.gray(` v${e} `)}`);var hn=C.object({repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),ir=new Command("add").description("Add blocks to your project.").argument("[blocks...]","Names of the blocks you want to add to your project. ex: (utils/math, github/ieedan/std/utils/math)").option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hn,t);ne(X.package.version),await yn(e,r),outro(P.green("All done!"));}),yn=async(e,t)=>{let r=h=>{t.verbose&&console.info(`${ft} ${h}`);};r(`Attempting to add ${JSON.stringify(e)}`);let o=spinner(),n=we(t.cwd),s=n.isErr(),i;if(n.isErr()){let h=t.yes;if(!t.yes){let S=await confirm({message:`You don't have ${fe} initialized in your project. Do you want to continue?`,initialValue:!1});isCancel(S)&&(cancel("Canceled!"),process.exit(0)),h=S;}h||(cancel("Canceled!"),process.exit(0)),i={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./src/blocks"},repos:[]};}else i=n.unwrap();let a=i.repos;t.repo&&(a=[t.repo]);for(let h of e){if(!q.find(j=>h.startsWith(j.name())))continue;let[S,d,w,...$]=h.split("/"),v;if($.length>2?v=`${S}/${d}/${w}/${$.slice(0,$.length-2).join("/")}`:v=`${S}/${d}/${w}`,!a.find(j=>j===v)){if(!t.allow){let j=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(v)}?`,initialValue:!0});(isCancel(j)||!j)&&(cancel("Canceled!"),process.exit(0));}a.push(v);}}if(!t.allow&&t.repo){let h=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(h)||!h)&&(cancel("Canceled!"),process.exit(0));}a.length===0&&(s&&program.error(P.red(`Fully quality blocks ex: (github/ieedan/std/utils/math) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),r(`Resolving ${P.cyan(a.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(a.join(", "))}`);let p=(await Ke(...a)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed to get info for ${P.cyan(h)}`),program.error(P.red(S));});r(`Resolved ${P.cyan(a.join(", "))}`),r(`Fetching blocks from ${P.cyan(a.join(", "))}`);let c=(await qe(...p)).match(h=>h,({repo:h,message:S})=>{o.stop(`Failed fetching blocks from ${P.cyan(h)}`),program.error(P.red(S));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(a.join(", "))}`),r(`Retrieved blocks from ${P.cyan(a.join(", "))}`);let l=Ye(c,i,t.cwd).map(h=>h.specifier),y=e;if(y.length===0){let h=await multiselect({message:"Select which blocks to add.",options:Array.from(c.entries()).filter(([S,d])=>d.list).map(([S,d])=>{let w=`${d.category}/${d.name}`,$=l.findIndex(j=>j===w)!==-1,v;return a.length>1?v=`${P.cyan(`${d.sourceRepo.name}/${d.sourceRepo.owner}/${d.sourceRepo.repoName}/${d.category}`)}/${d.name}`:v=`${P.cyan(d.category)}/${d.name}`,{label:$?P.gray(v):v,value:S,hint:$?"Installed":void 0}}),required:!0});isCancel(h)&&(cancel("Canceled!"),process.exit(0)),y=h;}r(`Installing blocks ${P.cyan(y.join(", "))}`),t.verbose&&console.log("Blocks map: ",c);let u=(await it(y,c,p)).match(h=>h,h=>program.error(h)),k=(await detect({cwd:t.cwd}))?.agent??"npm",x=[],A=new Set,m=new Set,R=le();if(s){let h=`${t.cwd}-zero-config`,S=C.safeParse(er,R.get(h)),d=S.success?S.output:i,w=Array.from(new Set(u.map(j=>j.block.category)));for(let j of w){let z=await text({message:`Where would you like to add ${P.cyan(j)}?`,placeholder:d?d.paths[j]:`./src/${j}`,initialValue:d?d.paths[j]:`./src/${j}`,defaultValue:d?d.paths[j]:`./src/${j}`,validate(ce){if(ce.trim()==="")return "Please provide a value"}});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.paths[j]=z;}if(!t.yes){let j=await confirm({message:"Include tests?",initialValue:d.includeTests});isCancel(j)&&(cancel("Canceled!"),process.exit(0)),i.includeTests=j;let z=await confirm({message:"Add watermark?",initialValue:d.watermark});isCancel(z)&&(cancel("Canceled!"),process.exit(0)),i.watermark=z;}let $="none";Ae.existsSync(Q.join(t.cwd,".prettierrc"))&&($="prettier"),Ae.existsSync(Q.join(t.cwd,"biome.json"))&&($="biome");let v=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(j=>({value:j.toLowerCase(),label:j})),initialValue:$==="none"?d.formatter?d.formatter:"none":$});isCancel(v)&&(cancel("Canceled!"),process.exit(0)),v!=="none"&&(i.formatter=v),R.set(h,i);}let{prettierOptions:M,biomeOptions:F}=await ht({formatter:i.formatter,cwd:t.cwd}),L=$e(i.paths,t.cwd);L.isErr()&&program.error(P.red(L.unwrapErr()));let f=L.unwrap(),g=[],E;for(let{block:h}of u){let S=`${h.sourceRepo.url}/${h.category}/${h.name}`,d=`${h.category}/${h.name}`,w=yt(X.package.version,h.sourceRepo.url),$=h.sourceRepo;r(`Setting up ${S}`);let v;if(f[h.category]!==void 0?v=Q.join(t.cwd,f[h.category]):v=Q.join(t.cwd,f["*"],h.category),l.find(z=>d===z)&&!t.yes&&!E){if(E===void 0){let z=u.map(ye=>`${ye.block.category}/${ye.block.name}`).filter(ye=>l.find(N=>N===ye));log.warn(`The following components ${P.bold.yellow("already exist")}: ${P.cyan(eo(z))}`);let ce=await confirm({message:`Would you like to ${P.bold.red("overwrite")} all existing components?`,active:"Yes, overwrite everything",inactive:"No, let me decide individually",initialValue:!1});isCancel(ce)&&(cancel("Canceled!"),process.exit(0)),E=ce;}if(!E){let z=await confirm({message:`${P.cyan(d)} already exists in your project would you like to overwrite it?`,initialValue:!1});if(isCancel(z)&&(cancel("Canceled!"),process.exit(0)),!z)continue}}g.push(d),x.push({run:async({message:z})=>{z(`Adding ${P.cyan(S)}`),r(`Creating directory ${P.bold(v)}`),Ae.mkdirSync(v,{recursive:!0}),r(`Created directory ${P.bold(v)}`);let ce=[],ye=async N=>{let B=await $.provider.fetchRaw($,N,{verbose:r});return B.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${S}`))),B.unwrap()};for(let N of h.files){if(!i.includeTests&&ue(N))continue;let B=Q.join(h.directory,N),ee;h.subdirectory?ee=Q.join(v,h.name,N):ee=Q.join(v,N),r(`Adding ${P.bold(B)}`);let et=await ye(B),ze=ee.slice(0,ee.length-N.length);r(`Creating directory ${P.bold(ze)}`),Ae.mkdirSync(ze,{recursive:!0}),r(`Created directory ${P.bold(ze)}`),ce.push({content:et,destPath:ee}),r(`Got ${P.bold(B)}`);}for(let N of ce){let B=await Ut({file:N,biomeOptions:F,prettierOptions:M,config:i,imports:h._imports_,watermark:w,verbose:r,cwd:t.cwd});B.isErr()&&program.error(P.red(B.unwrapErr())),r(`Writing to ${P.bold(N.destPath)}`),Ae.writeFileSync(N.destPath,B.unwrap());}if(i.includeTests&&h.tests){r("Trying to include tests");let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&A.add("vitest");}for(let N of h.devDependencies)A.add(N);for(let N of h.dependencies)m.add(N);}});}await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(g.join(", "))}`,tasks:x,verbose:t.verbose?r:void 0});let b=Dt(m,A,{cwd:t.cwd});if(m=b.dependencies,A=b.devDependencies,m.size>0||A.size>0){let h=t.yes;if(!t.yes){let w=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(w)&&(cancel("Canceled!"),process.exit(0)),h=w;}h&&(m.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(m),dev:!1,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dependencies"),program.error(w);})),A.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(k)}`),(await Ne({pm:k,deps:Array.from(A),dev:!0,cwd:t.cwd})).match(w=>{t.verbose||o.stop(`Installed ${P.cyan(w.join(", "))}`);},w=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(w);})));let S=[];if(!h){if(m.size>0){let w=resolveCommand(k,"install",[...m]);S.push(`Install dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}if(A.size>0){let w=resolveCommand(k,"install",[...A,"-D"]);S.push(`Install dev dependencies \`${P.cyan(`${w?.command} ${w?.args.join(" ")}`)}\``);}}S=S.map((w,$)=>`${$+1}. ${w}`),h||S.push(""),S.push("Import and use the blocks!");let d=vt(S);process.stdout.write(d);}};var Cn=C.object({token:C.optional(C.string()),provider:C.optional(C.string()),logout:C.boolean()}),lr=new Command("auth").description("Provide a token for access to private repositories.").option("--token <token>","The token to use for authenticating to your provider.").addOption(new Option("--provider <name>","The provider this token belongs to.").choices(q.map(e=>e.name()))).option("--logout","Erase tokens from each provider from storage.",!1).action(async e=>{let t=C.parse(Cn,e);ne(X.package.version),await xn(t),outro(P.green("All done!"));}),xn=async e=>{let t=le();if(e.logout){for(let r of q){let o=`${r.name()}-token`;if(t.get(o)===void 0){process.stdout.write(`${W}
41
41
  `),process.stdout.write(P.gray(`${W} Already logged out of ${r.name()}.
42
42
  `));continue}let n=await confirm({message:`Remove ${r.name()} token?`,initialValue:!0});isCancel(n)&&(cancel("Canceled!"),process.exit(0)),n&&t.delete(o);}return}if(q.length>1){let r=await select({message:"Which provider is this token for?",options:q.map(o=>({label:o.name(),value:o.name()})),initialValue:q[0].name()});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),e.provider=r;}else e.provider=q[0].name();if(e.token===void 0){let r=await password({message:"Paste your token",validate(o){if(o.trim()==="")return "Please provide a value"}});(isCancel(r)||!r)&&(cancel("Canceled!"),process.exit(0)),e.token=r;}t.set(`${e.provider}-token`,e.token);};var Sn=C.object({dirs:C.optional(C.array(C.string())),includeBlocks:C.optional(C.array(C.string())),includeCategories:C.optional(C.array(C.string())),excludeBlocks:C.optional(C.array(C.string())),excludeCategories:C.optional(C.array(C.string())),excludeDeps:C.optional(C.array(C.string())),listBlocks:C.optional(C.array(C.string())),listCategories:C.optional(C.array(C.string())),doNotListBlocks:C.optional(C.array(C.string())),doNotListCategories:C.optional(C.array(C.string())),preview:C.optional(C.boolean()),output:C.boolean(),verbose:C.boolean(),cwd:C.string()}),pr=new Command("build").description(`Builds the provided --dirs in the project root into a \`${ke}\` file.`).option("--dirs [dirs...]","The directories containing the blocks.").option("--include-blocks [blockNames...]","Include only the blocks with these names.").option("--include-categories [categoryNames...]","Include only the categories with these names.").option("--exclude-blocks [blockNames...]","Do not include the blocks with these names.").option("--exclude-categories [categoryNames...]","Do not include the categories with these names.").option("--list-blocks [blockNames...]","List only the blocks with these names.").option("--list-categories [categoryNames...]","List only the categories with these names.").option("--do-not-list-blocks [blockNames...]","Do not list the blocks with these names.").option("--do-not-list-categories [categoryNames...]","Do not list the categories with these names.").option("--exclude-deps [deps...]","Dependencies that should not be added.").option("--preview","Display a preview of the blocks list.").option("--no-output",`Do not output a \`${ke}\` file.`).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(Sn,e);ne(X.package.version),await Pn(t),outro(P.green("All done!"));}),Pn=async e=>{let t=spinner(),r=[],o=Ot(e.cwd).match(c=>{if(c===null)return {$schema:"",dirs:e.dirs??[],doNotListBlocks:e.doNotListBlocks??[],doNotListCategories:e.doNotListCategories??[],listBlocks:e.listBlocks??[],listCategories:e.listCategories??[],excludeDeps:e.excludeDeps??[],includeBlocks:e.includeBlocks??[],includeCategories:e.includeCategories??[],excludeBlocks:e.excludeBlocks??[],excludeCategories:e.excludeCategories??[],preview:e.preview};let l=c;return e.dirs&&(l.dirs=e.dirs),e.doNotListBlocks&&(l.doNotListBlocks=e.doNotListBlocks),e.doNotListCategories&&(l.doNotListCategories=e.doNotListCategories),e.listBlocks&&(l.listBlocks=e.listBlocks),e.listCategories&&(l.listCategories=e.listCategories),e.includeBlocks&&(l.includeBlocks=e.includeBlocks),e.includeCategories&&(l.includeCategories=e.includeCategories),e.excludeBlocks&&(l.excludeBlocks=e.excludeBlocks),e.excludeCategories&&(l.excludeCategories=e.excludeCategories),e.excludeDeps&&(l.excludeDeps=e.excludeDeps),e.preview!==void 0&&(l.preview=e.preview),l.rules={...Zt,...l.rules},l},c=>program.error(P.red(c))),n=Q.join(e.cwd,ke);for(let c of o.dirs){let l=Q.join(e.cwd,c);t.start(`Building ${P.cyan(l)}`),e.output&&Ae.existsSync(n)&&Ae.rmSync(n);let y=Jr(l,{cwd:e.cwd,config:o});for(let u of y){if(r.find(k=>k.name===u.name)!==void 0){console.warn(`${W} ${Ie} Skipped adding \`${P.cyan(`${c}/${u.name}`)}\` because a category with the same name already exists!`);continue}r.push(u);}t.stop(`Built ${P.cyan(l)}`);}t.start("Checking manifest");let{warnings:s,errors:i}=Ir(r,o,o.rules);t.stop("Completed checking manifest."),(s.length>0||i.length>0)&&console.log(W);for(let c of s)console.log(c);if(i.length>0){for(let c of i)console.log(c);program.error(P.red(`Completed checking manifest with ${P.bold(`${i.length} error(s)`)} and ${P.bold(`${s.length} warning(s)`)}`));}let[a,p]=zr(r);if(r=a,p>0&&log.step(`Removed ${p} unused block${p>1?"s":""}.`),o.preview){let c=r.flatMap(l=>l.blocks.filter(y=>y.list).map(y=>`${P.cyan(y.category)}/${y.name}`));log.message(`${P.yellow("Preview")}:`);for(let l of c)console.log(`${W} \u25FB ${l}`);}e.output&&(t.start(`Writing output to \`${P.cyan(n)}\``),Ae.writeFileSync(n,JSON.stringify(r,null," ")),t.stop(`Wrote output to \`${P.cyan(n)}\``));};var io=(e,t)=>{let r=0;for(let o of e)r=r+t(o);return r};var ao=e=>/^\s+$/g.test(e),$t=e=>{let t=e.length-1;for(;ao(e[t])&&t>=0;){if(e[t]===`
43
43
  `)return e[t-1]==="\r"?e.slice(0,t-1):e.slice(0,t);t--;}return e},Ht=({from:e,to:t,changes:r,expand:o=!1,maxUnchanged:n=5,colorRemoved:s=P.red,colorAdded:i=P.green,colorCharsRemoved:a=P.bgRed,colorCharsAdded:p=P.bgGreen,prefix:c,onUnchanged:l,intro:y})=>{let u="",k=io(r,m=>m.count??0).toString().length+1,x=0;if(r.length===1&&!r[0].added&&!r[0].removed)return l({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:y});u+=y({from:e,to:t,changes:r,expand:o,maxUnchanged:n,colorAdded:i,colorRemoved:s,prefix:c,onUnchanged:l,intro:y});let A=m=>P.gray(`${c?.()??""}${Rt(`${m+1+x} `,k)} `);for(let m=0;m<r.length;m++){let R=r[m],M=r[m-1]?.added||r[m-1]?.removed,F=r[m+1]?.added||r[m+1]?.removed;if(!R.added&&!R.removed){if(!o&&R.count!==void 0&&R.count>n){let g=x,E=re($t(R.value)),b=0;if(F&&(b+=n),M&&(b+=n),b>=E.length){u+=`${Z(E,{prefix:A})}
@@ -55,11 +55,11 @@ ${new Date().toLocaleDateString().replaceAll("/","-")}`;var xt=async(e,{verbose:
55
55
  ${F}`);}let _=diffLines(b,F),h=Q.join(`${u.name}/${u.owner}/${u.repoName}`,R),S=Ht({from:h,to:E,changes:_,expand:e.expand,maxUnchanged:e.maxUnchanged,colorAdded:P.greenBright,colorRemoved:P.redBright,colorCharsAdded:P.bgGreenBright,colorCharsRemoved:P.bgRedBright,prefix:()=>`${W} `,onUnchanged:({from:d,to:w,prefix:$})=>`${$?.()??""}${P.cyan(d)} \u2192 ${P.gray(w)} ${P.gray("(unchanged)")}
56
56
  `,intro:({from:d,to:w,changes:$,prefix:v})=>{let j=$.filter(z=>z.added).length;return `${v?.()??""}${P.cyan(d)} \u2192 ${P.gray(w)} (${j} change${j===1?"":"s"})
57
57
  ${v?.()??""}
58
- `}});process.stdout.write(S);}break}l||program.error(P.red(`Invalid block! ${P.bold(c)} does not exist!`));}};var qn=C.objectWithRest({repo:C.optional(C.string()),allow:C.boolean(),cwd:C.string()},C.unknown()),gr=new Command("exec").alias("x").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=C.parse(qn,t);ne(X.package.version),await Kn(e,o,r);}),Kn=async(e,t,r)=>{let o=e,n=spinner(),s=we(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./"},repos:[]}:a=s.unwrap();let p=a.repos;if(t.repo&&(p=[t.repo]),o&&q.find(d=>o?.startsWith(d.name()))){let[d,w,$,...v]=o.split("/"),j;if(v.length>2?j=`${d}/${w}/${$}/${v.slice(0,v.length-2).join("/")}`:j=`${d}/${w}/${$}`,!p.find(z=>z===j)){if(!t.allow){let z=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(j)}?`,initialValue:!0});(isCancel(z)||!z)&&(cancel("Canceled!"),process.exit(0));}p=[j];}}if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}p.length===0&&(i&&program.error(P.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${P.cyan(p.join(", "))}`);let c=(await Ke(...p)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed to get info for ${P.cyan(d)}`),program.error(P.red(w));}),l=(await qe(...c)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed fetching scripts from ${P.cyan(d)}`),program.error(P.red(w));});if(n.stop(`Retrieved scripts from ${P.cyan(p.join(", "))}`),!o){let d=await select({message:"Select which script to run.",options:Array.from(l.entries()).filter(([w,$])=>$.list).map(([w,$])=>{let v;return p.length>1?v=`${P.cyan(`${$.sourceRepo.name}/${$.sourceRepo.owner}/${$.sourceRepo.repoName}/${$.category}`)}/${$.name}`:v=`${P.cyan($.category)}/${$.name}`,{label:v,value:w}})});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o=d;}let y=(await it([o],l,c)).match(d=>d,d=>program.error(d)),u="temp-jsrepo-exec",k=`./${u}/${encodeURIComponent(o)}`,x=Q.join(process.cwd(),k);a.paths["*"]=k,Ae.mkdirSync(x,{recursive:!0});let A=(await detect({cwd:process.cwd()}))?.agent??"npm",m=[],R=new Set,M=new Set,F=$e(a.paths,t.cwd);F.isErr()&&program.error(P.red(F.unwrapErr()));let L=F.unwrap(),f=[];for(let{block:d}of y){let w=`${d.sourceRepo.url}/${d.category}/${d.name}`,$=`${d.category}/${d.name}`,v=d.sourceRepo,j=Q.join(t.cwd,L["*"],d.category);f.push($),m.push({run:async({message:z})=>{z(`Adding ${P.cyan(w)}`),Ae.mkdirSync(j,{recursive:!0});let ce=[],ye=async N=>{let B=await v.provider.fetchRaw(v,N);return B.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${w}`))),B.unwrap()};for(let N of d.files){if(!a.includeTests&&ue(N))continue;let B=Q.join(d.directory,N),ee;d.subdirectory?ee=Q.join(j,d.name,N):ee=Q.join(j,N);let et=await ye(B),ze=ee.slice(0,ee.length-N.length);Ae.mkdirSync(ze,{recursive:!0}),ce.push({content:et,destPath:ee});}for(let N of ce)Ae.writeFileSync(N.destPath,N.content);if(a.includeTests&&d.tests){let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&R.add("vitest");}for(let N of d.devDependencies)R.add(N);for(let N of d.dependencies)M.add(N);}});}if(await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(f.join(", "))}`,tasks:m}),M.size>0||R.size>0){let d={name:"temp-package",type:"module",version:"0.0.1"},w=Q.join(x,"package.json");Ae.writeFileSync(w,JSON.stringify(d,null," ")),M.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(M),dev:!1,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dependencies"),program.error($);})),R.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(R),dev:!0,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error($);}));}let E=r.parent.rawArgs.findIndex(d=>d==="--"),b=[];E!==-1&&(b=r.parent.rawArgs.slice(E+1)),console.clear();let _=y[0],h;_.block.subdirectory?h=Q.join(x,`${_.block.category}/${_.block.name}/index.js`):h=Q.join(x,`${_.block.category}/${_.block.name}.js`);let S=resolveCommand(A,"execute",["tsx",h,...b]);S||program.error(P.red("Error resolving run command!"));try{await execa(S.command,S.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Ae.rmSync(Q.join(process.cwd(),u),{recursive:!0,force:!0});}};var rs=C.object({repos:C.optional(C.array(C.string())),watermark:C.boolean(),tests:C.optional(C.boolean()),formatter:C.optional(Qt),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),yr=new Command("init").description("Initializes your project with a configuration file.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(rs,e);if(ne(X.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(P.red(`You cannot provide both ${P.bold("--project")} and ${P.bold("--registry")} at the same time.`)),t.registry===void 0&&t.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),t.registry=r==="registry";}t.registry?await ns(t):await os(t),outro(P.green("All done!"));}),os=async e=>{let t=le(),r=we(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:F=>{if(F.trim().length===0)return "Please provide a value";if(!q.find(L=>L.matches(F)))return `Invalid provider! Valid providers (${q.map(L=>L.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let k=q.find(F=>F.matches(u));k||program.error(P.red("Invalid provider!"));let x=`${k.name()}-token`;if(!t.get(x)){let F=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(F)&&(cancel("Canceled!"),process.exit(0)),F){let L=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),t.set(x,L);}}o.start(`Fetching categories from ${P.cyan(u)}`);let m=await k.fetchManifest(u);o.stop(`Fetched categories from ${P.cyan(u)}`),m.isErr()&&program.error(P.red(m.unwrapErr()));let R=m.unwrap(),M=await multiselect({message:"Which category paths would you like to configure?",options:R.map(F=>({label:F.name,value:F.name})),required:!1});if(isCancel(M)&&(cancel("Canceled!"),process.exit(0)),M.length>0)for(let F of M){let L=n[F],f=await text({message:`Where should ${F} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:L||`./src/${F}`,defaultValue:L,initialValue:L});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),n[F]=f;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Ae.existsSync(Q.join(e.cwd,".prettierrc"))&&(y="prettier"),Ae.existsSync(Q.join(e.cwd,"biome.json"))&&(y="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(k=>({value:k.toLowerCase(),label:k})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${X.package.version}/schemas/project-config.json`,repos:e.repos,includeTests:r.isOk()&&e.tests===void 0?r.unwrap().includeTests:e.tests??!1,watermark:e.watermark,formatter:e.formatter,paths:n};o.start(`Writing config to \`${tt}\``);let{prettierOptions:a,biomeOptions:p}=await ht({formatter:i.formatter,cwd:e.cwd}),c=Q.join(e.cwd,tt),l=await or.format(JSON.stringify(i,null," "),{biomeOptions:p,prettierOptions:a,filePath:c,formatter:i.formatter});Ae.writeFileSync(c,l),o.stop(`Wrote config to \`${tt}\`.`);},ns=async e=>{let t=spinner(),r=Q.join(e.cwd,"package.json");Ae.existsSync(r)||program.error(P.red(`Couldn't find your ${P.bold("package.json")}!`));let o=Ot(e.cwd).match(m=>m,m=>program.error(P.red(m))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${X.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let R=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break}let m=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:R=>{if(R.trim().length===0)return "Please provide a value!"}});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(m);}let s=JSON.parse(Ae.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let m=await confirm({message:`The \`${P.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m)break;{let R=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:M=>{if(M.trim().length===0)return "Please provide a value!"}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),e.script=R;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let m=await confirm({message:`Add ${fe} as a dev dependency?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),a=m;}let p=!n;if(!e.yes&&n){let m=await confirm({message:`Create a \`${P.cyan(Ue)}\` file?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),p=m;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",l="";if(a)l+="jsrepo build";else {let m=resolveCommand$1(c,"execute",["jsrepo","build"]);m||program.error(P.red(`Error resolving execute command for ${c}`)),l+=`${m.command} ${m.args.join(" ")} `;}p||(l+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=l;let y=[];y.push({loadingMessage:`Adding \`${P.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${P.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ae.writeFileSync(r,JSON.stringify(s,null," "));}catch(m){program.error(P.red(`Error writing to \`${P.bold(r)}\`. Error: ${m}`));}}}),p&&y.push({loadingMessage:`Writing config to \`${P.cyan(Ue)}\``,completedMessage:`Wrote config to \`${P.cyan(Ue)}\``,run:async()=>{let m=Q.join(e.cwd,Ue);try{Ae.writeFileSync(Q.join(m),JSON.stringify(o,null," "));}catch(R){program.error(P.red(`Error writing to \`${P.bold(m)}\`. Error: ${R}`));}}}),await xt(y,{});let u=i;if(a&&!i){let m=e.yes;if(!e.yes){let R=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),m=R;}m&&(t.start(`Installing ${fe}`),(await Ne({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${fe}.`),M=>{t.stop(`Failed to install ${fe}.`),program.error(M);}),u=!0);}let k=[];if(!u&&a){let m=resolveCommand$1(c,"install",["jsrepo","-D"]);k.push(`Install ${fe} as a dev dependency \`${P.cyan(`${m?.command} ${m?.args.join(" ")}`)}\``);}k.push(`Add categories to \`${P.cyan(o.dirs.join(", "))}\`.`);let x=resolveCommand$1(c,"run",[e.script]);k.push(`Run \`${P.cyan(`${x?.command} ${x?.args.join(" ")}`)}\` to build the registry.`),k=k.map((m,R)=>`${R+1}. ${m}`);let A=vt(k);process.stdout.write(A);};var hs=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),wr=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hs,t);ne(X.package.version),await ys(e,r),outro(P.green("All done!"));}),ys=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=we(t.cwd).match(f=>f,f=>program.error(P.red(f))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${P.cyan(i.join(", "))}`);for(let f of i){let g=(await st(f)).match(_=>_,_=>program.error(P.red(_))),E=await g.provider.fetchManifest(g);r(`Got info for provider ${P.cyan(g.name)}`),E.isErr()&&(t.verbose||n.stop(`Error fetching ${P.cyan(f)}`),program.error(P.red(`There was an error fetching the \`${ke}\` from the repository ${P.cyan(f)} make sure the target repository has a \`${ke}\` in its root?`)));let b=E.unwrap();for(let _ of b)for(let h of _.blocks)s.set(`${g.name}/${g.owner}/${g.repoName}/${_.name}/${h.name}`,{...h,sourceRepo:g});}r(`Retrieved blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${P.cyan(i.join(", "))}`);let a=Q.resolve(Q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${P.bold(a)}.`),Ae.mkdirSync(a,{recursive:!0});let p=()=>{Ae.rmSync(a,{recursive:!0,force:!0});},c=Ye(s,o,t.cwd).map(f=>f.specifier),l=e;e.length===0&&(l=c),l.length===0&&(p(),program.error(P.red("There were no blocks found in your project!")));let y=[];for(let f of l){let g;if(q.find(E=>f.startsWith(E.name()))){if(i.length===0){let[E,b,_,...h]=f.split("/"),S;h.length>2?S=`${E}/${b}/${_}/${h.slice(0,h.length-2).join("/")}`:S=`${E}/${b}/${_}`;let d=(await st(S)).match($=>$,$=>program.error(P.red($))),w=(await d.provider.fetchManifest(d)).match($=>$,$=>program.error(P.red($)));for(let $ of w)for(let v of $.blocks)s.set(`${d.name}/${d.owner}/${d.repoName}/${$.name}/${v.name}`,{...v,sourceRepo:d});}g=s.get(f);}else for(let E of i){let b=(await st(E)).unwrap(),_=s.get(`${b.name}/${b.owner}/${b.repoName}/${f}`);if(_!==void 0){g=_;break}}g||program.error(P.red(`Invalid block! ${P.bold(f)} does not exist!`)),y.push({name:f,block:g});}let u=$e(o.paths,t.cwd);u.isErr()&&program.error(P.red(u.unwrapErr()));let k=u.unwrap();for(let{block:f}of y){let g=f.sourceRepo,E=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(t.verbose||n.start(`Setting up test file for ${P.cyan(E)}`),!f.tests){n.stop(`No tests found for ${P.cyan(E)}`);continue}let b;k[f.category]!==void 0?b=Q.join(t.cwd,k[f.category]):b=Q.join(t.cwd,k["*"],f.category),b=Q.relative(a,b);let _=async d=>{let w=await g.provider.fetchRaw(g,d);return w.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${E}`))),w.unwrap()};r(`Downloading and copying test files for ${E}`);let h=[];for(let d of f.files.filter(w=>ue(w))){let w=await _(Q.join(f.directory,d)),$=Q.join(a,d);Ae.writeFileSync($,w),h.push($);}let S=new Project;for(let d of h){r(`Opening test file ${d}`);let w=S.addSourceFileAtPath(d);for(let $ of w.getImportDeclarations()){let v=$.getModuleSpecifierValue(),j;v.startsWith(".")&&(f.subdirectory?j=Q.join(b,f.name,v):j=Q.join(b,v)),j&&$.setModuleSpecifier(j.replaceAll(/\\/g,"/"));}}S.saveSync(),r(`Completed ${P.cyan.bold(E)} test file`),t.verbose||n.stop(`Completed setup for ${P.bold(E)}`);}r("Beginning testing");let x=await detect({cwd:t.cwd});x==null&&program.error(P.red("Could not detect package manager"));let A=resolveCommand(x.agent,"execute",["vitest","run",a]);A==null&&program.error(P.red(`Could not resolve add command for '${x.agent}'.`));let{command:m,args:R}=A,M=`${m} ${R.join(" ")}`,F=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${M}`,L=f=>console.info(f.toString());F.stdout.on("data",L),F.stderr.on("data",L);try{await F,p();}catch(f){t.debug?console.info(`${P.bold("--debug")} flag provided. Skipping cleanup. Run '${P.bold(M)}' to retry tests.
59
- `):p(),program.error(P.red(`Tests failed! Error ${f}`));}};var Cs=C.object({all:C.boolean(),expand:C.boolean(),maxUnchanged:C.number(),repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),kr=new Command("update").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",!1).option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(Cs,t);ne(X.package.version),await xs(e,r),outro(P.green("All done!"));}),xs=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=we(t.cwd).match(f=>f,f=>program.error(P.red(f))),s=n.repos;t.repo&&(s=[t.repo]);for(let f of e)q.find(g=>f.startsWith(g.name()))&&program.error(P.red(`Invalid value provided for block names \`${P.bold(f)}\`. Block names are expected to be provided in the format of \`${P.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${P.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(s.join(", "))}`);let i=(await Ke(...s)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed to get info for ${P.cyan(f)}`),program.error(P.red(g));});r(`Resolved ${P.cyan(s.join(", "))}`),r(`Fetching blocks from ${P.cyan(s.join(", "))}`);let a=(await qe(...i)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed fetching blocks from ${P.cyan(f)}`),program.error(P.red(g));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(s.join(", "))}`),r(`Retrieved blocks from ${P.cyan(s.join(", "))}`);let p=Ye(a,n,t.cwd);p.length===0&&program.error(P.red(`You haven't installed any blocks yet. Did you mean to \`${P.bold("add")}\`?`));let c=e;if(t.all&&(c=p.map(f=>f.specifier)),c.length===0){let f=await multiselect({message:"Which blocks would you like to update?",options:p.filter(g=>g.block.list).map(g=>({label:`${P.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}r(`Preparing to update ${P.cyan(c.join(", "))}`);let l=(await it(c,a,i)).match(f=>f,program.error),y=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],k=new Set,x=new Set,{prettierOptions:A,biomeOptions:m}=await ht({formatter:n.formatter,cwd:t.cwd}),R=$e(n.paths,t.cwd);R.isErr()&&program.error(P.red(R.unwrapErr()));let M=R.unwrap();for(let{block:f}of l){let g=`${f.sourceRepo.url}/${f.category}/${f.name}`,E=yt(X.package.version,f.sourceRepo.url),b=f.sourceRepo;r(`Attempting to add ${g}`);let _;M[f.category]!==void 0?_=Q.join(t.cwd,M[f.category]):_=Q.join(t.cwd,M["*"],f.category);let h=[],S=async d=>{let w=await b.provider.fetchRaw(b,d,{verbose:r});return w.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${g}`))),w.unwrap()};for(let d of f.files){if(!n.includeTests&&ue(d))continue;let w=Q.join(f.directory,d),$;f.subdirectory?$=Q.join(_,f.name,d):$=Q.join(_,d);let v=await S(w);Ae.mkdirSync($.slice(0,$.length-d.length),{recursive:!0}),h.push({content:v,destPath:$,fileName:d});}process.stdout.write(`${W}
58
+ `}});process.stdout.write(S);}break}l||program.error(P.red(`Invalid block! ${P.bold(c)} does not exist!`));}};var qn=C.objectWithRest({repo:C.optional(C.string()),allow:C.boolean(),cwd:C.string()},C.unknown()),gr=new Command("exec").alias("x").description("Execute a block as a script.").addArgument(new Argument("script","Name of the script you want to execute. ex: (general/hello, github/ieedan/std/general/hello)").argOptional()).option("--repo <repo>","Repository to download and run the script from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--cwd <path>","The current working directory.",process.cwd()).allowExcessArguments().allowUnknownOption().action(async(e,t,r)=>{let o=C.parse(qn,t);ne(X.package.version),await Kn(e,o,r);}),Kn=async(e,t,r)=>{let o=e,n=spinner(),s=we(t.cwd),i=s.isErr(),a;s.isErr()?a={$schema:"",includeTests:!1,watermark:!0,paths:{"*":"./"},repos:[]}:a=s.unwrap();let p=a.repos;if(t.repo&&(p=[t.repo]),o&&q.find(d=>o?.startsWith(d.name()))){let[d,w,$,...v]=o.split("/"),j;if(v.length>2?j=`${d}/${w}/${$}/${v.slice(0,v.length-2).join("/")}`:j=`${d}/${w}/${$}`,!p.find(z=>z===j)){if(!t.allow){let z=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(j)}?`,initialValue:!0});(isCancel(z)||!z)&&(cancel("Canceled!"),process.exit(0));}p=[j];}}if(!t.allow&&t.repo){let d=await confirm({message:`Allow ${fe} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(d)||!d)&&(cancel("Canceled!"),process.exit(0));}p.length===0&&(i&&program.error(P.red(`Fully quality your script ex: (github/ieedan/std/scripts/build) or provide the \`${P.bold("--repo")}\` flag to specify a registry.`)),program.error(P.red(`There were no repos present in your config and you didn't provide the \`${P.bold("--repo")}\` flag with a repo.`))),n.start(`Fetching scripts from ${P.cyan(p.join(", "))}`);let c=(await Ke(...p)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed to get info for ${P.cyan(d)}`),program.error(P.red(w));}),l=(await qe(...c)).match(d=>d,({repo:d,message:w})=>{n.stop(`Failed fetching scripts from ${P.cyan(d)}`),program.error(P.red(w));});if(n.stop(`Retrieved scripts from ${P.cyan(p.join(", "))}`),!o){let d=await select({message:"Select which script to run.",options:Array.from(l.entries()).filter(([w,$])=>$.list).map(([w,$])=>{let v;return p.length>1?v=`${P.cyan(`${$.sourceRepo.name}/${$.sourceRepo.owner}/${$.sourceRepo.repoName}/${$.category}`)}/${$.name}`:v=`${P.cyan($.category)}/${$.name}`,{label:v,value:w}})});isCancel(d)&&(cancel("Canceled!"),process.exit(0)),o=d;}let y=(await it([o],l,c)).match(d=>d,d=>program.error(d)),u="temp-jsrepo-exec",k=`./${u}/${encodeURIComponent(o)}`,x=Q.join(process.cwd(),k);a.paths["*"]=k,Ae.mkdirSync(x,{recursive:!0});let A=(await detect({cwd:process.cwd()}))?.agent??"npm",m=[],R=new Set,M=new Set,F=$e(a.paths,t.cwd);F.isErr()&&program.error(P.red(F.unwrapErr()));let L=F.unwrap(),f=[];for(let{block:d}of y){let w=`${d.sourceRepo.url}/${d.category}/${d.name}`,$=`${d.category}/${d.name}`,v=d.sourceRepo,j=Q.join(t.cwd,L["*"],d.category);f.push($),m.push({run:async({message:z})=>{z(`Adding ${P.cyan(w)}`),Ae.mkdirSync(j,{recursive:!0});let ce=[],ye=async N=>{let B=await v.provider.fetchRaw(v,N);return B.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(N)}`)),program.error(P.red(`There was an error trying to get ${w}`))),B.unwrap()};for(let N of d.files){if(!a.includeTests&&ue(N))continue;let B=Q.join(d.directory,N),ee;d.subdirectory?ee=Q.join(j,d.name,N):ee=Q.join(j,N);let et=await ye(B),ze=ee.slice(0,ee.length-N.length);Ae.mkdirSync(ze,{recursive:!0}),ce.push({content:et,destPath:ee});}for(let N of ce)Ae.writeFileSync(N.destPath,N.content);if(a.includeTests&&d.tests){let{devDependencies:N}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(N===void 0||N.vitest===void 0)&&R.add("vitest");}for(let N of d.devDependencies)R.add(N);for(let N of d.dependencies)M.add(N);}});}if(await Gt({startMessage:"Adding blocks",stopMessage:`Added ${P.cyan(f.join(", "))}`,tasks:m}),M.size>0||R.size>0){let d={name:"temp-package",type:"module",version:"0.0.1"},w=Q.join(x,"package.json");Ae.writeFileSync(w,JSON.stringify(d,null," ")),M.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(M),dev:!1,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dependencies"),program.error($);})),R.size>0&&(t.verbose||n.start(`Installing dependencies with ${P.cyan(A)}`),(await Ne({pm:A,deps:Array.from(R),dev:!0,cwd:x,ignoreWorkspace:!0})).match($=>{t.verbose||n.stop(`Installed ${P.cyan($.join(", "))}`);},$=>{t.verbose||n.stop("Failed to install dev dependencies"),program.error($);}));}let E=r.parent.rawArgs.findIndex(d=>d==="--"),b=[];E!==-1&&(b=r.parent.rawArgs.slice(E+1)),console.clear();let _=y[0],h;_.block.subdirectory?h=Q.join(x,`${_.block.category}/${_.block.name}/index.js`):h=Q.join(x,`${_.block.category}/${_.block.name}.js`);let S=resolveCommand(A,"execute",["tsx",h,...b]);S||program.error(P.red("Error resolving run command!"));try{await execa(S.command,S.args,{cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});}finally{Ae.rmSync(Q.join(process.cwd(),u),{recursive:!0,force:!0});}};var rs=C.object({repos:C.optional(C.array(C.string())),watermark:C.boolean(),tests:C.optional(C.boolean()),formatter:C.optional(Qt),project:C.optional(C.boolean()),registry:C.optional(C.boolean()),script:C.string(),yes:C.boolean(),cwd:C.string()}),yr=new Command("init").description("Initializes your project with a configuration file.").option("--repos [repos...]","Repository to install the blocks from.").option("--no-watermark","Will not add a watermark to each file upon adding it to your project.").option("--tests","Will include tests with the blocks.").addOption(new Option("--formatter <formatter>","What formatter to use when adding or updating blocks.").choices(["prettier","biome"])).option("-P, --project","Takes you through the steps to initialize a project.").option("-R, --registry","Takes you through the steps to initialize a registry.").option("--script <name>","The name of the build script. (For Registry setup)","build:registry").option("-y, --yes","Skip confirmation prompt.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async e=>{let t=C.parse(rs,e);if(ne(X.package.version),t.registry!==void 0&&t.project!==void 0&&program.error(P.red(`You cannot provide both ${P.bold("--project")} and ${P.bold("--registry")} at the same time.`)),t.registry===void 0&&t.project===void 0){let r=await select({message:"Initialize a project or registry?",options:[{value:"project",label:"project"},{value:"registry",label:"registry"}],initialValue:"project"});isCancel(r)&&(cancel("Canceled!"),process.exit(0)),t.registry=r==="registry";}t.registry?await ns(t):await os(t),outro(P.green("All done!"));}),os=async e=>{let t=le(),r=we(e.cwd),o=spinner(),n,s=await text({message:"Please enter a default path to install the blocks",validate(y){if(y.trim()==="")return "Please provide a value"},initialValue:r.isOk()?r.unwrap().paths["*"]:"./src/blocks"});if(isCancel(s)&&(cancel("Canceled!"),process.exit(0)),r.isOk()?n={...r.unwrap().paths,"*":s}:n={"*":s},!e.repos)for(e.repos=r.isOk()?r.unwrap().repos:[];;){let y=await confirm({message:`Add ${e.repos.length>0?"another":"a"} repo?`,initialValue:e.repos.length===0});if(isCancel(y)&&(cancel("Canceled!"),process.exit(0)),!y)break;let u=await text({message:"Where should we download the blocks from?",placeholder:"github/ieedan/std",validate:F=>{if(F.trim().length===0)return "Please provide a value";if(!q.find(L=>L.matches(F)))return `Invalid provider! Valid providers (${q.map(L=>L.name()).join(", ")})`}});isCancel(u)&&(cancel("Canceled!"),process.exit(0));let k=q.find(F=>F.matches(u));k||program.error(P.red("Invalid provider!"));let x=`${k.name()}-token`;if(!t.get(x)){let F=await confirm({message:"Would you like to add an auth token?",initialValue:!1});if(isCancel(F)&&(cancel("Canceled!"),process.exit(0)),F){let L=await password({message:"Paste your token",validate(f){if(f.trim()==="")return "Please provide a value"}});isCancel(L)&&(cancel("Canceled!"),process.exit(0)),t.set(x,L);}}o.start(`Fetching categories from ${P.cyan(u)}`);let m=await k.fetchManifest(u);o.stop(`Fetched categories from ${P.cyan(u)}`),m.isErr()&&program.error(P.red(m.unwrapErr()));let R=m.unwrap(),M=await multiselect({message:"Which category paths would you like to configure?",options:R.map(F=>({label:F.name,value:F.name})),required:!1});if(isCancel(M)&&(cancel("Canceled!"),process.exit(0)),M.length>0)for(let F of M){let L=n[F],f=await text({message:`Where should ${F} be added in your project?`,validate(g){if(g.trim()==="")return "Please provide a value"},placeholder:L||`./src/${F}`,defaultValue:L,initialValue:L});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),n[F]=f;}e.repos.push(u);}if(!e.formatter){let y=r.isErr()?"none":r.unwrap().formatter??"none";Ae.existsSync(Q.join(e.cwd,".prettierrc"))&&(y="prettier"),Ae.existsSync(Q.join(e.cwd,"biome.json"))&&(y="biome");let u=await select({message:"What formatter would you like to use?",options:["Prettier","Biome","None"].map(k=>({value:k.toLowerCase(),label:k})),initialValue:y});isCancel(u)&&(cancel("Canceled!"),process.exit(0)),u!=="none"&&(e.formatter=u);}let i={$schema:`https://unpkg.com/jsrepo@${X.package.version}/schemas/project-config.json`,repos:e.repos,includeTests:r.isOk()&&e.tests===void 0?r.unwrap().includeTests:e.tests??!1,watermark:e.watermark,formatter:e.formatter,paths:n};o.start(`Writing config to \`${tt}\``);let{prettierOptions:a,biomeOptions:p}=await ht({formatter:i.formatter,cwd:e.cwd}),c=Q.join(e.cwd,tt),l=await or.format(JSON.stringify(i,null," "),{biomeOptions:p,prettierOptions:a,filePath:c,formatter:i.formatter});Ae.writeFileSync(c,l),o.stop(`Wrote config to \`${tt}\`.`);},ns=async e=>{let t=spinner(),r=Q.join(e.cwd,"package.json");Ae.existsSync(r)||program.error(P.red(`Couldn't find your ${P.bold("package.json")}!`));let o=Ot(e.cwd).match(m=>m,m=>program.error(P.red(m))),n=o===null;for(o||(o={$schema:"",dirs:[],doNotListBlocks:[],doNotListCategories:[],listBlocks:[],listCategories:[],excludeDeps:[],includeBlocks:[],includeCategories:[],excludeBlocks:[],excludeCategories:[],preview:!1}),o.$schema=`https://unpkg.com/jsrepo@${X.package.version}/schemas/registry-config.json`;;){if(o.dirs.length>0){let R=await confirm({message:"Add another blocks directory?",initialValue:!1});if(isCancel(R)&&(cancel("Canceled!"),process.exit(0)),!R)break}let m=await text({message:"Where are your blocks located?",placeholder:"./src",defaultValue:"./src",initialValue:"./src",validate:R=>{if(R.trim().length===0)return "Please provide a value!"}});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),o.dirs.push(m);}let s=JSON.parse(Ae.readFileSync(r).toString());for(;!e.yes&&s.scripts&&s.scripts[e.script];){let m=await confirm({message:`The \`${P.cyan(e.script)}\` already exists overwrite?`,initialValue:!1});if(isCancel(m)&&(cancel("Canceled!"),process.exit(0)),m)break;{let R=await text({message:"What would you like to call the script?",placeholder:"build:registry",validate:M=>{if(M.trim().length===0)return "Please provide a value!"}});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),e.script=R;}}let i=s.devDependencies&&s.devDependencies.jsrepo!==void 0,a=e.yes||i;if(!e.yes&&!i){let m=await confirm({message:`Add ${fe} as a dev dependency?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),a=m;}let p=!n;if(!e.yes&&n){let m=await confirm({message:`Create a \`${P.cyan(Ue)}\` file?`,initialValue:!0});isCancel(m)&&(cancel("Canceled!"),process.exit(0)),p=m;}let c=(await detect$1({cwd:"cwd"}))?.agent??"npm",l="";if(a)l+="jsrepo build";else {let m=resolveCommand$1(c,"execute",["jsrepo","build"]);m||program.error(P.red(`Error resolving execute command for ${c}`)),l+=`${m.command} ${m.args.join(" ")} `;}p||(l+=` --dirs ${o.dirs.join(" ")} `),s.scripts===void 0&&(s.scripts={}),s.scripts[e.script]=l;let y=[];y.push({loadingMessage:`Adding \`${P.cyan(e.script)}\` to scripts in package.json`,completedMessage:`Added \`${P.cyan(e.script)}\` to scripts in package.json`,run:async()=>{try{Ae.writeFileSync(r,JSON.stringify(s,null," "));}catch(m){program.error(P.red(`Error writing to \`${P.bold(r)}\`. Error: ${m}`));}}}),p&&y.push({loadingMessage:`Writing config to \`${P.cyan(Ue)}\``,completedMessage:`Wrote config to \`${P.cyan(Ue)}\``,run:async()=>{let m=Q.join(e.cwd,Ue);try{Ae.writeFileSync(Q.join(m),JSON.stringify(o,null," "));}catch(R){program.error(P.red(`Error writing to \`${P.bold(m)}\`. Error: ${R}`));}}}),await xt(y,{});let u=i;if(a&&!i){let m=e.yes;if(!e.yes){let R=await confirm({message:"Install dependencies?",initialValue:!0});isCancel(R)&&(cancel("Canceled!"),process.exit(0)),m=R;}m&&(t.start(`Installing ${fe}`),(await Ne({pm:c,deps:["jsrepo"],dev:!0,cwd:e.cwd})).match(()=>t.stop(`Installed ${fe}.`),M=>{t.stop(`Failed to install ${fe}.`),program.error(M);}),u=!0);}let k=[];if(!u&&a){let m=resolveCommand$1(c,"install",["jsrepo","-D"]);k.push(`Install ${fe} as a dev dependency \`${P.cyan(`${m?.command} ${m?.args.join(" ")}`)}\``);}k.push(`Add categories to \`${P.cyan(o.dirs.join(", "))}\`.`);let x=resolveCommand$1(c,"run",[e.script]);k.push(`Run \`${P.cyan(`${x?.command} ${x?.args.join(" ")}`)}\` to build the registry.`),k=k.map((m,R)=>`${R+1}. ${m}`);let A=vt(k);process.stdout.write(A);};var hs=C.object({repo:C.optional(C.string()),allow:C.boolean(),debug:C.boolean(),verbose:C.boolean(),cwd:C.string()}),wr=new Command("test").description("Tests local blocks against most recent remote tests.").addArgument(new Argument("[blocks...]","The blocks you want to test.").default([])).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("--debug","Leaves the temp test file around for debugging upon failure.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(hs,t);ne(X.package.version),await ys(e,r),outro(P.green("All done!"));}),ys=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to test ${JSON.stringify(e)}`);let o=we(t.cwd).match(f=>f,f=>program.error(P.red(f))),n=spinner(),s=new Map,i=o.repos;if(t.repo&&(i=[t.repo]),!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Fetching blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.start(`Fetching blocks from ${P.cyan(i.join(", "))}`);for(let f of i){let g=(await st(f)).match(_=>_,_=>program.error(P.red(_))),E=await g.provider.fetchManifest(g);r(`Got info for provider ${P.cyan(g.name)}`),E.isErr()&&(t.verbose||n.stop(`Error fetching ${P.cyan(f)}`),program.error(P.red(`There was an error fetching the \`${ke}\` from the repository ${P.cyan(f)} make sure the target repository has a \`${ke}\` in its root?`)));let b=E.unwrap();for(let _ of b)for(let h of _.blocks)s.set(`${g.name}/${g.owner}/${g.repoName}/${_.name}/${h.name}`,{...h,sourceRepo:g});}r(`Retrieved blocks from ${P.cyan(i.join(", "))}`),t.verbose||n.stop(`Retrieved blocks from ${P.cyan(i.join(", "))}`);let a=Q.resolve(Q.join(t.cwd,`blocks-tests-temp-${Date.now()}`));r(`Trying to create the temp directory ${P.bold(a)}.`),Ae.mkdirSync(a,{recursive:!0});let p=()=>{Ae.rmSync(a,{recursive:!0,force:!0});},c=Ye(s,o,t.cwd).map(f=>f.specifier),l=e;e.length===0&&(l=c),l.length===0&&(p(),program.error(P.red("There were no blocks found in your project!")));let y=[];for(let f of l){let g;if(q.find(E=>f.startsWith(E.name()))){if(i.length===0){let[E,b,_,...h]=f.split("/"),S;h.length>2?S=`${E}/${b}/${_}/${h.slice(0,h.length-2).join("/")}`:S=`${E}/${b}/${_}`;let d=(await st(S)).match($=>$,$=>program.error(P.red($))),w=(await d.provider.fetchManifest(d)).match($=>$,$=>program.error(P.red($)));for(let $ of w)for(let v of $.blocks)s.set(`${d.name}/${d.owner}/${d.repoName}/${$.name}/${v.name}`,{...v,sourceRepo:d});}g=s.get(f);}else for(let E of i){let b=(await st(E)).unwrap(),_=s.get(`${b.name}/${b.owner}/${b.repoName}/${f}`);if(_!==void 0){g=_;break}}g||program.error(P.red(`Invalid block! ${P.bold(f)} does not exist!`)),y.push({name:f,block:g});}let u=$e(o.paths,t.cwd);u.isErr()&&program.error(P.red(u.unwrapErr()));let k=u.unwrap();for(let{block:f}of y){let g=f.sourceRepo,E=`${f.sourceRepo.url}/${f.category}/${f.name}`;if(t.verbose||n.start(`Setting up test file for ${P.cyan(E)}`),!f.tests){n.stop(`No tests found for ${P.cyan(E)}`);continue}let b;k[f.category]!==void 0?b=Q.join(t.cwd,k[f.category]):b=Q.join(t.cwd,k["*"],f.category),b=Q.relative(a,b);let _=async d=>{let w=await g.provider.fetchRaw(g,d);return w.isErr()&&(n.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${E}`))),w.unwrap()};r(`Downloading and copying test files for ${E}`);let h=[];for(let d of f.files.filter(w=>ue(w))){let w=await _(Q.join(f.directory,d)),$=Q.join(a,d);Ae.writeFileSync($,w),h.push($);}let S=new Project;for(let d of h){r(`Opening test file ${d}`);let w=S.addSourceFileAtPath(d);for(let $ of w.getImportDeclarations()){let v=$.getModuleSpecifierValue(),j;v.startsWith(".")&&(f.subdirectory?j=Q.join(b,f.name,v):j=Q.join(b,v)),j&&$.setModuleSpecifier(j.replaceAll(/\\/g,"/"));}}S.saveSync(),r(`Completed ${P.cyan.bold(E)} test file`),t.verbose||n.stop(`Completed setup for ${P.bold(E)}`);}r("Beginning testing");let x=await detect({cwd:t.cwd});x==null&&program.error(P.red("Could not detect package manager"));let A=resolveCommand(x.agent,"execute",["vitest","run",a]);A==null&&program.error(P.red(`Could not resolve add command for '${x.agent}'.`));let{command:m,args:R}=A,M=`${m} ${R.join(" ")}`,F=execa({cwd:t.cwd,stdio:["ignore","pipe","pipe"]})`${M}`,L=f=>console.info(f.toString());F.stdout.on("data",L),F.stderr.on("data",L);try{await F,p();}catch(f){t.debug?console.info(`${P.bold("--debug")} flag provided. Skipping cleanup. Run '${P.bold(M)}' to retry tests.
59
+ `):p(),program.error(P.red(`Tests failed! Error ${f}`));}};var Cs=C.object({all:C.boolean(),expand:C.boolean(),maxUnchanged:C.number(),repo:C.optional(C.string()),allow:C.boolean(),yes:C.boolean(),verbose:C.boolean(),cwd:C.string()}),kr=new Command("update").description("Update blocks to the code in the remote repository.").argument("[blocks...]","Names of the blocks you want to update. ex: (utils/math)").option("--all","Update all installed components.",!1).option("-E, --expand","Expands the diff so you see everything.",!1).option("--max-unchanged <number>","Maximum unchanged lines that will show without being collapsed.",e=>Number.parseInt(e),3).option("--repo <repo>","Repository to download the blocks from.").option("-A, --allow","Allow jsrepo to download code from the provided repo.",!1).option("-y, --yes","Skip confirmation prompt.",!1).option("--verbose","Include debug logs.",!1).option("--cwd <path>","The current working directory.",process.cwd()).action(async(e,t)=>{let r=C.parse(Cs,t);ne(X.package.version),await xs(e,r),outro(P.green("All done!"));}),xs=async(e,t)=>{let r=f=>{t.verbose&&console.info(`${ft} ${f}`);};r(`Attempting to update ${JSON.stringify(e)}`);let o=spinner(),n=we(t.cwd).match(f=>f,f=>program.error(P.red(f))),s=n.repos;t.repo&&(s=[t.repo]);for(let f of e)q.find(g=>f.startsWith(g.name()))&&program.error(P.red(`Invalid value provided for block names \`${P.bold(f)}\`. Block names are expected to be provided in the format of \`${P.bold("<category>/<name>")}\``));if(!t.allow&&t.repo){let f=await confirm({message:`Allow ${P.cyan("jsrepo")} to download and run code from ${P.cyan(t.repo)}?`,initialValue:!0});(isCancel(f)||!f)&&(cancel("Canceled!"),process.exit(0));}r(`Resolving ${P.cyan(s.join(", "))}`),t.verbose||o.start(`Fetching blocks from ${P.cyan(s.join(", "))}`);let i=(await Ke(...s)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed to get info for ${P.cyan(f)}`),program.error(P.red(g));});r(`Resolved ${P.cyan(s.join(", "))}`),r(`Fetching blocks from ${P.cyan(s.join(", "))}`);let a=(await qe(...i)).match(f=>f,({repo:f,message:g})=>{o.stop(`Failed fetching blocks from ${P.cyan(f)}`),program.error(P.red(g));});t.verbose||o.stop(`Retrieved blocks from ${P.cyan(s.join(", "))}`),r(`Retrieved blocks from ${P.cyan(s.join(", "))}`);let p=Ye(a,n,t.cwd);p.length===0&&program.error(P.red(`You haven't installed any blocks yet. Did you mean to \`${P.bold("add")}\`?`));let c=e;if(t.all&&(c=p.map(f=>f.specifier)),c.length===0){let f=await multiselect({message:"Which blocks would you like to update?",options:p.filter(g=>g.block.list).map(g=>({label:`${P.cyan(g.block.category)}/${g.block.name}`,value:g.specifier})),required:!0});isCancel(f)&&(cancel("Canceled!"),process.exit(0)),c=f;}r(`Preparing to update ${P.cyan(c.join(", "))}`);let l=(await it(c,a,i)).match(f=>f,program.error),y=(await detect({cwd:t.cwd}))?.agent??"npm",u=[],k=new Set,x=new Set,{prettierOptions:A,biomeOptions:m}=await ht({formatter:n.formatter,cwd:t.cwd}),R=$e(n.paths,t.cwd);R.isErr()&&program.error(P.red(R.unwrapErr()));let M=R.unwrap();for(let{block:f}of l){let g=`${f.sourceRepo.url}/${f.category}/${f.name}`,E=yt(X.package.version,f.sourceRepo.url),b=f.sourceRepo;r(`Attempting to add ${g}`);let _;M[f.category]!==void 0?_=Q.join(t.cwd,M[f.category]):_=Q.join(t.cwd,M["*"],f.category);let h=[],S=async d=>{let w=await b.provider.fetchRaw(b,d,{verbose:r});return w.isErr()&&(o.stop(P.red(`Error fetching ${P.bold(d)}`)),program.error(P.red(`There was an error trying to get ${g}`))),w.unwrap()};for(let d of f.files){if(!n.includeTests&&ue(d))continue;let w=Q.join(f.directory,d),$;f.subdirectory?$=Q.join(_,f.name,d):$=Q.join(_,d);let v=await S(w);Ae.mkdirSync($.slice(0,$.length-d.length),{recursive:!0}),h.push({content:v,destPath:$,fileName:d});}process.stdout.write(`${W}
60
60
  `),process.stdout.write(`${W} ${g}
61
61
  `);for(let d of h){let w=await Ut({file:d,biomeOptions:m,prettierOptions:A,config:n,imports:f._imports_,watermark:E,verbose:r,cwd:t.cwd});w.isErr()&&program.error(P.red(w.unwrapErr()));let $=w.unwrap(),v=t.yes;if(!t.yes){process.stdout.write(`${W}
62
62
  `);let j="";Ae.existsSync(d.destPath)&&(j=Ae.readFileSync(d.destPath).toString());let z=diffLines(j,$),ce=Q.join(`${b.name}/${b.owner}/${b.repoName}`,d.fileName),ye=Q.relative(t.cwd,d.destPath),N=Ht({from:ce,to:ye,changes:z,expand:t.expand,maxUnchanged:t.maxUnchanged,colorAdded:P.greenBright,colorRemoved:P.redBright,colorCharsAdded:P.bgGreenBright,colorCharsRemoved:P.bgRedBright,prefix:()=>`${W} `,onUnchanged:({from:B,to:ee,prefix:et})=>`${et?.()??""}${P.cyan(B)} \u2192 ${P.gray(ee)} ${P.gray("(unchanged)")}
63
63
  `,intro:({from:B,to:ee,changes:et,prefix:ze})=>{let br=et.filter(wo=>wo.added).length;return `${ze?.()??""}${P.cyan(B)} \u2192 ${P.gray(ee)} (${br} change${br===1?"":"s"})
64
64
  ${ze?.()??""}
65
- `}});if(process.stdout.write(N),z.length>1||j===""){let B=await confirm({message:"Accept changes?",initialValue:!0});isCancel(B)&&(cancel("Canceled!"),process.exit(0)),v=B;}}v&&await xt([{loadingMessage:`Writing changes to ${P.cyan(d.destPath)}`,completedMessage:`Wrote changes to ${P.cyan(d.destPath)}.`,run:async()=>Ae.writeFileSync(d.destPath,$)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&f.tests){r("Trying to include tests");let{devDependencies:d}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(d===void 0||d.vitest===void 0)&&k.add("vitest");}for(let d of f.devDependencies)k.add(d);for(let d of f.dependencies)x.add(d);}await xt(u,{verbose:t.verbose?r:void 0});let F=Dt(x,k,{cwd:t.cwd});if(x=F.dependencies,k=F.devDependencies,x.size>0||k.size>0){let f=t.yes;if(!t.yes){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),f=b;}f&&(x.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(x),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),k.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(k),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let g=[];if(!f){if(x.size>0){let b=resolveCommand(y,"install",[...x]);g.push(`Install dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(k.size>0){let b=resolveCommand(y,"install",[...k,"-D"]);g.push(`Install dev dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}g=g.map((b,_)=>`${_+1}. ${b}`),f||g.push(""),g.push("Import and use the blocks!");let E=vt(g);process.stdout.write(E);}};var go=e=>{let t=fileURLToPath(import.meta.url);return Q.join(t,"../..",e)},{version:ho,name:yo,description:vo,repository:Ps}=JSON.parse(Ae.readFileSync(go("package.json"),"utf-8")),X={package:{name:yo,description:vo,version:ho,repository:Ps},resolveRelativeToRoot:go};console.clear();program.name(yo).description(vo).version(ho).addCommand(ir).addCommand(lr).addCommand(pr).addCommand(fr).addCommand(gr).addCommand(yr).addCommand(wr).addCommand(kr);program.parse();export{X as context};
65
+ `}});if(process.stdout.write(N),z.length>1||j===""){let B=await confirm({message:"Accept changes?",initialValue:!0});isCancel(B)&&(cancel("Canceled!"),process.exit(0)),v=B;}}v&&await xt([{loadingMessage:`Writing changes to ${P.cyan(d.destPath)}`,completedMessage:`Wrote changes to ${P.cyan(d.destPath)}.`,run:async()=>Ae.writeFileSync(d.destPath,$)}],{verbose:t.verbose?r:void 0});}if(n.includeTests&&f.tests){r("Trying to include tests");let{devDependencies:d}=JSON.parse(Ae.readFileSync(Q.join(t.cwd,"package.json")).toString());(d===void 0||d.vitest===void 0)&&k.add("vitest");}for(let d of f.devDependencies)k.add(d);for(let d of f.dependencies)x.add(d);}await xt(u,{verbose:t.verbose?r:void 0});let F=Dt(x,k,{cwd:t.cwd});if(x=F.dependencies,k=F.devDependencies,x.size>0||k.size>0){let f=t.yes;if(!t.yes){let b=await confirm({message:"Would you like to install dependencies?",initialValue:!0});isCancel(b)&&(cancel("Canceled!"),process.exit(0)),f=b;}f&&(x.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(x),dev:!1,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dependencies"),program.error(b);})),k.size>0&&(t.verbose||o.start(`Installing dependencies with ${P.cyan(y)}`),(await Ne({pm:y,deps:Array.from(k),dev:!0,cwd:t.cwd})).match(b=>{t.verbose||o.stop(`Installed ${P.cyan(b.join(", "))}`);},b=>{t.verbose||o.stop("Failed to install dev dependencies"),program.error(b);})));let g=[];if(!f){if(x.size>0){let b=resolveCommand(y,"install",[...x]);g.push(`Install dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}if(k.size>0){let b=resolveCommand(y,"install",[...k,"-D"]);g.push(`Install dev dependencies \`${P.cyan(`${b?.command} ${b?.args.join(" ")}`)}\``);}}g=g.map((b,_)=>`${_+1}. ${b}`),f||g.push(""),g.push("Import and use the blocks!");let E=vt(g);process.stdout.write(E);}};var uo=e=>{let t=fileURLToPath(import.meta.url);return Q.join(t,"../..",e)},{version:go,name:ho,description:yo,repository:Ts}=JSON.parse(Ae.readFileSync(uo("package.json"),"utf-8")),X={package:{name:ho,description:yo,version:go,repository:Ts},resolveRelativeToRoot:uo},vo=program.name(ho).description(yo).version(go).addCommand(ir).addCommand(lr).addCommand(pr).addCommand(fr).addCommand(gr).addCommand(yr).addCommand(wr).addCommand(kr);console.clear();vo.parse();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "jsrepo",
3
3
  "description": "A CLI to add shared code from remote repositories.",
4
- "version": "1.23.2",
4
+ "version": "1.23.3",
5
5
  "license": "MIT",
6
6
  "homepage": "https://jsrepo.dev",
7
7
  "author": {
@@ -36,7 +36,7 @@
36
36
  "devDependencies": {
37
37
  "@biomejs/biome": "1.9.4",
38
38
  "@types/diff": "^6.0.0",
39
- "@types/node": "^22.10.3",
39
+ "@types/node": "^22.10.5",
40
40
  "@types/validate-npm-package-name": "^4.0.2",
41
41
  "tsup": "^8.3.5",
42
42
  "typescript": "^5.7.2",
@@ -62,7 +62,7 @@
62
62
  "parse5": "^7.2.1",
63
63
  "pathe": "^1.1.2",
64
64
  "prettier": "^3.4.2",
65
- "svelte": "^5.16.0",
65
+ "svelte": "^5.16.1",
66
66
  "ts-morph": "^25.0.0",
67
67
  "valibot": "^0.42.1",
68
68
  "validate-npm-package-name": "^6.0.0"
@@ -74,6 +74,7 @@
74
74
  "lint": "biome lint --write",
75
75
  "check": "biome check && tsc",
76
76
  "test": "vitest",
77
- "check:types": "tsc"
77
+ "check:types": "tsc",
78
+ "build:docs": "pnpm dlx tsx ./scripts/generate-docs.ts ../../sites/docs/static/docs/cli/llms.txt"
78
79
  }
79
80
  }