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