@turbo/gen 2.4.3-canary.2 → 2.4.3-canary.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +1 -1
  2. package/package.json +5 -5
package/dist/cli.js CHANGED
@@ -73,7 +73,7 @@ Please report this to https://github.com/szmarczak/http2-wrapper/`);b(_)}return}
73
73
  `+e.slice(o+1):u+=e.slice(i),u.slice(1)}function E5(e){for(var t="",r=0,n,i=0;i<e.length;r>=65536?i+=2:i++)r=ls(e,i),n=Ge[r],!n&&ps(r)?(t+=e[i],r>=65536&&(t+=e[i+1])):t+=n||f5(r);return t}function w5(e,t,r){var n="",i=e.tag,s,o,a;for(s=0,o=r.length;s<o;s+=1)a=r[s],e.replacer&&(a=e.replacer.call(r,String(s),a)),(cr(e,t,a,!1,!1)||typeof a=="undefined"&&cr(e,t,null,!1,!1))&&(n!==""&&(n+=","+(e.condenseFlow?"":" ")),n+=e.dump);e.tag=i,e.dump="["+n+"]"}function fg(e,t,r,n){var i="",s=e.tag,o,a,u;for(o=0,a=r.length;o<a;o+=1)u=r[o],e.replacer&&(u=e.replacer.call(r,String(o),u)),(cr(e,t+1,u,!0,!0,!1,!0)||typeof u=="undefined"&&cr(e,t+1,null,!0,!0,!1,!0))&&((!n||i!=="")&&(i+=cl(e,t)),e.dump&&hs===e.dump.charCodeAt(0)?i+="-":i+="- ",i+=e.dump);e.tag=s,e.dump=i||"[]"}function v5(e,t,r){var n="",i=e.tag,s=Object.keys(r),o,a,u,c,l;for(o=0,a=s.length;o<a;o+=1)l="",n!==""&&(l+=", "),e.condenseFlow&&(l+='"'),u=s[o],c=r[u],e.replacer&&(c=e.replacer.call(r,u,c)),cr(e,t,u,!1,!1)&&(e.dump.length>1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),cr(e,t,c,!1,!1)&&(l+=e.dump,n+=l));e.tag=i,e.dump="{"+n+"}"}function A5(e,t,r,n){var i="",s=e.tag,o=Object.keys(r),a,u,c,l,f,h;if(e.sortKeys===!0)o.sort();else if(typeof e.sortKeys=="function")o.sort(e.sortKeys);else if(e.sortKeys)throw new rt("sortKeys must be a boolean or a function");for(a=0,u=o.length;a<u;a+=1)h="",(!n||i!=="")&&(h+=cl(e,t)),c=o[a],l=r[c],e.replacer&&(l=e.replacer.call(r,c,l)),cr(e,t+1,c,!0,!0,!0)&&(f=e.tag!==null&&e.tag!=="?"||e.dump&&e.dump.length>1024,f&&(e.dump&&hs===e.dump.charCodeAt(0)?h+="?":h+="? "),h+=e.dump,f&&(h+=cl(e,t)),cr(e,t+1,l,!0,f)&&(e.dump&&hs===e.dump.charCodeAt(0)?h+=":":h+=": ",h+=e.dump,i+=h));e.tag=s,e.dump=i||"{}"}function hg(e,t,r){var n,i,s,o,a,u;for(i=r?e.explicitTypes:e.implicitTypes,s=0,o=i.length;s<o;s+=1)if(a=i[s],(a.instanceOf||a.predicate)&&(!a.instanceOf||typeof t=="object"&&t instanceof a.instanceOf)&&(!a.predicate||a.predicate(t))){if(r?a.multi&&a.representName?e.tag=a.representName(t):e.tag=a.tag:e.tag="?",a.represent){if(u=e.styleMap[a.tag]||a.defaultStyle,Ug.call(a.represent)==="[object Function]")n=a.represent(t,u);else if(Gg.call(a.represent,u))n=a.represent[u](t,u);else throw new rt("!<"+a.tag+'> tag resolver accepts not "'+u+'" style');e.dump=n}return!0}return!1}function cr(e,t,r,n,i,s,o){e.tag=null,e.dump=r,hg(e,r,!1)||hg(e,r,!0);var a=Ug.call(e.dump),u=n,c;n&&(n=e.flowLevel<0||e.flowLevel>t);var l=a==="[object Object]"||a==="[object Array]",f,h;if(l&&(f=e.duplicates.indexOf(r),h=f!==-1),(e.tag!==null&&e.tag!=="?"||h||e.indent!==2&&t>0)&&(i=!1),h&&e.usedDuplicates[f])e.dump="*ref_"+f;else{if(l&&h&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),a==="[object Object]")n&&Object.keys(e.dump).length!==0?(A5(e,t,e.dump,i),h&&(e.dump="&ref_"+f+e.dump)):(v5(e,t,e.dump),h&&(e.dump="&ref_"+f+" "+e.dump));else if(a==="[object Array]")n&&e.dump.length!==0?(e.noArrayIndent&&!o&&t>0?fg(e,t-1,e.dump,i):fg(e,t,e.dump,i),h&&(e.dump="&ref_"+f+e.dump)):(w5(e,t,e.dump),h&&(e.dump="&ref_"+f+" "+e.dump));else if(a==="[object String]")e.tag!=="?"&&_5(e,e.dump,t,s,u);else{if(a==="[object Undefined]")return!1;if(e.skipInvalid)return!1;throw new rt("unacceptable kind of an object to dump "+a)}e.tag!==null&&e.tag!=="?"&&(c=encodeURI(e.tag[0]==="!"?e.tag.slice(1):e.tag).replace(/!/g,"%21"),e.tag[0]==="!"?c="!"+c:c.slice(0,18)==="tag:yaml.org,2002:"?c="!!"+c.slice(18):c="!<"+c+">",e.dump=c+" "+e.dump)}return!0}function D5(e,t){var r=[],n=[],i,s;for(fl(e,r,n),i=0,s=n.length;i<s;i+=1)t.duplicates.push(r[n[i]]);t.usedDuplicates=new Array(s)}function fl(e,t,r){var n,i,s;if(e!==null&&typeof e=="object")if(i=t.indexOf(e),i!==-1)r.indexOf(i)===-1&&r.push(i);else if(t.push(e),Array.isArray(e))for(i=0,s=e.length;i<s;i+=1)fl(e[i],t,r);else for(n=Object.keys(e),i=0,s=n.length;i<s;i+=1)fl(e[n[i]],t,r)}function x5(e,t){t=t||{};var r=new d5(t);r.noRefs||D5(e,r);var n=e;return r.replacer&&(n=r.replacer.call({"":n},"",n)),cr(r,0,n,!0,!0)?r.dump+`
74
74
  `:""}var S5=x5,C5={dump:S5};function yl(e,t){return function(){throw new Error("Function yaml."+e+" is removed in js-yaml 4. Use yaml."+t+" instead, which is now safe by default.")}}var R5=je,F5=mg,T5=bg,O5=Dg,k5=xg,P5=dl,B5=$g.load,I5=$g.loadAll,L5=C5.dump,N5=rt,M5={binary:Tg,float:Ag,map:_g,null:Eg,pairs:kg,set:Pg,timestamp:Rg,bool:wg,int:vg,merge:Fg,omap:Og,seq:yg,str:gg},q5=yl("safeLoad","load"),j5=yl("safeLoadAll","loadAll"),H5=yl("safeDump","dump"),$5={Type:R5,Schema:F5,FAILSAFE_SCHEMA:T5,JSON_SCHEMA:O5,CORE_SCHEMA:k5,DEFAULT_SCHEMA:P5,load:B5,loadAll:I5,dump:L5,YAMLException:N5,types:M5,safeLoad:q5,safeLoadAll:j5,safeDump:H5},ey=$5;var ow=X(H_());var L={};KC(L,{bold:()=>FB,dimmed:()=>OB,error:()=>Dt,grey:()=>kB,info:()=>RB,item:()=>PB,log:()=>dr,turboBlue:()=>mi,turboGradient:()=>CB,turboLoader:()=>Mh,turboRed:()=>iw,underline:()=>TB,warn:()=>qh,yellow:()=>sw});var ut=require("picocolors"),ew=X(SE()),tw=X(QE()),rw="#0099F7",nw="#F11712",SB="#FFFF00",Nh=e=>{let t=BB(e);return r=>`\x1B[38;5;${t}m${r}${(0,ut.reset)("")}`},CB=(0,tw.default)(rw,nw),mi=Nh(rw),iw=Nh(nw),sw=Nh(SB),Mh=e=>(0,ew.default)({text:e,spinner:{frames:[" ",mi("> "),mi(">> "),mi(">>>")]}}),RB=(...e)=>{dr(mi((0,ut.bold)(">>>")),e.join(" "))},FB=(...e)=>{dr((0,ut.bold)(e.join(" ")))},TB=(...e)=>{dr((0,ut.underline)(e.join(" ")))},OB=(...e)=>{dr((0,ut.dim)(e.join(" ")))},kB=(...e)=>{dr((0,ut.gray)(e.join(" ")))},PB=(...e)=>{dr(mi((0,ut.bold)(" \u2022")),e.join(" "))},dr=(...e)=>{console.log(...e)},qh=(...e)=>{console.error(sw((0,ut.bold)(">>>")),e.join(" "))},Dt=(...e)=>{console.error(iw((0,ut.bold)(">>>")),e.join(" "))};function BB(e){let t=parseInt(e.slice(1),16),r=Math.floor(t/(256*256))%256,n=Math.floor(t/256)%256,i=t%256;return 16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5)}var IB="turbo.json";var jh={};function LB(e){try{if(Fs.default.existsSync(wn.default.join(e,"pnpm-workspace.yaml")))return ey.load(Fs.default.readFileSync(wn.default.join(e,"pnpm-workspace.yaml"),"utf8")).packages||[];let t=JSON.parse(Fs.default.readFileSync(wn.default.join(e,"package.json"),"utf8"));if(t.workspaces){if("packages"in t.workspaces)return t.workspaces.packages||[];if(Array.isArray(t.workspaces))return t.workspaces}return[]}catch{return[]}}function Hh(e,t){var s;let r=cs(e,t),n=[],i=(s=t==null?void 0:t.cache)!=null?s:!0;if(i&&e&&e in jh)return jh[e];if(r){let a=LB(r).map(c=>`${c}/turbo.json`);(0,ow.sync)([IB,...a],{cwd:r,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0}).map(c=>wn.default.join(r,c)).forEach(c=>{try{let l=Fs.default.readFileSync(c,"utf8"),f=Co.parse(l),h=wn.default.dirname(c)===r;if(h){if("extends"in f)return}else if(!("extends"in f))return;n.push({config:f,turboConfigPath:c,workspacePath:wn.default.dirname(c),isRootConfig:h})}catch(l){qh(l)}})}return i&&e&&(jh[e]=n),n}var FL=X(require("os")),TL=X(Pv());var Bv=X(require("fs-extra")),OL=[".DS_Store",".git",".gitattributes",".gitignore",".gitlab-ci.yml",".hg",".hgcheck",".hgignore",".idea",".npmignore",".travis.yml","LICENSE","Thumbs.db","docs","mkdocs.yml","npm-debug.log","yarn-debug.log","yarn-error.log","yarnrc.yml",".yarn"];function Bs(e){let t=Bv.default.readdirSync(e).filter(r=>!OL.includes(r)).filter(r=>!r.endsWith(".iml"));return{isEmpty:t.length===0,conflicts:t}}var id=X(require("path")),sd=X(require("fs-extra")),od=X(require("picocolors"));function Wa(e){let t=id.default.resolve(e),r=id.default.basename(t),n=sd.default.existsSync(t),i=sd.default.lstatSync(t,{throwIfNoEntry:!1});if(i&&!i.isDirectory())return{valid:!1,root:t,projectName:r,error:`${od.default.dim(r)} is not a directory - please try a different location`};if(n){let{isEmpty:s,conflicts:o}=Bs(t);if(!s)return{valid:!1,root:t,projectName:r,error:`${od.default.dim(r)} (${t}) has ${o.length} conflicting ${o.length===1?"file":"files"} - please try a different location`}}return{valid:!0,root:t,projectName:r}}var rC=require("stream"),nC=require("util"),iC=require("path"),sC=require("os"),fo=require("fs"),em=X(Ox()),xc=X(tC()),m9=(0,nC.promisify)(rC.Stream.pipeline);async function Dc(e){try{return(await xc.default.head(e)).statusCode===200}catch{return!1}}async function tm(e,t){let[,r,n,i,s,...o]=e.pathname.split("/"),a=t?t.replace(/^\//,""):o.join("/");if(i===void 0||i===""&&s===void 0)try{let c=await(0,xc.default)(`https://api.github.com/repos/${r}/${n}`),l=JSON.parse(c.body);return{username:r,name:n,branch:l.default_branch,filePath:a}}catch{return}let u=t?`${s}/${o.join("/")}`.replace(new RegExp(`/${a}|/$`),""):s;if(r&&n&&u&&i==="tree")return{username:r,name:n,branch:u,filePath:a}}function rm({username:e,name:t,branch:r,filePath:n}){let i=`https://api.github.com/repos/${e}/${t}/contents`,s=`${n?`/${n}`:""}/package.json`;return Dc(`${i+s}?ref=${r}`)}function nm(e){try{let t=new URL(e);return Dc(t.href)}catch{return Dc(`https://api.github.com/repos/vercel/turborepo/contents/examples/${encodeURIComponent(e)}`)}}async function oC(e,t){let r=(0,iC.join)((0,sC.tmpdir)(),`${t}.temp-${Date.now()}`);return await m9(xc.default.stream(e),(0,fo.createWriteStream)(r)),r}async function im(e,{username:t,name:r,branch:n,filePath:i}){let s=await oC(`https://codeload.github.com/${t}/${r}/tar.gz/${n}`,"turbo-ct-example"),o=null;await(0,em.x)({file:s,cwd:e,strip:i?i.split("/").length+1:1,filter:a=>{if(o===null){let u=a.split("/");o=u.length?u[0]:null}return a.startsWith(`${o}${i?`/${i}/`:"/"}`)}}),await fo.promises.unlink(s)}async function sm(e,t){let r=await oC("https://codeload.github.com/vercel/turborepo/tar.gz/main","turbo-ct-example"),n=null;await(0,em.x)({file:r,cwd:e,strip:2+t.split("/").length,filter:i=>{if(n===null){let s=i.split("/");n=s.length?s[0]:null}return i.includes(`${n}/examples/${t}/`)}}),await fo.promises.unlink(r)}var om=X(require("fs-extra"));async function am(e){try{return await om.default.access(e,om.default.constants.W_OK),!0}catch{return!1}}var ts=X(require("path")),um=X(dC()),Nn=X(require("picocolors")),Sc=X(require("fs-extra"));function b9(e){return typeof e=="object"&&e!==null&&typeof e.message=="string"}var Cc=class extends Error{};async function cm({appPath:e,example:t,isDefaultExample:r,examplePath:n}){let i,s;if(r)i={username:"vercel",name:"turborepo",branch:"main",filePath:"examples/basic"};else{try{s=new URL(t)}catch(p){p.code!=="ERR_INVALID_URL"&&(Dt(p),process.exit(1))}s?(s.origin!=="https://github.com"&&(Dt(`Invalid URL: ${Nn.default.red(`"${t}"`)}. Only GitHub repositories are supported. Please use a GitHub URL and try again.`),process.exit(1)),i=await tm(s,n),i||(Dt(`Unable to fetch repository information from: ${Nn.default.red(`"${t}"`)}. Please fix the URL and try again.`),process.exit(1)),await rm(i)||(Dt(`Could not locate the repository for ${Nn.default.red(`"${t}"`)}. Please check that the repository exists and try again.`),process.exit(1))):await nm(t)||(Dt(`Could not locate an example named ${Nn.default.red(`"${t}"`)}. It could be due to the following:
75
75
  `,`1. Your spelling of example ${Nn.default.red(`"${t}"`)} might be incorrect.
76
- `,"2. You might not be connected to the internet or you are behind a proxy."),process.exit(1))}let o=ts.default.resolve(e);await am(ts.default.dirname(o))||(Dt("The application path is not writable, please check folder permissions and try again."),Dt("It is likely you do not have write permissions for this folder."),process.exit(1));let a=ts.default.basename(o);try{await Sc.default.mkdir(o,{recursive:!0})}catch(p){Dt("Unable to create project directory"),Dt(p),process.exit(1)}let{isEmpty:u,conflicts:c}=Bs(o);u||(Dt(`${Nn.default.dim(o)} has ${c.length} conflicting ${c.length===1?"file":"files"} - please try a different location`),process.exit(1));let l=process.cwd();process.chdir(o),dr();let f=Mh("Downloading files... (This might take a moment)");try{!r&&i?(f.start(),await(0,um.default)(()=>im(o,i),{retries:3})):(f.start(),await(0,um.default)(()=>sm(o,t),{retries:3}))}catch(p){throw new Cc(b9(p)?p.message:String(p))}finally{f.stop()}let h=ts.default.join(o,"package.json"),g=Sc.default.existsSync(h),b=[];if(g){let p;try{p=Sc.default.readJsonSync(h)}catch{}p&&b.push(...Object.keys(p.scripts||{}))}let _=e;return ts.default.join(l,a)===e&&(_=a),{cdPath:_,hasPackageJson:g,availableScripts:b,repoInfo:i}}function lm(e,t={to:"camel"}){switch(t.to){case"camel":return e.replace(/(?:[-_][a-z])/g,r=>r.toUpperCase().replace("-","").replace("_",""));default:throw new Error("Not implemented")}}var $C=require("proxy-agent");var ho={name:"@turbo/gen",version:"2.4.3-canary.2",description:"Extend a Turborepo",homepage:"https://turbo.build/repo",license:"MIT",repository:{type:"git",url:"https://github.com/vercel/turborepo",directory:"packages/turbo-gen"},bugs:{url:"https://github.com/vercel/turborepo/issues"},bin:"dist/cli.js",types:"dist/types.d.ts",scripts:{build:"tsup",test:"jest",lint:"eslint src/","check-types":"tsc --noEmit"},dependencies:{"@turbo/workspaces":"workspace:*",commander:"^10.0.0","fs-extra":"^10.1.0",inquirer:"^8.2.4",minimatch:"^9.0.0","node-plop":"^0.26.3",picocolors:"1.0.1","proxy-agent":"^6.2.2","ts-node":"^10.9.2","update-check":"^1.5.4","validate-npm-package-name":"^5.0.0"},devDependencies:{"@jest/globals":"^29.7.0","@turbo/eslint-config":"workspace:*","@turbo/test-utils":"workspace:*","@turbo/tsconfig":"workspace:*","@turbo/utils":"workspace:*","@types/fs-extra":"^9.0.13","@types/inquirer":"^8.2.5","@types/node":"^18.17.2","@types/validate-npm-package-name":"^4.0.0",jest:"^29.7.0","ts-jest":"^29.2.5",tsup:"^6.7.0",typescript:"5.5.4"},files:["dist"],publishConfig:{access:"public"}};var fm=X(require("picocolors")),pC=X(require("update-check"));var w9=(0,pC.default)(ho).catch(()=>null);async function hm(){try{let e=await w9;e!=null&&e.latest&&(L.log(),L.log(fm.default.yellow(fm.default.bold(`A new version of \`${ho.name}\` is available!`))),L.log()),process.exit()}catch{}}var mC=require("@turbo/workspaces");async function Rc({root:e}){let t=e||process.cwd(),r=cs(t);if(!r)L.error("Unable to infer repository root - override with --root");else try{return(0,mC.getWorkspaceDetails)({root:r})}catch{L.error(`Unable to determine workspace details. Make sure "${t}" is the root, or add "packageManager" to "package.json" or ensure a lockfile is present.`)}process.exit(1)}var Tr=X(require("path")),Tc=X(require("fs-extra")),Fc=X(require("node-plop")),gC=require("ts-node"),yC=require("inquirer");var $e=class extends Error{constructor(r,n){var i;super(r);this.name="GenerateError",this.type=(i=n==null?void 0:n.type)!=null?i:"unknown",Error.captureStackTrace(this,$e)}};var _C=["ts","js","cjs"],v9=Tr.default.join("turbo","generators"),bC=_C.map(e=>Tr.default.join(v9,`config.${e}`)),A9=[...bC,..._C.map(e=>Tr.default.join(`plopfile.${e}`))];function EC({project:e,configPath:t}){(0,gC.register)({transpileOnly:!0,cwd:e.paths.root,compilerOptions:{module:"nodenext",moduleResolution:"nodenext"}});let r=x9({project:e}),n;if(t){if(!Tc.default.existsSync(t))throw new $e(`No config at "${t}"`,{type:"plop_no_config"});try{n=(0,Fc.default)(t,{destBasePath:t,force:!1})}catch(i){L.error(i)}}else{for(let i of A9){let s=Tr.default.join(e.paths.root,i);if(Tc.default.existsSync(s))try{n=(0,Fc.default)(s,{destBasePath:e.paths.root,force:!1});break}catch(o){L.error(o)}}!n&&r.length>0&&(n=(0,Fc.default)(r[0].config,{destBasePath:r[0].root,force:!1}),r.shift())}return n&&r.forEach(i=>{try{n.load(i.config,{destBasePath:i.root,force:!1})}catch(s){L.error(s)}}),n}function dm({project:e,configPath:t}){let r=EC({project:e,configPath:t});if(!r)return[];let i=r.getGeneratorList().map(a=>r.getGenerator(a.name)),s={};i.forEach(a=>{let u=a,c=e.workspaceData.workspaces.find(l=>{if(u.basePath===e.paths.root)return!1;let f=u.basePath.split(Tr.default.sep);return f.pop(),f.pop(),Tr.default.join("/",...f)===l.paths.root});c?(c.name in s||(s[c.name]=[]),s[c.name].push(u)):("root"in s||(s.root=[]),s.root.push(u))});let o=[];return Object.keys(s).forEach(a=>{o.push(new yC.Separator(a)),o.push(...s[a])}),o}function D9({project:e,generator:t}){let r={cwd:process.cwd(),root:e.paths.root,workspace:t.basePath?us({cwd:t.basePath,target:"package.json"}):void 0},n={};try{n=Hh(t.basePath)}catch{}return{turbo:{paths:r,configs:n}}}function x9({project:e}){let t=[];return e.workspaceData.workspaces.forEach(r=>{for(let n of bC)Tc.default.existsSync(Tr.default.join(r.paths.root,n))&&t.push({config:Tr.default.join(r.paths.root,n),root:r.paths.root})}),t}async function wC({project:e,generator:t,bypassArgs:r,configPath:n}){let i=EC({project:e,configPath:n});if(!i)throw new $e("Unable to load generators",{type:"plop_unable_to_load_config"});let s=i.getGenerator(t);if(!s)throw new $e(`Generator ${t} not found`,{type:"plop_generator_not_found"});let o=await s.runPrompts(r),a=await s.runActions({...o,...D9({project:e,generator:s})},{onComment:u=>{L.dimmed(u)}});if(a.failures.length>0)throw a.failures.forEach(u=>{u instanceof Error?L.error(`Error - ${u.message}`):L.error(`Error - ${u.error}. Unable to ${u.type} to "${u.path}"`)}),new $e(`Failed to run "${t}" generator`,{type:"plop_error_running_generator"});a.changes.length>0&&(L.info("Changes made:"),a.changes.forEach(u=>{u.path&&L.item(`${u.path} (${u.type})`)}))}var Mn=require("inquirer");async function vC({generators:e,generator:t}){if(t){if(e.find(n=>!(n instanceof Mn.Separator)&&n.name===t))return{selectedGenerator:t};L.warn(`Generator "${t}" not found`),L.log()}return await(0,Mn.prompt)({type:"list",name:"selectedGenerator",message:"Select generator to run",choices:e.map(n=>n instanceof Mn.Separator?n:{name:n.description?` ${n.name}: ${n.description}`:` ${n.name}`,value:n.name})})}async function AC(){return(0,Mn.prompt)({type:"list",name:"answer",message:"Should the generator config be created with TS or JS?",default:"ts",choices:[{name:"JavaScript",value:"js"},{name:"TypeScript",value:"ts"}]})}async function DC({message:e}){return(0,Mn.prompt)({type:"confirm",name:"answer",message:e})}var pm=X(require("path")),mm=X(require("fs-extra"));async function xC({project:e,template:t}){let r=pm.default.join(e.paths.root,"turbo","generators"),n=`simple-${t}`;if(await mm.default.pathExists(r))throw new $e(`Generator config directory already exists at ${r}`,{type:"config_directory_already_exists"});await mm.default.copy(pm.default.join(__dirname,"templates",n),r,{recursive:!0})}async function gm({generator:e,project:t,opts:r}){let n=!1,i=dm({project:t,configPath:r.config});if(!i.length){L.error("No generators found."),L.log();let{answer:o}=await DC({message:`Would you like to add a config with a sample custom generator to ${t.name}?`});if(o){n=!0;let{answer:a}=await AC();try{await xC({project:t,template:a})}catch(u){throw u instanceof $e||L.error("Failed to create generator config"),u}if(L.log(),L.info("Generator config successfully created!"),L.info("Loading generator config..."),L.log(),i=dm({project:t,configPath:r.config}),!i.length){L.error("Error loading generator");return}}else{L.log(),L.dimmed("Learn more about custom Turborepo generators - https://turbo.build/repo/docs/core-concepts/monorepos/code-generation#custom-generators");return}}let{selectedGenerator:s}=await vC({generators:i,generator:e});try{await wC({project:t,generator:s,bypassArgs:r.args,configPath:r.config})}catch(o){if(o instanceof $e)throw o;let a="Failed to run generator";throw o instanceof Error&&(a=o.message),new $e(a,{type:"plop_error_running_generator"})}finally{n&&(L.log(),L.info("Congrats! You just ran your first Turborepo generator"),L.dimmed("Learn more about custom Turborepo generators - https://turbo.build/repo/docs/core-concepts/monorepos/code-generation#custom-generators"))}L.log(),L.bold(L.turboGradient(">>> Success!"))}var Em=X(require("path")),Bc=X(require("fs-extra")),LC=X(require("picocolors"));var po=X(require("path")),FC=X(require("fs-extra")),Bt=require("inquirer"),TC=require("minimatch"),bm=X(require("validate-npm-package-name"));var ym=X(require("path"));var SC=X(require("path"));function CC({project:e}){let r=e.workspaceData.workspaces.map(i=>SC.default.relative(e.paths.root,i.paths.root)),n=new Set;return e.workspaceData.globs.forEach(i=>{if(!r.includes(i)){if(!i.startsWith("!")){let o=i.split("/")[0];n.add(o)}}}),Array.from(n)}function _m({project:e,workspace:t}){return ym.default.relative(e.paths.root,t.paths.root).split(ym.default.sep)[0]}function Oc({project:e}){let t=CC({project:e}),r=t.includes("apps"),n=t.includes("packages"),i={},s=[];return e.workspaceData.workspaces.forEach(o=>{let a=_m({project:e,workspace:o});a!=="apps"&&s.push(o),a in i||(i[a]=[]),i[a].push(o)}),{hasRootApps:r,hasRootPackages:n,workspacesByGroup:i,nonAppWorkspaces:s}}var RC=require("inquirer");function kc({project:e,type:t,showAllDependencies:r}){let n=Oc({project:e}),i=[],s=e.workspaceData.workspaces;r||(t==="app"&&n.hasRootApps?s=n.workspacesByGroup.apps:t==="package"&&n.nonAppWorkspaces.length>0&&(s=n.nonAppWorkspaces));let o;return s.forEach(a=>{let u=_m({project:e,workspace:a});u!==o&&i.push(new RC.Separator(u)),o=u,i.push(a)}),i}async function OC({override:e,suggestion:t,workspaceType:r}){let{validForNewPackages:n}=(0,bm.default)(e||"");return e&&n?{answer:e}:(0,Bt.prompt)({type:"input",name:"answer",default:t,validate:i=>{let{validForNewPackages:s}=(0,bm.default)(i);return s||`Invalid ${r} name`},message:`What is the name of the ${r}?`})}async function kC({override:e,message:t}){return e?{answer:e}:(0,Bt.prompt)({type:"list",name:"answer",message:t!=null?t:"What type of workspace should be added?",choices:[{name:"app",value:"app"},{name:"package",value:"package"}]})}async function PC({workspaceType:e,workspaceName:t,destination:r,project:n}){let i=t.includes("/")?t.split("/")[1]:t;if(r){let{valid:u,root:c}=Wa(r);if(u)return{absolute:c,relative:po.default.relative(n.paths.root,c)}}let s,o=Oc({project:n});e==="app"&&o.hasRootApps?s=`${n.paths.root}/apps/${i}`:e==="package"&&o.hasRootPackages&&(s=`${n.paths.root}/packages/${i}`);let{answer:a}=await(0,Bt.prompt)({type:"input",name:"answer",message:`Where should "${t}" be added?`,default:s?po.default.relative(n.paths.root,s):void 0,validate:u=>{let c=po.default.join(n.paths.root,u),{valid:l,error:f}=Wa(c),h=n.workspaceData.globs.some(g=>(0,TC.minimatch)(u,g));return l&&h?!0:h?f:`${u} is not a valid workspace location`}});return{absolute:po.default.join(n.paths.root,a),relative:a}}async function BC({override:e,workspaces:t,workspaceName:r}){if(e){let i=t.find(s=>s instanceof Bt.Separator?!1:s.name===e);if(i)return{answer:i};L.warn(`Workspace "${e}" not found`),L.log()}return await(0,Bt.prompt)({type:"list",name:"answer",loop:!1,pageSize:25,message:`Which workspace should "${r}" start from?`,choices:t.map(i=>i instanceof Bt.Separator?i:{name:` ${i.name}`,value:i})})}async function IC({workspaceName:e,project:t,workspaceSource:r,showAllDependencies:n}){let i={dependencies:{},devDependencies:{},peerDependencies:{},optionalDependencies:{}},{answer:s}=await C9({message:`Add workspace dependencies to "${e}"?`});if(!s)return i;let{answer:o}=await(0,Bt.prompt)({type:"checkbox",name:"answer",message:`Select all dependencies types to modify for "${e}"`,loop:!1,choices:[{name:"dependencies",value:"dependencies"},{name:"devDependencies",value:"devDependencies"},{name:"peerDependencies",value:"peerDependencies"},{name:"optionalDependencies",value:"optionalDependencies"}]}),a=kc({project:t,type:"package",showAllDependencies:n}),u=r?FC.default.readJsonSync(r.paths.packageJson):void 0;for(let c of o){let{answer:l}=await(0,Bt.prompt)({type:"checkbox",name:"answer",default:u&&Object.keys(u[c]||{}),pageSize:15,message:`Which packages should be added as ${c} to "${e}?`,loop:!1,choices:a.map(h=>h instanceof Bt.Separator?h:{name:` ${h.name}`,value:h.name})}),f=(u==null?void 0:u[c])||{};if(Object.keys(f).length){let h=new Set(Object.keys(f));l.forEach(g=>{h.has(g)||(f[g]=t.packageManager==="pnpm"?"workspace:*":"*")}),i[c]=f}else i[c]=l.reduce((h,g)=>({...h,[g]:t.packageManager==="pnpm"?"workspace:*":"*"}),{})}return i}async function C9({message:e}){return(0,Bt.prompt)({type:"confirm",name:"answer",message:e})}async function Pc({project:e,opts:t}){var u;let r,n=t.method==="copy"&&t.copy.type==="external"?((u=t.examplePath)==null?void 0:u.split("/").pop())||t.copy.source.split("/").pop():void 0,{answer:i}=await kC({override:t.type,message:t.method==="copy"&&t.copy.source==="external"&&n?`What type of workspace should "${n}" be created as?`:void 0}),{answer:s}=await OC({override:t.name,workspaceType:i,suggestion:n});if(t.method==="copy"&&t.copy.type==="internal"){let{answer:c}=await BC({override:t.copy.source,workspaces:kc({project:e,type:i}),workspaceName:s});r=c}let o=await PC({workspaceType:i,workspaceName:s,project:e,destination:t.destination}),a=await IC({workspaceName:s,project:e,workspaceSource:r,showAllDependencies:t.showAllDependencies});return{type:i,name:s,location:o,source:r,dependencies:a}}async function wm({project:e,opts:t}){let{name:r,location:n,dependencies:i}=await Pc({project:e,opts:t}),s={name:r,version:"0.0.0",private:!0,scripts:{dev:"echo 'Add dev script here'",build:"echo 'Add build script here'",test:"echo 'Add test script here'",lint:"echo 'Add lint script here'"}};Object.keys(i).forEach(o=>{let a=i[o];a&&Object.keys(a).length>0&&(s[o]=a)}),Bc.default.mkdirSync(n.absolute,{recursive:!0}),Bc.default.writeFileSync(Em.default.join(n.absolute,"package.json"),JSON.stringify(s,null,2)),Bc.default.writeFileSync(Em.default.join(n.absolute,"README.md"),`# \`${r}\``),L.log(),L.log(`${LC.default.bold(L.turboGradient(">>> Success!"))} Created ${r} at "${n.relative}"`)}var vm=X(require("path")),an=X(require("fs-extra")),NC=X(require("picocolors"));async function Am({project:e,opts:t}){let{name:r,type:n,location:i,source:s,dependencies:o}=await Pc({project:e,opts:t}),a=vm.default.join(i.absolute,"package.json");if(t.copy.type==="external"){L.log(),L.warn("Some manual modifications may be required."),L.dimmed(`This ${n} may require local dependencies or a different package manager than what is available in this repo`),await cm({appPath:i.absolute,example:t.copy.source,examplePath:t.examplePath});try{if(an.default.existsSync(a)){if((await an.default.readJSON(a)).workspaces)throw new Error("New workspace root detected - unexpected 'workspaces' field in package.json")}else throw new Error("New workspace is missing a package.json file");if(an.default.existsSync(vm.default.join(i.absolute,"pnpm-workspace.yaml")))throw new Error("New workspace root detected - unexpected pnpm-workspace.yaml")}catch(c){let l="UNKNOWN_ERROR";c instanceof Error&&(l=c.message),L.error(l),await an.default.rm(i.absolute,{recursive:!0,force:!0});return}}else if(s){let c=async f=>Promise.resolve(!f.includes("node_modules")),l=L.turboLoader(`Creating "${r}" from "${s.name}"...`);l.start(),await an.default.copy(s.paths.root,i.absolute,{filter:c}),l.stop()}let u=await an.default.readJSON(a);u.name=r,Object.keys(o).forEach(c=>{let l=o[c];l&&Object.keys(l).length>0&&(u[c]=l)}),await an.default.writeJSON(a,u,{spaces:2}),L.log(),L.log(`${NC.default.bold(L.turboGradient(">>> Success!"))} Created ${r} at "${i.relative}"`)}function F9(e){let{copy:t,...r}=e,n=t===!0||typeof t=="string"?"copy":"empty",i=typeof t=="string"?t:"",s=typeof t=="string"&&t.startsWith("https://")?"external":"internal";return{method:n,copy:{type:s,source:i},...r}}async function mo(e){let t=await Rc(e),r=F9(e);L.log();let n={project:t,opts:r};r.method==="copy"?(r.copy.type==="external"?L.info(`Copy a remote workspace from ${r.copy.source}`):L.info(`Copy an existing workspace from "${t.name}"`),L.log(),await Am(n)):(L.info(`Add an empty workspace to "${t.name}"`),L.log(),await wm(n))}async function go(e,t){let r=await Rc(t);L.log(),L.info(`Modify "${r.name}" using custom generators`),L.log(),await gm({generator:e,project:r,opts:t})}function MC(e){try{let t=JSON.parse(e),r={};for(let n in t){let i=lm(n,{to:"camel"});r[i]=t[n]}return r}catch(t){L.error("Error parsing arguments",t),process.exit(1)}}async function Dm(e,t){var r;if(e==="workspace"){let n=MC(t.json);n.showAllDependencies=(r=n.showAllDependencies)!=null?r:!1;let i=!1,s=n.empty||!0;n.copy===""||n.copy===!0?(i=!0,s=!1):n.copy&&n.copy.length>0&&(i=n.copy,s=!1),n.copy=i,n.empty=s,await mo(n)}else if(e==="run"){let n=MC(t.json),{generatorName:i,...s}=n;await go(i,s)}else L.error(`Received unknown command - "${e}" (must be one of "workspace" | "run")`),process.exit(1)}var UC=new $C.ProxyAgent;qC.default.globalAgent=UC;jC.default.globalAgent=UC;var yo=new Ue.Command;yo.name(HC.default.bold(L.turboGradient("@turbo/gen"))).description("Extend your Turborepo").version(ho.version,"-v, --version","Output the current version").helpOption("-h, --help","Display help for command").showHelpAfterError(!1);yo.command("run",{isDefault:!0}).alias("r").description("Run custom generators").addArgument(new Ue.Argument("[generator-name]","The name of the generator to run")).addOption(new Ue.Option("-c, --config <config>","Generator configuration file (default: turbo/generators/config.js")).addOption(new Ue.Option("-r, --root <dir>","The root of your repository (default: directory with root turbo.json)")).addOption(new Ue.Option("-a, --args <args...>","Arguments passed directly to generator").default([])).action(go);yo.command("workspace").aliases(["w"]).description("Add a new package or app to your project").addOption(new Ue.Option("-n, --name <workspace-name>","Name for the new workspace")).addOption(new Ue.Option("-b, --empty","Generate an empty workspace").conflicts("copy").default(!0)).addOption(new Ue.Option("-c, --copy [source]",`Generate a workspace using an existing workspace as a template. Can be the name of a local workspace
76
+ `,"2. You might not be connected to the internet or you are behind a proxy."),process.exit(1))}let o=ts.default.resolve(e);await am(ts.default.dirname(o))||(Dt("The application path is not writable, please check folder permissions and try again."),Dt("It is likely you do not have write permissions for this folder."),process.exit(1));let a=ts.default.basename(o);try{await Sc.default.mkdir(o,{recursive:!0})}catch(p){Dt("Unable to create project directory"),Dt(p),process.exit(1)}let{isEmpty:u,conflicts:c}=Bs(o);u||(Dt(`${Nn.default.dim(o)} has ${c.length} conflicting ${c.length===1?"file":"files"} - please try a different location`),process.exit(1));let l=process.cwd();process.chdir(o),dr();let f=Mh("Downloading files... (This might take a moment)");try{!r&&i?(f.start(),await(0,um.default)(()=>im(o,i),{retries:3})):(f.start(),await(0,um.default)(()=>sm(o,t),{retries:3}))}catch(p){throw new Cc(b9(p)?p.message:String(p))}finally{f.stop()}let h=ts.default.join(o,"package.json"),g=Sc.default.existsSync(h),b=[];if(g){let p;try{p=Sc.default.readJsonSync(h)}catch{}p&&b.push(...Object.keys(p.scripts||{}))}let _=e;return ts.default.join(l,a)===e&&(_=a),{cdPath:_,hasPackageJson:g,availableScripts:b,repoInfo:i}}function lm(e,t={to:"camel"}){switch(t.to){case"camel":return e.replace(/(?:[-_][a-z])/g,r=>r.toUpperCase().replace("-","").replace("_",""));default:throw new Error("Not implemented")}}var $C=require("proxy-agent");var ho={name:"@turbo/gen",version:"2.4.3-canary.3",description:"Extend a Turborepo",homepage:"https://turbo.build/repo",license:"MIT",repository:{type:"git",url:"https://github.com/vercel/turborepo",directory:"packages/turbo-gen"},bugs:{url:"https://github.com/vercel/turborepo/issues"},bin:"dist/cli.js",types:"dist/types.d.ts",scripts:{build:"tsup",test:"jest",lint:"eslint src/","check-types":"tsc --noEmit"},dependencies:{"@turbo/workspaces":"workspace:*",commander:"^10.0.0","fs-extra":"^10.1.0",inquirer:"^8.2.4",minimatch:"^9.0.0","node-plop":"^0.26.3",picocolors:"1.0.1","proxy-agent":"^6.2.2","ts-node":"^10.9.2","update-check":"^1.5.4","validate-npm-package-name":"^5.0.0"},devDependencies:{"@jest/globals":"^29.7.0","@turbo/eslint-config":"workspace:*","@turbo/test-utils":"workspace:*","@turbo/tsconfig":"workspace:*","@turbo/utils":"workspace:*","@types/fs-extra":"^9.0.13","@types/inquirer":"^8.2.5","@types/node":"^18.17.2","@types/validate-npm-package-name":"^4.0.0",jest:"^29.7.0","ts-jest":"^29.2.5",tsup:"^6.7.0",typescript:"5.5.4"},files:["dist"],publishConfig:{access:"public"}};var fm=X(require("picocolors")),pC=X(require("update-check"));var w9=(0,pC.default)(ho).catch(()=>null);async function hm(){try{let e=await w9;e!=null&&e.latest&&(L.log(),L.log(fm.default.yellow(fm.default.bold(`A new version of \`${ho.name}\` is available!`))),L.log()),process.exit()}catch{}}var mC=require("@turbo/workspaces");async function Rc({root:e}){let t=e||process.cwd(),r=cs(t);if(!r)L.error("Unable to infer repository root - override with --root");else try{return(0,mC.getWorkspaceDetails)({root:r})}catch{L.error(`Unable to determine workspace details. Make sure "${t}" is the root, or add "packageManager" to "package.json" or ensure a lockfile is present.`)}process.exit(1)}var Tr=X(require("path")),Tc=X(require("fs-extra")),Fc=X(require("node-plop")),gC=require("ts-node"),yC=require("inquirer");var $e=class extends Error{constructor(r,n){var i;super(r);this.name="GenerateError",this.type=(i=n==null?void 0:n.type)!=null?i:"unknown",Error.captureStackTrace(this,$e)}};var _C=["ts","js","cjs"],v9=Tr.default.join("turbo","generators"),bC=_C.map(e=>Tr.default.join(v9,`config.${e}`)),A9=[...bC,..._C.map(e=>Tr.default.join(`plopfile.${e}`))];function EC({project:e,configPath:t}){(0,gC.register)({transpileOnly:!0,cwd:e.paths.root,compilerOptions:{module:"nodenext",moduleResolution:"nodenext"}});let r=x9({project:e}),n;if(t){if(!Tc.default.existsSync(t))throw new $e(`No config at "${t}"`,{type:"plop_no_config"});try{n=(0,Fc.default)(t,{destBasePath:t,force:!1})}catch(i){L.error(i)}}else{for(let i of A9){let s=Tr.default.join(e.paths.root,i);if(Tc.default.existsSync(s))try{n=(0,Fc.default)(s,{destBasePath:e.paths.root,force:!1});break}catch(o){L.error(o)}}!n&&r.length>0&&(n=(0,Fc.default)(r[0].config,{destBasePath:r[0].root,force:!1}),r.shift())}return n&&r.forEach(i=>{try{n.load(i.config,{destBasePath:i.root,force:!1})}catch(s){L.error(s)}}),n}function dm({project:e,configPath:t}){let r=EC({project:e,configPath:t});if(!r)return[];let i=r.getGeneratorList().map(a=>r.getGenerator(a.name)),s={};i.forEach(a=>{let u=a,c=e.workspaceData.workspaces.find(l=>{if(u.basePath===e.paths.root)return!1;let f=u.basePath.split(Tr.default.sep);return f.pop(),f.pop(),Tr.default.join("/",...f)===l.paths.root});c?(c.name in s||(s[c.name]=[]),s[c.name].push(u)):("root"in s||(s.root=[]),s.root.push(u))});let o=[];return Object.keys(s).forEach(a=>{o.push(new yC.Separator(a)),o.push(...s[a])}),o}function D9({project:e,generator:t}){let r={cwd:process.cwd(),root:e.paths.root,workspace:t.basePath?us({cwd:t.basePath,target:"package.json"}):void 0},n={};try{n=Hh(t.basePath)}catch{}return{turbo:{paths:r,configs:n}}}function x9({project:e}){let t=[];return e.workspaceData.workspaces.forEach(r=>{for(let n of bC)Tc.default.existsSync(Tr.default.join(r.paths.root,n))&&t.push({config:Tr.default.join(r.paths.root,n),root:r.paths.root})}),t}async function wC({project:e,generator:t,bypassArgs:r,configPath:n}){let i=EC({project:e,configPath:n});if(!i)throw new $e("Unable to load generators",{type:"plop_unable_to_load_config"});let s=i.getGenerator(t);if(!s)throw new $e(`Generator ${t} not found`,{type:"plop_generator_not_found"});let o=await s.runPrompts(r),a=await s.runActions({...o,...D9({project:e,generator:s})},{onComment:u=>{L.dimmed(u)}});if(a.failures.length>0)throw a.failures.forEach(u=>{u instanceof Error?L.error(`Error - ${u.message}`):L.error(`Error - ${u.error}. Unable to ${u.type} to "${u.path}"`)}),new $e(`Failed to run "${t}" generator`,{type:"plop_error_running_generator"});a.changes.length>0&&(L.info("Changes made:"),a.changes.forEach(u=>{u.path&&L.item(`${u.path} (${u.type})`)}))}var Mn=require("inquirer");async function vC({generators:e,generator:t}){if(t){if(e.find(n=>!(n instanceof Mn.Separator)&&n.name===t))return{selectedGenerator:t};L.warn(`Generator "${t}" not found`),L.log()}return await(0,Mn.prompt)({type:"list",name:"selectedGenerator",message:"Select generator to run",choices:e.map(n=>n instanceof Mn.Separator?n:{name:n.description?` ${n.name}: ${n.description}`:` ${n.name}`,value:n.name})})}async function AC(){return(0,Mn.prompt)({type:"list",name:"answer",message:"Should the generator config be created with TS or JS?",default:"ts",choices:[{name:"JavaScript",value:"js"},{name:"TypeScript",value:"ts"}]})}async function DC({message:e}){return(0,Mn.prompt)({type:"confirm",name:"answer",message:e})}var pm=X(require("path")),mm=X(require("fs-extra"));async function xC({project:e,template:t}){let r=pm.default.join(e.paths.root,"turbo","generators"),n=`simple-${t}`;if(await mm.default.pathExists(r))throw new $e(`Generator config directory already exists at ${r}`,{type:"config_directory_already_exists"});await mm.default.copy(pm.default.join(__dirname,"templates",n),r,{recursive:!0})}async function gm({generator:e,project:t,opts:r}){let n=!1,i=dm({project:t,configPath:r.config});if(!i.length){L.error("No generators found."),L.log();let{answer:o}=await DC({message:`Would you like to add a config with a sample custom generator to ${t.name}?`});if(o){n=!0;let{answer:a}=await AC();try{await xC({project:t,template:a})}catch(u){throw u instanceof $e||L.error("Failed to create generator config"),u}if(L.log(),L.info("Generator config successfully created!"),L.info("Loading generator config..."),L.log(),i=dm({project:t,configPath:r.config}),!i.length){L.error("Error loading generator");return}}else{L.log(),L.dimmed("Learn more about custom Turborepo generators - https://turbo.build/repo/docs/core-concepts/monorepos/code-generation#custom-generators");return}}let{selectedGenerator:s}=await vC({generators:i,generator:e});try{await wC({project:t,generator:s,bypassArgs:r.args,configPath:r.config})}catch(o){if(o instanceof $e)throw o;let a="Failed to run generator";throw o instanceof Error&&(a=o.message),new $e(a,{type:"plop_error_running_generator"})}finally{n&&(L.log(),L.info("Congrats! You just ran your first Turborepo generator"),L.dimmed("Learn more about custom Turborepo generators - https://turbo.build/repo/docs/core-concepts/monorepos/code-generation#custom-generators"))}L.log(),L.bold(L.turboGradient(">>> Success!"))}var Em=X(require("path")),Bc=X(require("fs-extra")),LC=X(require("picocolors"));var po=X(require("path")),FC=X(require("fs-extra")),Bt=require("inquirer"),TC=require("minimatch"),bm=X(require("validate-npm-package-name"));var ym=X(require("path"));var SC=X(require("path"));function CC({project:e}){let r=e.workspaceData.workspaces.map(i=>SC.default.relative(e.paths.root,i.paths.root)),n=new Set;return e.workspaceData.globs.forEach(i=>{if(!r.includes(i)){if(!i.startsWith("!")){let o=i.split("/")[0];n.add(o)}}}),Array.from(n)}function _m({project:e,workspace:t}){return ym.default.relative(e.paths.root,t.paths.root).split(ym.default.sep)[0]}function Oc({project:e}){let t=CC({project:e}),r=t.includes("apps"),n=t.includes("packages"),i={},s=[];return e.workspaceData.workspaces.forEach(o=>{let a=_m({project:e,workspace:o});a!=="apps"&&s.push(o),a in i||(i[a]=[]),i[a].push(o)}),{hasRootApps:r,hasRootPackages:n,workspacesByGroup:i,nonAppWorkspaces:s}}var RC=require("inquirer");function kc({project:e,type:t,showAllDependencies:r}){let n=Oc({project:e}),i=[],s=e.workspaceData.workspaces;r||(t==="app"&&n.hasRootApps?s=n.workspacesByGroup.apps:t==="package"&&n.nonAppWorkspaces.length>0&&(s=n.nonAppWorkspaces));let o;return s.forEach(a=>{let u=_m({project:e,workspace:a});u!==o&&i.push(new RC.Separator(u)),o=u,i.push(a)}),i}async function OC({override:e,suggestion:t,workspaceType:r}){let{validForNewPackages:n}=(0,bm.default)(e||"");return e&&n?{answer:e}:(0,Bt.prompt)({type:"input",name:"answer",default:t,validate:i=>{let{validForNewPackages:s}=(0,bm.default)(i);return s||`Invalid ${r} name`},message:`What is the name of the ${r}?`})}async function kC({override:e,message:t}){return e?{answer:e}:(0,Bt.prompt)({type:"list",name:"answer",message:t!=null?t:"What type of workspace should be added?",choices:[{name:"app",value:"app"},{name:"package",value:"package"}]})}async function PC({workspaceType:e,workspaceName:t,destination:r,project:n}){let i=t.includes("/")?t.split("/")[1]:t;if(r){let{valid:u,root:c}=Wa(r);if(u)return{absolute:c,relative:po.default.relative(n.paths.root,c)}}let s,o=Oc({project:n});e==="app"&&o.hasRootApps?s=`${n.paths.root}/apps/${i}`:e==="package"&&o.hasRootPackages&&(s=`${n.paths.root}/packages/${i}`);let{answer:a}=await(0,Bt.prompt)({type:"input",name:"answer",message:`Where should "${t}" be added?`,default:s?po.default.relative(n.paths.root,s):void 0,validate:u=>{let c=po.default.join(n.paths.root,u),{valid:l,error:f}=Wa(c),h=n.workspaceData.globs.some(g=>(0,TC.minimatch)(u,g));return l&&h?!0:h?f:`${u} is not a valid workspace location`}});return{absolute:po.default.join(n.paths.root,a),relative:a}}async function BC({override:e,workspaces:t,workspaceName:r}){if(e){let i=t.find(s=>s instanceof Bt.Separator?!1:s.name===e);if(i)return{answer:i};L.warn(`Workspace "${e}" not found`),L.log()}return await(0,Bt.prompt)({type:"list",name:"answer",loop:!1,pageSize:25,message:`Which workspace should "${r}" start from?`,choices:t.map(i=>i instanceof Bt.Separator?i:{name:` ${i.name}`,value:i})})}async function IC({workspaceName:e,project:t,workspaceSource:r,showAllDependencies:n}){let i={dependencies:{},devDependencies:{},peerDependencies:{},optionalDependencies:{}},{answer:s}=await C9({message:`Add workspace dependencies to "${e}"?`});if(!s)return i;let{answer:o}=await(0,Bt.prompt)({type:"checkbox",name:"answer",message:`Select all dependencies types to modify for "${e}"`,loop:!1,choices:[{name:"dependencies",value:"dependencies"},{name:"devDependencies",value:"devDependencies"},{name:"peerDependencies",value:"peerDependencies"},{name:"optionalDependencies",value:"optionalDependencies"}]}),a=kc({project:t,type:"package",showAllDependencies:n}),u=r?FC.default.readJsonSync(r.paths.packageJson):void 0;for(let c of o){let{answer:l}=await(0,Bt.prompt)({type:"checkbox",name:"answer",default:u&&Object.keys(u[c]||{}),pageSize:15,message:`Which packages should be added as ${c} to "${e}?`,loop:!1,choices:a.map(h=>h instanceof Bt.Separator?h:{name:` ${h.name}`,value:h.name})}),f=(u==null?void 0:u[c])||{};if(Object.keys(f).length){let h=new Set(Object.keys(f));l.forEach(g=>{h.has(g)||(f[g]=t.packageManager==="pnpm"?"workspace:*":"*")}),i[c]=f}else i[c]=l.reduce((h,g)=>({...h,[g]:t.packageManager==="pnpm"?"workspace:*":"*"}),{})}return i}async function C9({message:e}){return(0,Bt.prompt)({type:"confirm",name:"answer",message:e})}async function Pc({project:e,opts:t}){var u;let r,n=t.method==="copy"&&t.copy.type==="external"?((u=t.examplePath)==null?void 0:u.split("/").pop())||t.copy.source.split("/").pop():void 0,{answer:i}=await kC({override:t.type,message:t.method==="copy"&&t.copy.source==="external"&&n?`What type of workspace should "${n}" be created as?`:void 0}),{answer:s}=await OC({override:t.name,workspaceType:i,suggestion:n});if(t.method==="copy"&&t.copy.type==="internal"){let{answer:c}=await BC({override:t.copy.source,workspaces:kc({project:e,type:i}),workspaceName:s});r=c}let o=await PC({workspaceType:i,workspaceName:s,project:e,destination:t.destination}),a=await IC({workspaceName:s,project:e,workspaceSource:r,showAllDependencies:t.showAllDependencies});return{type:i,name:s,location:o,source:r,dependencies:a}}async function wm({project:e,opts:t}){let{name:r,location:n,dependencies:i}=await Pc({project:e,opts:t}),s={name:r,version:"0.0.0",private:!0,scripts:{dev:"echo 'Add dev script here'",build:"echo 'Add build script here'",test:"echo 'Add test script here'",lint:"echo 'Add lint script here'"}};Object.keys(i).forEach(o=>{let a=i[o];a&&Object.keys(a).length>0&&(s[o]=a)}),Bc.default.mkdirSync(n.absolute,{recursive:!0}),Bc.default.writeFileSync(Em.default.join(n.absolute,"package.json"),JSON.stringify(s,null,2)),Bc.default.writeFileSync(Em.default.join(n.absolute,"README.md"),`# \`${r}\``),L.log(),L.log(`${LC.default.bold(L.turboGradient(">>> Success!"))} Created ${r} at "${n.relative}"`)}var vm=X(require("path")),an=X(require("fs-extra")),NC=X(require("picocolors"));async function Am({project:e,opts:t}){let{name:r,type:n,location:i,source:s,dependencies:o}=await Pc({project:e,opts:t}),a=vm.default.join(i.absolute,"package.json");if(t.copy.type==="external"){L.log(),L.warn("Some manual modifications may be required."),L.dimmed(`This ${n} may require local dependencies or a different package manager than what is available in this repo`),await cm({appPath:i.absolute,example:t.copy.source,examplePath:t.examplePath});try{if(an.default.existsSync(a)){if((await an.default.readJSON(a)).workspaces)throw new Error("New workspace root detected - unexpected 'workspaces' field in package.json")}else throw new Error("New workspace is missing a package.json file");if(an.default.existsSync(vm.default.join(i.absolute,"pnpm-workspace.yaml")))throw new Error("New workspace root detected - unexpected pnpm-workspace.yaml")}catch(c){let l="UNKNOWN_ERROR";c instanceof Error&&(l=c.message),L.error(l),await an.default.rm(i.absolute,{recursive:!0,force:!0});return}}else if(s){let c=async f=>Promise.resolve(!f.includes("node_modules")),l=L.turboLoader(`Creating "${r}" from "${s.name}"...`);l.start(),await an.default.copy(s.paths.root,i.absolute,{filter:c}),l.stop()}let u=await an.default.readJSON(a);u.name=r,Object.keys(o).forEach(c=>{let l=o[c];l&&Object.keys(l).length>0&&(u[c]=l)}),await an.default.writeJSON(a,u,{spaces:2}),L.log(),L.log(`${NC.default.bold(L.turboGradient(">>> Success!"))} Created ${r} at "${i.relative}"`)}function F9(e){let{copy:t,...r}=e,n=t===!0||typeof t=="string"?"copy":"empty",i=typeof t=="string"?t:"",s=typeof t=="string"&&t.startsWith("https://")?"external":"internal";return{method:n,copy:{type:s,source:i},...r}}async function mo(e){let t=await Rc(e),r=F9(e);L.log();let n={project:t,opts:r};r.method==="copy"?(r.copy.type==="external"?L.info(`Copy a remote workspace from ${r.copy.source}`):L.info(`Copy an existing workspace from "${t.name}"`),L.log(),await Am(n)):(L.info(`Add an empty workspace to "${t.name}"`),L.log(),await wm(n))}async function go(e,t){let r=await Rc(t);L.log(),L.info(`Modify "${r.name}" using custom generators`),L.log(),await gm({generator:e,project:r,opts:t})}function MC(e){try{let t=JSON.parse(e),r={};for(let n in t){let i=lm(n,{to:"camel"});r[i]=t[n]}return r}catch(t){L.error("Error parsing arguments",t),process.exit(1)}}async function Dm(e,t){var r;if(e==="workspace"){let n=MC(t.json);n.showAllDependencies=(r=n.showAllDependencies)!=null?r:!1;let i=!1,s=n.empty||!0;n.copy===""||n.copy===!0?(i=!0,s=!1):n.copy&&n.copy.length>0&&(i=n.copy,s=!1),n.copy=i,n.empty=s,await mo(n)}else if(e==="run"){let n=MC(t.json),{generatorName:i,...s}=n;await go(i,s)}else L.error(`Received unknown command - "${e}" (must be one of "workspace" | "run")`),process.exit(1)}var UC=new $C.ProxyAgent;qC.default.globalAgent=UC;jC.default.globalAgent=UC;var yo=new Ue.Command;yo.name(HC.default.bold(L.turboGradient("@turbo/gen"))).description("Extend your Turborepo").version(ho.version,"-v, --version","Output the current version").helpOption("-h, --help","Display help for command").showHelpAfterError(!1);yo.command("run",{isDefault:!0}).alias("r").description("Run custom generators").addArgument(new Ue.Argument("[generator-name]","The name of the generator to run")).addOption(new Ue.Option("-c, --config <config>","Generator configuration file (default: turbo/generators/config.js")).addOption(new Ue.Option("-r, --root <dir>","The root of your repository (default: directory with root turbo.json)")).addOption(new Ue.Option("-a, --args <args...>","Arguments passed directly to generator").default([])).action(go);yo.command("workspace").aliases(["w"]).description("Add a new package or app to your project").addOption(new Ue.Option("-n, --name <workspace-name>","Name for the new workspace")).addOption(new Ue.Option("-b, --empty","Generate an empty workspace").conflicts("copy").default(!0)).addOption(new Ue.Option("-c, --copy [source]",`Generate a workspace using an existing workspace as a template. Can be the name of a local workspace
77
77
  within your monorepo, or a fully qualified GitHub URL with any branch and/or subdirectory.
78
78
  `).conflicts("empty")).addOption(new Ue.Option("-d, --destination <dir>","Where the new workspace should be created")).addOption(new Ue.Option("-t, --type <type>","The type of workspace to create").choices(["app","package"])).addOption(new Ue.Option("-r, --root <dir>","The root of your repository (default: directory with root turbo.json)")).addOption(new Ue.Option("-p, --example-path <path-to-example>",`In a rare case, your GitHub URL might contain a branch name with
79
79
  a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turbo/gen",
3
- "version": "2.4.3-canary.2",
3
+ "version": "2.4.3-canary.3",
4
4
  "description": "Extend a Turborepo",
5
5
  "homepage": "https://turbo.build/repo",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "ts-node": "^10.9.2",
26
26
  "update-check": "^1.5.4",
27
27
  "validate-npm-package-name": "^5.0.0",
28
- "@turbo/workspaces": "2.4.3-canary.2"
28
+ "@turbo/workspaces": "2.4.3-canary.3"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@jest/globals": "^29.7.0",
@@ -37,10 +37,10 @@
37
37
  "ts-jest": "^29.2.5",
38
38
  "tsup": "^6.7.0",
39
39
  "typescript": "5.5.4",
40
- "@turbo/test-utils": "0.0.0",
41
- "@turbo/eslint-config": "0.0.0",
42
40
  "@turbo/tsconfig": "0.0.0",
43
- "@turbo/utils": "0.0.0"
41
+ "@turbo/eslint-config": "0.0.0",
42
+ "@turbo/utils": "0.0.0",
43
+ "@turbo/test-utils": "0.0.0"
44
44
  },
45
45
  "files": [
46
46
  "dist"