UNPKG

builda

Version:

The everything generator

62 lines (47 loc) 60.3 kB
#! /usr/bin/env node var Tt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import ri from"yargs";import oi from"chalk";var m={version:"5.2.3",buildaDir:".builda",websiteUrl:"https://www.builda.app",buildaReadmeFileName:"getting-started.md",repository:{type:"git",url:"git+https://github.com/spacenectar/builda"}};import Oo from"execa";import Wo from"inquirer";import Xt from"fs";import er from"path";import Ve from"process";import Ae from"chalk";var z=()=>console.log(Ae.magenta(` \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 ${Ae.white(`v${m.version} `)} \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2584\u2584\u2588\u2588\u2580 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2584 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2584 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2584\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580 \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 ${Ae.white.bold("The Everything Generator")} \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 `));import k from"chalk";import jt from"process";import Pt from"readline";var xr={interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},pe=jt.stdout,vr=jt.stderr,L,kr=(e,t,o)=>{let r=null;if(t&&t==="error"&&(L!==void 0&&clearInterval(L),r=k.red(`\u{1F6A8} ${e}`)),t&&t==="danger"&&(r=k.red(`${e}`)),t&&t==="warning"&&(r=k.yellow(`\u{1F514} ${e}`)),t&&t==="config"&&(r=k.blue(`\u{1F527} ${e}`)),t&&t==="downloading"&&(r=k.blue(`\u{1F30D} ${e}`)),t&&t==="copying"&&(r=k.blue(`\u{1F4C2} ${e}`)),t&&t==="installing"&&(r=k.blue(`\u{1F4E6} ${e}`)),t&&t==="notice"&&(r=k.blue(`\u{1F4DD} ${e}`)),t&&t==="info"&&(r=k.bgHex("#6699CC").white.bold(" i ")+" "+k.reset.blue(e)),t&&t==="success"&&(L!==void 0&&clearInterval(L),r=k.green(`\u2705 ${e}`)),t&&t==="watch"&&(r=k.magenta(`\u{1F440} ${e}`)),t&&t==="build"&&(r=k.magenta(`\u{1F3D7} ${e}`)),t&&t==="run"&&(r=k.magenta(`\u{1F3C3} ${e}`)),t&&t==="primary"&&(r=k.magenta(`${e}`)),t&&t==="secondary"&&(r=k.white(`${e}`)),t&&t==="processing"){let s=xr,n=s.frames,a=s.interval,c=0;L!==void 0&&clearInterval(L),L=setInterval(()=>{let f=n[c];f==null&&(c=0,f=n[c]),Pt.clearLine(pe,0),Pt.cursorTo(pe,0),pe.write(f),c=c>=n.length?0:c+1},a),r=k.blue(`${e}`)}return t||(r=e),o?r:(t==="error"?vr:pe).write(`${r} `)},p=kr;import Rr from"chalk";var Fe=["adorable","adventurous","aggressive","agreeable","alert","alive","amused","angry","annoyed","annoying","anxious","arrogant","ashamed","attractive","average","awful","bad","beautiful","better","bewildered","black","bloody","blue","blue-eyed","blushing","bored","brainy","brave","breakable","bright","busy","calm","careful","cautious","charming","cheerful","clean","clear","clever","cloudy","clumsy","colorful","combative","comfortable","concerned","condemned","confused","cooperative","courageous","crazy","creepy","crowded","cruel","curious","cute","dangerous","dark","dead","defeated","defiant","delightful","depressed","determined","different","difficult","disgusted","distinct","disturbed","dizzy","doubtful","drab","dull","eager","easy","elated","elegant","embarrassed","enchanting","encouraging","energetic","enthusiastic","envious","evil","excited","expensive","exuberant","fair","faithful","famous","fancy","fantastic","fierce","filthy","fine","foolish","fragile","frail","frantic","friendly","frightened","funny","gentle","gifted","glamorous","gleaming","glorious","good","gorgeous","graceful","grieving","grotesque","grumpy","handsome","happy","healthy","helpful","helpless","hilarious","homeless","homely","horrible","hungry","hurt","ill","important","impossible","inexpensive","innocent","inquisitive","itchy","jealous","jittery","jolly","joyous","kind","lazy","light","lively","lonely","long","lovely","lucky","magnificent","misty","modern","motionless","muddy","mushy","mysterious","nasty","naughty","nervous","nice","nutty","obedient","obnoxious","odd","old-fashioned","open","outrageous","outstanding","panicky","perfect","plain","pleasant","poised","poor","powerful","precious","prickly","proud","putrid","puzzled","quaint","real","relieved","repulsive","rich","scary","selfish","shiny","shy","silly","sleepy","smiling","smoggy","sore","sparkling","splendid","spotless","stormy","strange","stupid","successful","super","talented","tame","tasty","tender","tense","terrible","thankful","thoughtful","thoughtless","tired","tough","troubled","ugliest","ugly","uninterested","unsightly","unusual","upset","uptight","vast","victorious","vivacious","wandering","weary","wicked","wide-eyed","wild","witty","worried","worrisome","wrong","zany","zealous"],Ne=["Actor","Gold","Painting","Advertisement","Grass","Parrot","Afternoon","Greece","Pencil","Airport","Guitar","Piano","Ambulance","Hair","Pillow","Animal","Hamburger","Pizza","Answer","Helicopter","Planet","Apple","Helmet","Plastic","Army","Holiday","Portugal","Australia","Honey","Potato","Balloon","Horse","Queen","Banana","Hospital","Quill","Battery","House","Rain","Beach","Hydrogen","Rainbow","Beard","Ice","Raincoat","Bed","Insect","Refrigerator","Belgium","Insurance","Restaurant","Boy","Iron","River","Branch","Island","Rocket","Breakfast","Jackal","Room","Brother","Jelly","Rose","Camera","Jewellery","Russia","Candle","Jordan","Sandwich","Car","Juice","School","Caravan","Kangaroo","Scooter","Carpet","King","Shampoo","Cartoon","Kitchen","Shoe","China","Kite","Soccer","Church","Knife","Spoon","Crayon","Lamp","Stone","Crowd","Lawyer","Sugar","Daughter","Leather","Sweden","Death","Library","Teacher","Denmark","Lighter","Telephone","Diamond","Lion","Television","Dinner","Lizard","Tent","Disease","Lock","Thailand","Doctor","London","Tomato","Dog","Lunch","Toothbrush","Dream","Machine","Traffic","Dress","Magazine","Train","Easter","Magician","Truck","Egg","Manchester","Uganda","Eggplant","Market","Umbrella","Egypt","Match","Van","Elephant","Microphone","Vase","Energy","Monkey","Vegetable","Engine","Morning","Vulture","England","Motorcycle","Wall","Evening","Nail","Whale","Eye","Napkin","Window","Family","Needle","Wire","Finland","Nest","Xylophone","Fish","Nigeria","Yacht","Flag","Night","Yak","Flower","Notebook","Zebra","Football","Ocean","Zoo","Forest","Oil","Garden","Fountain","Orange","Gas","France","Oxygen","Girl","Furniture","Oyster","Glass","Garage","Ghost"];var $r=()=>{let e=Fe[Math.floor(Math.random()*Fe.length)],t=Ne[Math.floor(Math.random()*Ne.length)];return`${e.toLowerCase()}-${t.toLowerCase()}`},ue=$r;var Et={root:{root:"/"},tradeStore:{root:"trade-store",prefabs:"prefabs",blueprints:"blueprints"},docs:{root:"docs",gettingStarted:"getting-started",prefabs:"prefabs",config:"config-file",blueprints:"blueprints",telemetry:"telemetry",init:"initialise-a-project",resolvers:"resolvers",indexes:"indexes"}};var E=(e,t)=>{let{websiteUrl:o}=m,r=e.split("/"),i=Et,s=r[0]||"./",n=r.map(a=>{var c;return a===s?a:(c=i[s])==null?void 0:c[a]});return`${o}/${n.join("/")}${t?`#${t}`:""}`};var Tr=e=>e.startsWith("/")||e.startsWith("./")||e.startsWith("..")||e.startsWith("~")?"local":"remote",R=Tr;var At=e=>{let t=/^(?:[a-zA-Z:]+_[a-zA-Z:]+)+$/,o=/^(?:[A-Z]{1}[a-zA-Z:]+[A-Z]{1}[a-zA-Z:]+)+$/,r=/^(?:[a-z]{1}[a-zA-Z:]+[A-Z]{1}[a-zA-Z:]+)+$/,i=/^(?:[a-zA-Z:]+ [a-zA-Z:]+)+$/,s=/^(?:[a-zA-Z:]+-[a-zA-Z:]+)+$/;return t.test(e)?"snake":o.test(e)?"pascal":r.test(e)?"camel":i.test(e)?"sentence":s.test(e)?"kebab":"unknown"};var V=e=>e.replace(/\s{2,}/g," ").trim(),Ft=e=>{let t=At(e),o=e.split(/(?=[A-Z:])/).filter(i=>i!==":"),r=o.slice(1).map(i=>i.toLowerCase());if(t==="snake"){let i=e.replace(/_/g," ").toLowerCase().replace(/:/g," ");return V(i)}if(t==="pascal"){let i=e.split(/(?=[A-Z])/).map(s=>s.toLowerCase()).join(" ").replace(/:/g," ");return V(i)}if(t==="camel"){let i=o[0]||"";r.unshift(i.toLowerCase());let s=r.join(" ");return V(s)}if(t==="kebab"){let i=e.replace(/-/g," ").replace(/:/g," ").toLowerCase();return V(i)}return t==="sentence"?V(e.replace(/:/g,"")):e};var de=["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"],Pr=["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],Nt=["","","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"],fe=e=>{let t=/\d+/g,o=e.match(t);if(o){let r=o.map(i=>{let s=parseInt(i,10);if(s<10)return":"+de[s];if(s<20)return":"+Pr[s-10];if(s<100)return":"+Nt[Math.floor(s/10)]+de[s%10];if(s<1e3){let n=s%100===0,a=":"+de[Math.floor(s/100)]+":Hundred";return n||(a+=":And:"+Nt[Math.floor(s%100/10)]+":"+de[s%10]),a}if(s<1e6)return fe(Math.floor(s/1e3).toString())+":Thousand"+fe((s%1e3).toString());throw new Error("Numbers larger than 1 million are not supported")}).join(":");return e.replace(t,r)}return e};var Rt=e=>e.replace(/&/g,":And").replace(/@/g,":At").replace(/#/g,":Hash").replace(/\$/g,":Dollar").replace(/£/g,":Pound").replace(/%/g,":Percent").replace(/\+/g,":Plus").replace(/\*/g,":Asterisk");var jr=(e,t)=>t.startsWith("builda")||t.startsWith("run-s")||t.startsWith("run-p")||t.startsWith("npm-run-all")||t.startsWith("concurrently")?t:`builda x ${e}`,me=jr;var Cr=(e,t)=>{let r=Rt(e),i=fe(r),n=Ft(i).split(" ");switch(t){case"snakeCase":return n.join("_").toLowerCase();case"kebabCase":return n.join("-").toLowerCase();case"pascalCase":return n.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("");case"camelCase":return n.map((a,c)=>c===0?a.charAt(0).toLowerCase()+a.slice(1):a.charAt(0).toUpperCase()+a.slice(1)).join("");case"sentenceCase":default:return n.map((a,c)=>c===0?a.charAt(0).toUpperCase()+a.slice(1):a.charAt(0).toLowerCase()+a.slice(1)).join(" ")}},x=Cr;var j=({link:e,anchor:t,endText:o})=>(o=o||"for more information.",` See `+Rr.blue.underline(E(e,t))+" "+o);import J from"chalk";import Ir from"inquirer";var b=(e,t)=>{console.clear(),z();let o=new Ir.ui.BottomBar,r=process.stdout.columns;t=t||"info";let i="bgBlue",s="i";t==="error"&&(i="bgRed",s="\u2716"),t==="success"&&(i="bgGreen",s="\u2714"),t==="warning"&&(i="bgYellow",s="\u26A0"),t==="builda"&&(i="bgMagenta",s="B\u0333");let n=" "+J.bold.white[i](` ${s} `),a=" "+J[i](" ".repeat(5))+" "+J[i](" ".repeat(r-10))+` `,c=a+n+" "+J.bold.white[i](` ${t.toUpperCase()}${" ".repeat(r-t.length-12)} `)+a,f=J.white("\u2500".repeat(r)),d=e.replace(/\n/g,` `).replace(new RegExp(`(.{${r-20}})(\\s|$)`,"g"),`$1 `);o.log.write(` ${c}\r ${J.white(d)}\r ${f}\r `)};var l=e=>{let t=p(e,"danger",!0);throw new Error(t)};import Mr from"chalk";import It from"process";import Dr from"readline";var Lr=e=>new Promise(t=>{let o=Dr.createInterface({input:It.stdin,output:It.stdout});o.question(Mr.blue(`\u{1F914} ${e} [y/N] `),r=>{r=r.toLowerCase(),o.close(),t(r==="y")})}),q=Lr;import Or from"fs";var Wr=(e,t)=>Or.cpSync(e,t,{dereference:!0,recursive:!0,force:!0}),ge=Wr;import X from"fs";import Mt from"path";var Dt=(e,t)=>{X.existsSync(t)||X.mkdirSync(t,{recursive:!0}),X.readdirSync(e).forEach(o=>{let r=Mt.resolve(e,o),i=Mt.join(t,o);X.lstatSync(r).isDirectory()?Dt(r,i):X.cpSync(r,i,{recursive:!0,dereference:!0})})},ee=Dt;import Re from"fs";import Ie from"path";var Br=e=>{if(Re.existsSync(Ie.resolve(process.cwd(),"package.json"))){let r={...JSON.parse(Re.readFileSync(Ie.resolve(process.cwd(),"package.json"),"utf8")),builda:e===null?void 0:{...e}};Re.writeFileSync(Ie.resolve(process.cwd(),"package.json"),JSON.stringify(r,null,2))}else l("No package.json found in project")},M=Br;import Lt from"fs";var zr=async e=>{try{return Lt.existsSync(e)||Lt.mkdirSync(e,{recursive:!0}),!0}catch{return!1}},P=zr;import Ot from"fs";import Wt from"path";var Jr=e=>{if(Ot.existsSync(Wt.resolve(process.cwd(),"package.json"))){let o=JSON.parse(Ot.readFileSync(Wt.resolve(process.cwd(),"package.json"),"utf8")).builda;if(!o&&!e)l('No "builda" entry found in package.json');else if(!o&&e)return{};return o}return l("No package.json found in project")},$=Jr;import he from"fs";import U from"path";var qr=(e,t)=>{let o=[],i=he.readFileSync(e,"utf8").split(` `);for(let s of i)if(s!==""&&s.startsWith("@extends")){let n=s.split(" ")[1];if(he.existsSync(U.resolve(t,n))){let c=he.readFileSync(U.resolve(t,n),"utf8").split(` `);for(let f of c)if(f!==""&&!f.startsWith("#"))if(n!=null&&n.includes("/")){let u=n.split("/").pop(),d=n.replace(u,"");o.push(U.join(d,f))}else o.push(f)}else l(`File ${n} does not exist. Please check your .buildaignore file.`)}else if(s!==""&&s.startsWith("@"))l(`Invalid line in .buildaignore file: ${s}. Only @extends is allowed to start with @.`);else{if(s!==""&&s.startsWith("!"))continue;s!==""&&!s.startsWith("#")&&o.push(s)}return[...new Set(o)]},Ur=(e,t)=>{let o=[];for(let r of t){let i=U.join(e,r);r.includes("*")||(r.includes("/")?o.push(i):o.push(`**/${r}`))}return o},Gr=(e,t)=>{let o=t?"module":U.join(e,"modules","prefab"),r=U.resolve(o,".buildaignore");if(he.existsSync(r)){let i=qr(r,o);return Ur(o,i)}return[]},Me=Gr;import G from"path";import De from"fs";import Yr from"glob";var Le=async({log:e,name:t,paths:o,substitute:r,source:i,destination:s})=>{let{buildaDir:n}=m,a=G.join(n,"modules","prefab"),c={log:e,name:t,paths:o,substitute:r,source:i,destination:s},f=[];for(let u of o){let d=G.join(i,u);if(!Y(n,d))if(u.includes("*")){let h=Yr.sync(d).map(g=>G.relative(a,g));f.push(await Le({...c,paths:h}))}else if(De.lstatSync(d).isDirectory()){let g=De.readdirSync(d).map(w=>G.join(u,w));f.push(await Le({...c,paths:g}))}else f.push(new Promise(h=>{let g=G.dirname(u),w=G.join(s,g);if(!Y(n,d)){if(P(w),De.existsSync(d)){let y=r.map(v=>v.reverseInExport&&(w.includes("export")||w.includes("prefab"))?{...v,replace:v.with,with:v.replace}:v);O({file:d,outputDir:w,substitute:y,name:t})}h(d)}}))}await Promise.all(f)},I=Le;import Bt from"fs";import zt from"path";import _r from"prettier";var Hr=["css","html","js","jsx","json","less","md","mdx","scss","sass","ts","tsx","yaml","yml","graphql"],Zr=({file:e,rename:t,content:o,outputDir:r,substitute:i,name:s})=>{let n=e;t&&(n=t),n=n==null?void 0:n.split("/").pop();let a=e?Bt.readFileSync(zt.resolve(e),"utf8"):"",c=o??a;s&&(c=a.replace(/prefab-name-replace-string/g,x(s,"kebabCase")).replace(/%KEBAB_CASE%/g,x(s,"kebabCase")).replace(/%CAMEL_CASE%/g,x(s,"camelCase")).replace(/%SNAKE_CASE%/g,x(s,"snakeCase")).replace(/%PASCAL_CASE%/g,x(s,"pascalCase")).replace(/%SENTENCE_CASE%/g,x(s,"sentenceCase"))),i&&i.length>0&&i.forEach(u=>{let d=`${u.replace}`,h=new RegExp(d,"g");c=c.replace(h,u.with)});let f=n==null?void 0:n.split(".").pop();if(f&&Hr.includes(f)&&(c=e?_r.format(c,{filepath:zt.resolve(e)}):c),c)return Bt.writeFileSync(`${r}/${n}`,c);throw new Error(`Could not write file ${n}`)},O=Zr;import Jt from"fs";import Oe from"path";var{buildaDir:Qr}=m,te=async(e,t,o)=>{let r=Oe.join(t,Qr,"modules","prefab");e.forEach(async i=>{let s=Oe.join(r,i);Jt.cpSync(s,Oe.join(t,i),{recursive:!0}),o&&Jt.rmSync(s,{recursive:!0,force:!0})})};import we from"path";import Kr from"fs";import ye from"path";import be from"fs";var We=async()=>{if(be.existsSync(ye.resolve(process.cwd(),"package.json"))){let e=JSON.parse(be.readFileSync(ye.resolve(process.cwd(),"package.json"),"utf8")),o=JSON.parse(be.readFileSync(ye.resolve(process.cwd(),m.buildaDir,"modules","prefab","package.json"),"utf8")).scripts,r=e.scripts,i=Object.keys(r).filter(a=>!Object.keys(o).includes(a)),s={...o};i.forEach(a=>{s[a]=r[a]});let n={...e,scripts:s,dependencies:{...e.dependencies},devDependencies:e.devDependencies?{...e.devDependencies}:void 0,peerDependencies:e.peerDependencies?{...e.peerDependencies}:void 0};be.writeFileSync(ye.resolve(process.cwd(),m.buildaDir,"export","package.json"),JSON.stringify(n,null,2))}else l("No package.json found in project")},Be=We;var Vr=async({type:e,pathString:t})=>{var s,n;let o=process.cwd(),r=we.join(o,m.buildaDir,"export"),i=await T(r);if(e==="copy")return t==="package.json"?void 0:ge(`${o}/${t}`,we.join(r,t));if(e==="update"){if(t==="package.json")return We();let a=(n=(s=i.generatorOptions)==null?void 0:s.rootFiles)==null?void 0:n.find(c=>typeof c=="string"||!c.substitutions||c.substitutions.length===0?!1:c.path===t);if(a)await I({log:!0,name:i.name,paths:[t],substitute:a.substitutions,source:o,destination:r});else return ge(`${o}/${t}`,we.join(r,t))}if(e==="delete")return t==="package.json"&&l("package.json deleted. This will break your project"),Kr.rmSync(we.join(r,t),{recursive:!0,force:!0})},C=Vr;var Xr=(e,t)=>{let o=Me(e);for(let r of o)if(r.startsWith("**/")){let i=r.replace("**/",""),s=t.split("/").pop();if(i===s)return!0}else if(r===t)return!0;return!1},Y=Xr;import re from"fs";import qt from"path";async function eo({buildaDir:e,prefabDir:t}){re.existsSync(t)||l("No prefab found, cannot export");let o=qt.join(e,"export");p("Creating export path...","processing"),re.existsSync(o)&&re.rmSync(o,{recursive:!0}),ee(t,o),p("Export path created","success");let r=qt.join(o,".builda");re.existsSync(r)&&re.rmSync(r,{recursive:!0}),p("Initial export created","success")}var W=eo;import to from"fs";import ze from"path";async function ro({prefabPath:e,rootDir:t,prefabDir:o,name:r,buildaDir:i}){var c,f;let s;if(R(e)==="remote"){let u=N({registryPath:e}).url;u||l("No registry found"),s=await H(u,t)}else s=await _(e,t);s!=null&&s.name||l("No prefab found");let n=s.name,a=s.version;if(p(`Installed ${n}@${a}`,"success"),(f=(c=s==null?void 0:s.generatorOptions)==null?void 0:c.rootFiles)==null||f.forEach(async u=>{if(typeof u!="string"){let d=u.substitutions??[];await I({name:r,paths:[u.path],substitute:d,source:o,destination:o})}}),s.blueprints){p("Installing prefab blueprints...","installing");let u=[],d=Object.keys(s.blueprints);for(let h of d){let g=s.blueprints[h];p(`Installing blueprint: "${h}"`,"processing");let w=ze.join(t,i,"modules","blueprints");if(P(w),g.location==="prefab"){let y=ze.join(o,i,"modules","blueprints",h);to.existsSync(y)&&ee(y,ze.join(w,h))}else{let y=R(g.location);u.push(new Promise(v=>{if(y==="local"&&_(g.location,t),y==="remote"){let A=N({registryPath:g.location}).url;A||l("No registry found"),H(A,t)}v(h)}))}p(`${h} installed`,"success")}await Promise.all(u)}return p("Prefab has been set up.","success"),s}var oe=ro;import xe from"path";import Ut from"fs";import oo from"glob";var Je=async({log:e,paths:t,source:o})=>{let{buildaDir:r}=m,i=xe.join(r,"modules","prefab"),s={log:e,paths:t,source:o},n=[];for(let a of t){let c=xe.join(o,a);if(!Y(r,c))if(a.includes("*")){let f=oo.sync(c).map(u=>xe.relative(i,u));n.push(await Je({...s,paths:f}))}else if(Ut.lstatSync(c).isDirectory()){let u=Ut.readdirSync(c).map(d=>xe.join(a,d));n.push(await Je({...s,paths:u}))}else n.push(new Promise(f=>{f(c)}))}return Promise.all(n.flat())},qe=Je;import ve from"fs";import io from"tar";import so from"path";var no=async(e,t,o)=>{ve.existsSync(`${e}/${o}.tgz`)?(ve.copyFileSync(`${e}/${o}.tgz`,`${t}/${o}.tgz`),await io.extract({file:`${t}/${o}.tgz`,cwd:t}),ve.unlinkSync(`${t}/${o}.tgz`)):l("No tarball found. Please run `builda package` first")},ao=async(e,t)=>{let o=so.join(t||"./",m.buildaDir),r=await T(e),i=r.type==="blueprint"?`${o}/modules/blueprints/${r.name}`:`${o}/modules/prefab`;return await P(i),await no(e,i,"module"),ve.writeFileSync(`${i}/registry.json`,JSON.stringify(r)),r},_=ao;import ke from"fs";import fo from"path";import mo from"axios";import go from"tar";import lo from"fs";import co from"process";import po from"axios";var uo=async e=>{let t="registry.json";if(e=e||co.cwd(),R(e)==="local")return JSON.parse(lo.readFileSync(`${e}/${t}`,"utf8"));let r=N({registryPath:e});r.error&&l(r.error);let i=r.url;i.includes("%FILE_NAME%")?i=i.replace("%FILE_NAME%",t):i=`${i}/${t}`;let s=await B(i,!0);return s.status||l(s.message),po.get(i,{responseType:"json"}).then(n=>n.data).catch(n=>{l(n.message)})},T=uo;var ho=async(e,t)=>{let o=fo.join(t||"./",m.buildaDir),r=await T(e),i=r.type==="blueprint"?`${o}/modules/blueprints/${r.name}`:`${o}/modules/prefab`;return await P(i),p(`Downloading ${r.name}...`,"downloading"),await mo.get(`${e}/module.tgz`,{responseType:"arraybuffer",headers:{"Content-Type":"application/gzip"}}).then(s=>ke.writeFileSync(`${i}/module.tgz`,s.data,{encoding:"binary"})).then(async()=>{if(ke.existsSync(`${i}/module.tgz`)){p("Extracting module files...","config");try{await go.extract({file:`${i}/module.tgz`,cwd:i}),ke.unlinkSync(`${i}/module.tgz`)}catch(s){l(s)}}}).catch(s=>{l(`There was an error downloading the tarball. Please check the URL and try again. ${s}`)}).finally(()=>{p("Copying the registry file...","copying"),ke.writeFileSync(`${i}/registry.json`,JSON.stringify(r,null,2))}),p("Done.","success"),r},H=ho;var Gt={builda:"https://builda.app/modules/%REPO_NAME%",github:"https://raw.githubusercontent.com/%REPO_NAME%",bitbucket:"https://bitbucket.org/%REPO_NAME%/raw"};var bo=({resolver:e,modulePath:t,version:o,resolvers:r})=>{let i=r[e];if(!i)return"";let s=i;return s.includes("%REPO_NAME%")?s=s.replace("%REPO_NAME%",t):s=s.replace(`${e}`,""),s.includes("%VERSION%")?s=s.replace("%VERSION%",o):s=`${s}/${o||"latest"}`,s.endsWith("/")&&(s=s.slice(0,-1)),Ue(s)},Yt=bo;var wo=({registryPath:e,config:t})=>{var n;let o=e,r="",i=Gt;if(o.startsWith("http")||o.startsWith("https")){let a=o;return o.includes("github.com")&&(a=o.replace("github.com","raw.githubusercontent.com").replace("/blob","").replace("/tree","")),o.includes("bitbucket.org")&&(a=o.replace("src","raw")),a.endsWith("/")&&(a=a.slice(0,-1)),{url:a,error:r}}let s=o.match(/^([a-z]+:{1}[/]{0})([a-z0-9-/]+)((?:@{1}v?[0-9.]+)?(?:[\w\d-]*))?$/);if(s){let a=((n=s[1])==null?void 0:n.replace(":",""))||"",c=s[2]||"",f=s[3]?s[3].replace("@",""):"latest";t!=null&&t.resolvers&&(i={...i,...t.resolvers});let u=Yt({resolver:a,modulePath:c,version:f,resolvers:i});return u||(r=`Could not find a resolver for ${o}`),{url:u,error:r}}else return r='Paths must start with a colon terminated lowercase string with no spaces or special characters (e.g. "builda:" or "([a-z]+:{1}[/]{0})" ) if using a resolver or "http(s)" if using a url',{url:"",error:r}},N=wo;import xo from"fs";import vo from"path";import ko from"process";var $o=(e,t,o)=>{if(t){let r=`${e}s`,i=vo.resolve(ko.cwd(),`${m.buildaDir}/modules/${r}/${o.use}`),s=JSON.parse(xo.readFileSync(`${i}/registry.json`,"utf8"));return{path:i,registry:s}}throw new Error("Could not find config file")},Ge=$o;var So=({name:e,registry:t,script:o})=>{var s,n;let r=[],i=o!=null&&o.substitute&&((s=o.substitute)==null?void 0:s.length)>0?o==null?void 0:o.substitute:(n=t==null?void 0:t.generatorOptions)==null?void 0:n.substitutions;return i&&i.length&&i.forEach(a=>{var h;let c=a.with==="script"?e:a.with,f=(a==null?void 0:a.replace)||a.replace,d=(a==null?void 0:a.with)||c||"";!c&&!f&&a.required&&l(`"--${a.replace}" missing in arguments. This is required. `),d&&!f&&r.push({replace:f.toUpperCase(),with:d}),f&&(d===""&&l(`"--${a.replace}" requires a value`),a.valid&&d!==""&&!((h=a.valid)!=null&&h.includes(d))&&l(` "${d}" is not a valid ${a.replace}. Please use one of the following: - ${a.valid.join(` - `)} `),r.push({replace:a.replace.toUpperCase(),with:d}))}),r},Ye=So;import Po from"axios";import jo from"ajv";var _t={$schema:"http://json-schema.org/draft-07/schema#",definitions:{ModuleConfig:{additionalProperties:{$ref:"#/definitions/ModuleConfigContents"},type:"object"},ModuleConfigContents:{additionalProperties:!1,properties:{location:{description:"The location of the module. This can be a local path, a remote url, a resolver or 'prefab' (if preinstalled inside a prefab)",type:"string"},outputDir:{description:"If the module should have a custom output directory, specify it here (relative to the app_root)",type:"string"},resolve:{anyOf:[{type:"string"},{additionalProperties:!1,properties:{type:{type:"string"},url:{type:"string"}},required:["url","type"],type:"object"}],description:"The custom resolver to use for the module"},version:{description:"The version of the module (not required for blueprints preinstalled inside a prefab)",type:"string"}},required:["location"],type:"object"},ModuleRegistry:{additionalProperties:!1,description:"See (https://builda.app/docs/build-a-module/registry) for more info",properties:{author:{additionalProperties:!1,description:"The module author's details",properties:{buildaUser:{description:"The builda username of the author. This is optional but is required if you want to publish your module to the builda trade store (see (https://builda.app/docs/trade-store))",type:"string"},email:{description:"The author's email",type:"string"},name:{description:"The author's name",type:"string"},website:{description:"The author's website",type:"string"}},required:["name"],type:"object"},blueprints:{$ref:"#/definitions/ModuleConfig",description:"If the module is a prefab and requires blueprints or has it's own blueprints, you should add them here if the module is a blueprint, this field is ignored",examples:["github:cool-developer/blueprint-cool-module@3.0.0","internal:blueprint-name"]},funding:{description:"Is this module looking for funding? If so, you can add a list of funding links here.",items:{type:"string"},type:"array"},generatorOptions:{additionalProperties:!1,description:"A set of options which will be passed to the module generator when the module has been installed",properties:{extraFolders:{description:"Extra folders which should be created in the module root when the module is installed (Will create any folders which don't already exist in the tree)",items:{type:"string"},type:"array"},substitutions:{additionalProperties:!1,description:"A set of substitutions which should be made in the module files when the module is installed",type:"array",items:{$ref:"#/definitions/TSubstitution"}},postScripts:{description:"Any post install scripts which should be run after the module has been installed and all files have been copied across and substitutions made (script paths are relative to the module root and should be in the form of a node cli script)",items:{type:"string"},type:"array"},rootFiles:{description:"Any files which should be copied to the module root when the module is installed in addition to the default files (see (https://builda.app/docs/build-a-module/prefabs#root-files)) e.g. .env files",items:{type:"string"},type:"array"}},type:"object"},keywords:{description:"The module keywords (optional but recommended if you want to publish your module to the builda trade store)",items:{type:"string"},type:"array"},name:{description:"The name of the module",type:"string"},prerelease:{default:!1,description:"If this is a prerelease, set this to true",type:"boolean"},publishToTradeStore:{default:!1,description:"Do you want to publish this module to the builda trade store? (see (https://builda.app/docs/trade-store))",type:"boolean"},type:{description:"The module type",enum:["blueprint","prefab"],type:"string"},url:{description:"The url of the module (generally a git repository) You can also use resolver aliases here. See (https://builda.app/docs/resolvers)",type:"string"},version:{description:"The module version number (in semver format)",pattern:"^\\d+\\.\\d+\\.\\d+$",type:"string"}},required:["name","type","version","url"],type:"object"},RootFile:{additionalProperties:!1,properties:{path:{description:"The path to the root file (relative to the .builda/export directory)",type:"string"},rewrite:{default:!1,description:"Should the file contents be rewritten with the default substitutions? https://builda.app/docs/build-a-module/substitutions",type:"boolean"},substitutions:{description:"Are there any custom substitutions to be made? see (https://builda.app/docs/build-a-module/substitutions)",items:{$ref:"#/definitions/TSubstitution"},type:"array"}},required:["path","substitutions"],type:"object"},TSubstitution:{additionalProperties:!1,properties:{replace:{description:"The string to be replaced",pattern:"^%[A-Z_]+%$",type:"string"},required:{default:!1,description:"Is this substitution required? (i.e. if it is not found, should the build fail?)",type:"boolean"},valid:{description:"Do you want to provide a list of valid options for this substitution? (i.e. if it is not found, should the build fail?)",items:{type:"string"},type:"array"},with:{description:"The string to replace with",type:"string"}},required:["replace","with"],type:"object"}}};var Co=new jo,B=async(e,t)=>{let o=e;if(!t){let i=N({registryPath:e});if(i.error)return{status:!1,message:i.error};o=i.url}let r=o.includes("registry.json")?o:`${o}/registry.json`;return Po.get(r).then(i=>{var a;if(!i.data)return{status:!1,message:"Something went wrong while fetching the registry. No data was returned and no error was provided."};let s=Co.compile(_t);return s(i.data)?{status:!0,message:"Registry fetched successfully"}:((a=s.errors)==null||a.forEach(c=>{console.log(`Registry validation error: ${c.message}`)}),{status:!1,message:"The registry file is not valid. Please check the documentation for the correct format."})}).catch(i=>i.code==="ENOTFOUND"||i.code==="ERR_BAD_REQUEST"?{status:!1,message:"The url must point to a folder that contains a registry.json file"}:i.code==="ECONNREFUSED"?{status:!1,message:`The server at ${r} is not responding are you sure it is correct?`}:{status:!1,message:i.message})};import Ao from"inquirer";import _e from"chalk";var Ht=[{name:"Test Blueprint",value:"github:builda-modules/blueprint-test"},{name:"Fake blueprint",value:""},{name:"Another fake blueprint",value:""},{name:"Yet another fake blueprint",value:""}];var Zt=async(e,t)=>{let o=await B(e);if(o.status){if(t.prefabRegistry){let i=t.prefabRegistry.blueprints;return i&&i[e]?{status:!1,message:"A blueprint with that name already exists"}:{status:!0,message:""}}return{status:!0,message:""}}return{status:!1,message:o.message||"Could not validate the blueprint"}},He=async e=>(b(`These questions are all about adding blueprints to your project.\r If you're not sure what a blueprint is`+j({link:"docs/blueprints"})),Ao.prompt([{type:"confirm",name:"addBlueprints",message:()=>{let t=[],o=e.prefabRegistry,r=o==null?void 0:o.blueprints;return e.prefab&&r&&(t=Object.keys(r),b(`You are generating this project from the ${_e.blue(o.name)} prefab. It comes with the following blueprints: `+t.map(i=>_e.blue(i)).join(` `)+` Ensure that any additional blueprints you add are compatible with this prefab.`,"warning")),`Do you want to add any${t.length?"additional":""} blueprints to your project?`},default:!0},{type:"list",name:"blueprintChoice",message:"Do you have url(s) for your blueprint(s) or do you want to choose from a list?",choices:[{name:"I have url(s)",value:"url"},{name:"I want to choose from a list (coming soon)",value:"list",disabled:"This option is not available yet"}]},{type:"input",name:"blueprintUrls",message:"Enter the blueprint url(s) (if adding more than one, please separate them with a space):",when:t=>t.blueprintChoice==="url",validate:async t=>{if(!t)return"You must enter at least one url";let o=t.split(" ");for(let r of o){let i=await Zt(r,e);if(!i.status)return`The module at ${r} returned an error: ${i.message}`}return!0}},{type:"checkbox",name:"blueprintList",message:()=>(b("This list is not exhaustive. You can find more blueprints at "+_e.blue.underline(E("tradeStore/blueprints"))),"Choose your blueprints:"),choices:Ht,when:t=>t.blueprintChoice==="list",validate:async t=>{if(!t.length)return"You must choose at least one blueprint";for(let o of t){let r=await Zt(o,e);if(!r.status)return`The module at ${o} returned an error: ${r.message}`}return!0}}]));import $e from"fs";import Fo from"inquirer";import Qt from"chalk";var Ze=async()=>{let e=()=>{try{return JSON.parse($e.readFileSync("package.json","utf8"))}catch{return""}};e()||(b("You must have a package.json file in the root of your project to add to an existing project.","error"),process.exit(1));let{name:t}=e(),r=(()=>!!($e.existsSync("lerna.json")||e().workspaces))(),s=(()=>$e.existsSync("yarn.lock")?"yarn":$e.existsSync("package-lock.json")?"npm":"unknown")();return Fo.prompt([{type:"input",name:"projectName",message:`We think your project is called ${Qt.bold.magenta(t)}. Press enter if correct? If not, enter the correct name here.`,default:t},{type:"input",name:"appRoot",message:()=>(b(`The app root is the directory where your app files are stored. This is usually your current working directory but if you are using a monorepo or if you'd like to store your app files in a different directory, you can specify it here it here. If you're not sure, just press enter to use the current working directory.`),`We think your app root ${r?"may be in a monorepo, please enter the package name. If it is not a monorepo, just press enter to use ./ or specify the directory your app is store in":"is ./"}`),default:"./"},{type:"list",name:"packageManager",message:()=>(b("Builda works with both npm and yarn. If you are using a different package manager, unfortunately, Builda may not work for you."),"We think you are using "+Qt.bold.magenta(s)+". Press enter if correct? If not, select the correct package manager."),choices:["npm","yarn"],default:s}])};import No from"inquirer";import Ro from"chalk";var Qe=async e=>{let t=ue();return e&&b(`Great! That prefab is ready to install! First things first though, we need a few more details, to get you set up.`,"success"),No.prompt([{type:"input",name:"appName",required:!0,message:`What do you want to call your project? This will also be the folder name we will create for your app. (If you don't know, just press enter to use ${Ro.bold.magenta(t)})`,default:t}])};import Mo from"inquirer";import Se from"chalk";var Kt=[{name:"Test Prefab",value:"github:builda-modules/prefab-test"},{name:"Fake prefab",value:""},{name:"Another fake prefab",value:""},{name:"Yet another fake prefab",value:""}];var Ke=async()=>(b(`These questions are all about building a project from a prefab. If you're not sure what a prefab is, visit `+Se.blue.underline(E("docs/prefabs"))+Se.white(" for more information.")),Mo.prompt([{type:"list",name:"prefabChoice",message:"Do you have a prefab url or do you want to choose from a list?",choices:[{name:"I have a url",value:"url"},{name:"I want to choose from a list (coming soon)",value:"list",disabled:"This option is not available yet"}]},{type:"input",name:"prefabUrl",message:()=>(b("The url should point to the folder that the prefabs registry.json file is in. It can be a regular link or use a resolver."+j({link:"docs/resolvers"})),"Enter the prefab url:"),when:e=>e.prefabChoice==="url",validate:async e=>{if(!e)return"You must enter a url";let t=await B(e);return t.status!==!0&&Se.red(t.message),t.status}},{type:"list",name:"prefabList",message:()=>(b("This list is not exhaustive. You can find more prefabs at "+Se.blue.underline(E("tradeStore/prefabs"))),"Choose a prefab:"),choices:Kt,when:e=>e.prefabChoice==="list"}]));var Do=e=>e.startsWith("http")||e.startsWith("https")?e:`https://${e}`,Ue=Do;import Lo from"axios";import ie from"fs";import se from"path";async function Vt({module:e,rootDir:t,prefabDir:o,name:r,buildaDir:i,websiteUrl:s,buildaReadmeFileName:n}){var y,v,A,F;let a=se.join(t,i,"export");ie.existsSync(a)||l("No export directory found"),(v=(y=e==null?void 0:e.generatorOptions)==null?void 0:y.rootFiles)==null||v.forEach(async S=>{if(typeof S=="string")te([S],t);else{let K=S.substitutions??[];await I({log:!0,name:r,paths:[S.path],substitute:K,source:o.replace(`${t}/`,""),destination:t})}}),(F=(A=e==null?void 0:e.generatorOptions)==null?void 0:A.extraFolders)==null||F.forEach(async S=>{ie.mkdirSync(se.join(t,S),{recursive:!0}),ie.writeFileSync(se.join(t,S,".gitkeep"),"")});let c=ie.readFileSync(se.resolve(o,"package.json"),{encoding:"utf8"}),f=JSON.parse(c),u={...f,name:x(r,"kebabCase")},d=f.scripts,h={};Object.entries(d).forEach(([S,K])=>{h[S]=me(S,K)}),u.scripts=h,ie.writeFileSync(se.join(t,"package.json"),JSON.stringify(u,null,2));let g=`${s}/assets/prefab-getting-started.md`,w=[{replace:"%PREFAB_NAME%",with:e.name},{replace:"%PREFAB_URL%",with:e.url},{replace:"%PREFAB_VERSION%",with:e.version}];return await Lo.get(g,{headers:{"Content-Type":"text/plain"}}).then(S=>{S.status===200&&O({content:S.data,rename:n,outputDir:t,substitute:w})}).catch(S=>{console.log(S),p(`Could not download the getting started file. Visit ${s}/docs/getting-started#prefab for assistance`,"warning")}),p("All files copied to application.","success"),e}var ne=async({appName:e,prefab:t,smokeTest:o})=>{let{buildaDir:r,websiteUrl:i,buildaReadmeFileName:s}=m;z();let n={};if(!t){let{usePrefab:g}=await Wo.prompt([{type:"confirm",name:"usePrefab",message:"Do you want to set the project up using a prefab?",default:!0}]);if(g){let w=await Ke();n.prefab=w.prefabUrl||w.prefabList}else b(`You can set up a project from scratch by answering a few questions about your project.\r If you are unsure about any of these, you can always change them later by editing the 'builda' section of your package.json file.`);n.prefab&&b(`Great! That prefab is ready to install! First things first though, we need a few more details, to get you set up.`,"success")}let a={};(!t||!e)&&(a=await Qe()),n={...n,...a};let c=e||n.appName,f=t||n.prefab,u=x(c,"kebabCase"),d=er.join(Ve.cwd(),u);await P(u),Ve.chdir(u);let h=er.join(d,r,"modules","prefab");if(Xt.readdirSync(d).length!==0&&l(`The directory: '${u}' already exists. It is not recommended to install a prefab into an existing project.`),f){let g=await oe({prefabPath:f,rootDir:d,prefabDir:h,name:c,buildaDir:r});await W({buildaDir:r,prefabDir:h}),await Vt({module:g,rootDir:d,prefabDir:h,name:c,buildaDir:r,websiteUrl:i,buildaReadmeFileName:s})}p(`Your application, "${c}" has been initialised!`,"success"),o?(Ve.chdir("../"),Xt.rm(c,{recursive:!0,force:!0},g=>{g&&console.log(g),p("This was a smoke test. No files were created.","primary")})):(Oo("cd",[c]),p(`For more information about how to use your application, visit: ${i}/docs/getting-started`,"primary"))};var Xe=()=>({command:"project [appName]",desc:"Generate a new app from a prefab",aliases:["app","--app","--project"],builder:e=>e.positional("appName",{describe:"The name of the app",type:"string",default:""}).option("prefab",{alias:"p",default:"",describe:"The prefab to use (url, local path, or preset name)",type:"string"}).option("smokeTest",{alias:"s",default:!1,describe:"Runs the command but deletes the output immediately",type:"boolean"}),handler:async e=>{let t={appName:e.appName,prefab:e.prefab,smokeTest:e.smokeTest};await ne({...t})}});import tr from"chalk";import Te from"process";import Z from"path";import ae from"fs";import Bo from"execa";var et=async({command:e,args:t})=>{var f;let o=Te.cwd(),r=Z.join(Te.cwd(),m.buildaDir,"export");o.split("/").pop()==="export"&&(r=o);let i=ae.readFileSync(Z.resolve(r,"package.json"),{encoding:"utf8"}),a=JSON.parse(i).scripts[e],c="";ae.existsSync(Z.resolve(o,"yarn.lock"))&&ae.existsSync(Z.resolve(o,"package-lock.json"))?l("Builda detected a yarn.lock file and a package-lock.json file. Please delete one of these files and try again"):ae.existsSync(Z.resolve(o,"yarn.lock"))?c="yarn":ae.existsSync(Z.resolve(o,"package-lock.json"))?c="npm":l("Builda could not detect a yarn.lock or package-lock.json file. Please run `yarn` or `npm install` and try again"),a||l(`No script found with the name '${e}'`),r||l(`No path found for script '${e}'`),e||l("No command found");try{let u=`${c} run ${e}`;if(t){let d=Object.keys(t),h=Object.values(t),g=d.reduce((w,y,v)=>{let A=h[v],F="";return y==="_"||y==="command"||y==="$0"?w:(y.length===1?F=`-${y}`:F=`--${y}`,A&&typeof A=="boolean"?` ${w} ${F}`:` ${w} ${F}="${A}"`)},"");u=`${u}${g}`}Te.stdout.write(tr.magenta("Running with Builda: ")+tr.white.bold(`'${u}'`)+` `),(f=Bo.command(u,{cwd:r,stdio:"inherit"}).stdout)==null||f.pipe(Te.stdout)}catch(u){l(u.message)}};var tt=()=>({command:"execute <command>",desc:"Execute a command from within the export directory",aliases:["x","exec"],builder:e=>e.positional("command",{describe:"The name of the command",type:"string",demandOption:!0}),handler:async e=>et({command:e.command,args:e})});import Pe from"process";import rr from"fs";var rt=async({pathString:e})=>{var i;let t=$();e||l("A path must be provided"),(i=t.ejected)!=null&&i.includes(e)&&l(`${e} has already been ejected.`);let o=e.replace(`${Pe.cwd()}/`,""),r=`${Pe.cwd()}/.builda/export/${o}`;try{rr.existsSync(r)||l(`No file found at ${r}.`),p(`Moving ${o} to application...`,"info"),te([o],Pe.cwd()),p(`Deleting original from ${r}`,"info"),rr.rmSync(r,{recursive:!0,force:!0});let s=e.replace(`${Pe.cwd()}/`,""),n=t.ejected??[];n.push(s);let a={...t,ejected:n};M(a),p(`Ejected ${e}. You can now edit this file directly.`,"success")}catch(s){l(s.message)}};var ot=()=>({command:"eject <pathString>",desc:"Eject a file or directory from builda to make it editable",builder:e=>e.positional("pathString",{describe:"The path to the file or directory to eject",type:"string",demandOption:!0}).option("configPath",{aliases:["c","config"],default:"",describe:"The path to a config file",type:"string"}),handler:async e=>rt({pathString:e.pathString})});import it from"fs";import je from"path";var Q=async e=>{var h;let{buildaDir:t}=m,o=process.cwd(),r=je.join(o,t),i,s;it.existsSync(je.resolve(process.cwd(),"package.json"))&&(i=JSON.parse(it.readFileSync(je.resolve(process.cwd(),"package.json"),"utf8")),s=i.builda,s||l('No "builda" entry found in package.json'));let n=i.name;it.existsSync(t)&&!e&&(p("A .builda directory already exists. The directory will be deleted and rebuilt from the prefab.","warning"),await q("Do you wish to proceed?")||(p("Installation aborted","error"),process.exit(1))),e?p(`Updating ${n}`,"installing"):p(`Installing ${n}`,"installing");let a=`${(h=s.prefab)==null?void 0:h.location}`,c=je.join(r,"modules","prefab");await oe({prefabPath:a,rootDir:o,prefabDir:c,name:n,buildaDir:t}),await W({buildaDir:t,prefabDir:c}),await Be();let f=await T(c),u=f.name.replace("prefab-",""),d=f.version;e?p(`${u}, been updated to v${d}`,"success"):p(`${u}, v${d} has been installed`,"success")};var st=()=>({command:"install",desc:"Installs the applications prefab and builds the export directory",builder:e=>e.option("configPath",{aliases:["c","config"],default:"",describe:"The path to a config file",type:"string"}),handler:async()=>Q()});import zo from"path";import Jo from"process";var le=async({modulePath:e,fromScript:t})=>{var a;let o={},r=$(),i=Jo.cwd(),s=zo.join(i,m.buildaDir,"modules"),n=e.includes(" ")?e.split(" "):[e];await P(s);for(let c of n){if(R(c)==="remote"){let f=N({registryPath:c}).url;f||l("No registry found"),o=await H(f)}else o=await _(c);if(!t)if(o!=null&&o.name){let f=o.type,u=o.name,d=o.version;f==="blueprint"&&(r!=null&&r.blueprints||(r.blueprints={}),(a=r==null?void 0:r.blueprints)!=null&&a[u]?l(`A blueprint called ${u} already exists. Perhaps you meant 'builda update ${u}?'`):r.blueprints[u]={version:d,location:c}),f==="prefab"&&l("You cannot add a prefab as a module. A prefab is used to set up a new project. Try 'builda project' instead."),M(r),p(`Added ${u} to your project`,"success")}else l("Something went wrong")}};var{websiteUrl:qo}=m,nt=()=>({command:"add <blueprintPath>",desc:"Adds a new blueprint",builder:e=>e.positional("blueprintPath",{describe:`The path to the blueprint (can be a resolver - see http://${qo}/docs/resolvers)`,type:"string",demandOption:!0}).option("configPath",{aliases:["c","config"],default:"",describe:"The path to a config file",type:"string"}),handler:async e=>le({modulePath:e.blueprintPath})});import D from"fs";import Go from"tar";import Uo from"fs";var or=(e,t)=>Uo.existsSync(e)?{error:!1,message:""}:{error:!0,message:`Cannot find ${t&&"a folder called"} '${e}' in the current directory.`};var ce=async e=>{let t=await T(),{name:o,type:r,version:i}=t,s="registry.json",n="module",a=[];if(D.existsSync(".npmignore")){let w=D.readFileSync(".npmignore","utf8").split(` `).filter(y=>y!==""&&!y.startsWith("#")&&!y.startsWith("!"));a.push(...w)}if(D.existsSync(`${n}/.gitignore`)){let w=D.readFileSync(`${n}/.gitignore`,"utf8").split(` `).filter(y=>y!==""&&!y.startsWith("#")&&!y.startsWith("!"));a.push(...w)}a.includes(".builda")&&a.splice(a.indexOf(".builda"),1),t||l(`No ${s} file found. See ${j({link:"docs/packaging"})} for more information.`),o||l(`No name entry found in ${s}. Please add one.\r`),r||l(`No type entry found in ${s}. Please add one.\r`),!i&&!e&&l(`No version entry found in ${s}. Please add one.\r`);let c=or(n,!0);c.error&&l(c.message),o.startsWith(`${r}-`)||l(`The name entry in ${s} must be prefixed with ${r}-.\r`),p("All checks passed.","success");let u=(e==null?void 0:e.replace("v",""))||i,d={...t,version:u},h=JSON.stringify(d,null,2);if(D.writeFileSync(s,h),D.existsSync(`${n}.tgz`)){if(p("A module package already exists. Do you want to overwrite it?","warning"),!await q("Overwrite?")){p("Package process aborted","error");return}D.unlinkSync(`${n}.tgz`)}p(`Packaging ${o}...`,"processing"),await Go.create({file:`${n}.tgz`,gzip:!0,cwd:n,filter:g=>!a.includes(g)},D.readdirSync(n)),p("Package created","success")};var at=()=>({command:"package",desc:"Package a module ready for publishing",aliases:["package","pack"],handler:async()=>ce()});import nr from"fs";import{simpleGit as _o}from"simple-git";var ir=async()=>!0;import Yo from"fs";var sr=(e,t)=>Yo.existsSync(e)?{error:!1,message:""}:{error:!0,message:`Cannot find ${t&&"a folder called"} '${e}' in the current directory.`};var lt=async e=>{let t=await T(),{name:o,type:r,version:i,publishToTradeStore:s}=t,n="registry.json",a="README.md",c="module.tgz";t||l(`No ${n} file found. Publish can only be ran in the context of a module`),o||l(`No name entry found in ${n}. Please add one.\r`),r||l(`No type entry found in ${n}. Please add one.\r`),!i&&!e&&l(`No version entry found in ${n}. Please add one.\r`),s||p(`No tradeStore entry found in ${n}. This module will not be published to the Builda Trade Store (https://builda.app/trade-store).\r`,"info"),nr.existsSync(c)||(p("No module package found. Building package...","processing"),await ce(e),p("Package built","success")),o.startsWith(`${r}-`)||l(`The name entry in ${n} must be prefixed with ${r}-.\r`);let u=sr(a);u.error&&l(u.message);let d=_o();d.checkIsRepo()||l("This is not a git repository. Please initialise git and try again.\r"),(await d.status()).isClean()||l("The git repository is not clean. Please commit all changes and try again.\r"),p("All checks passed.","success");let g=(e==null?void 0:e.replace("v",""))||i,w={...t,version:g},y=JSON.stringify(w,null,2);nr.writeFileSync(n,y),p(`Adding ${c} to git...`,"processing"),await d.add(`${c}`),await d.commit(`Adds updated ${c}`),p("Added to git","success"),p("Tagging the latest commit...","processing");let v=await d.tags();(v.all.includes(g)||v.all.includes(`v${g}`))&&l(`A tag with the version number v${g} already exists. Please update the version number in ${n} and try again.\r`),await d.addTag(`v${g}`);let F="tags";if(t.prerelease)p("Prerelease entry found in registry.json. Skipping latest tag...","info"),F="tag";else{let K=(await d.listRemote(["--tags"])).includes("refs/tags/latest"),wr=(await d.tags()).all.includes("latest");(K||wr)&&(await d.tag(["--delete","latest"]),await d.push(["origin","--delete","latest"])),await d.addTag("latest")}await d.pushTags("origin"),p(`${F} created.`,"success"),p("Pushing changes to git...","processing"),await d.push(),p("Changes pushed to git.","success"),s&&(p("Publishing to the Builda Trade Store...","processing"),ir()),p("Module published.","success")};var ct=()=>({command:"publish",desc:"publish a module",aliases:["pub","push"],builder:e=>e.option("version",{aliases:["v","ver"],default:"",describe:"update module version (semver)",type:"string"}),handler:async e=>lt(e.version)});import Ho from"chokidar";var pt=e=>{let{prefab:t}=e,o=[...e.ignored??[]];o.includes(m.buildaDir)||o.push(m.buildaDir),t||l("No prefab found in config file. Watch cannot be run without a prefab"),Ho.watch(".",{persistent:!0