@nest-arch/tui 0.1.39 → 0.1.46

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 (48) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/index-BQXvSdO-.js +4 -0
  3. package/dist/index-lnGBhuOD.js +117 -0
  4. package/dist/index.js +1 -1
  5. package/dist/templates/addons/husky/pre-commit.hbs +1 -1
  6. package/dist/templates/base/.env.hbs +17 -0
  7. package/dist/templates/base/.gitignore.hbs +3 -0
  8. package/dist/templates/base/README.md.hbs +37 -0
  9. package/dist/templates/base/pnpm-workspace.yaml.hbs +4 -0
  10. package/dist/templates/base/prisma.config.ts.hbs +11 -0
  11. package/dist/templates/base/src/app.controller.spec.ts.hbs +21 -2
  12. package/dist/templates/base/src/app.controller.ts.hbs +6 -1
  13. package/dist/templates/base/src/app.module.ts.hbs +20 -1
  14. package/dist/templates/base/src/app.service.ts.hbs +7 -0
  15. package/dist/templates/base/src/database/adapters/interfaces/db-adapter.interface.ts.hbs +14 -0
  16. package/dist/templates/base/src/database/adapters/mongo/prisma-mongo.adapter.ts.hbs +25 -0
  17. package/dist/templates/base/src/database/adapters/mongo/raw-mongo.adapter.ts.hbs +17 -0
  18. package/dist/templates/base/src/database/adapters/sql/drizzle-sql.adapter.ts.hbs +24 -0
  19. package/dist/templates/base/src/database/adapters/sql/prisma-sql.adapter.ts.hbs +29 -0
  20. package/dist/templates/base/src/database/adapters/sql/raw-sql.adapter.ts.hbs +49 -0
  21. package/dist/templates/base/src/database/adapters/sql/typeorm-sql.adapter.ts.hbs +23 -0
  22. package/dist/templates/base/src/database/db.module.ts.hbs +244 -0
  23. package/dist/templates/base/src/database/db.service.ts.hbs +88 -0
  24. package/dist/templates/base/src/database/entities/todo.entity.ts.hbs +32 -0
  25. package/dist/templates/base/src/database/index.ts.hbs +10 -0
  26. package/dist/templates/base/src/database/orm/drizzle/schema.ts.hbs +30 -0
  27. package/dist/templates/base/src/database/orm/typeorm/data-source.ts.hbs +24 -0
  28. package/dist/templates/base/src/database/schema/index.ts.hbs +32 -0
  29. package/dist/templates/base/src/main.ts.hbs +1 -1
  30. package/dist/templates/base/tsconfig.json.hbs +1 -1
  31. package/dist/templates/extras/docker/Dockerfile.hbs +22 -2
  32. package/dist/templates/extras/docker/docker-compose.yml.hbs +11 -3
  33. package/dist/templates/monorepo/apps/api-gateway/src/app.controller.spec.ts.hbs +21 -2
  34. package/dist/templates/monorepo/apps/api-gateway/src/app.module.ts.hbs +20 -1
  35. package/dist/templates/monorepo/apps/api-gateway/src/app.service.ts.hbs +7 -0
  36. package/dist/templates/monorepo/packages/db/package.json.hbs +21 -0
  37. package/dist/templates/monorepo/packages/db/tsconfig.json.hbs +4 -0
  38. package/dist/templates/monorepo/packages/env/src/api-gateway.ts.hbs +12 -0
  39. package/dist/templates/monorepo/root/.gitignore.hbs +3 -0
  40. package/dist/templates/monorepo/root/README.md.hbs +37 -0
  41. package/dist/templates/single-project/architecture/nest-gateway/src/app.module.ts.hbs +20 -1
  42. package/dist/templates/single-project/architecture/nest-gateway/src/app.service.ts.hbs +7 -1
  43. package/dist/templates/single-project/architecture/nest-microservice/src/app.module.ts.hbs +20 -1
  44. package/dist/templates/single-project/architecture/nest-microservice/src/app.service.ts.hbs +7 -0
  45. package/dist/templates/single-project/shared/config/env.ts.hbs +16 -0
  46. package/package.json +2 -2
  47. package/dist/index--w1UOCDp.js +0 -4
  48. package/dist/index-DuMVjfjC.js +0 -51
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import"./index-DuMVjfjC.js";import"react/jsx-runtime";import"ink";import"react";import"ink-text-input";import"@t3-oss/env-nextjs";import"zod";import"node:fs";import"node:os";import"node:path";import"node:child_process";import"node:fs/promises";import"node:util";import"handlebars";import"ts-morph";import"open";
2
+ import"./index-lnGBhuOD.js";import"react/jsx-runtime";import"ink";import"react";import"ink-text-input";import"@t3-oss/env-nextjs";import"zod";import"node:fs";import"node:os";import"node:path";import"node:fs/promises";import"handlebars";import"node:child_process";import"node:util";import"ts-morph";import"node:events";import"open";
@@ -0,0 +1,4 @@
1
+ var i=Object.defineProperty;var r=(e,a)=>i(e,"name",{value:a,configurable:!0});import{e as t}from"./index-lnGBhuOD.js";import"react/jsx-runtime";import"ink";import"react";import"ink-text-input";import"@t3-oss/env-nextjs";import"zod";import"node:fs";import"node:os";import"node:path";import"node:fs/promises";import"handlebars";import"node:child_process";import"node:util";import"ts-morph";import"node:events";import"open";function s(e){return[`pnpm create nest-arch@latest ${e.projectName}`,`--package-manager ${e.packageManager}`,`--http-provider ${e.httpProvider}`,`--project-type ${e.projectType}`,`--architecture ${e.architecture}`,`--database ${e.database.length>0?e.database.join(" "):"none"}`,`--orm ${e.orm.length>0?e.orm.join(" "):"none"}`,`--api ${e.api.length>0?e.api.join(" "):"none"}`,`--auth ${e.auth}`,`--extras ${e.extras.length>0?e.extras.join(" "):"none"}`,`--microservices ${e.microservices.length>0?e.microservices.join(" "):"none"}`,`--addons ${e.addons.length>0?e.addons.join(" "):"none"}`,e.initGit?"--git":"--no-git"].join(" ")}r(s,"buildReproducibleCommand");function p(e){return{$schema:t.NEST_ARCH_SCHEMA_URL,addons:e.addons,api:e.api,architecture:e.architecture,auth:e.auth,createdAt:new Date().toISOString(),database:e.database,description:e.description,extras:e.extras,httpProvider:e.httpProvider,initGit:e.initGit,microservices:e.microservices,orm:e.orm,packageManager:e.packageManager,projectName:e.projectName,projectType:e.projectType,reproducibleCommand:s(e),version:t.NEST_ARCH_VERSION}}r(p,"buildMetadata");function o(e){return`${["// nest-arch","//","// Project scaffolding tool for NestJS applications","//","// This file records the options used to generate this project.","// It can be used to reproduce the exact same project setup.","// This file is safe to delete.",""].join(`
2
+ `)+JSON.stringify(e,null,2)}
3
+ `}r(o,"serializeMetadata");function n(){return`${JSON.stringify({$schema:"http://json-schema.org/draft-07/schema#",description:"NestArch project configuration metadata file schema",properties:{$schema:{type:"string"},addons:{items:{enum:["agent-skills","husky","ultracite","nestjs-zod","scalar-ui"]},type:"array"},api:{items:{enum:["rest","trpc","graphql"]},type:"array"},architecture:{enum:["nest-api","nest-gateway","nest-microservice"]},auth:{enum:["passport","better-auth","better-auth:stateless","none"]},createdAt:{format:"date-time",type:"string"},database:{items:{enum:["postgresql","mysql","sqlite","mongodb"]},type:"array"},description:{type:"string"},extras:{items:{enum:["docker","health-check","rate-limiting","swagger","packages/shared"]},type:"array"},httpProvider:{enum:["express","fastify"]},initGit:{type:"boolean"},microservices:{items:{enum:["redis","mqtt","nats","rabbitmq","kafka","grpc"]},type:"array"},orm:{items:{enum:["prisma","typeorm","drizzle"]},type:"array"},packageManager:{enum:["pnpm","npm","yarn","bun"]},projectName:{type:"string"},projectType:{enum:["single","monorepo"]},reproducibleCommand:{type:"string"},version:{type:"string"}},required:["version","createdAt","reproducibleCommand","projectName","packageManager","httpProvider","projectType","architecture","database","orm","api","auth","extras","microservices","addons","initGit"],title:"NestArchMetadata",type:"object"},null,2)}
4
+ `}r(n,"buildSchemaContent");export{p as buildMetadata,n as buildSchemaContent,o as serializeMetadata};
@@ -0,0 +1,117 @@
1
+ var Vt=Object.defineProperty;var u=(t,e)=>Vt(t,"name",{value:e,configurable:!0});import{jsx as i,jsxs as b,Fragment as z}from"react/jsx-runtime";import{Box as y,Text as d,useInput as ae,useStdout as Fe,render as Qt,useApp as Xt}from"ink";import{useState as C,useEffect as ne,useMemo as J,useRef as Be,useCallback as S}from"react";import Zt from"ink-text-input";import{createEnv as er}from"@t3-oss/env-nextjs";import{z as pe}from"zod";import{existsSync as Se,readFileSync as tr,mkdirSync as rr,writeFileSync as sr}from"node:fs";import{homedir as ut}from"node:os";import k,{join as Y}from"node:path";import Z,{access as ar,readFile as ke,writeFile as he,rm as nr}from"node:fs/promises";import B from"handlebars";import{execFile as dt,exec as or,spawn as Ae}from"node:child_process";import{promisify as Ue}from"node:util";import{Project as ir,Scope as mt}from"ts-morph";import{once as se}from"node:events";import cr from"open";const ht="Nest Arch",Pe="v0.1.46",Ee="The comfy way to build NestJS projects",A="#e54545",R="#A0A0A0",ge="#6B6B6B",q="#E5E5E5",U="#61AFEF",ue="#3A3A3A",gt="#7FD99A",oe="#E8C468",Re="#e96142ff",fe=u(({borderTop:t=!0})=>i(y,{borderStyle:"single",borderBottom:!t,borderLeft:!1,borderRight:!1,borderTop:t,borderColor:ue,height:1,width:"full"}),"Divider"),lr=` \uFF0Fl\u3001
2
+ \uFF08\uFF9F\uFF64 \uFF61\uFF17
3
+ l\u3001\uFF9E ~\u30FD
4
+ \u3058\u3057(_,)\u30CE
5
+ `,He=` ,-. _,---._ __ /\\
6
+ / ) .-' \`./ / \\
7
+ ( ( ,' \` / /|
8
+ \\ \`-" \\'\\ / |
9
+ \`. , \\ \\ / |
10
+ /\`. ,'-\`----Y |
11
+ ( ; | '
12
+ | ,-. ,-' Angel's | /
13
+ | | ( | Stuff | /
14
+ ) | \\ \`.___________|/
15
+ \`--' \`--'
16
+ `,pr=u(t=>t>=4352&&t<=4447||t>=9001&&t<=9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=131072&&t<=196605||t>=196608&&t<=262141,"isFullwidthCodePoint"),ft=u(t=>{let e=0;for(const r of t){const s=r.codePointAt(0)??0;e+=pr(s)?2:1}return e},"getDisplayWidth"),ur=2,yt=[0,1,2,3,2,1],bt=["",".","..","..."],wt=u(({message:t="Scaffolding your project",isError:e=!1,showProgressText:r=!0,paddingX:s=2})=>{const[o,a]=C(0),[n,c]=C(0);ne(()=>{if(e)return;const _=setInterval(()=>{a(G=>(G+1)%yt.length)},200),N=setInterval(()=>{c(G=>(G+1)%bt.length)},400);return()=>{clearInterval(_),clearInterval(N)}},[e]);const l=lr.trimEnd().split(`
17
+ `),p=Math.max(...l.map(ft)),h=yt[o],m=e?A:oe,f=e?"\u2717":"\u25CF";return b(y,{flexDirection:"column",paddingX:s,children:[i(y,{flexDirection:"column",children:l.map((_,N)=>{const G=ft(_),$=N===0||N===l.length-1,L=p-G+ur-($?1:0),j=N===h;return b(d,{color:A,children:[_," ".repeat(L),j?i(d,{color:m,children:f}):" "]},N)})}),r&&b(d,{color:e?q:R,children:[t,e?"":bt[n]]})]})},"ScaffoldingAnimation"),We=[{id:"generate-files",label:"Generate project"},{id:"initialize-git",label:"Initialize Git"},{id:"initial-commit",label:"Initial commit"},{id:"install-dependencies",label:"Install dependencies"},{id:"run-formatter",label:"Run formatter"},{id:"formatter-commit",label:"Commit formatting"}],dr=We.map(t=>t.id),jt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function mr(t,e){if(!t)return We.map(s=>({stage:s,status:"pending"}));const r=dr.indexOf(t);return We.map((s,o)=>o<r?{stage:s,status:e?"failed":"completed"}:o===r?e?{stage:s,status:"failed"}:{stage:s,status:"active"}:e&&o>r?{stage:s,status:"pending"}:e?{stage:s,status:"failed"}:{stage:s,status:"pending"})}u(mr,"getStages");function hr(t,e){switch(t){case"completed":return"\u2713";case"active":return e;case"failed":return"\u2717";case"skipped":return"\u2013";case"pending":return"\u25CB";default:return t}}u(hr,"statusIcon");function gr(t){switch(t){case"completed":return gt;case"active":return oe;case"failed":return A;case"skipped":case"pending":return ge;default:return t}}u(gr,"statusColor");function fr(t){return t===void 0?"":` (${t}%)`}u(fr,"formatPercentage");function yr(t){return t?.message?t.message:"Installing dependencies..."}u(yr,"getInstallMessage");const br=u(({currentStage:t,generationMessage:e,installProgress:r,isError:s})=>{const o=J(()=>mr(t,s),[t,s]),[a,n]=C(0);ne(()=>{if(s)return;const l=setInterval(()=>{n(p=>(p+1)%jt.length)},80);return()=>clearInterval(l)},[s]);const c=jt[a]??"\u280B";return b(y,{flexDirection:"column",paddingX:2,children:[i(y,{marginBottom:1,children:i(wt,{showProgressText:!1,paddingX:0,isError:s})}),i(y,{flexDirection:"column",rowGap:0,children:o.map(l=>{const p=l.status==="active",h=p&&l.stage.id==="install-dependencies",m=r?.percentage,f=16,_=m===void 0?0:Math.round(m/100*f),N=f-_;return b(y,{flexDirection:"column",children:[b(y,{children:[b(d,{bold:p,color:gr(l.status),children:[hr(l.status,c)," ",l.stage.label]}),h?i(d,{children:m===void 0?null:b(z,{children:[i(d,{color:oe,children:fr(m)})," ",i(d,{color:oe,children:"\u2588".repeat(_)}),i(d,{color:ue,children:"\u2591".repeat(N)})]})}):null]}),h?i(y,{marginLeft:4,children:i(d,{color:R,children:yr(r)})}):null]},l.stage.id)})}),!s&&t===null?i(y,{marginTop:1,children:i(d,{color:R,children:e})}):null,s?i(y,{marginTop:1,flexDirection:"column",children:e.split(`
18
+ `).map((l,p)=>i(d,{color:l.startsWith(" ")?R:A,children:l},p))}):null]})},"InstallationProgress"),Je=u(({action:t="select",showBack:e=!1})=>b(d,{children:[t==="select"||t==="multi-select"?i(d,{color:R,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,i(d,{color:R,children:t==="confirm"?b(z,{children:[i(d,{color:q,children:"Enter "}),"to confirm"]}):t==="multi-select"?b(z,{children:[i(d,{color:q,children:"Space "}),"to toggle \u2022",i(d,{color:q,children:" Enter "}),"to confirm"]}):b(z,{children:[i(d,{color:q,children:"Enter "}),"to select"]})}),b(d,{color:R,children:[e?b(z,{children:[" ","\u2022",i(d,{color:q,children:" Ctrl+B "}),"to go back"]}):"",b(z,{children:[" ","\u2022",i(d,{color:q,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),vt=u(({architecture:t,projectName:e,packageManager:r,isGitInitialized:s,dependenciesInstalled:o,outputDir:a})=>i(y,{flexDirection:"column",children:b(y,{flexDirection:"column",marginTop:1,children:[i(d,{color:gt,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),b(y,{marginTop:1,children:[i(d,{color:q,children:"Project: "}),i(d,{color:U,bold:!0,children:e})]}),b(y,{children:[i(d,{color:q,children:"Architecture: "}),i(d,{color:U,bold:!0,children:t})]}),a?b(y,{children:[i(d,{color:q,children:"Location: "}),i(d,{color:U,bold:!0,children:a})]}):null,s?i(y,{marginTop:1,children:i(d,{color:R,children:"Git repository initialized"})}):null,b(y,{flexDirection:"column",borderStyle:"round",borderColor:A,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[i(d,{color:q,bold:!0,children:"\u{1F680} NEXT STEPS"}),i(y,{height:1}),i(d,{color:q,children:"1. Move into the project directory:"}),i(d,{color:U,bold:!0,children:` cd ${e}`}),i(y,{height:1}),o?i(y,{children:i(d,{color:R,children:"2. Dependencies already installed"})}):b(z,{children:[i(d,{color:q,children:"2. Install dependencies:"}),i(d,{color:U,bold:!0,children:` ${r} install`})]}),i(y,{height:1}),b(d,{color:q,children:["3."," Start development server:"]}),i(d,{color:U,bold:!0,children:` ${r} run dev`})]}),i(y,{marginTop:1,children:i(d,{color:R,children:"(Press enter to exit)"})})]})}),"DoneStep"),wr=100,_e=u(t=>{const e=Be(0);ae((r,s)=>{if(s.upArrow||s.downArrow||s.leftArrow||s.rightArrow||r==="k"||r==="j"||r==="h"||r==="l"){const a=Date.now();if(a-e.current<wr)return;e.current=a}t(r,s)})},"useArrowSelect"),ie=u(({initialSelected:t,onConfirm:e,onChange:r,options:s,prompt:o,minified:a=!1})=>{const n=J(()=>new Set(s.map(P=>P.value)),[s]),c=S(P=>P.filter(O=>n.has(O)),[n]),[l,p]=C(0),[h,m]=C(()=>c(t)),f=Be(h);f.current=h;const _=Be(r);_.current=r,ne(()=>{const P=c(t);m(P),p(0),_.current?.(P)},[t,c]);const N=S(P=>h.includes(P),[h]),G=S(P=>{const O=s[P];O&&m(I=>{const W=I.includes(O.value)?I.filter(V=>V!==O.value):[...I,O.value];return f.current=W,r?.(W),W})},[s,r]),$=S(()=>{e(f.current)},[e]),L=s.length>16,j=L?Math.ceil(s.length/2):s.length;_e((P,O)=>{O.upArrow||P==="k"?p(I=>(I-1+s.length)%s.length):O.downArrow||P==="j"?p(I=>(I+1)%s.length):L&&(O.leftArrow||P==="h")?p(I=>(I-j+s.length)%s.length):L&&(O.rightArrow||P==="l")?p(I=>(I+j)%s.length):O.return?$():(P===" "||P==="x")&&G(l)});const H=h.length,ee=u((P,O)=>{const I=N(P.value),W=O===l,V=I?"\u25CF":"\u25CB";return b(y,{flexDirection:"column",children:[i(d,{children:W?b(z,{children:[i(d,{color:A,children:"> "}),i(d,{color:I?A:R,children:`${V} `}),i(d,{color:I?A:q,children:P.label})]}):b(z,{children:[i(d,{color:I?A:R,children:` ${V}`}),i(d,{color:ge,children:` ${P.label}`})]})}),W&&!L?b(d,{color:R,children:[" ",P.description]}):null]},P.value)},"renderOption");let te;return L||(te=a?0:1),b(y,{flexDirection:"column",children:[i(d,{color:R,children:o}),i(d,{color:oe,children:H===0?"No options selected yet \u2014 pick what you need":`${H} selected`}),i(y,{marginTop:1,flexDirection:L?"row":"column",rowGap:te,columnGap:L?4:void 0,overflow:"hidden",children:L?b(z,{children:[i(y,{flexDirection:"column",rowGap:a?0:1,flexGrow:1,flexBasis:0,children:s.slice(0,j).map((P,O)=>ee(P,O))}),i(y,{flexDirection:"column",rowGap:a?0:1,flexGrow:1,flexBasis:0,children:s.slice(j).map((P,O)=>ee(P,O+j))})]}):s.map((P,O)=>ee(P,O))})]})},"MultiSelectStep"),St="my-nest-app",kt=64,jr=/^[a-z][a-z0-9-]*$/u;function ce(t){return t.trim()||St}u(ce,"resolveProjectName");function Te(t){const e=t.trim();return e?e.length>kt?`Project name must be at most ${kt} characters`:jr.test(e)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}u(Te,"validateProjectName");const At=u(({error:t,onChange:e,onSubmit:r,value:s})=>(ae((o,a)=>{a.return&&r()}),b(y,{flexDirection:"column",children:[i(d,{color:R,children:"Enter a name for your project"}),b(y,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[i(d,{color:q,children:"Project name:"}),i(Zt,{placeholder:St,value:s,onChange:e})]}),t?i(d,{color:A,children:t}):null]})),"ProjectNameStep"),K=u(({onConfirm:t,options:e,prompt:r,initialValue:s})=>{const[o,a]=C(()=>{const c=e.findIndex(l=>l.value===s);return Math.max(c,0)});ne(()=>{const c=e.findIndex(l=>l.value===s);a(Math.max(c,0))},[s,e]);const n=S(()=>{const c=e[o];c&&t(c.value)},[t,e,o]);return _e((c,l)=>{l.upArrow||c==="k"?a(p=>(p-1+e.length)%e.length):l.downArrow||c==="j"?a(p=>(p+1)%e.length):l.return&&n()}),b(y,{flexDirection:"column",children:[i(d,{color:R,children:r}),i(y,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((c,l)=>{const p=l===o;return b(y,{flexDirection:"column",children:[i(d,{children:p?b(z,{children:[i(d,{color:A,children:"> "}),i(d,{color:A,children:c.label})]}):i(d,{color:ge,children:` ${c.label}`})}),p?i(d,{color:R,children:c.description}):null]},c.value)})})]})},"SingleSelectStep"),Pt=[{description:"Fast, disk-efficient package manager (recommended)",label:"pnpm",value:"pnpm"},{description:"Default Node.js package manager",label:"npm",value:"npm"},{description:"Classic alternative with workspaces support",label:"yarn",value:"yarn"},{description:"A superfast Node.js-compatible package manager",label:"bun",value:"bun"}],Ye=[{description:"The modern, all-in-one toolchain written in Rust",label:"Biome",value:"biome"},{description:"The fastest linter available, 50-100x faster than ESLint",label:"Oxlint + Oxfmt",value:"oxlint-oxfmt"},{description:"No formatter and no linter. Welcome to the jungle",label:"(None)",value:"none"}],Et=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],Rt=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",label:"Monorepo (Turborepo)",value:"monorepo"}],_t=[{description:"Standard REST or GraphQL API application",label:"NestJS API",value:"nest-api"},{description:"Gateway routing for microservices (monorepo only)",label:"NestJS API Gateway",value:"nest-gateway"},{description:"Message-based or RPC microservice",label:"NestJS Microservice",value:"nest-microservice"}],Ke=[{description:"Relational database with strong ecosystem",label:"PostgreSQL",value:"postgresql"},{description:"Popular relational database",label:"MySQL",value:"mysql"},{description:"Embedded database for local development",label:"SQLite",value:"sqlite"},{description:"Document database",label:"MongoDB",value:"mongodb"}],Ve=[{description:"Type-safe ORM with schema and migrations",label:"Prisma",value:"prisma"},{description:"Decorator-based ORM for TypeScript",label:"TypeORM",value:"typeorm"},{description:"Lightweight SQL ORM <insert MongoDB unsupported joke here>",label:"Drizzle",value:"drizzle"}],Tt=[{description:"RESTful HTTP endpoints",label:"REST",value:"rest"},{description:"End-to-end typesafe APIs",label:"tRPC",value:"trpc"},{description:"GraphQL schema and resolvers",label:"GraphQL",value:"graphql"}],Qe=[{description:"No authentication scaffolding",label:"None",value:"none"},{description:"Flexible authentication \u2014 stateless (JWE cookies) when no database, ORM-backed when database selected",label:"Passport",value:"passport"},{description:"Modern auth library with database-backed sessions",label:"Better Auth",value:"better-auth"},{description:"Better Auth without a database \u2014 Oauth session data stored in signed/encrypted cookies",label:"Better Auth (Stateless)",value:"better-auth:stateless"}],Xe=[{description:"Dockerfile and docker-compose setup",label:"Docker",value:"docker"},{description:"Terminus health check endpoints",label:"Health Check",value:"health-check"},{description:"Request throttling middleware",label:"Rate Limiting",value:"rate-limiting"},{description:"OpenAPI documentation",label:"Swagger",value:"swagger"},{description:"Shared packages for API types in a monorepo",label:"packages/shared",value:"packages/shared"}],Ze=[{description:"Cursor agent skills library (.agents/skills)",label:"Agent Skills",value:"agent-skills"},{description:"Git hooks for pre-commit checks",label:"Husky",value:"husky"},{description:"Configurate ultracite for your developer tools",label:"Ultracite",value:"ultracite"},{description:"Zod-based DTO validation",label:"NestJS-Zod",value:"nestjs-zod"},{description:"Modern OpenAPI documentation UI",label:"Scalar UI (Recommended)",value:"scalar-ui"}],vr=[{description:"Pub/sub or streaming protocol",label:"Redis",value:"redis"},{description:"Lightweight MQTT messaging",label:"MQTT",value:"mqtt"},{description:"Cloud-native messaging broker",label:"NATS",value:"nats"},{description:"Enterprise messaging with RabbitMQ",label:"RabbitMQ",value:"rabbitmq"},{description:"Highly scalable Kafka streaming",label:"Kafka",value:"kafka"},{description:"RPC-style gRPC communication",label:"gRPC",value:"grpc"}],Ot=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],Sr=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],kr=[{description:"Universal (creates .vscode/settings.json for Visual Studio Code, Cursor, Windsurf, and more)",label:"Universal",value:"universal"},{description:"Zed (creates .zed/settings.json)",label:"Zed",value:"zed"}],Ar=[{description:"Universal (creates AGENTS.md for Codex, Jules, Devin, and more)",label:".agents (Universal)",value:"universal"},{description:"Claude (creates .claude/CLAUDE.md)",label:"Claude",value:"claude"},{description:"Replit (creates replit.md)",label:"Replit",value:"replit"},{description:"Aider (creates ultracite.md)",label:"Aider",value:"aider"},{description:"Gemini (creates GEMINI.md)",label:"Gemini",value:"gemini"},{description:"Roo (creates .roo/rules/ultracite.md)",label:"Roo",value:"roo-code"},{description:"Amazon Q CLI (creates .amazonq/rules/ultracite.md)",label:"Amazon Q CLI",value:"amazon-q-cli"},{description:"Firebender (creates firebender.json)",label:"Firebender",value:"firebender"}],Pr=[{description:"Cursor agent hooks",label:"Cursor",value:"cursor"},{description:"Windsurf agent hooks",label:"Windsurf",value:"windsurf"},{description:"CodeBuddy agent hooks",label:"CodeBuddy",value:"codebuddy"},{description:"Claude agent hooks",label:"Claude",value:"claude"}],Er=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],Rr={addons:"Addons",apiLayer:"API layer",architecture:"Architecture",auth:"Authentication",database:"Database",done:"Done",extras:"Extras",formatter:"Formatter",httpProvider:"HTTP provider",initGit:"Git repository",installDependencies:"Install dependencies",installing:"Installing",microservices:"Microservices communication",orm:"ORM",packageManager:"Package manager",projectName:"Project name",projectType:"Project type",summary:"Summary",ultraciteAgents:"Ultracite agents",ultraciteEditors:"Ultracite editors",ultraciteHooks:"Ultracite hooks",ultraciteInstallSkill:"Ultracite skill",ultraciteSetup:"Ultracite setup"},_r=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","ultraciteSetup","installing","done"];function Tr(t){return t.includes("mongodb")}u(Tr,"databaseIncludesMongodb");function Ct(t){return t.length===0}u(Ct,"databaseIsEmpty");function Oe(t){return Ct(t)}u(Oe,"shouldSkipOrmStep");function ye(t){return _r.filter(e=>!(e==="orm"&&Oe(t.database)||e==="microservices"&&t.architecture!=="nest-gateway"||(e==="ultraciteEditors"||e==="ultraciteAgents"||e==="ultraciteHooks"||e==="ultraciteInstallSkill"||e==="ultraciteSetup")&&(!t.addons.includes("ultracite")||t.formatter==="none")))}u(ye,"getVisibleSteps");const xt=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function be(t){return xt.includes(t)}u(be,"isUltraciteSubStep");function Or(t,e){if(!be(t))return null;const r=xt.filter(c=>ye(e).includes(c)),s=r.indexOf(t);if(s===-1)return null;const o=r.length,a=s+1,n=Math.round(a/o*100);return{current:a,percent:n,total:o}}u(Or,"getUltraciteSubStepInfo");function et(t){return ye(t).filter(e=>e!=="installing"&&e!=="done"&&!be(e)).length}u(et,"getTotalSteps");function Cr(t,e){const r=ye(e).filter(a=>a!=="installing"&&a!=="done");if(t==="installing"||t==="done")return et(e);if(be(t)){const a=r.indexOf("addons");return a===-1?1:a+1}const o=r.filter(a=>!be(a)).indexOf(t);return o===-1?1:o+1}u(Cr,"getDisplayStepNumber");function xr(t,e){const r=ye(e),s=r.indexOf(t);return s===-1||s>=r.length-1?null:r[s+1]??null}u(xr,"getNextStepId");function Mr(t,e){const r=ye(e),s=r.indexOf(t);return s<=0?null:r[s-1]??null}u(Mr,"getPreviousStepId");function Ir(t){return t==="monorepo"?_t:_t.filter(e=>e.value!=="nest-gateway")}u(Ir,"filterArchitectureOptions");function Mt(t){return Tr(t)?Ve.filter(e=>e.value!=="drizzle"):Ve}u(Mt,"filterOrmOptions");function Dr(t){return t.includes("drizzle")?Ke.filter(e=>e.value!=="mongodb"):Ke}u(Dr,"filterDatabaseOptions");function Nr(t){return Ct(t)?Qe.filter(e=>e.value!=="better-auth"):Qe}u(Nr,"filterAuthOptions");function zr(t,e){return e.includes("drizzle")?t.filter(r=>r!=="mongodb"):t}u(zr,"sanitizeDatabaseForOrm");function It(t){return"nest-api"}u(It,"defaultArchitecture");function Dt(t,e){if(Oe(e))return[];const r=new Set(Mt(e).map(s=>s.value));return t.filter(s=>r.has(s))}u(Dt,"sanitizeOrmForDatabase");function de(t,e){return t.find(r=>r.value===e)?.label??e}u(de,"labelFor$1");function me(t,e){return e.length===0?"None":e.map(r=>de(t,r)).join(", ")}u(me,"labelsFor");const qr=u(({onConfirm:t,state:e})=>{ae((o,a)=>{a.return&&t()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},s=[{label:"Project",value:ce(e.projectName)},{label:"Package manager",value:e.packageManager?de(Pt,e.packageManager):"\u2014"},{label:"Formatter",value:e.formatter?de(Ye,e.formatter):"\u2014"},{label:"HTTP provider",value:e.httpProvider?de(Et,e.httpProvider):"\u2014"},{label:"Project type",value:e.projectType?de(Rt,e.projectType):"\u2014"},{label:"Architecture",value:e.architecture?r[e.architecture]??e.architecture:"\u2014"},{label:"Database",value:me(Ke,e.database)}];return Oe(e.database)||s.push({label:"ORM",value:me(Ve,e.orm)}),s.push({label:"API layer",value:me(Tt,e.api)}),e.architecture==="nest-gateway"&&s.push({label:"Microservices",value:me([{label:"Redis",value:"redis"},{label:"MQTT",value:"mqtt"},{label:"NATS",value:"nats"},{label:"RabbitMQ",value:"rabbitmq"},{label:"Kafka",value:"kafka"},{label:"gRPC",value:"grpc"}],e.microservices)}),s.push({label:"Auth",value:e.auth?de(Qe,e.auth):"\u2014"},{label:"Extras",value:me(Xe,e.extras)},{label:"Addons",value:me(Ze,e.addons)},{label:"Git",value:e.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:e.installDependencies==="yes"?"Install":"Skip"}),b(z,{children:[i(y,{flexDirection:"column",marginBottom:1,children:b(d,{children:[i(d,{color:A,children:"\u2726 "}),i(d,{color:U,children:"Review your selections"})]})}),i(y,{flexDirection:"column",rowGap:0,overflow:"hidden",children:s.map(o=>b(y,{flexDirection:"row",columnGap:1,children:[i(d,{color:Re,children:`${o.label}:`}),i(d,{color:oe,children:o.value})]},o.label))})]})},"SummaryStep");function Gr(t,e){return t.find(r=>r.value===e)?.label??e}u(Gr,"labelFor");const $r=u(({onConfirm:t,state:e})=>{ae((a,n)=>{n.return&&t()});const r=(()=>{switch(e.formatter){case"biome":return"biome";case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return"eslint";default:return"oxlint"}})(),s=[];e.addons.includes("husky")&&s.push("husky");const o=[{label:"Linter",value:`${r} (from ${Gr(Ye,e.formatter??"oxlint-oxfmt")})`},{label:"Package manager",value:e.packageManager??"pnpm"},{label:"Frameworks",value:"nestjs"},{label:"Integrations",value:s.length>0?s.join(", "):"none"},{label:"Flags",value:"--quiet"}];return b(z,{children:[b(y,{flexDirection:"column",marginBottom:1,children:[b(d,{children:[i(d,{color:A,children:"\u2726 "}),i(d,{color:U,children:"Ultracite Configuration"})]}),i(d,{color:Re,children:"The following configuration will be applied:"})]}),b(y,{flexDirection:"column",rowGap:1,overflow:"hidden",children:[o.map(a=>b(y,{flexDirection:"row",columnGap:1,children:[i(d,{color:Re,children:`${a.label}:`}),i(d,{color:oe,children:a.value})]},a.label)),i(y,{marginTop:1,children:b(d,{color:Re,children:["Command: npx ultracite init --quiet --pm ",e.packageManager," ","--linter ",r," --frameworks nestjs",s.length>0?` --integrations ${s.join(",")}`:""]})})]})]})},"UltraciteSetupStep"),tt=er({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:pe.string().pipe(pe.coerce.number()).default(95),NEST_ARCH_BETA_MODE:pe.enum(["true","false"]).default("false").transform(t=>t==="true"),NEST_ARCH_SCHEMA_URL:pe.string().default("./schema.json"),NEST_ARCH_VERSION:pe.string().default("0.0.1"),NODE_ENV:pe.enum(["development","production","test"]).default("development")}});function rt(t){return t.length===0?"\u2014":t.join(", ")}u(rt,"formatList");const Lr=u(({state:t,stepId:e})=>{const{stdout:r}=Fe(),s=r.columns||r.getWindowSize?.()[0]||80,o=Math.min(tt.APP_MAX_WIDTH,s-4),a=[];if(e!=="projectName"&&t.projectName.trim()&&a.push(ce(t.projectName)),t.packageManager&&a.push(t.packageManager),t.httpProvider&&a.push(t.httpProvider),t.projectType&&a.push(t.projectType==="monorepo"?"Monorepo":"Single"),t.architecture){const l={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};a.push(l[t.architecture]??t.architecture)}if(t.database.length>0&&a.push(rt(t.database)),t.orm.length>0&&a.push(rt(t.orm)),t.api.length>0&&a.push(rt(t.api)),t.auth&&a.push(t.auth),t.extras.length>0&&a.push(`+${t.extras.length} extras`),t.addons.length>0&&!be(e)&&a.push(`+${t.addons.length} addons`),t.initGit&&a.push(t.initGit==="yes"?"git init":"no git"),a.length===0)return b(d,{children:[i(d,{color:A,children:"\u25C6 "}),i(d,{color:A,children:"Create a new NestJS project"})]});const[n,...c]=a;return b(z,{children:[b(d,{children:[i(d,{color:A,children:"\u25C6 "}),i(d,{color:A,children:"Create a new NestJS project"})]}),e!=="summary"&&i(y,{borderStyle:"single",borderColor:ue,width:o,children:b(d,{children:[i(d,{children:"Project Name: "}),i(d,{color:A,children:n}),i(d,{color:R,children:" Selected: "}),c.length>0?i(d,{color:R,children:`${c.filter(l=>l!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),Fr=u(({displayStep:t,stepId:e,subProgress:r,totalSteps:s})=>b(y,{paddingLeft:2,paddingTop:e==="summary"?2:1,marginBottom:1,children:[i(d,{color:q,children:"Create project"}),i(d,{color:R,children:` \u2014 step ${t}/${s}`}),r?i(d,{color:U,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):i(d,{color:U,children:` \xB7 ${Rr[e]}`})]}),"WizardTitle$1"),st=Y(ut(),".nestarch"),at=Y(st,"last-used.json");function Br(){try{if(!Se(at))return null;const t=tr(at,"utf-8");return JSON.parse(t)}catch{return null}}u(Br,"getLastUsedConfig");function Nt(t){try{Se(st)||rr(st,{recursive:!0}),sr(at,JSON.stringify(t,null,2),"utf-8")}catch{}}u(Nt,"saveLastUsedConfig");function Ur(t){const e=[t.packageManager];t.httpProvider&&e.push(t.httpProvider),t.api.length>0&&e.push(t.api.join(", ")),t.projectType&&e.push(t.projectType);const r=new Date,s=r.toLocaleString("en-US",{month:"short"}),o=r.getDate(),a=r.getFullYear(),n=`${s} ${o}, ${a}`;return`${e.join(", ")} (last used ${n})`}u(Ur,"buildLastUsedDescription");class lt{static{u(this,"TemplateEngine")}cache={};cacheEnabled;templatesDir;constructor(e,r={}){this.templatesDir=e,this.cacheEnabled=r.cache??!0,lt.registerHelpers(r.helpers)}static registerHelpers(e){if(B.registerHelper("eq",(r,s)=>r===s),B.registerHelper("ne",(r,s)=>r!==s),B.registerHelper("lt",(r,s)=>r<s),B.registerHelper("gt",(r,s)=>r>s),B.registerHelper("and",(r,s)=>r&&s),B.registerHelper("or",(r,s)=>r||s),B.registerHelper("uppercase",r=>r?.toUpperCase?.()),B.registerHelper("lowercase",r=>r?.toLowerCase?.()),B.registerHelper("capitalize",r=>r?r.charAt(0).toUpperCase()+r.slice(1):""),B.registerHelper("camelCase",r=>r?.split("-").map((s,o)=>o===0?s.toLowerCase():s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),B.registerHelper("pascalCase",r=>r?.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),B.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),e)for(const[r,s]of Object.entries(e))B.registerHelper(r,s)}async loadTemplate(e){const r=e;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const s=k.join(this.templatesDir,e),o=await Z.readFile(s,"utf-8"),a=B.compile(o);return this.cacheEnabled&&(this.cache[r]=a),a}async renderTemplate(e,r){return(await this.loadTemplate(e))(r.context)}async renderToFile(e,r,s){return{content:await this.renderTemplate(e,s),filePath:r,isBinary:!1}}clearCache(){this.cache={}}getCacheStats(){return{enabled:this.cacheEnabled,size:Object.keys(this.cache).length}}}class Hr{static{u(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(e){this.baseDir=e}getBaseDir(){return this.baseDir}async writeFile(e,r={}){const s=k.join(this.baseDir,e.filePath),o=k.dirname(s);try{await Z.mkdir(o,{recursive:!0});let a=!1;try{await Z.stat(s),a=!0}catch{a=!1}if(a&&!r.overwrite)return{backed:!1,error:"File already exists and overwrite is disabled",filePath:s,written:!1};let n=!1;if(a&&r.createBackups&&!r.dryRun){const c=`${s}.bak`;await Z.copyFile(s,c),n=!0}return r.dryRun||(await Z.writeFile(s,e.content,"utf-8"),this.writtenFiles.add(s)),{backed:n,filePath:s,written:!r.dryRun}}catch(a){return{backed:!1,error:a instanceof Error?a.message:"Unknown error",filePath:s,written:!1}}}writeFiles(e,r={}){return Promise.all(e.map(s=>this.writeFile(s,r)))}async fileExists(e){const r=k.join(this.baseDir,e);try{return await Z.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(e,r){const s=[],o=k.join(this.baseDir,e),a=k.join(this.baseDir,r);await Z.mkdir(a,{recursive:!0});const n=await Z.readdir(o,{withFileTypes:!0});for(const c of n){const l=k.join(o,c.name),p=k.join(a,c.name);if(c.isDirectory()){const h=await this.copyDirectory(k.relative(this.baseDir,l),k.relative(this.baseDir,p));s.push(...h)}else{const h=await Z.readFile(l,"utf-8");await Z.writeFile(p,h,"utf-8"),s.push(p),this.writtenFiles.add(p)}}return s}}const Ce=Ue(dt);async function Wr(t){await Ce("git",["init"],{cwd:t})}u(Wr,"gitInit");async function zt(t){await Ce("git",["add","."],{cwd:t})}u(zt,"gitAddAll");async function qt(t,e){await Ce("git",["commit","--no-verify","-m",e],{cwd:t})}u(qt,"gitCommit");async function Jr(t){try{const{stdout:e}=await Ce("git",["diff","--cached","--name-only"],{cwd:t});return e.trim().length>0}catch{return!1}}u(Jr,"gitHasStagedChanges");async function Yr(t){try{return await ar(Y(t,".git")),!0}catch{return!1}}u(Yr,"gitDirectoryExists");const Kr=Ue(dt),Vr={bun:["Bun is not installed or not found in your PATH.",""," Install Bun: https://bun.sh",""," Then restart your terminal and try again."].join(`
19
+ `),npm:["npm is not installed or not found in your PATH.",""," Install npm: https://nodejs.org/en/download",""," Then restart your terminal and try again."].join(`
20
+ `),pnpm:["pnpm is not installed or not found in your PATH.",""," Install pnpm: npm install -g pnpm"," Or enable Corepack: corepack enable && corepack prepare pnpm@latest --activate",""," Then restart your terminal and try again."].join(`
21
+ `),yarn:["Yarn is not installed or not found in your PATH.",""," Install Yarn: npm install -g yarn",""," Then restart your terminal and try again."].join(`
22
+ `)};function Qr(t){switch(t){case"pnpm":return["pnpm",["dlx","ultracite","fix","--unsafe"]];case"npm":return["npx",["--yes","ultracite","fix","--unsafe"]];case"yarn":return["yarn",["dlx","ultracite","fix","--unsafe"]];case"bun":return["bunx",["ultracite","fix","--unsafe"]];default:{const e=t;throw new Error(`Unsupported package manager: ${e}`)}}}u(Qr,"getFormatterCommand");function Xr(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="EINVAL")}u(Xr,"isNodeNotFoundError");async function Zr(t,e){const[r,s]=Qr(t);try{return await Kr(r,s,{cwd:e,shell:!0,timeout:12e4}),{success:!0}}catch(o){return Xr(o)?{error:Vr[t],success:!1}:{success:!0}}}u(Zr,"runFormatter");const es=Ue(or);function ts(t){switch(t){case"biome":return"biome";case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return"eslint";case"oxlint-oxfmt":return"oxlint";case"none":return"none";default:return"oxlint"}}u(ts,"mapFormatterToLinter");async function rs(t){const e=Y(t,"package.json");try{const s=await ke(e,"utf-8"),o=JSON.parse(s);o.devDependencies&&(o.devDependencies=Object.fromEntries(Object.entries(o.devDependencies).filter(([a])=>!a.startsWith("stylelint")))),await he(e,`${JSON.stringify(o,null,2)}
23
+ `,"utf-8")}catch{}const r=[".stylelintrc",".stylelintrc.json",".stylelintrc.js",".stylelintrc.yaml",".stylelintrc.yml","stylelint.config.js","stylelint.config.mjs","stylelint.config.cjs"];for(const s of r){const o=Y(t,s);Se(o)&&await nr(o,{force:!0})}}u(rs,"removeStylelint");async function ss(t,e){const r=ts(e.formatter);if(r==="none")return{message:"Skipping ultracite init (no formatter selected)",success:!0};const s=[];e.addons.includes("husky")&&s.push("husky");const o=["ultracite","init","--quiet","--skip-install","--pm",e.packageManager,"--linter",r,"--frameworks","nestjs"];s.length>0&&o.push("--integrations",...s),e.addons.includes("ultracite")&&(e.ultraciteEditors.length>0&&o.push("--editors",...e.ultraciteEditors),e.ultraciteAgents.length>0&&o.push("--agents",...e.ultraciteAgents),e.ultraciteHooks.length>0&&o.push("--hooks",...e.ultraciteHooks),e.ultraciteInstallSkill==="yes"&&o.push("--install-skill"));const a=`npx --yes ${o.join(" ")}`;try{const{stderr:n}=await es(a,{cwd:t,timeout:12e4});return n?.trim()&&console.error(`[ultracite-init] stderr: ${n.trim()}`),e.formatter==="eslint-prettier-no-stylelint"&&await rs(t),{message:"Ultracite setup completed",success:!0}}catch(n){let c=n instanceof Error?n.message:String(n);if(n&&typeof n=="object"&&"stderr"in n){const l=n.stderr?.trim();l&&(c=`${c}
24
+ ${l}`)}return console.error(`[ultracite-init] Failed: ${c}`),{message:`Ultracite setup failed: ${c}`,success:!1}}}u(ss,"runUltraciteInit");class as{static{u(this,"TemplateRegistry")}templates=new Map;groups=new Map;registerTemplate(e){this.templates.set(e.id,e)}registerTemplates(e){for(const r of e)this.registerTemplate(r)}registerGroup(e){this.groups.set(e.id,e);for(const r of e.templates)this.registerTemplate(r)}getTemplate(e){return this.templates.get(e)}getGroup(e){return this.groups.get(e)}getAllTemplates(){return[...this.templates.values()]}getAllGroups(){return[...this.groups.values()]}getTemplatesByGroup(e){return this.groups.get(e)?.templates||[]}getTemplatesByFormat(e){return[...this.templates.values()].filter(r=>r.format===e)}async loadFromDirectory(e,r){const s=[];try{const o=await Z.readdir(e,{withFileTypes:!0});for(const a of o){if(!a.isFile())continue;const{name:n}=a,c=k.extname(n);if(c===".hbs"){const l=k.basename(n,c),p={description:`Template: ${l}`,format:"handlebars",id:l,name:l.replaceAll(/[-_]/gu," "),optional:n.startsWith("_"),path:k.join(k.relative(k.dirname(e),e),n)};s.push(p),this.registerTemplate(p)}}if(r&&s.length>0){const a={description:`Templates from ${e}`,id:r,name:r,templates:s};this.registerGroup(a)}}catch(o){console.error(`Failed to load templates from ${e}:`,o)}return s}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function x(t,e,r){const s="[ultracite-inject]";if(r){const o=r instanceof Error?r.message:String(r);console.error(`${s} ${t}: ${e} \u2014 ${o}`)}else console.error(`${s} ${t}: ${e}`)}u(x,"log");const nt={biome:{complexity:{noStaticOnlyClass:"off",noUselessConstructor:"off"},performance:{noNamespaceImport:"off"},style:{noParameterProperties:"off",useImportType:"off"}},eslint:{"@typescript-eslint/consistent-type-imports":"off","@typescript-eslint/no-extraneous-class":"off","@typescript-eslint/parameter-properties":"off","class-methods-use-this":"off","func-style":["off"],"no-useless-constructor":"off","unicorn/no-static-only-class":"off","vitest/consistent-test-filename":"off"},oxlint:{"class-methods-use-this":"off","func-style":["off"],"no-useless-constructor":"off","oxc/no-const-enum":"off","typescript/consistent-type-imports":"off","typescript/no-extraneous-class":"off","typescript/parameter-properties":"off","unicorn/no-static-only-class":"off"}};async function ns(t){const e=Y(t,"oxlint.config.ts");let r;try{r=await ke(e,"utf-8"),x("read",`Read ${e}`)}catch(n){x("error",`Cannot read ${e}`,n);return}let s=r;/import vitest from "ultracite\/oxlint\/vitest"/u.test(r)||(s=s.replace(/(import nestjs from "ultracite\/oxlint\/nestjs";)/u,`$1
25
+ import vitest from "ultracite/oxlint/vitest";`),x("add-import","Added vitest import"));const o=Object.entries(nt.oxlint).map(([n,c])=>{const l=Array.isArray(c)?JSON.stringify(c):`"${c}"`;return` "${n}": ${l}`}).join(`,
26
+ `),a=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);s=s.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(n,c)=>{const l=c.includes("vitest"),p=c.includes("ignorePatterns"),h=c.includes("rules:"),m=c.includes("overrides:");let f=c;return l||(f=f.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(_,N,G,$)=>`${N}${G}
27
+ vitest,
28
+ ${$}`),x("add-extends","Added vitest to extends array")),p||(f=f.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
29
+ ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**"],`),x("add-ignorePatterns","Added ignorePatterns")),m||(f=`${f} overrides: [
30
+ {
31
+ files: ["**/*.{test,spec}.{ts,tsx,js,jsx}"],
32
+ plugins: ["vitest"],
33
+ rules: {
34
+ "vitest/consistent-test-filename": ${a},
35
+ },
36
+ },
37
+ ],
38
+ `,x("add-overrides","Added vitest override block")),h||(f=`${f} rules: {
39
+ ${o},
40
+ },
41
+ `,x("add-rules","Added custom NestJS rules")),`export default defineConfig({${f}});`});try{await he(e,s,"utf-8"),x("write",`Written ${e}`)}catch(n){x("error",`Cannot write ${e}`,n)}}u(ns,"injectOxlintRules");async function os(t){const e=Y(t,"biome.jsonc");let r;try{r=await ke(e,"utf-8"),x("read",`Read ${e}`)}catch(n){x("error",`Cannot read ${e}`,n);return}const s=nt.biome,o=r.includes('"linter"'),a=r.includes('"rules"');if(o&&a){const n=Object.entries(s).flatMap(([l,p])=>Object.entries(p).map(([h,m])=>` "${l}": {
42
+ "${h}": "${m}"
43
+ }`)).join(`,
44
+ `),c=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(l,p,h,m)=>{const f=h.trim().endsWith(",")?"":",";return`${p}${h}${f}
45
+ ${n}
46
+ ${m}`});try{await he(e,c,"utf-8"),x("write",`Written ${e} (existing linter block)`)}catch(l){x("error",`Cannot write ${e}`,l)}}else{const c=` "linter": {
47
+ "rules": {
48
+ ${Object.entries(s).map(([p,h])=>{const m=Object.entries(h).map(([f,_])=>` "${f}": "${_}"`).join(`,
49
+ `);return` "${p}": {
50
+ ${m}
51
+ }`}).join(`,
52
+ `)}
53
+ }
54
+ }`,l=r.replace(/(\}\s*)$/u,p=>`,
55
+ ${c}
56
+ ${p}`);try{await he(e,l,"utf-8"),x("write",`Written ${e} (new linter block)`)}catch(p){x("error",`Cannot write ${e}`,p)}}}u(os,"injectBiomeRules");async function is(t){const e=Y(t,"eslint.config.mjs");let r;try{r=await ke(e,"utf-8"),x("read",`Read ${e}`)}catch(a){x("error",`Cannot read ${e}`,a);return}if(r.includes("rules:")){x("skip","Rules already present in eslint.config.mjs");return}const s=Object.entries(nt.eslint).map(([a,n])=>{const c=Array.isArray(n)?JSON.stringify(n):`"${n}"`;return` "${a}": ${c}`}).join(`,
57
+ `),o=r.replace(/\];?$/u,` {
58
+ rules: {
59
+ ${s},
60
+ },
61
+ },
62
+ ];`);try{await he(e,o,"utf-8"),x("write",`Written ${e}`)}catch(a){x("error",`Cannot write ${e}`,a)}}u(is,"injectEslintRules");async function cs(t,e){switch(x("start",`Injecting rules for formatter: ${e}`),e){case"oxlint-oxfmt":return await ns(t),x("done","Oxlint configuration updated"),{success:!0};case"biome":return await os(t),x("done","Biome configuration updated"),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await is(t),x("done","ESLint configuration updated"),{success:!0};default:return x("skip",`No injection for formatter: ${e}`),{message:"No injection needed",success:!0}}}u(cs,"injectUltraciteRules");const ls="single-project/architecture/nest-api",ps="single-project/architecture/nest-gateway",us="single-project/architecture/nest-microservice",ds="monorepo/root",ms="monorepo/apps/api-gateway",hs="monorepo/packages",gs="addons/husky",fs="extras/docker",ys="extras/swagger",bs="extras/database",ws="monorepo/packages/db",js=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[ls]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[ps]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[us]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[ds,ms,hs]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[gs]},{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[fs]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[ys]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[bs]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[ws]}];function vs(t){t.registerAll(js)}u(vs,"initializeTemplateMappings");class Me{static{u(this,"TemplateMapper")}mappings=[];register(e){this.mappings.push(e),this.mappings.sort((r,s)=>(s.priority??0)-(r.priority??0))}registerAll(e){for(const r of e)this.register(r)}resolve(e){const r=[];for(const n of this.mappings)Me.matches(n.conditions,e)&&r.push(n);const s=[],o={},a=[];for(const n of r){for(const c of n.templateGroups)s.includes(c)||s.push(c);Object.assign(o,n.extraVariables),a.push(n.id)}return{extraVariables:o,matchedMappings:a,templateGroups:s}}findFirst(e){return this.mappings.find(r=>Me.matches(r.conditions,e))}getAll(){return[...this.mappings]}getById(e){return this.mappings.find(r=>r.id===e)}clear(){this.mappings=[]}static matches(e,r){return!(e.architecture!==void 0&&e.architecture!==r.architecture||e.projectType!==void 0&&e.projectType!==r.projectType||e.database!==void 0&&!e.database.some(s=>r.database.includes(s))||e.orm!==void 0&&!e.orm.some(s=>r.orm.includes(s))||e.api!==void 0&&!e.api.some(s=>r.api.includes(s))||e.extras!==void 0&&!e.extras.some(s=>r.extras.includes(s))||e.addons!==void 0&&!e.addons.some(s=>r.addons.includes(s))||e.microservices!==void 0&&!e.microservices.some(s=>r.microservices.includes(s)))}}function Ss(t){return t.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}u(Ss,"toKebabCase");function ks(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toLowerCase())}u(ks,"toCamelCase");function As(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toUpperCase())}u(As,"toPascalCase");function Ps(t){const e=t.database.includes("postgresql"),r=t.database.includes("mysql"),s=t.database.includes("sqlite"),o=t.database.includes("mongodb"),a=t.orm.includes("prisma"),n=t.orm.includes("typeorm"),c=t.orm.includes("drizzle"),l=t.database.length>0&&!a&&!n&&!c;return{addons:[...t.addons],apiType:t.api[0]??null,apis:[...t.api],architecture:t.architecture,auth:t.auth,databasePorts:{mongodb:27017,mysql:3306,postgres:5432},databaseType:t.database[0]??null,databases:[...t.database],description:t.description||"A NestJS application",docker:t.extras.includes("docker"),extras:[...t.extras],hasAuth:t.auth!=="none",hasDatabase:t.database.length>0,hasMongodb:o,hasMysql:r,hasOrm:t.orm.length>0,hasPostgres:e,hasSqlite:s,httpProvider:t.httpProvider,initGit:t.initGit,isBun:t.packageManager==="bun",isMonorepo:t.projectType==="monorepo",isNpm:t.packageManager==="npm",isPnpm:t.packageManager==="pnpm",isSingle:t.projectType==="single",isYarn:t.packageManager==="yarn",microservices:[...t.microservices],ormType:t.orm[0]??null,orms:[...t.orm],packageManager:t.packageManager,projectName:t.projectName,projectNameCamelCase:ks(t.projectName),projectNameKebab:Ss(t.projectName),projectNamePascalCase:As(t.projectName),projectType:t.projectType,supportsCatalog:["pnpm","yarn","bun"].includes(t.packageManager),swagger:t.extras.includes("swagger"),useDrizzle:c,usePrisma:a,useRawSql:l,useTypeorm:n,year:new Date().getFullYear()}}u(Ps,"buildTemplateVariables");function Es(t,e){return{...t,...e}}u(Es,"mergeTemplateExtras");class Rs{static{u(this,"AuthModuleGenerator")}project;config;constructor(e){this.config=e,this.project=new ir}generate(){const e=`${this.config.outputDir}/auth`,r=this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy;r==="passport"?this.generatePassportAuth(e):r==="better-auth"&&this.generateBetterAuth(e)}generatePassportAuth(e){(this.config.database?.length??0)>0?this.generatePassportDbAuth(e):this.generatePassportStatelessAuth(e)}generatePassportStatelessAuth(e){const r=['import { Injectable } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";','import { Request } from "express";',"","interface JwtPayload {"," sub: string;"," email?: string;"," [key: string]: unknown;","}","","@Injectable()","export class JwtStrategy extends PassportStrategy(Strategy) {"," constructor() {"," super({"," jwtFromRequest: ExtractJwt.fromExtractors(["," (request: Request) => request?.cookies?.access_token ?? null,"," ExtractJwt.fromAuthHeaderAsBearerToken(),"," ]),"," ignoreExpiration: false,",' secretOrKey: process.env.JWT_SECRET || "your-secret-key",'," });"," }",""," async validate(payload: JwtPayload) {"," // Stateless: no DB lookup \u2014 trust the token payload"," return { userId: payload.sub, ...payload };"," }","}",""].join(`
63
+ `),s=k.join(e,"strategies/jwt.strategy.ts");this.project.createSourceFile(s,r,{overwrite:!0});const o=k.join(e,"auth.service.ts"),a=this.project.createSourceFile(o,"",{overwrite:!0});a.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),a.addImportDeclaration({moduleSpecifier:"@nestjs/jwt",namedImports:["JwtService"]}),a.addClass({ctors:[{parameters:[{decorators:[{name:"Inject"}],isReadonly:!0,name:"jwtService",scope:mt.Private,type:"JwtService"}]}],decorators:[{arguments:[],name:"Injectable"}],isExported:!0,methods:[{name:"login",parameters:[{name:"user",type:"Record<string, unknown>"}],returnType:"{ access_token: string }",statements:["const payload = { sub: user.id as string, ...user };","return { access_token: this.jwtService.sign(payload) };"]},{name:"verifyToken",parameters:[{name:"token",type:"string"}],returnType:"any",statements:["return this.jwtService.verify(token);"]}],name:"AuthService"});const n=["import {"," Controller,"," Post, Get, Body, UseGuards, Req, Res",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";','import { AuthService } from "./auth.service.js";','import type { Request, Response } from "express";',"",'@Controller("auth")',"export class AuthController {"," constructor(private readonly authService: AuthService) {}","",' @Post("login")'," async login("," @Body() body: Record<string, unknown>,"," @Res({ passthrough: true }) response: Response,"," ) {"," const result = await this.authService.login(body);",' response.cookie("access_token", result.access_token, {'," httpOnly: true,",' secure: process.env.NODE_ENV === "production",',' sameSite: "strict",'," });"," return result;"," }","",' @Get("profile")',' @UseGuards(AuthGuard("jwt"))'," getProfile(@Req() request: Request) {"," return request.user;"," }","",' @Post("logout")'," async logout(@Res({ passthrough: true }) response: Response) {",' response.clearCookie("access_token");',' return { message: "Logged out" };'," }","}",""].join(`
64
+ `),c=k.join(e,"auth.controller.ts");this.project.createSourceFile(c,n,{overwrite:!0}),this.generatePassportDecorators(e),this.generatePassportGuard(e);const l=['import { Module } from "@nestjs/common";','import { APP_GUARD } from "@nestjs/core";','import { JwtModule } from "@nestjs/jwt";','import { PassportModule } from "@nestjs/passport";','import { AuthController } from "./auth.controller.js";','import { AuthService } from "./auth.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";','import { JwtAuthGuard } from "./guards/jwt-auth.guard.js";',"","@Module({"," imports: [",' PassportModule.register({ defaultStrategy: "jwt" }),'," JwtModule.register({",' secret: process.env.JWT_SECRET || "your-secret-key",',' signOptions: { expiresIn: "24h" },'," }),"," ],"," controllers: [AuthController],"," providers: ["," AuthService,"," JwtStrategy,"," {"," provide: APP_GUARD,"," useClass: JwtAuthGuard,"," },"," ],"," exports: [AuthService],","})","export class AuthModule {}",""].join(`
65
+ `),p=k.join(e,"auth.module.ts");this.project.createSourceFile(p,l,{overwrite:!0})}generatePassportDbAuth(e){const r=this.config.orm??[],s=r.includes("prisma"),o=r.includes("typeorm");let a,n;s?(n=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";','import { PrismaClient } from "@prisma/client";'],a=["const prisma = new PrismaClient();","const user = await prisma.user.findUnique({"," where: { id: payload.sub },","});","if (!user) {",' throw new UnauthorizedException("User not found");',"}","return user;"]):o?(n=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";','import { InjectRepository } from "@nestjs/typeorm";','import { Repository } from "typeorm";','import { UserEntity } from "../../modules/users/entities/user.entity.js";'],a=["const user = await this.userRepository.findOne({"," where: { id: payload.sub },","});","if (!user) {",' throw new UnauthorizedException("User not found");',"}","return user;"]):(n=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";'],a=["// Add your ORM user lookup here","// const user = await db.select().from(users).where(eq(users.id, payload.sub)).limit(1);","if (!payload.sub) {",' throw new UnauthorizedException("Invalid token");',"}","return { userId: payload.sub, ...payload };"]);const c=[" super({"," jwtFromRequest: ExtractJwt.fromExtractors(["," (request: { cookies?: Record<string, string> }) => request?.cookies?.access_token ?? null,"," ExtractJwt.fromAuthHeaderAsBearerToken(),"," ]),"," ignoreExpiration: false,",' secretOrKey: process.env.JWT_SECRET || "your-secret-key",'," });"].join(`
66
+ `),l=o?`
67
+ constructor(
68
+ @InjectRepository(UserEntity)
69
+ private readonly userRepository: Repository<UserEntity>,
70
+ ) {
71
+ ${c}
72
+ }`:`
73
+ constructor() {
74
+ ${c}
75
+ }`,p=[...n,"","interface JwtPayload {"," sub: string;"," [key: string]: unknown;","}","","@Injectable()","export class JwtStrategy extends PassportStrategy(Strategy) {",l,""," async validate(payload: JwtPayload) {",...a.map(H=>` ${H}`)," }","}",""].join(`
76
+ `),h=k.join(e,"strategies/jwt.strategy.ts");this.project.createSourceFile(h,p,{overwrite:!0});const m=k.join(e,"auth.service.ts"),f=this.project.createSourceFile(m,"",{overwrite:!0});f.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),f.addImportDeclaration({moduleSpecifier:"@nestjs/jwt",namedImports:["JwtService"]}),f.addClass({ctors:[{parameters:[{decorators:[{name:"Inject"}],isReadonly:!0,name:"jwtService",scope:mt.Private,type:"JwtService"}]}],decorators:[{arguments:[],name:"Injectable"}],isExported:!0,methods:[{name:"login",parameters:[{name:"user",type:"Record<string, unknown>"}],returnType:"{ access_token: string }",statements:["const payload = { sub: user.id as string, ...user };","return { access_token: this.jwtService.sign(payload) };"]},{name:"verifyToken",parameters:[{name:"token",type:"string"}],returnType:"any",statements:["return this.jwtService.verify(token);"]}],name:"AuthService"});const _=["import {"," Controller,"," Post, Get, Body, UseGuards, Req, Res",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";','import { AuthService } from "./auth.service.js";','import type { Request, Response } from "express";',"",'@Controller("auth")',"export class AuthController {"," constructor(private readonly authService: AuthService) {}","",' @Post("login")'," async login("," @Body() body: Record<string, unknown>,"," @Res({ passthrough: true }) response: Response,"," ) {"," const result = await this.authService.login(body);",' response.cookie("access_token", result.access_token, {'," httpOnly: true,",' secure: process.env.NODE_ENV === "production",',' sameSite: "strict",'," });"," return result;"," }","",' @Get("profile")',' @UseGuards(AuthGuard("jwt"))'," getProfile(@Req() request: Request) {"," return request.user;"," }","",' @Post("logout")'," async logout(@Res({ passthrough: true }) response: Response) {",' response.clearCookie("access_token");',' return { message: "Logged out" };'," }","}",""].join(`
77
+ `),N=k.join(e,"auth.controller.ts");this.project.createSourceFile(N,_,{overwrite:!0}),this.generatePassportDecorators(e),this.generatePassportGuard(e);const G=['import { Module } from "@nestjs/common";','import { APP_GUARD } from "@nestjs/core";','import { JwtModule } from "@nestjs/jwt";','import { PassportModule } from "@nestjs/passport";','import { AuthController } from "./auth.controller.js";','import { AuthService } from "./auth.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";','import { JwtAuthGuard } from "./guards/jwt-auth.guard.js";'];o&&G.push('import { TypeOrmModule } from "@nestjs/typeorm";','import { UserEntity } from "../../modules/users/entities/user.entity.js";');const $=[" imports: [",' PassportModule.register({ defaultStrategy: "jwt" }),'," JwtModule.register({",' secret: process.env.JWT_SECRET || "your-secret-key",',' signOptions: { expiresIn: "24h" },'," }),",o?" TypeOrmModule.forFeature([UserEntity]),":" // Import your ORM module here"," ],"," controllers: [AuthController],"," providers: ["," AuthService,"," JwtStrategy,"," {"," provide: APP_GUARD,"," useClass: JwtAuthGuard,"," },"," ],"," exports: [AuthService],"].join(`
78
+ `),L=[...G,"","@Module({",$,"})","export class AuthModule {}",""].join(`
79
+ `),j=k.join(e,"auth.module.ts");this.project.createSourceFile(j,L,{overwrite:!0})}generatePassportDecorators(e){const r=k.join(e,"decorators"),s=['import { SetMetadata } from "@nestjs/common";',"",'export const ALLOW_ANONYMOUS_KEY = "auth:allowAnonymous";',"export const AllowAnonymous = () =>"," SetMetadata(ALLOW_ANONYMOUS_KEY, true);",""].join(`
80
+ `);this.project.createSourceFile(k.join(r,"allow-anonymous.decorator.ts"),s,{overwrite:!0});const o=['import { SetMetadata } from "@nestjs/common";',"",'export const OPTIONAL_AUTH_KEY = "auth:optionalAuth";',"export const OptionalAuth = () => SetMetadata(OPTIONAL_AUTH_KEY, true);",""].join(`
81
+ `);this.project.createSourceFile(k.join(r,"optional-auth.decorator.ts"),o,{overwrite:!0});const a=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const Session = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user ?? null;"," },",");",""].join(`
82
+ `);this.project.createSourceFile(k.join(r,"session.decorator.ts"),a,{overwrite:!0});const n=['import { SetMetadata } from "@nestjs/common";',"",'export const ROLES_KEY = "auth:roles";',"export const Roles = (...roles: string[]) =>"," SetMetadata(ROLES_KEY, roles);",""].join(`
83
+ `);this.project.createSourceFile(k.join(r,"roles.decorator.ts"),n,{overwrite:!0});const c=['import { SetMetadata } from "@nestjs/common";',"",'export const ORG_ROLES_KEY = "auth:orgRoles";',"export const OrgRoles = (...roles: string[]) =>"," SetMetadata(ORG_ROLES_KEY, roles);",""].join(`
84
+ `);this.project.createSourceFile(k.join(r,"org-roles.decorator.ts"),c,{overwrite:!0});const l=['import { SetMetadata } from "@nestjs/common";',"",'export const USER_PERMISSIONS_KEY = "auth:userPermissions";',"","export interface UserPermissionCheck {"," permission?: Record<string, string[]>;"," permissions?: Record<string, string[]>;"," role?: string;"," userId?: string;","}","","export const UserHasPermission = (check: UserPermissionCheck) =>"," SetMetadata(USER_PERMISSIONS_KEY, check);",""].join(`
85
+ `);this.project.createSourceFile(k.join(r,"user-has-permission.decorator.ts"),l,{overwrite:!0});const p=['import { SetMetadata } from "@nestjs/common";',"",'export const MEMBER_PERMISSIONS_KEY = "auth:memberPermissions";',"","export interface MemberPermissionCheck {"," permissions: Record<string, string[]>;","}","","export const MemberHasPermission = (check: MemberPermissionCheck) =>"," SetMetadata(MEMBER_PERMISSIONS_KEY, check);",""].join(`
86
+ `);this.project.createSourceFile(k.join(r,"member-has-permission.decorator.ts"),p,{overwrite:!0});const h=['export { AllowAnonymous, ALLOW_ANONYMOUS_KEY } from "./allow-anonymous.decorator.js";','export { OptionalAuth, OPTIONAL_AUTH_KEY } from "./optional-auth.decorator.js";','export { Session } from "./session.decorator.js";','export { Roles, ROLES_KEY } from "./roles.decorator.js";','export { OrgRoles, ORG_ROLES_KEY } from "./org-roles.decorator.js";',"export {"," UserHasPermission,"," USER_PERMISSIONS_KEY,"," UserPermissionCheck,",'} from "./user-has-permission.decorator.js";',"export {"," MemberHasPermission,"," MEMBER_PERMISSIONS_KEY,"," MemberPermissionCheck,",'} from "./member-has-permission.decorator.js";',""].join(`
87
+ `);this.project.createSourceFile(k.join(r,"index.ts"),h,{overwrite:!0})}generatePassportGuard(e){const r=k.join(e,"guards"),s=['import { Injectable, ExecutionContext, ForbiddenException } from "@nestjs/common";','import { Reflector } from "@nestjs/core";','import { AuthGuard } from "@nestjs/passport";','import { ALLOW_ANONYMOUS_KEY } from "../decorators/allow-anonymous.decorator.js";','import { OPTIONAL_AUTH_KEY } from "../decorators/optional-auth.decorator.js";','import { ROLES_KEY } from "../decorators/roles.decorator.js";','import { ORG_ROLES_KEY } from "../decorators/org-roles.decorator.js";','import { USER_PERMISSIONS_KEY } from "../decorators/user-has-permission.decorator.js";','import { MEMBER_PERMISSIONS_KEY } from "../decorators/member-has-permission.decorator.js";',"","@Injectable()",'export class JwtAuthGuard extends AuthGuard("jwt") {'," constructor(private readonly reflector: Reflector) {"," super();"," }",""," canActivate(context: ExecutionContext) {"," const isAllowAnonymous = this.reflector.getAllAndOverride<boolean>("," ALLOW_ANONYMOUS_KEY,"," [context.getHandler(), context.getClass()],"," );"," if (isAllowAnonymous) {"," return true;"," }",""," return super.canActivate(context) as boolean | Promise<boolean>;"," }",""," handleRequest("," err: Error | null,"," user: Record<string, unknown> | null,"," _info: unknown,"," context: ExecutionContext,"," ) {"," const isOptional = this.reflector.getAllAndOverride<boolean>("," OPTIONAL_AUTH_KEY,"," [context.getHandler(), context.getClass()],"," );",""," if (isOptional && (err || !user)) {"," return null;"," }",""," if (err || !user) {",' throw err || new ForbiddenException("Invalid token");'," }",""," const roles = this.reflector.getAllAndOverride<string[]>("," ROLES_KEY,"," [context.getHandler(), context.getClass()],"," );"," if (roles?.length > 0) {"," const userRole = (user as Record<string, string>).role;"," if (!userRole || !roles.includes(userRole)) {",' throw new ForbiddenException("Insufficient role permissions");'," }"," }",""," const orgRoles = this.reflector.getAllAndOverride<string[]>("," ORG_ROLES_KEY,"," [context.getHandler(), context.getClass()],"," );"," if (orgRoles?.length > 0) {"," const session = (user as Record<string, unknown>).session as Record<string, unknown> | undefined;"," const memberRole = session?.activeOrganizationId"," ? (user as Record<string, string>).role"," : null;"," if (!memberRole || !orgRoles.includes(memberRole)) {",' throw new ForbiddenException("Insufficient organization role permissions");'," }"," }",""," // Placeholder: implement user permission check logic here"," const _userPermission = this.reflector.getAllAndOverride<unknown>("," USER_PERMISSIONS_KEY,"," [context.getHandler(), context.getClass()],"," );",""," // Placeholder: implement member permission check logic here"," const _memberPermission = this.reflector.getAllAndOverride<unknown>("," MEMBER_PERMISSIONS_KEY,"," [context.getHandler(), context.getClass()],"," );",""," return user;"," }","}",""].join(`
88
+ `);this.project.createSourceFile(k.join(r,"jwt-auth.guard.ts"),s,{overwrite:!0})}generateBetterAuth(e){const r=this.config.orm??[],s=this.config.database??[];if(!(s.length>0)){this.generateBetterAuthStateless(e);return}const a=r.includes("prisma"),n=r.includes("drizzle"),c=r.includes("typeorm");a?(this.generateBetterAuthPrisma(e,s),this.generateBetterAuthModule(e,"prisma")):n?(this.generateBetterAuthDrizzle(e,s),this.generateBetterAuthModule(e,"drizzle")):c?(this.generateBetterAuthNative(e,s),this.generateBetterAuthTypeormModule(e,s)):(this.generateBetterAuthNative(e,s),this.generateBetterAuthModule(e,"raw.sql"))}generateBetterAuthPrisma(e,r){const s=r.includes("postgresql"),o=r.includes("mysql");let a;s?a="postgresql":o?a="mysql":a="sqlite";let n,c,l;s?(n="PrismaPg",c="@prisma/adapter-pg",l="new PrismaPg({ connectionString: '' })"):o?(n="PrismaMySql",c="@prisma/adapter-mysql2",l="new PrismaMySql({ uri: '' })"):(n="PrismaBetterSqlite3",c="@prisma/adapter-better-sqlite3",l="new PrismaBetterSqlite3({ url: ':memory:' })");const p=[`import { ${n} } from "${c}";`,'import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";','import { PrismaClient } from "../database/orm/prisma/generated/client.js";',"","export function createAuth(prisma: PrismaClient) {"," return betterAuth({",` database: prismaAdapter(prisma, { provider: "${a}" }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },"," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","// no connectionString needed because auth@latest generate doesnt access the DB","function createCliAuth() {",` const adapter = ${l};`," const prisma = new PrismaClient({ adapter });"," return createAuth(prisma);","}","","let instance: ReturnType<typeof createAuth>;","","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_, prop) {"," if (!instance) {"," instance = createCliAuth();"," }"," return Reflect.get(instance, prop, instance);"," },","});","export type UserSession = typeof instance.$Infer.Session"],h=k.join(e,"auth.ts");this.project.createSourceFile(h,p.join(`
89
+ `),{overwrite:!0})}generateBetterAuthDrizzle(e,r){const s=r.includes("postgresql"),o=r.includes("mysql"),a=r.includes("sqlite");let n,c,l,p,h,m;s?(n='import { drizzle } from "drizzle-orm/node-postgres";',c='import { Pool } from "pg";',l="NodePgDatabase",p="pg",h='new Pool({ connectionString: "" })',m="drizzle({ client: pool, schema })"):o?(n='import { drizzle } from "drizzle-orm/mysql2";',c='import mysql from "mysql2/promise";',l="MySql2Database",p="mysql",h='mysql.createPool({ uri: "" })',m="drizzle({ client: pool, schema })"):(n='import { drizzle } from "drizzle-orm/better-sqlite3";',c='import Database from "better-sqlite3";',l="BetterSqlite3Database",p="sqlite",h='new Database(":memory:")',m="drizzle({ client: sqliteDb, schema })");const f=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',n,c,'import * as schema from "../database/orm/drizzle/schema.js";',"",`export function createAuth(db: ${l}<typeof schema>) {`," return betterAuth({",` database: drizzleAdapter(db, { provider: "${p}", usePlural: true }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },"," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",a?` const sqliteDb = ${h};`:` const pool = ${h};`,...a?[` const db = ${m};`]:[` const db = ${m};`]," return createAuth(db);","}","","let instance: ReturnType<typeof createAuth>;","","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_, prop) {"," if (!instance) {"," instance = createCliAuth();"," }"," return Reflect.get(instance, prop, instance);"," },","});","export type UserSession = typeof instance.$Infer.Session"],_=k.join(e,"auth.ts");this.project.createSourceFile(_,f.join(`
90
+ `),{overwrite:!0})}generateBetterAuthNative(e,r){const s=r.includes("postgresql"),o=r.includes("mysql");let a,n,c;s?(a=`import { Pool } from "pg";
91
+ `,n="Pool",c='new Pool({ connectionString: "" })'):o?(a=`import { createPool } from "mysql2";
92
+ `,n="ReturnType<typeof createPool>",c='createPool({ uri: "" })'):(a=`import Database from "better-sqlite3";
93
+ `,n="Database.Database",c='new Database(":memory:")');const l=['import { betterAuth } from "better-auth";',a.trim(),"",`export function createAuth(pool: ${n}) {`," return betterAuth({"," database: pool,"," emailAndPassword: { enabled: true },"," experimental: { joins: true },"," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",` const pool = ${c};`," return createAuth(pool);","}","","let instance: ReturnType<typeof createAuth>;","","export const auth = new Proxy({} as ReturnType<typeof createAuth>, {"," get(_, prop) {"," if (!instance) {"," instance = createCliAuth();"," }"," return Reflect.get(instance, prop, instance);"," },","});","export type UserSession = typeof instance.$Infer.Session"],p=k.join(e,"auth.ts");this.project.createSourceFile(p,l.join(`
94
+ `),{overwrite:!0})}generateBetterAuthStateless(e){const r=['import { betterAuth } from "better-auth";',"","export const auth = betterAuth({"," session: {"," cookieCache: {"," enabled: true,"," maxAge: 7 * 24 * 60 * 60, // 7 days",' strategy: "jwe",'," },"," },"," account: {"," storeAccountCookie: true,",' storeStateStrategy: "cookie",'," },"," experimental: { joins: true },","});",""].join(`
95
+ `),s=k.join(e,"auth.ts");this.project.createSourceFile(s,r,{overwrite:!0}),this.generateBetterAuthStatelessModule(e)}generateBetterAuthModule(e,r){const s=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";','import { DbService } from "../database/db.service.js";','import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," inject: [DbService],"," useFactory: (db: DbService) => ({",` auth: createAuth(db.${r}),`," }),"," }),"," ],","})","export class AuthModule {}",""],o=k.join(e,"auth.module.ts");this.project.createSourceFile(o,s.join(`
96
+ `),{overwrite:!0})}generateBetterAuthTypeormModule(e,r){const s=r.includes("postgresql"),o=r.includes("mysql");let a,n;s?(a='import { Pool } from "pg";',n="new Pool({ connectionString: process.env.POSTGRES_URL! })"):o?(a='import { createPool } from "mysql2";',n="createPool({ uri: process.env.MYSQL_URL! })"):(a='import Database from "better-sqlite3";',n='new Database(process.env.SQLITE_PATH ?? ":memory:")');const c=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',a,'import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," useFactory: () => ({",` auth: createAuth(${n}),`," }),"," }),"," ],","})","export class AuthModule {}",""],l=k.join(e,"auth.module.ts");this.project.createSourceFile(l,c.join(`
97
+ `),{overwrite:!0})}generateBetterAuthStatelessModule(e){const r=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";','import { auth } from "./auth.js";',"","@Module({"," imports: [BetterAuthModule.forRoot({ auth })],"," exports: [BetterAuthModule],","})","export class AuthModule {}",""],s=k.join(e,"auth.module.ts");this.project.createSourceFile(s,r.join(`
98
+ `),{overwrite:!0})}async save(){await this.project.save()}}class Gt{static{u(this,"PresetComposer")}presets=new Map;constructor(){this.registerDefaultPresets()}registerDefaultPresets(){this.registerPreset({architectures:["nest-api"],description:"RESTful API with JWT authentication and Swagger documentation",extras:["swagger"],generators:["auth"],id:"rest-api",name:"REST API"}),this.registerPreset({architectures:["nest-api"],description:"GraphQL API with Apollo Server and authentication",extras:["graphql","apollo"],generators:["auth"],id:"graphql-api",name:"GraphQL API"}),this.registerPreset({architectures:["nest-microservice"],description:"Microservice with messaging and inter-service communication",extras:["nats","rabbitmq"],generators:["auth"],id:"microservice",name:"Microservice"}),this.registerPreset({architectures:["nest-gateway"],description:"API Gateway for routing and load balancing",extras:["rate-limiting","load-balance"],generators:[],id:"gateway",name:"API Gateway"}),this.registerPreset({architectures:["nest-api"],description:"Complete application with database, auth, and all extras",extras:["swagger","docker","health-check","rate-limiting"],generators:["auth","config","database"],id:"fullstack",name:"Full Stack"})}registerPreset(e){this.presets.set(e.id,e)}getPreset(e){return this.presets.get(e)}getAllPresets(){return[...this.presets.values()]}getPresetsForArchitecture(e){return[...this.presets.values()].filter(r=>r.architectures.includes(e))}static composeGenerators(e){const r=new Set;return e.auth!=="none"&&r.add("auth"),e.database.length>0&&r.add("database"),[...r]}static composeExtras(e){const r=new Set(e.extras);return e.api.includes("rest")&&e.extras.includes("swagger")&&r.add("swagger"),e.orm.includes("prisma")&&r.add("prisma"),e.orm.includes("typeorm")&&r.add("typeorm"),[...r]}suggestPreset(e){if(this.getPresetsForArchitecture(e.architecture).length!==0)return e.api.includes("graphql")?this.presets.get("graphql-api"):e.architecture==="nest-microservice"?this.presets.get("microservice"):e.architecture==="nest-gateway"?this.presets.get("gateway"):e.database.length>0&&e.auth!=="none"?this.presets.get("fullstack")??this.presets.get("rest-api"):this.presets.get("rest-api")}validateContext(e,r){const s=this.getPreset(r);return s?s.architectures.includes(e.architecture):!1}}async function $t(t,e,r){const s=[];for(const o of r)try{if(o==="auth"){const a=new Rs({database:t.database,orm:t.orm,outputDir:`${e}/src`,strategy:t.auth});await a.generate(),await a.save(),s.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${o} not yet implemented`)}catch(a){s.push({error:a instanceof Error?a.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return s}u($t,"executePresetGenerators");function Lt(t){const e=["services:",` ${t.projectName}:`," build:"," context: ."," dockerfile: Dockerfile"," ports:",` - "${t.httpProvider==="fastify"?"3001:3001":"3000:3000"}"`," environment:"," - NODE_ENV=development"],r=[],s=t.projectName;if(t.database.includes("postgresql")&&r.push("postgres"),t.database.includes("mysql")&&r.push("mysql"),t.database.includes("mongodb")&&r.push("mongodb"),r.length>0){e.push(" depends_on:");for(const a of r)e.push(` - ${a}`)}return e.push(" volumes:"),e.push(" - .:/app"),e.push(" - /app/node_modules"),t.database.includes("postgresql")&&(e.push(""),e.push(" postgres:"),e.push(" image: postgres:17-alpine"),e.push(" environment:"),e.push(" POSTGRES_USER: postgres"),e.push(" POSTGRES_PASSWORD: postgres"),e.push(` POSTGRES_DB: ${s}_db`),e.push(" ports:"),e.push(' - "5432:5432"'),e.push(" volumes:"),e.push(" - postgres_data:/var/lib/postgresql/data")),t.database.includes("mysql")&&(e.push(""),e.push(" mysql:"),e.push(" image: mysql:9"),e.push(" environment:"),e.push(" MYSQL_ROOT_PASSWORD: mysql"),e.push(` MYSQL_DATABASE: ${s}_db`),e.push(" ports:"),e.push(' - "3306:3306"'),e.push(" volumes:"),e.push(" - mysql_data:/var/lib/mysql")),t.database.includes("mongodb")&&(e.push(""),e.push(" mongodb:"),e.push(" image: mongo:8"),e.push(" environment:"),e.push(` MONGO_INITDB_DATABASE: ${s}_db`),e.push(" ports:"),e.push(' - "27017:27017"'),e.push(" volumes:"),e.push(" - mongo_data:/data/db")),t.database.some(a=>["postgresql","mysql","mongodb"].includes(a))&&(e.push(""),e.push("volumes:"),t.database.includes("postgresql")&&e.push(" postgres_data:"),t.database.includes("mysql")&&e.push(" mysql_data:"),t.database.includes("mongodb")&&e.push(" mongo_data:")),`${e.join(`
99
+ `)}
100
+ `}u(Lt,"generateDockerCompose");const _s={name:"@nest-arch/dependencies-reference",version:"0.0.0",description:"Single source of truth for dependency versions used across all generated templates. Do not install this package.",private:!0,catalog:{"@types/node":"^22.13.14",dotenv:"^17.2.2",typescript:"^6.0.2",zod:"^4.4.3"},dependencies:{"@better-auth/drizzle-adapter":"^1.2.0","@grpc/grpc-js":"^1.12.0","@grpc/proto-loader":"^0.7.13","@nestjs/apollo":"^14.0.0-next.0","@nestjs/common":"next","@nestjs/core":"next","@nestjs/graphql":"^14.0.0-next.0","@nestjs/jwt":"next","@nestjs/microservices":"next","@nestjs/passport":"next","@nestjs/platform-express":"next","@nestjs/platform-fastify":"next","@nestjs/swagger":"next","@nestjs/terminus":"next","@nestjs/throttler":"next","@nestjs/typeorm":"11.0.1","@prisma/adapter-pg":"^7.8.0","@prisma/adapter-ppg":"^7.8.0","@prisma/client":"^7.8.0","@scalar/nestjs":"^0.3.0","@t3-oss/env-core":"^0.13.11","@thallesp/nestjs-better-auth":"^2.6.1","@trpc/client":"^11.0.0","@trpc/server":"^11.0.0",amqplib:"^0.10.5","apollo-server-express":"^3.13.0","apollo-server-fastify":"^3.13.0","better-auth":"^1.6.17","better-sqlite3":"^12.19.0",dotenv:"^17.2.2","drizzle-orm":"^0.45.2",graphql:"^16.10.0",ioredis:"^5.6.0",kafkajs:"^2.2.4",mongodb:"^6.13.0",mqtt:"^5.10.0",mysql2:"^3.12.0",nats:"^2.28.0","nestjs-zod":"^5.4.0",passport:"^0.7.0","passport-jwt":"^4.0.1","passport-local":"^1.0.0",pg:"^8.21.0","reflect-metadata":"^0.2.2",rxjs:"^7.8.1",typeorm:"^1.0.0",zod:"^4.4.3"},devDependencies:{"@nestjs/cli":"next","@nestjs/schematics":"next","@nestjs/testing":"next","@types/amqplib":"^0.10.6","@types/better-sqlite3":"^9.4.4","@types/express":"^5.0.0","@types/node":"^24.0.0","@types/passport-jwt":"^4.0.1","@types/passport-local":"^1.0.38","@types/pg":"^8.11.11","@types/supertest":"^7.0.0","@vitest/coverage-v8":"4.1.6","drizzle-kit":"^0.31.10",husky:"^9.1.7",oxfmt:"^0.52.0",oxlint:"^1.67.0",prisma:"^7.8.0","source-map-support":"^0.5.21",supertest:"^7.0.0",turbo:"^2.8.12",typescript:"^6.0.2",ultracite:"7.8.3",vitest:"^4.1.2"}};function Ft(){return _s}u(Ft,"loadReference");function g(t){const e=Ft(),r=e.dependencies[t]??e.devDependencies[t];if(!r)throw new Error(`Dependency "${t}" not found in reference package.json`);return r}u(g,"getDependencyVersion");function Ts(){return{...Ft().catalog}}u(Ts,"getCatalogDependencies");const Os=[{dest:"tsconfig.json",src:"base/tsconfig.json.hbs"},{dest:"tsconfig.build.json",src:"base/tsconfig.build.json.hbs"},{dest:"nest-cli.json",src:"base/nest-cli.json.hbs"},{dest:".gitignore",src:"base/.gitignore.hbs"},{dest:".env",src:"base/.env.hbs"},{dest:"README.md",src:"base/README.md.hbs"},{dest:"vitest.config.ts",src:"base/vitest.config.ts.hbs"},{dest:"vitest.config.e2e.ts",src:"base/vitest.config.e2e.ts.hbs"},{dest:"src/main.ts",src:"base/src/main.ts.hbs"},{dest:"src/app.module.ts",src:"base/src/app.module.ts.hbs"},{dest:"src/app.service.ts",src:"base/src/app.service.ts.hbs"},{dest:"src/app.controller.ts",src:"base/src/app.controller.ts.hbs"},{dest:"src/app.controller.spec.ts",src:"base/src/app.controller.spec.ts.hbs"},{dest:"src/config/env.ts",src:"single-project/shared/config/env.ts.hbs"},{dest:"test/app.e2e-spec.ts",src:"base/test/app.e2e-spec.ts.hbs"}],Cs={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},xs={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},Ms=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],Is=[{dest:"Dockerfile",src:"extras/docker/Dockerfile.hbs"},{dest:"docker-compose.yml",src:"extras/docker/docker-compose.yml.hbs"},{dest:".dockerignore",src:"extras/docker/.dockerignore.hbs"}],Ds=[{dest:"src/database/adapters/interfaces/db-adapter.interface.ts",src:"base/src/database/adapters/interfaces/db-adapter.interface.ts.hbs"},{dest:"src/database/adapters/sql/prisma-sql.adapter.ts",src:"base/src/database/adapters/sql/prisma-sql.adapter.ts.hbs"},{dest:"src/database/adapters/sql/drizzle-sql.adapter.ts",src:"base/src/database/adapters/sql/drizzle-sql.adapter.ts.hbs"},{dest:"src/database/adapters/sql/typeorm-sql.adapter.ts",src:"base/src/database/adapters/sql/typeorm-sql.adapter.ts.hbs"},{dest:"src/database/adapters/sql/raw-sql.adapter.ts",src:"base/src/database/adapters/sql/raw-sql.adapter.ts.hbs"},{dest:"src/database/adapters/mongo/prisma-mongo.adapter.ts",src:"base/src/database/adapters/mongo/prisma-mongo.adapter.ts.hbs"},{dest:"src/database/adapters/mongo/raw-mongo.adapter.ts",src:"base/src/database/adapters/mongo/raw-mongo.adapter.ts.hbs"},{dest:"src/database/db.service.ts",src:"base/src/database/db.service.ts.hbs"},{dest:"src/database/db.module.ts",src:"base/src/database/db.module.ts.hbs"},{dest:"src/database/index.ts",src:"base/src/database/index.ts.hbs"},{dest:"src/database/orm/drizzle/schema.ts",src:"base/src/database/orm/drizzle/schema.ts.hbs"},{dest:"src/database/orm/typeorm/data-source.ts",src:"base/src/database/orm/typeorm/data-source.ts.hbs"},{dest:"src/database/entities/todo.entity.ts",src:"base/src/database/entities/todo.entity.ts.hbs"}],Ns=[{dest:"packages/db/package.json",src:"monorepo/packages/db/package.json.hbs"},{dest:"packages/db/tsconfig.json",src:"monorepo/packages/db/tsconfig.json.hbs"},{dest:"packages/db/src/adapters/interfaces/db-adapter.interface.ts",src:"base/src/database/adapters/interfaces/db-adapter.interface.ts.hbs"},{dest:"packages/db/src/adapters/sql/prisma-sql.adapter.ts",src:"base/src/database/adapters/sql/prisma-sql.adapter.ts.hbs"},{dest:"packages/db/src/adapters/sql/drizzle-sql.adapter.ts",src:"base/src/database/adapters/sql/drizzle-sql.adapter.ts.hbs"},{dest:"packages/db/src/adapters/sql/typeorm-sql.adapter.ts",src:"base/src/database/adapters/sql/typeorm-sql.adapter.ts.hbs"},{dest:"packages/db/src/adapters/sql/raw-sql.adapter.ts",src:"base/src/database/adapters/sql/raw-sql.adapter.ts.hbs"},{dest:"packages/db/src/adapters/mongo/prisma-mongo.adapter.ts",src:"base/src/database/adapters/mongo/prisma-mongo.adapter.ts.hbs"},{dest:"packages/db/src/adapters/mongo/raw-mongo.adapter.ts",src:"base/src/database/adapters/mongo/raw-mongo.adapter.ts.hbs"},{dest:"packages/db/src/db.service.ts",src:"base/src/database/db.service.ts.hbs"},{dest:"packages/db/src/db.module.ts",src:"base/src/database/db.module.ts.hbs"},{dest:"packages/db/src/index.ts",src:"base/src/database/index.ts.hbs"},{dest:"packages/db/src/orm/drizzle/schema.ts",src:"base/src/database/orm/drizzle/schema.ts.hbs"},{dest:"packages/db/src/orm/typeorm/data-source.ts",src:"base/src/database/orm/typeorm/data-source.ts.hbs"},{dest:"packages/db/src/entities/todo.entity.ts",src:"base/src/database/entities/todo.entity.ts.hbs"}],zs={"single-project/architecture/nest-api":[{dest:"src/main.ts",src:"single-project/architecture/nest-api/src/main.ts.hbs"},{dest:".env",src:"single-project/architecture/nest-api/.env.hbs"},{dest:"package.json",src:"single-project/architecture/nest-api/package.json.hbs"},{dest:"pnpm-workspace.yaml",src:"single-project/architecture/nest-api/pnpm-workspace.yaml.hbs"}],"single-project/architecture/nest-gateway":[{dest:"src/main.ts",src:"single-project/architecture/nest-gateway/src/main.ts.hbs"},{dest:"src/app.module.ts",src:"single-project/architecture/nest-gateway/src/app.module.ts.hbs"},{dest:"src/app.controller.ts",src:"single-project/architecture/nest-gateway/src/app.controller.ts.hbs"},{dest:"src/app.service.ts",src:"single-project/architecture/nest-gateway/src/app.service.ts.hbs"},{dest:"package.json",src:"single-project/architecture/nest-api/package.json.hbs"},{dest:"pnpm-workspace.yaml",src:"single-project/architecture/nest-api/pnpm-workspace.yaml.hbs"}],"single-project/architecture/nest-microservice":[{dest:"src/main.ts",src:"single-project/architecture/nest-microservice/src/main.ts.hbs"},{dest:"src/app.module.ts",src:"single-project/architecture/nest-microservice/src/app.module.ts.hbs"},{dest:"src/app.controller.ts",src:"single-project/architecture/nest-microservice/src/app.controller.ts.hbs"},{dest:"src/app.service.ts",src:"single-project/architecture/nest-microservice/src/app.service.ts.hbs"},{dest:".env",src:"single-project/architecture/nest-microservice/.env.hbs"},{dest:"package.json",src:"single-project/architecture/nest-api/package.json.hbs"},{dest:"pnpm-workspace.yaml",src:"single-project/architecture/nest-api/pnpm-workspace.yaml.hbs"}]},Bt=[{dest:"turbo.json",src:"monorepo/root/turbo.json.hbs"},{dest:"tsconfig.json",src:"monorepo/root/tsconfig.json.hbs"},{dest:".gitignore",src:"monorepo/root/.gitignore.hbs"},{dest:"README.md",src:"monorepo/root/README.md.hbs"}],qs="package.json",Gs=[{dest:"apps/api-gateway/src/main.ts",src:"monorepo/apps/api-gateway/src/main.ts.hbs"},{dest:"apps/api-gateway/src/app.module.ts",src:"monorepo/apps/api-gateway/src/app.module.ts.hbs"},{dest:"apps/api-gateway/src/app.controller.ts",src:"monorepo/apps/api-gateway/src/app.controller.ts.hbs"},{dest:"apps/api-gateway/src/app.service.ts",src:"monorepo/apps/api-gateway/src/app.service.ts.hbs"},{dest:"apps/api-gateway/src/app.controller.spec.ts",src:"monorepo/apps/api-gateway/src/app.controller.spec.ts.hbs"},{dest:"apps/api-gateway/test/app.e2e-spec.ts",src:"monorepo/apps/api-gateway/test/app.e2e-spec.ts.hbs"},{dest:"apps/api-gateway/tsconfig.json",src:"monorepo/apps/api-gateway/tsconfig.json.hbs"},{dest:"apps/api-gateway/tsconfig.build.json",src:"monorepo/apps/api-gateway/tsconfig.build.json.hbs"},{dest:"apps/api-gateway/nest-cli.json",src:"monorepo/apps/api-gateway/nest-cli.json.hbs"},{dest:"apps/api-gateway/vitest.config.ts",src:"monorepo/apps/api-gateway/vitest.config.ts.hbs"},{dest:"apps/api-gateway/vitest.config.e2e.ts",src:"monorepo/apps/api-gateway/vitest.config.e2e.ts.hbs"}],$s=[{dest:"packages/config/package.json",src:"monorepo/packages/config/package.json.hbs"},{dest:"packages/config/tsconfig.base.json",src:"monorepo/packages/config/tsconfig.base.json.hbs"},{dest:"packages/config/tsconfig.nestjs.json",src:"monorepo/packages/config/tsconfig.nestjs.json.hbs"},{dest:"packages/env/package.json",src:"monorepo/packages/env/package.json.hbs"},{dest:"packages/env/src/api-gateway.ts",src:"monorepo/packages/env/src/api-gateway.ts.hbs"},{dest:"packages/env/tsconfig.json",src:"monorepo/packages/env/tsconfig.json.hbs"},{dest:"packages/shared/package.json",src:"monorepo/packages/shared/package.json.hbs"},{dest:"packages/shared/tsconfig.json",src:"monorepo/packages/shared/tsconfig.json.hbs"}],Ut={"addons/husky":Ms,"extras/database":Ds,"extras/docker":Is,"extras/swagger":[],"monorepo/apps/api-gateway":Gs,"monorepo/packages":$s,"monorepo/packages/db":Ns,"monorepo/root":Bt};function Ht(t,e,r){t.auth==="passport"?(e["@nestjs/jwt"]=g("@nestjs/jwt"),e["@nestjs/passport"]=g("@nestjs/passport"),e.passport=g("passport"),e["passport-jwt"]=g("passport-jwt"),r["@types/passport-jwt"]=g("@types/passport-jwt"),t.database.length>0&&t.orm.includes("typeorm")&&(e["@nestjs/typeorm"]=g("@nestjs/typeorm"),e.typeorm=g("typeorm"))):(t.auth==="better-auth"||t.auth==="better-auth:stateless")&&(e["better-auth"]=g("better-auth"),e["@thallesp/nestjs-better-auth"]=g("@thallesp/nestjs-better-auth"),t.orm.includes("drizzle")&&(e["@better-auth/drizzle-adapter"]=g("@better-auth/drizzle-adapter")));for(const s of t.api)if(s==="graphql"){e["@nestjs/graphql"]=g("@nestjs/graphql"),e["@nestjs/apollo"]=g("@nestjs/apollo"),e.graphql=g("graphql");const o=t.httpProvider==="fastify"?"apollo-server-fastify":"apollo-server-express";e[o]=g(o)}else s==="trpc"&&(e["@trpc/server"]=g("@trpc/server"),e["@trpc/client"]=g("@trpc/client"));t.extras.includes("swagger")&&(e["@nestjs/swagger"]=g("@nestjs/swagger")),t.extras.includes("health-check")&&(e["@nestjs/terminus"]=g("@nestjs/terminus")),t.extras.includes("rate-limiting")&&(e["@nestjs/throttler"]=g("@nestjs/throttler"));for(const s of t.microservices)s==="redis"?e.ioredis=g("ioredis"):s==="mqtt"?e.mqtt=g("mqtt"):s==="nats"?e.nats=g("nats"):s==="rabbitmq"?(e.amqplib=g("amqplib"),r["@types/amqplib"]=g("@types/amqplib")):s==="kafka"?e.kafkajs=g("kafkajs"):s==="grpc"&&(e["@grpc/grpc-js"]=g("@grpc/grpc-js"),e["@grpc/proto-loader"]=g("@grpc/proto-loader"));t.addons.includes("nestjs-zod")&&(e["nestjs-zod"]=g("nestjs-zod")),t.addons.includes("scalar-ui")&&(e["@scalar/nestjs"]=g("@scalar/nestjs"))}u(Ht,"addConditionalDependencies");function Wt(t,e,r){const s=t.orm.includes("prisma"),o=t.orm.includes("drizzle"),a=t.orm.includes("typeorm"),n=t.database.length>0&&!s&&!o&&!a;for(const c of t.orm)c==="prisma"?(e["@prisma/client"]=g("@prisma/client"),r.prisma=g("prisma"),t.database.includes("postgresql")&&(e["@prisma/adapter-pg"]=g("@prisma/adapter-pg")),t.database.includes("mysql")&&(e["@prisma/adapter-mysql2"]=g("@prisma/adapter-mysql2")),t.database.includes("sqlite")&&(e["@prisma/adapter-better-sqlite3"]=g("@prisma/adapter-better-sqlite3"))):c==="typeorm"?(e.typeorm=g("typeorm"),e["@nestjs/typeorm"]=g("@nestjs/typeorm"),t.database.includes("postgresql")&&(e.pg=g("pg"),r["@types/pg"]=g("@types/pg"))):c==="drizzle"&&(e["drizzle-orm"]=g("drizzle-orm"),r["drizzle-kit"]=g("drizzle-kit"));t.database.includes("postgresql")&&o&&(e.pg=g("pg"),r["@types/pg"]=g("@types/pg")),t.database.includes("mysql")&&o&&(e.mysql2=g("mysql2")),t.database.includes("sqlite")&&o&&(e["better-sqlite3"]=g("better-sqlite3"),r["@types/better-sqlite3"]=g("@types/better-sqlite3")),t.database.includes("mongodb")&&n&&(e.mongodb=g("mongodb"))}u(Wt,"addDatabaseDependencies");async function Ls(t,e,r,s,o,a){try{const n=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",c={"@nestjs/common":g("@nestjs/common"),"@nestjs/core":g("@nestjs/core"),[n]:g(n),"@t3-oss/env-core":g("@t3-oss/env-core"),dotenv:g("dotenv"),"reflect-metadata":g("reflect-metadata"),rxjs:g("rxjs"),zod:g("zod")},l={"@nestjs/cli":g("@nestjs/cli"),"@nestjs/schematics":g("@nestjs/schematics"),"@nestjs/testing":g("@nestjs/testing"),"@types/node":g("@types/node"),"@types/supertest":g("@types/supertest"),"@vitest/coverage-v8":g("@vitest/coverage-v8"),"source-map-support":g("source-map-support"),supertest:g("supertest"),typescript:g("typescript"),vitest:g("vitest")};t.httpProvider==="express"&&(l["@types/express"]=g("@types/express"));const p={build:"nest build",dev:"nest start --watch",start:"nest start","start:debug":"nest start --debug --watch","start:dev":"nest start --watch","start:prod":"node dist/main",test:"vitest run","test:cov":"vitest run --coverage","test:debug":"vitest --inspect-brk --no-file-parallelism","test:e2e":"vitest run --config ./vitest.config.e2e.ts","test:watch":"vitest"};Ht(t,c,l),Wt(t,c,l),t.addons.includes("ultracite")&&(l.ultracite=g("ultracite"),p.check="ultracite check",p.fix="ultracite fix"),t.addons.includes("husky")&&(l.husky=g("husky"),p.prepare="husky"),t.orm.includes("prisma")&&(p["prisma:generate"]="prisma generate",p["prisma:push"]="prisma db push",p["prisma:studio"]="prisma studio",p["prisma:migrate"]="prisma migrate dev",p["prisma:migrate:deploy"]="prisma migrate deploy",p.postinstall="prisma generate"),t.orm.includes("drizzle")&&(p["db:generate"]="drizzle-kit generate",p["db:migrate"]="drizzle-kit migrate",p["db:studio"]="drizzle-kit studio",p["db:push"]="drizzle-kit push"),t.orm.includes("typeorm")&&(p["typeorm:run"]="typeorm migration:run -d src/database/orm/typeorm/data-source.ts",p["typeorm:revert"]="typeorm migration:revert -d src/database/orm/typeorm/data-source.ts",p["typeorm:generate"]="typeorm migration:generate -d src/database/orm/typeorm/data-source.ts",p["typeorm:create"]="typeorm migration:create");const h={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:p,dependencies:c,devDependencies:l},m=JSON.stringify(h,null,2),f=await r.writeFile({content:m,filePath:"package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});f.written&&o.push(f.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);a.push(`Failed to generate package.json: ${c}`),console.error("Failed to generate package.json:",n)}}u(Ls,"generateSingleProjectPackageJson");async function Fs(t,e,r,s,o,a){try{const n={build:"turbo build","check-types":"turbo check-types",dev:"turbo dev"},c={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},l={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:g("turbo"),typescript:"catalog:"};t.addons.includes("ultracite")&&(n.check="ultracite check"),t.addons.includes("husky")&&(l.husky=g("husky"),n.prepare="husky");const h={bun:"bun@1.3.14",npm:void 0,pnpm:"pnpm@11.6.0",yarn:"yarn@4.6.0"}[t.packageManager],m={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,workspaces:["apps/*","packages/*"],type:"module",...h?{packageManager:h}:{},...t.packageManager==="bun"?{catalog:Ts()}:{},scripts:n,dependencies:c,devDependencies:l},f=JSON.stringify(m,null,2),_=await r.writeFile({content:f,filePath:qs,isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});_.written&&o.push(_.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);a.push(`Failed to generate monorepo root package.json: ${c}`),console.error("Failed to generate monorepo root package.json:",n)}}u(Fs,"generateMonorepoRootPackageJson");async function Bs(t,e,r,s,o,a){try{const n=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",c={"@nestjs/common":g("@nestjs/common"),"@nestjs/core":g("@nestjs/core"),[n]:g(n),"@repo/env":"workspace:*","reflect-metadata":g("reflect-metadata"),rxjs:g("rxjs"),zod:"catalog:"};t.database.length>0&&(c["@repo/db"]="workspace:*");const l={"@nestjs/cli":g("@nestjs/cli"),"@nestjs/schematics":g("@nestjs/schematics"),"@nestjs/testing":g("@nestjs/testing"),"@repo/config":"workspace:*","@types/node":"catalog:","@types/supertest":g("@types/supertest"),"@vitest/coverage-v8":g("@vitest/coverage-v8"),"source-map-support":g("source-map-support"),supertest:g("supertest"),typescript:"catalog:",vitest:g("vitest")};t.httpProvider==="express"&&(l["@types/express"]=g("@types/express"));const p={build:"nest build",dev:"nest start --watch",start:"nest start","start:debug":"nest start --debug --watch","start:dev":"nest start --watch","start:prod":"node dist/main",test:"vitest run","test:cov":"vitest run --coverage","test:debug":"vitest --inspect-brk --no-file-parallelism","test:e2e":"vitest run --config ./vitest.config.e2e.ts","test:watch":"vitest"};Ht(t,c,l),t.addons.includes("ultracite")&&(l.ultracite=g("ultracite"),p.check="ultracite check",p.fix="ultracite fix"),t.addons.includes("husky")&&(l.husky=g("husky"),p.prepare="husky");const h={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:p,dependencies:c,devDependencies:l},m=JSON.stringify(h,null,2),f=await r.writeFile({content:m,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});f.written&&o.push(f.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);a.push(`Failed to generate monorepo app package.json: ${c}`),console.error("Failed to generate monorepo app package.json:",n)}}u(Bs,"generateMonorepoAppPackageJson");async function Us(t,e,r,s,o,a){try{const n={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:"},c={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:"catalog:"};Wt(t,n,c);const l={};t.orm.includes("prisma")&&(l["prisma:generate"]="prisma generate",l["prisma:push"]="prisma db push",l["prisma:studio"]="prisma studio",l["prisma:migrate"]="prisma migrate dev",l["prisma:migrate:deploy"]="prisma migrate deploy",l.postinstall="prisma generate"),t.orm.includes("drizzle")&&(l["db:generate"]="drizzle-kit generate",l["db:migrate"]="drizzle-kit migrate",l["db:studio"]="drizzle-kit studio",l["db:push"]="drizzle-kit push"),t.orm.includes("typeorm")&&(l["typeorm:run"]="typeorm-ts esm migration:run -d src/database/orm/typeorm/data-source.ts",l["typeorm:revert"]="typeorm-ts esm migration:revert -d src/database/orm/typeorm/data-source.ts",l["typeorm:generate"]="typeorm-ts esm migration:generate -d src/database/orm/typeorm/data-source.ts",l["typeorm:create"]="typeorm migration:create");const p={name:"@repo/db",version:"0.0.1",private:!0,type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},...Object.keys(l).length>0?{scripts:l}:{},dependencies:n,devDependencies:c},h=JSON.stringify(p,null,2),m=await r.writeFile({content:h,filePath:"packages/db/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});m.written&&o.push(m.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);a.push(`Failed to generate monorepo db package.json: ${c}`),console.error("Failed to generate monorepo db package.json:",n)}}u(Us,"generateMonorepoDbPackageJson");class Hs{static{u(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(e,r){this.options=r,this.fileWriter=new Hr(e),this.templateEngine=new lt(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new as,this.mapper=new Me,vs(this.mapper)}getMapper(){return this.mapper}async generate(e){const r=Date.now(),s=[],o=[];try{const a=this.mapper.resolve(e);let n=Ps(e);n=Es(n,a.extraVariables),n.hasUltracite=e.addons.includes("ultracite"),n.hasHusky=e.addons.includes("husky"),await(e.projectType==="monorepo"?this.generateMonorepo(e,n,a.templateGroups,s,o):this.generateSingleProject(e,n,a.templateGroups,s,o));const c=Date.now()-r,l=o.length===0;return l&&await this.generateMetadata(e,n,s,o),console.log(`\u2705 Project generated in ${c}ms`),{error:l&&o.length===0?void 0:o.join(`
101
+ `),filesCount:s.length,generatedFiles:s,success:l&&o.length===0}}catch(a){return{error:a instanceof Error?a.message:"Unknown error",filesCount:0,generatedFiles:s,success:!1}}}async generateSingleProject(e,r,s,o,a){const n={dryRun:this.options.dryRun,overwrite:this.options.overwrite},c=[...Os];r.packageManager==="pnpm"?c.push(Cs):r.packageManager==="yarn"&&c.push(xs),await Ls(e,r,this.fileWriter,n,o,a);for(const l of c)await this.renderAndWrite(l.src,l.dest,r,o,a);for(const l of s){if(l==="monorepo/packages/db")continue;const p=zs[l];if(p){for(const f of p)f.dest==="package.json"||f.dest==="pnpm-workspace.yaml"||f.dest===".yarnrc.yml"||await this.renderAndWrite(f.src,f.dest,r,o,a);continue}const h=Ut[l];if(!h)continue;const m=l==="extras/database"||l==="monorepo/packages/db"?this.filterDatabaseTemplates(h,r):h;for(const f of m)f.dest==="docker-compose.yml"&&e.database.length>0||await this.renderAndWrite(f.src,f.dest,r,o,a)}if(e.extras.includes("docker")&&e.database.length>0){const l=Lt(e),p=await this.fileWriter.writeFile({content:l,filePath:"docker-compose.yml",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});p.written&&o.push(p.filePath)}if(e.extras.includes("swagger")&&console.log("Swagger support added to project"),e.orm.includes("prisma")&&(await this.generatePrismaSchema(e,o,a),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,o,a)),e.orm.includes("drizzle")&&await this.generateDrizzleConfig(e,o,a),e.auth!=="none"){const l=Gt.composeGenerators(e),p=await $t(e,this.fileWriter.getBaseDir(),l);for(const h of p)!h.success&&h.error&&a.push(h.error)}}async generateMonorepo(e,r,s,o,a){const n={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await Fs(e,r,this.fileWriter,n,o,a),await Bs(e,r,this.fileWriter,n,o,a),e.database.length>0&&await Us(e,r,this.fileWriter,n,o,a);for(const c of s){if(c==="monorepo/root"){for(const h of Bt)await this.renderAndWrite(h.src,h.dest,r,o,a);r.packageManager==="pnpm"?await this.renderAndWrite("monorepo/root/pnpm-workspace.yaml.hbs","pnpm-workspace.yaml",r,o,a):r.packageManager==="yarn"&&await this.renderAndWrite("monorepo/root/.yarnrc.yml.hbs",".yarnrc.yml",r,o,a);continue}const l=Ut[c];if(!l)continue;const p=c==="extras/database"||c==="monorepo/packages/db"?this.filterDatabaseTemplates(l,r):l;for(const h of p)h.dest!=="packages/db/package.json"&&(h.dest==="docker-compose.yml"&&e.database.length>0||await this.renderAndWrite(h.src,h.dest,r,o,a))}if(e.extras.includes("docker")&&e.database.length>0){const c=Lt(e),l=await this.fileWriter.writeFile({content:c,filePath:"docker-compose.yml",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});l.written&&o.push(l.filePath)}if(e.orm.includes("prisma")&&(await this.generatePrismaSchema(e,o,a),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,o,a)),e.orm.includes("drizzle")&&await this.generateDrizzleConfig(e,o,a),e.auth!=="none"){const c=Gt.composeGenerators(e),l=await $t(e,this.fileWriter.getBaseDir(),c);for(const p of l)!p.success&&p.error&&a.push(p.error)}}async generateMetadata(e,r,s,o){try{const{buildMetadata:a,serializeMetadata:n,buildSchemaContent:c}=await import("./index-BQXvSdO-.js"),l=a(e),p=n(l),h=await this.fileWriter.writeFile({content:p,filePath:"nest-arch.jsonc",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});h.written&&s.push(h.filePath);const m=c(),f=await this.fileWriter.writeFile({content:m,filePath:"schema.json",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});f.written&&s.push(f.filePath)}catch(a){const n=a instanceof Error?a.message:String(a);o.push(`Failed to generate nest-arch.jsonc/schema.json: ${n}`)}}filterDatabaseTemplates(e,r){const s=!!r.usePrisma,o=!!r.useTypeorm,a=!!r.useDrizzle,n=!!r.useRawSql,c=!!r.hasPostgres,l=!!r.hasMysql,p=!!r.hasSqlite,h=!!r.hasMongodb;return e.filter(m=>{const{dest:f}=m;return f.includes("prisma-sql.adapter")?s&&(c||l||p):f.includes("prisma-mongo.adapter")?s&&h:f.includes("typeorm-sql.adapter")?o&&(c||l||p):f.includes("orm/typeorm/data-source")||f.includes("entities/")?o:f.includes("drizzle-sql.adapter")?a:f.includes("raw-sql.adapter")?n&&(c||l||p):f.includes("raw-mongo.adapter")?n&&h:f.includes("orm/drizzle/schema")?a:!0})}async generatePrismaSchema(e,r,s){let o="postgresql";e.database.includes("mysql")?o="mysql":e.database.includes("sqlite")?o="sqlite":e.database.includes("mongodb")&&(o="mongodb");const a=["generator client {",' provider = "prisma-client"',' output = "./generated"',"}","","datasource db {",` provider = "${o}"`,"}",""].join(`
102
+ `);try{const n=await this.fileWriter.writeFile({content:a,filePath:"src/database/orm/prisma/schema.prisma",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});n.written&&r.push(n.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);s.push(`Failed to generate src/database/orm/prisma/schema.prisma: ${c}`)}}async generateDrizzleConfig(e,r,s){let o="postgresql";e.database.includes("mysql")?o="mysql":e.database.includes("sqlite")&&(o="sqlite");const a=e.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",n=a.replace("/schema.ts","/migrations");let c="process.env.POSTGRES_URL!";e.database.includes("mysql")?c="process.env.MYSQL_URL!":e.database.includes("sqlite")&&(c="process.env.SQLITE_PATH!");const l=[e.formatter==="oxlint-oxfmt"?"// oxlint-disable typescript/no-non-null-assertion":"","import 'dotenv/config';","import { defineConfig } from 'drizzle-kit';","","export default defineConfig({"," dbCredentials: {",` url: ${c},`," },",` dialect: '${o}',`,` out: '${n}',`,` schema: '${a}',`,"});",""].join(`
103
+ `);try{const p=await this.fileWriter.writeFile({content:l,filePath:"drizzle.config.ts",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});p.written&&r.push(p.filePath)}catch(p){const h=p instanceof Error?p.message:String(p);s.push(`Failed to generate drizzle.config.ts: ${h}`)}}async renderAndWrite(e,r,s,o,a){try{const n=await this.templateEngine.renderToFile(e,r,{context:s}),c=await this.fileWriter.writeFile(n,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});c.written&&o.push(c.filePath)}catch(n){const c=n instanceof Error?n.message:String(n);a.push(`Failed to generate ${r}: ${c}`),console.error(`Failed to generate ${r}:`,n)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}const Ws=/Resolved|Resolving/iu,Js=/Downloaded?|downloaded/iu,Ys=/Link(ed|ing)/iu,Ks=/saved (to )?(lockfile|bun)/iu;function Vs(t){const e=[],r=t.split(`
104
+ `);for(const s of r){const o=s.trim();if(o){if(Ws.test(o)){e.push({message:"Resolving packages...",phase:"resolve"});continue}if(Js.test(o)){e.push({message:"Downloading...",phase:"download"});continue}if(Ys.test(o)){e.push({message:"Linking packages...",phase:"link"});continue}if(o.includes("packages installed")){e.push({message:o,percentage:100,phase:"link"});continue}if(Ks.test(o)){e.push({message:"Saving lockfile...",phase:"postinstall"});continue}(o.includes("[script]")||o.includes("postinstall"))&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}}return e}u(Vs,"parseBunText");class Qs{static{u(this,"BunInstaller")}async install(e,r,s){const o=Ae("bun install",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let a="";const n=u(l=>{const p=l.toString();a+=p;const h=Vs(p);for(const m of h)r?.(m)},"handleData");o.stderr.on("data",n),o.stdout.on("data",n);const[c]=await Promise.race([se(o,"close"),se(o,"error").then(([l])=>{const p=l;throw p.code==="ENOENT"||p.code==="EINVAL"?new Error(["Bun is not installed or not found in your PATH.",""," Install Bun: https://bun.sh",""," Then restart your terminal and try again."].join(`
105
+ `)):new Error(p.message)})]);if(c===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(a.trim()||`bun install exited with code ${c}`)}}const Xs=/^(\d+)\/(\d+)\s+resolving/iu,Zs=/^(\d+)\/(\d+)\s+extract:/iu,ea=/^(\d+)\/(\d+)\s+(\S+)/iu,ta=/^(\d+)ms\s+(.*)/iu;function ra(t){const e=[],r=t.split(`
106
+ `);for(const s of r){const o=s.trim();if(o.includes("resolving")){const a=Xs.exec(o);a?e.push({completed:Number(a[1]),message:"Resolving packages...",percentage:Math.round(Number(a[1])/Number(a[2])*100),phase:"resolve",total:Number(a[2])}):e.push({message:"Resolving packages...",phase:"resolve"});continue}if(o.includes("extract:")||o.includes("http fetch")){const a=Zs.exec(o)||ea.exec(o);a?e.push({completed:Number(a[1]),message:"Downloading...",percentage:Math.round(Number(a[1])/Number(a[2])*100),phase:"download",total:Number(a[2])}):e.push({message:"Downloading...",phase:"download"});continue}if(o.includes("timing")){const a=ta.exec(o);if(a){const n=a[2]??"";n.includes("build")?e.push({message:"Building dependencies...",phase:"build"}):n.includes("link")&&e.push({message:"Linking packages...",phase:"link"})}continue}o.includes("postinstall")&&!o.includes("timing")&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}return e}u(ra,"parseNpmText");class sa{static{u(this,"NpmInstaller")}async install(e,r,s){const o=Ae("npm install --loglevel silly",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let a="";const n=u(l=>{const p=l.toString();a+=p;const h=ra(p);for(const m of h)r?.(m)},"handleData");o.stderr.on("data",n),o.stdout.on("data",()=>{});const[c]=await Promise.race([se(o,"close"),se(o,"error").then(([l])=>{const p=l;throw p.code==="ENOENT"||p.code==="EINVAL"?new Error(["npm is not installed or not found in your PATH.",""," Install npm: https://nodejs.org/en/download",""," Then restart your terminal and try again."].join(`
107
+ `)):new Error(p.message)})]);if(c===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(a.trim()||`npm install exited with code ${c}`)}}function aa(t,e){const r=e?.status,s=e?.progress;switch(r){case"resolving":return{message:"Resolving packages...",percentage:s??0,phase:"resolve"};case"downloading":case"fetching":return{message:"Downloading...",percentage:s??e?.progress,phase:"download"};case"linking":return{message:"Linking packages...",percentage:s??0,phase:"link"};case"build":return{message:"Building dependencies...",percentage:s??0,phase:"build"};default:return{message:r||"Installing dependencies...",percentage:s??0,phase:"download"}}}u(aa,"mapPnpmStage");function na(t){const e=t?.status;return e==="downloaded"?{message:"Downloaded packages",percentage:100,phase:"download"}:e==="installed"?{message:"Packages installed",percentage:100,phase:"link"}:null}u(na,"mapPnpmStat");function oa(t){const e=t.data;return e&&e.total>0?{completed:e.fetched,message:`Downloading ${e.package}...`,percentage:Math.round(e.fetched/e.total*100),phase:"download",total:e.total}:{message:"Downloading...",phase:"download"}}u(oa,"mapPnpmFetching");function ia(t){if(!t.type)return null;switch(t.type){case"stage":{const e=t.data?.stage;return e?aa(e,t.data):null}case"stat":return na(t.data);case"fetching":return oa(t);case"warning":case"error":return{message:t.message??t.type,phase:"download"};default:return null}}u(ia,"parsePnpmLine");class ca{static{u(this,"PnpmInstaller")}async install(e,r,s){const o=Ae("pnpm install --reporter ndjson",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let a="";o.stdout.on("data",c=>{const l=c.toString().split(`
108
+ `).filter(Boolean);for(const p of l)try{const h=JSON.parse(p),m=ia(h);m&&r&&r(m)}catch{}}),o.stderr.on("data",c=>{a+=c.toString()});const[n]=await Promise.race([se(o,"close"),se(o,"error").then(([c])=>{const l=c;throw l.code==="ENOENT"||l.code==="EINVAL"?new Error(["pnpm is not installed or not found in your PATH.",""," Install pnpm: npm install -g pnpm"," Or enable Corepack: corepack enable && corepack prepare pnpm@latest --activate",""," Then restart your terminal and try again."].join(`
109
+ `)):new Error(l.message)})]);if(n===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(a.trim()||`pnpm install exited with code ${n}`)}}function la(t){switch(t.type){case"step":{const e=t.displayName??"";return e.includes("Resolution")?{message:"Resolving packages...",phase:"resolve"}:e.includes("Fetch")?{message:"Downloading...",phase:"download"}:e.includes("Link")?{message:"Linking packages...",phase:"link"}:e.includes("Build")?{message:"Building dependencies...",phase:"build"}:{message:e||"Installing...",phase:"postinstall"}}case"progress":{const e=typeof t.data=="object"?t.data:void 0,r=e?.current,s=e?.total;return r!==void 0&&s!==void 0?{completed:r,message:"Processing...",percentage:Math.round(r/s*100),phase:"download",total:s}:null}case"success":return{message:typeof t.data=="string"?t.data:t.data?.message??"Done",percentage:100,phase:"complete"};case"error":return{message:typeof t.data=="string"?t.data:t.data?.message??"Error",phase:"download"};default:return null}}u(la,"parseYarnLine");class pa{static{u(this,"YarnInstaller")}async install(e,r,s){const o=Ae("yarn install --json",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let a="";o.stdout.on("data",c=>{const l=c.toString().split(`
110
+ `).filter(Boolean);for(const p of l)try{const h=JSON.parse(p),m=la(h);m&&r&&r(m)}catch{}}),o.stderr.on("data",c=>{a+=c.toString()});const[n]=await Promise.race([se(o,"close"),se(o,"error").then(([c])=>{const l=c;throw l.code==="ENOENT"||l.code==="EINVAL"?new Error(["Yarn is not installed or not found in your PATH.",""," Install Yarn: npm install -g yarn",""," Then restart your terminal and try again."].join(`
111
+ `)):new Error(l.message)})]);if(n===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(a.trim()||`yarn install exited with code ${n}`)}}function ua(t){switch(t){case"pnpm":return new ca;case"npm":return new sa;case"yarn":return new pa;case"bun":return new Qs;default:throw new Error(`Unhandled package manager: ${t}`)}}u(ua,"createPackageInstaller");class da{static{u(this,"ProjectPipeline")}outputDir;generatorOptions;constructor(e,r){this.outputDir=e,this.generatorOptions=r}async execute(e,r){const s=[],o=[],a=u(m=>{r?.onStageChange?.(m)},"emitStage"),n=u(m=>{s.push(m)},"addPhase");a("generate-files");const c=new Hs(this.outputDir,this.generatorOptions);try{const m=await c.generate(e);if(o.push(...m.generatedFiles),!m.success)return n({error:m.error,phase:"generate-files",success:!1}),this.buildResult(!1,s,o);if(e.formatter!=="none"){const f=await ss(this.outputDir,e);if(!f.success)return n({error:f.message,phase:"generate-files",success:!1}),this.buildResult(!1,s,o);const _=await cs(this.outputDir,e.formatter);if(!_.success)return n({error:_.message??"Rule injection failed",phase:"generate-files",success:!1}),this.buildResult(!1,s,o)}n({phase:"generate-files",success:!0})}catch(m){return n({error:m instanceof Error?m.message:String(m),phase:"generate-files",success:!1}),this.buildResult(!1,s,o)}if(e.initGit){a("initialize-git");try{await Yr(this.outputDir)||await Wr(this.outputDir),n({phase:"initialize-git",success:!0})}catch(m){n({error:m instanceof Error?m.message:String(m),phase:"initialize-git",success:!1})}if(s[1]?.success){a("initial-commit");try{await zt(this.outputDir),await qt(this.outputDir,"Initial project scaffold"),n({phase:"initial-commit",success:!0})}catch(m){n({error:m instanceof Error?m.message:String(m),phase:"initial-commit",success:!1})}}else n({phase:"initial-commit",skipped:!0,success:!0})}else n({phase:"initialize-git",skipped:!0,success:!0}),n({phase:"initial-commit",skipped:!0,success:!0});let l=!1;if(e.installDependencies){a("install-dependencies");try{await ua(e.packageManager).install(this.outputDir,f=>{r?.onInstallProgress?.(f)}),l=!0,n({phase:"install-dependencies",success:!0})}catch(m){n({error:m instanceof Error?m.message:String(m),phase:"install-dependencies",success:!1})}}else n({phase:"install-dependencies",skipped:!0,success:!0});if(l&&e.formatter!=="none"){a("run-formatter");try{const m=await Zr(e.packageManager,this.outputDir);m.success?n({phase:"run-formatter",success:!0}):n({error:m.error,phase:"run-formatter",success:!1})}catch(m){n({error:m instanceof Error?m.message:String(m),phase:"run-formatter",success:!1})}}else n({phase:"run-formatter",skipped:!0,success:!0});const{4:p}=s;if(e.initGit&&p?.success&&!p.skipped){a("formatter-commit");try{await zt(this.outputDir),await Jr(this.outputDir)&&await qt(this.outputDir,"Apply formatter"),n({phase:"formatter-commit",success:!0})}catch(m){n({error:m instanceof Error?m.message:String(m),phase:"formatter-commit",success:!1})}}else n({phase:"formatter-commit",skipped:!0,success:!0});a("complete");const h=s.every(m=>m.success||m.skipped);return this.buildResult(h,s,o)}buildResult(e,r,s){return{generatedFiles:s,outputDir:this.outputDir,phases:r,success:e}}}function ma(t){return{addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth,database:t.database,description:`${t.projectName} NestJS application`,extras:t.extras,formatter:t.formatter,httpProvider:t.httpProvider,initGit:t.initGit==="yes",installDependencies:t.installDependencies==="yes",microservices:t.microservices,orm:t.orm,packageManager:t.packageManager,projectName:t.projectName,projectType:t.projectType,ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill}}u(ma,"buildGeneratorContext");function ot(t){return tt.NEST_ARCH_BETA_MODE?Y(ut(),"test-projects",t):Y(process.cwd(),t)}u(ot,"getOutputDir");function ha(){const t=import.meta.dirname;if(t){const r=Y(t,"templates");if(Se(r))return r}return Y(t??process.cwd(),"..","..","..","..","packages","core","templates")}u(ha,"getTemplatesDir");async function Jt(t,e){const r=ot(t.projectName),s=ma(t),o=ha(),a=new da(r,{cacheTemplates:!0,templatesDir:o});try{const n=await a.execute(s,e),c={"formatter-commit":"Commit formatting","generate-files":"Generate project","initial-commit":"Initial commit","initialize-git":"Initialize Git","install-dependencies":"Install dependencies","run-formatter":"Run formatter"},l=n.phases.filter(p=>!p.success&&!p.skipped&&p.error).map(p=>`${c[p.phase]||p.phase} failed:
112
+ ${p.error}`);return l.length>0?{message:l.join(`
113
+
114
+ `),outputDir:r,success:!1}:{message:`Project created with ${n.generatedFiles.length} files`,outputDir:r,success:!0}}catch(n){return{message:`Failed to generate project: ${n instanceof Error?n.message:String(n)}`,outputDir:r,success:!1}}}u(Jt,"generateProject");const ga=u(()=>({addons:[],api:[],architecture:null,auth:null,database:[],extras:[],formatter:null,httpProvider:null,initGit:null,installDependencies:null,microservices:[],orm:[],packageManager:null,projectName:"",projectType:null,ultraciteAgents:[],ultraciteEditors:[],ultraciteHooks:[],ultraciteInstallSkill:null}),"initialState");function fa(t){return!t.packageManager||!t.formatter||!t.httpProvider||!t.projectType||!t.architecture||!t.auth||!t.initGit||!t.installDependencies?null:{addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth,database:t.database,extras:t.extras,formatter:t.formatter,httpProvider:t.httpProvider,initGit:t.initGit,installDependencies:t.installDependencies,microservices:t.architecture==="nest-gateway"?t.microservices:[],orm:Oe(t.database)?[]:t.orm,packageManager:t.packageManager,projectName:ce(t.projectName),projectType:t.projectType,ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill??"no"}}u(fa,"buildResult");const ya=u(({onBack:t,onExit:e,onStepChange:r})=>{const[s,o]=C("projectName"),[a,n]=C(ga),[c,l]=C(null),[p,h]=C(null),[m,f]=C(null),[_,N]=C(null),G=J(()=>et(a),[a]),$=J(()=>Cr(s,a),[s,a]),L=J(()=>Or(s,a),[s,a]),j=S(v=>{const w=xr(s,v);w&&(o(w),r?.(w))},[s,r]),H=S(()=>{const v=Mr(s,a);if(v){o(v),r?.(v);return}t()},[t,a,s,r]),ee=S(()=>{const v=Te(a.projectName);if(v){l(v);return}const w={...a,projectName:ce(a.projectName)};n(w),j(w)},[j,a]),te=S(v=>{const w={...a,packageManager:v};n(w),j(w)},[j,a]),P=S(v=>{const w={...a,formatter:v};n(w),j(w)},[j,a]),O=S(v=>{const w={...a,httpProvider:v};n(w),j(w)},[j,a]),I=S(v=>{const w=v==="single"&&a.architecture==="nest-gateway"?It():a.architecture??It(),E={...a,architecture:w,extras:v==="single"?a.extras.filter(D=>D!=="packages/shared"):a.extras,microservices:w==="nest-gateway"?a.microservices:[],projectType:v};n(E),j(E)},[j,a]),W=S(v=>{const w={...a,architecture:v,microservices:v==="nest-gateway"?a.microservices:[]};n(w),j(w)},[j,a]),V=S(v=>{const w=v==="none"?[]:[v],E=Dt(a.orm,w),D={...a,database:w,orm:E};n(D),j(D)},[j,a]),we=S(v=>{const w=v==="none"?[]:[v],E=zr(a.database,w),D={...a,database:E,orm:Dt(w,E)};n(D),j(D)},[j,a]),M=S(v=>{const w={...a,api:v};n(w),j(w)},[j,a]),Q=S(v=>{const w={...a,auth:v};n(w),j(w)},[j,a]),le=S(v=>{const w={...a,extras:v};n(w),j(w)},[j,a]),re=J(()=>a.projectType==="monorepo"?Xe:Xe.filter(v=>v.value!=="packages/shared"),[a.projectType]),X=S(v=>{const w={...a,microservices:v};n(w),j(w)},[j,a]),Ie=S(v=>{const w={...a,addons:v};n(w),j(w)},[j,a]),De=S(v=>{const w={...a,ultraciteEditors:v};n(w),j(w)},[j,a]),Ne=S(v=>{const w={...a,ultraciteAgents:v};n(w),j(w)},[j,a]),ze=S(v=>{const w={...a,ultraciteHooks:v};n(w),j(w)},[j,a]),F=S(v=>{const w={...a,ultraciteInstallSkill:v};n(w),j(w)},[j,a]),qe=S(v=>{const w={...a,initGit:v};n(w),j(w)},[j,a]),Ge=S(v=>{const w={...a,installDependencies:v};n(w),j(w)},[j,a]),T=S(()=>{j(a)},[j,a]),je=S(async()=>{const v=fa(a);if(v){o("installing"),r?.("installing"),h({isError:!1,message:"Scaffolding your project"});try{const w=await Jt(v,{onInstallProgress:u(E=>{N(E)},"onInstallProgress"),onStageChange:u(E=>{f(E)},"onStageChange")});h({isError:!w.success,message:w.message}),w.success&&(Nt(v),setTimeout(()=>{o("done"),r?.("done")},1e3))}catch(w){h({isError:!0,message:`Error: ${w instanceof Error?w.message:String(w)}`})}}},[a,r]),$e=S(()=>{o("summary"),r?.("summary"),h(null)},[r]),ve=J(()=>s==="projectName"||s==="summary"||s==="ultraciteSetup"?"confirm":s==="database"||s==="orm"||s==="apiLayer"||s==="extras"||s==="microservices"||s==="addons"||s==="ultraciteEditors"||s==="ultraciteAgents"||s==="ultraciteHooks"?"select":s==="installing"&&p?.isError?"confirm":"select",[s,p?.isError]);return{architectureOpts:J(()=>Ir(a.projectType),[a.projectType]),currentStage:m,displayStep:$,extrasStepOptions:re,generationStatus:p,goBack:H,handleAddons:Ie,handleApi:M,handleArchitecture:W,handleAuth:Q,handleDatabase:V,handleExtras:le,handleFormatter:P,handleHttpProvider:O,handleInitGit:qe,handleInstallDependencies:Ge,handleMicroservices:X,handleOrm:we,handlePackageManager:te,handleProjectNameSubmit:ee,handleProjectType:I,handleRetry:$e,handleSummaryConfirm:je,handleUltraciteAgents:Ne,handleUltraciteEditors:De,handleUltraciteHooks:ze,handleUltraciteInstallSkill:F,handleUltraciteSetupConfirm:T,installProgress:_,projectNameError:c,setProjectNameError:l,setState:n,state:a,statusAction:ve,stepId:s,subProgress:L,totalSteps:G}},"useCreateProjectWizard"),ba=u(({onBack:t,onDone:e,onExit:r,onStepChange:s})=>{const{architectureOpts:o,currentStage:a,displayStep:n,extrasStepOptions:c,generationStatus:l,goBack:p,handleProjectNameSubmit:h,handlePackageManager:m,handleFormatter:f,handleHttpProvider:_,handleProjectType:N,handleArchitecture:G,handleDatabase:$,handleOrm:L,handleApi:j,handleAuth:H,handleExtras:ee,handleMicroservices:te,handleAddons:P,handleUltraciteEditors:O,handleUltraciteAgents:I,handleUltraciteHooks:W,handleUltraciteInstallSkill:V,handleInitGit:we,handleInstallDependencies:M,handleRetry:Q,handleSummaryConfirm:le,handleUltraciteSetupConfirm:re,installProgress:X,projectNameError:Ie,setProjectNameError:De,setState:Ne,statusAction:ze,stepId:F,subProgress:qe,totalSteps:Ge,state:T}=ya({onBack:t,onExit:r,onStepChange:s}),[je,$e]=C([]),[ve]=C([]),pt=J(()=>{let E=T;return F==="addons"&&(E={...E,addons:je}),F==="database"&&(E={...E,database:ve}),et(E)},[F,T,je,ve,Ge]);ne(()=>{F==="done"&&e()},[F,e]),ae((E,D)=>{if(D.ctrl&&E==="c"){r();return}if(D.ctrl&&E==="b"&&F!=="done"){p();return}if(F==="done"&&D.return){r();return}F==="installing"&&l?.isError&&D.return&&Q()});const v=u(()=>{switch(F){case"projectName":return i(At,{error:Ie,onChange:u(E=>{Ne(D=>({...D,projectName:E})),De(Te(E))},"onChange"),onSubmit:h,value:T.projectName});case"packageManager":return i(K,{onConfirm:m,options:Pt,prompt:"Choose a package manager"},"packageManager");case"formatter":return i(K,{onConfirm:f,options:Ye,prompt:"Choose a formatter-linter (with ultracite preset) setup"},"formatter");case"httpProvider":return i(K,{onConfirm:_,options:Et,prompt:"Choose an HTTP provider"},"httpProvider");case"projectType":return i(K,{onConfirm:N,options:Rt,prompt:"Choose a project layout"},"projectType");case"architecture":return i(K,{onConfirm:G,options:o,prompt:"Choose an application architecture"},"architecture");case"database":{const D=[{description:"Skip database scaffolding for now",label:"No database",value:"none"},...Dr(T.orm)];return i(K,{initialValue:T.database[0]??"none",onConfirm:$,options:D,prompt:"Select a database for your project (optional)"},"database")}case"orm":{const E=Mt(T.database),Le=[{description:"Use plain database access without an ORM",label:"No ORM",value:"none"},...E];return i(K,{initialValue:T.orm[0]??"none",onConfirm:L,options:Le,prompt:"Select an ORM to include"},"orm")}case"apiLayer":{const E=T.architecture==="nest-api"&&T.api.length===0?["rest"]:T.api;return i(ie,{initialSelected:E,onConfirm:j,options:Tt,prompt:"Select API layers (optional)"},"apiLayer")}case"auth":{const E=Nr(T.database);return i(K,{onConfirm:H,options:E,prompt:"Choose an authentication strategy"},"auth")}case"extras":return i(ie,{initialSelected:T.extras,onConfirm:ee,options:c,prompt:"Select extras (optional)"},"extras");case"microservices":return i(ie,{initialSelected:T.microservices,onConfirm:te,options:vr,prompt:"Select microservice communication protocols"},"microservices");case"addons":{const E=T.formatter==="none"?Ze.filter(D=>D.value!=="ultracite"):Ze;return i(ie,{initialSelected:T.addons,onConfirm:P,onChange:$e,options:E,prompt:"Select addons (optional)"},"addons")}case"ultraciteEditors":return i(ie,{initialSelected:T.ultraciteEditors,onConfirm:O,options:kr,prompt:"Select Ultracite editors",minified:!0},"ultraciteEditors");case"ultraciteAgents":return i(ie,{initialSelected:T.ultraciteAgents,onConfirm:I,options:Ar,prompt:"Select Ultracite agents",minified:!0},"ultraciteAgents");case"ultraciteHooks":return i(ie,{initialSelected:T.ultraciteHooks,onConfirm:W,options:Pr,prompt:"Select Ultracite hooks"},"ultraciteHooks");case"ultraciteInstallSkill":return i(K,{onConfirm:V,options:Er,prompt:"Install Ultracite skill?"},"ultraciteInstallSkill");case"initGit":return i(K,{onConfirm:we,options:Ot,prompt:"Initialize a git repository?"},"initGit");case"installDependencies":return i(K,{onConfirm:M,options:Sr,prompt:"Install dependencies?"},"installDependencies");case"summary":return i(qr,{onConfirm:le,state:T});case"ultraciteSetup":return i($r,{onConfirm:re,state:T});case"installing":return b(y,{flexDirection:"column",children:[i(br,{currentStage:a,generationMessage:l?.message??"Scaffolding your project",installProgress:X,isError:l?.isError??!1,packageManager:T.packageManager??void 0}),l?.isError?i(y,{marginTop:1,children:b(d,{color:R,children:["Press ",i(d,{color:A,children:"Enter"})," to go back to Summary and retry, or ",i(d,{color:R,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const E=ce(T.projectName),D=T.initGit==="yes",Le=ot(E),Kt=T.installDependencies==="yes";return i(vt,{architecture:T.architecture||"nest-api",projectName:E,packageManager:T.packageManager||"pnpm",dependenciesInstalled:Kt,isGitInitialized:D,outputDir:Le})}default:return null}},"renderStep"),w=F!=="installing"&&F!=="done";return b(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[w?b(z,{children:[i(Lr,{state:T,stepId:F}),i(y,{height:0}),i(Fr,{displayStep:n,stepId:F,subProgress:qe??void 0,totalSteps:pt}),i(y,{height:2})]}):null,v(),i(y,{flexGrow:1}),w?b(z,{children:[i(fe,{}),i(y,{height:1}),i(Je,{action:ze,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),it=` _ _ ___ ___ _____ _ ___ ___ _ _
115
+ | \\| | __/ __|_ _| /_\\ | _ \\/ __| || |
116
+ | .\` | _|\\__ \\ | | / _ \\| / (__| __ |
117
+ |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,wa=12,ja=4,Yt=u(({onlyCat:t=!1})=>{const{stdout:e}=Fe(),r=e.columns||e.getWindowSize?.()[0]||80,s=e.rows||e.getWindowSize?.()[1]||24;return t?s<15||r<20?i(y,{flexDirection:"column",alignItems:"center",children:i(d,{bold:!0,color:A,children:ht})}):i(y,{flexDirection:"column",alignItems:"center",children:i(d,{color:A,children:He})}):s<15||r<38?b(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[i(d,{bold:!0,color:A,children:ht}),i(d,{color:R,children:Ee}),i(d,{color:U,children:Pe})]}):s<15+ja||r<55?b(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[i(d,{color:A,children:it}),i(d,{color:R,children:Ee}),i(d,{color:U,children:Pe})]}):s<15+wa||r<80?b(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[i(d,{color:A,children:He}),i(d,{color:A,children:it}),i(d,{color:R,children:Ee}),i(d,{color:U,children:Pe})]}):b(y,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[i(d,{color:A,children:He}),b(y,{flexDirection:"column",children:[i(d,{color:A,children:it}),b(d,{color:R,children:[" ",Ee]}),b(d,{color:U,children:[" ",Pe]})]})]})},"Header"),ct={addons:["ultracite","husky"],api:["rest"],architecture:"nest-api",auth:"none",database:[],extras:[],formatter:"oxlint-oxfmt",httpProvider:"express",installDependencies:"yes",microservices:[],orm:[],packageManager:"pnpm",projectType:"single",ultraciteAgents:[],ultraciteEditors:[],ultraciteHooks:[],ultraciteInstallSkill:"no"},va=u(({onSelect:t,options:e})=>{const[r,s]=C(0),o=S(()=>{const a=e[r];a&&!a.disabled&&t(a)},[t,e,r]);return _e((a,n)=>{n.upArrow||a==="k"?s(c=>Math.max(0,c-1)):n.downArrow||a==="j"?s(c=>Math.min(e.length-1,c+1)):n.return&&o()}),b(y,{flexDirection:"column",children:[i(d,{color:R,children:"Choose a project preset"}),i(y,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((a,n)=>b(y,{flexDirection:"column",children:[i(d,{children:n===r?b(z,{children:[i(d,{color:a.disabled?ue:A,children:"> "}),i(d,{color:a.disabled?ue:A,children:a.name})]}):i(d,{color:a.disabled?ue:ge,children:` ${a.name}`})}),n===r&&a.description?i(d,{color:R,children:a.description}):null]},a.name))})]})},"PresetStep"),Sa={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},ka=u(({step:t})=>b(d,{children:[i(d,{color:A,children:"\u2727 "}),i(d,{color:q,children:Sa[t]})]}),"WizardTitle"),Aa=u(({onBack:t,onDone:e,onExit:r,onStepChange:s})=>{const[o,a]=C("preset"),[n,c]=C(""),[l,p]=C(null),[h,m]=C(null),[f,_]=C(null),[N,G]=C("");ne(()=>{o==="done"&&e()},[o,e]);const $=J(()=>Br(),[]),L=J(()=>{const M=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return $?M.push({description:Ur($),name:"Last Used"}):M.push({description:"",disabled:!0,name:"Last Used"}),M},[$]),[j,H]=C(ct),ee=S(()=>{switch(o){case"projectName":{a("preset"),s?.("preset"),p(null);return}case"initGit":{a("projectName"),s?.("projectName");return}default:t()}},[t,o,s]),te=S(M=>{if(M.name==="Last Used"&&$){const{projectName:Q,initGit:le,...re}=$;H(re)}else M.name==="API Gateway"?H({...ct,architecture:"nest-gateway",projectType:"monorepo"}):H(ct);a("projectName"),s?.("projectName")},[$,s]),P=S(M=>{c(M),p(Te(M))},[]),O=S(()=>{const M=Te(n);if(M){p(M);return}a("initGit"),s?.("initGit")},[n,s]),I=S(async M=>{m(M);const Q=ce(n),le=ot(Q);G(le),a("installing"),s?.("installing");const re={...j,initGit:M,projectName:Q};try{const X=await Jt(re);_({isError:!X.success,message:X.message}),X.success&&(Nt(re),setTimeout(()=>{a("done"),s?.("done")},1e3))}catch(X){_({isError:!0,message:`Error: ${X instanceof Error?X.message:String(X)}`})}},[n,j,s]);ae((M,Q)=>{if(Q.ctrl&&M==="c"){r();return}if(Q.ctrl&&M==="b"&&o!=="done"){ee();return}o==="done"&&Q.return&&r()});const W=J(()=>o==="projectName"?"confirm":"select",[o]),V=o!=="installing"&&o!=="done";return b(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[V?b(z,{children:[i(Yt,{}),i(fe,{}),i(y,{height:1}),i(ka,{step:o}),i(y,{height:2})]}):null,u(()=>{switch(o){case"preset":return i(va,{onSelect:te,options:L});case"projectName":return i(At,{error:l,onChange:P,onSubmit:O,value:n});case"initGit":return i(K,{onConfirm:I,options:Ot,prompt:"Initialize a git repository?"});case"installing":return b(y,{flexDirection:"column",children:[i(wt,{message:f?.message||"Scaffolding your project",isError:f?.isError??!1}),f?.isError?i(y,{marginTop:1,children:b(d,{color:R,children:["Press ",i(d,{color:A,children:"Enter"})," to go back to Summary and retry, or ",i(d,{color:R,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const M=ce(n);return i(vt,{architecture:j.architecture||"nest-api",projectName:M,packageManager:j.packageManager||"pnpm",isGitInitialized:h==="yes",outputDir:N})}default:return null}},"renderStep")(),i(y,{flexGrow:1}),V?b(z,{children:[i(fe,{}),i(y,{height:1}),i(Je,{action:W,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),xe=[{description:"Scaffold a new project with best practices",name:"Create a new NestJS project"},{description:"Choose from predefined configurations",name:"Use a project preset"},{description:"Browse the Nest Arch docs",name:"View documentation"},{description:"Close Nest Arch",name:"Exit"}],Pa=u(({onSelect:t})=>{const[e,r]=C(0),s=S(()=>{const n=xe[e]??null;n?.disabled||t(e,n)},[t,e]),o=[];for(let n=0;n<xe.length;n+=1)xe[n].disabled||o.push(n);const a=o.indexOf(e);return _e((n,c)=>{if(c.upArrow||n==="k"){const l=o[a-1];l!==void 0&&r(l)}else if(c.downArrow||n==="j"){const l=o[a+1];l!==void 0&&r(l)}else c.return&&s()}),b(y,{flexDirection:"column",children:[i(d,{color:R,children:" What would you like to do?"}),i(y,{marginTop:1,flexDirection:"column",rowGap:1,children:xe.map((n,c)=>i(d,{children:c===e&&!n.disabled?b(z,{children:[i(d,{color:A,children:"> "}),i(d,{color:A,children:n.name})]}):i(d,{color:ge,children:` ${n.name}`})},n.name))})]})},"MainMenu"),Ea=u(()=>b(d,{children:[i(d,{color:A,children:"\u2727 "}),i(d,{color:q,children:" Welcome to "}),i(d,{color:A,children:"Nest Arch"}),i(d,{color:q,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),Ra=u(({onCreateProject:t,onExit:e,onUsePreset:r})=>{const s=S(async()=>{const a="https://github.com/Angel-Mario";try{await cr(a,{wait:!1})}catch{}},[]),o=S((a,n)=>{n?.name==="Exit"?e():n?.name==="Create a new NestJS project"?t():n?.name==="Use a project preset"?r():n?.name==="View documentation"&&s()},[t,e,r,s]);return ae((a,n)=>{n.ctrl&&a==="c"&&e()}),b(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[i(Yt,{}),i(fe,{}),i(y,{height:1}),i(Ea,{}),i(y,{height:2}),i(Pa,{onSelect:o}),i(y,{flexGrow:1}),i(fe,{borderTop:!1}),i(y,{height:1}),i(Je,{})]})},"WelcomeScreen"),_a=u(({onDone:t})=>{const[e,r]=C("welcome"),{stdout:s}=Fe(),{exit:o}=Xt(),[a,n]=C(s?.rows??24);ne(()=>{if(!s)return;const f=u(()=>{n(s.rows)},"handleResize");return s.on("resize",f),()=>{s.off("resize",f)}},[s]);const c=S(()=>{o()},[o]),l=S(()=>{r("preset-wizard")},[]),p=S(()=>{r("create-wizard")},[]),h=S(()=>{r("welcome")},[]);return i(y,{height:a,flexDirection:"column",children:u(()=>e==="create-wizard"?i(ba,{onBack:h,onDone:t,onExit:c}):e==="preset-wizard"?i(Aa,{onBack:h,onDone:t,onExit:c}):i(Ra,{onCreateProject:p,onExit:c,onUsePreset:l}),"renderScreen")()})},"App");async function Ta(){process.stdout.write("\x1B[?1049h");let t=!1;try{await Qt(i(_a,{onDone:u(()=>{process.stdout.write("\x1B[?1049l"),t=!0},"onDone")})).waitUntilExit()}finally{t||process.stdout.write("\x1B[?1049l")}}u(Ta,"main");try{await Ta()}catch(t){console.error("Error:",t),process.exit(1)}export{tt as e};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import"react/jsx-runtime";import"ink";import"react";import"./index-DuMVjfjC.js";import"ink-text-input";import"@t3-oss/env-nextjs";import"zod";import"node:fs";import"node:os";import"node:path";import"node:child_process";import"node:fs/promises";import"node:util";import"handlebars";import"ts-morph";import"open";
1
+ import"react/jsx-runtime";import"ink";import"react";import"./index-lnGBhuOD.js";import"ink-text-input";import"@t3-oss/env-nextjs";import"zod";import"node:fs";import"node:os";import"node:path";import"node:fs/promises";import"handlebars";import"node:child_process";import"node:util";import"ts-morph";import"node:events";import"open";
@@ -13,7 +13,7 @@ if [ -z "$STAGED_FILES" ]; then
13
13
  fi
14
14
 
15
15
  # Run formatter
16
- {{#if isPnpm}}pnpm dlx ultracite fix{{else if isYarn}}yarn dlx ultracite fix{{else if isBun}}bunx ultracite fix{{else}}npx ultracite fix{{/if}}
16
+ {{#if isPnpm}}pnpm dlx ultracite fix{{else if isYarn}}yarn dlx ultracite fix{{else if isBun}}bunx ultracite fix{{else}}npx --yes ultracite fix{{/if}}
17
17
  FORMAT_EXIT_CODE=$?
18
18
 
19
19
  # Re-stage files that were already staged
@@ -1,2 +1,19 @@
1
1
  CORS_ORIGIN=http://localhost:3001
2
2
  PORT=3000
3
+
4
+ {{#if hasPostgres}}
5
+ POSTGRES_URL=postgresql://postgres:postgres@localhost:5432/{{projectNameKebab}}_db?schema=public
6
+ {{/if}}
7
+ {{#if hasMysql}}
8
+ MYSQL_URL=mysql://root:mysql@localhost:3306/{{projectNameKebab}}_db
9
+ {{/if}}
10
+ {{#if hasSqlite}}
11
+ SQLITE_PATH=sqlite.db
12
+ {{/if}}
13
+ {{#if hasMongodb}}
14
+ MONGODB_URL=mongodb://localhost:27017/{{projectNameKebab}}_db
15
+ {{/if}}
16
+ {{#if (or (eq auth "better-auth") (eq auth "better-auth:stateless"))}}
17
+ BETTER_AUTH_SECRET=change-me-to-a-random-secret-at-least-32-characters-long
18
+ BETTER_AUTH_URL=http://localhost:3000
19
+ {{/if}}
@@ -3,6 +3,9 @@
3
3
  /node_modules
4
4
  /build
5
5
 
6
+ # Prisma generated
7
+ **/prisma/generated
8
+
6
9
  # Logs
7
10
  logs
8
11
  *.log
@@ -35,3 +35,40 @@ npm run start{{/if}}
35
35
  # test coverage
36
36
  {{#if isPnpm}}pnpm test:cov{{else if isYarn}}yarn test:cov{{else if isBun}}bun run test:cov{{else}}npm run test:cov{{/if}}
37
37
  ```
38
+
39
+ {{#if (or (eq auth "better-auth") (eq auth "better-auth:stateless"))}}
40
+ ## Auth Setup
41
+
42
+ This project uses **Better Auth**. Generate the database schema by running:
43
+
44
+ ```bash
45
+ {{#if isPnpm}}pnpm dlx auth@latest generate --config src/auth/auth.ts --output src/database/orm/prisma/schema.prisma -y{{else if isYarn}}yarn dlx auth@latest generate --config src/auth/auth.ts --output src/database/orm/prisma/schema.prisma -y{{else if isBun}}bun x auth@latest generate --config src/auth/auth.ts --output src/database/orm/prisma/schema.prisma -y{{else}}npx auth@latest generate --config src/auth/auth.ts --output src/database/orm/prisma/schema.prisma -y{{/if}}
46
+ ```
47
+
48
+ {{#if useDrizzle}}Then run Drizzle migrations:
49
+
50
+ ```bash
51
+ {{#if isPnpm}}pnpm drizzle-kit generate && pnpm drizzle-kit migrate{{else if isYarn}}yarn drizzle-kit generate && yarn drizzle-kit migrate{{else}}npx drizzle-kit generate && npx drizzle-kit migrate{{/if}}
52
+ ```
53
+
54
+ {{/if}}
55
+ See https://better-auth.com/docs/adapters/prisma for more details.
56
+
57
+ ### Usage
58
+
59
+ Access the authenticated user's session in any controller with full type safety (including better-auth plugins):
60
+
61
+ ```typescript
62
+ import { Controller, Get } from "@nestjs/common";
63
+ import { Session } from "@thallesp/nestjs-better-auth";
64
+ import type { UserSession } from "./auth/auth.js";
65
+
66
+ @Controller()
67
+ export class AppController {
68
+ @Get()
69
+ getSession(@Session() session: UserSession): UserSession {
70
+ return session;
71
+ }
72
+ }
73
+ ```
74
+ {{/if}}
@@ -1,2 +1,6 @@
1
1
  allowBuilds:
2
2
  "@nestjs/core": true
3
+ {{#if usePrisma}}
4
+ prisma: true
5
+ "@prisma/engines": true
6
+ {{/if}}