@nest-arch/tui 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +1 -2
  2. package/dist/cli.js +1 -1
  3. package/dist/{constants-LZTzRAoQ.js → constants-DBtqeoTh.js} +1 -1
  4. package/dist/index.js +59 -59
  5. package/dist/templates/base/.env.example.hbs +1 -1
  6. package/dist/templates/base/.env.hbs +1 -1
  7. package/dist/templates/base/pnpm-workspace.yaml.hbs +3 -0
  8. package/dist/templates/base/src/app.module.ts.hbs +11 -5
  9. package/dist/templates/base/src/database/db.module.ts.hbs +2 -4
  10. package/dist/templates/base/src/main.ts.hbs +6 -0
  11. package/dist/templates/extras/swagger/create-docs.ts.hbs +13 -1
  12. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs +14 -189
  13. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.module.ts.hbs +24 -0
  14. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.router.ts.hbs +76 -0
  15. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.service.ts.hbs +145 -0
  16. package/dist/templates/monorepo/apps/api-gateway/src/app.module.ts.hbs +11 -5
  17. package/dist/templates/monorepo/apps/api-gateway/src/main.ts.hbs +6 -0
  18. package/dist/templates/monorepo/root/pnpm-workspace.yaml.hbs +3 -0
  19. package/dist/templates/single-project/architecture/nest-api/.env.hbs +1 -1
  20. package/dist/templates/single-project/architecture/nest-api/pnpm-workspace.yaml.hbs +3 -0
  21. package/dist/templates/single-project/architecture/nest-api/src/main.ts.hbs +6 -0
  22. package/dist/templates/single-project/architecture/nest-gateway/src/main.ts.hbs +6 -0
  23. package/dist/templates/single-project/architecture/nest-microservice/src/main.ts.hbs +6 -0
  24. package/package.json +4 -4
  25. package/dist/templates/base/src/libs/trpc/scripts/fix-trpc-generated.mjs.hbs +0 -21
  26. package/dist/templates/base/src/libs/trpc/scripts/watch-trpc.mjs.hbs +0 -91
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var Yt=Object.defineProperty;var u=(t,e)=>Yt(t,"name",{value:e,configurable:!0});import{jsx as l,jsxs as j,Fragment as L}from"react/jsx-runtime";import{Box as w,Text as d,useInput as le,useStdout as We,render as Xt,useApp as Kt}from"ink";import{useState as C,useEffect as ae,useMemo as W,useRef as Je,useCallback as T,useLayoutEffect as ut}from"react";import{COLOR_DIVIDER as pe,COLOR_RED as P,COLOR_WARM as ue,COLOR_DIM as q,COLOR_FG as M,COLOR_SUCCESS as je,COLOR_DIMMER as ve,COLOR_ACCENT as H,COLOR_WARM_SECONDARY as Zt,APP_NAME as dt,APP_TAGLINE as xe,APP_VERSION as Ie}from"./constants-LZTzRAoQ.js";import er from"ink-text-input";import{createEnv as tr}from"@t3-oss/env-nextjs";import{z as de}from"zod";import{existsSync as Se,readFileSync as rr,mkdirSync as sr,writeFileSync as ar}from"node:fs";import{homedir as mt}from"node:os";import v,{join as Q}from"node:path";import K,{access as or,readFile as Ce,writeFile as ke,rm as nr}from"node:fs/promises";import J from"handlebars";import{execFile as ir,exec as ht,spawn as Oe}from"node:child_process";import{promisify as He}from"node:util";import{Scope as cr,Project as lr}from"ts-morph";import{once as re}from"node:events";import pr from"open";const Ae=u(({borderTop:t=!0})=>l(w,{borderStyle:"single",borderBottom:!t,borderLeft:!1,borderRight:!1,borderTop:t,borderColor:pe,height:1,width:"full"}),"Divider"),ur=` \uFF0Fl\u3001
1
+ var Yt=Object.defineProperty;var u=(t,e)=>Yt(t,"name",{value:e,configurable:!0});import{jsx as c,jsxs as w,Fragment as D}from"react/jsx-runtime";import{Box as y,Text as m,useInput as pe,useStdout as He,render as Xt,useApp as Kt}from"ink";import{useState as O,useEffect as ae,useMemo as J,useRef as We,useCallback as T,useLayoutEffect as dt}from"react";import{COLOR_DIVIDER as ue,COLOR_RED as P,COLOR_WARM as de,COLOR_DIM as q,COLOR_FG as N,COLOR_SUCCESS as Se,COLOR_DIMMER as oe,COLOR_ACCENT as W,COLOR_WARM_SECONDARY as Zt,APP_NAME as mt,APP_TAGLINE as Ie,APP_VERSION as Oe}from"./constants-DBtqeoTh.js";import er from"ink-text-input";import{createEnv as tr}from"@t3-oss/env-nextjs";import{z as me}from"zod";import{existsSync as ke,readFileSync as rr,mkdirSync as sr,writeFileSync as ar}from"node:fs";import{homedir as ht}from"node:os";import v,{join as Q}from"node:path";import{exec as Ve,execFile as or,spawn as Ce}from"node:child_process";import{promisify as _e}from"node:util";import K,{access as nr,readFile as Ge,writeFile as Ae,rm as ir}from"node:fs/promises";import H from"handlebars";import{Scope as cr,Project as lr}from"ts-morph";import{once as re}from"node:events";import pr from"open";const Te=u(({borderTop:t=!0})=>c(y,{borderStyle:"single",borderBottom:!t,borderLeft:!1,borderRight:!1,borderTop:t,borderColor:ue,height:1,width:"full"}),"Divider"),ur=` \uFF0Fl\u3001
2
2
  \uFF08\uFF9F\uFF64 \uFF61\uFF17
3
3
  l\u3001\uFF9E ~\u30FD
4
4
  \u3058\u3057(_,)\u30CE
5
- `,Ve=` ,-. _,---._ __ /\\
5
+ `,Qe=` ,-. _,---._ __ /\\
6
6
  / ) .-' \`./ / \\
7
7
  ( ( ,' \` / /|
8
8
  \\ \`-" \\'\\ / |
@@ -13,20 +13,20 @@ var Yt=Object.defineProperty;var u=(t,e)=>Yt(t,"name",{value:e,configurable:!0})
13
13
  | | ( | Stuff | /
14
14
  ) | \\ \`.___________|/
15
15
  \`--' \`--'
16
- `,dr=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"),gt=u(t=>{let e=0;for(const r of t){const a=r.codePointAt(0)??0;e+=dr(a)?2:1}return e},"getDisplayWidth"),mr=2,ft=[0,1,2,3,2,1],yt=["",".","..","..."],hr=u(({message:t="Scaffolding your project",isError:e=!1,isComplete:r=!1,showProgressText:a=!0,paddingX:n=2})=>{const[s,o]=C(0),[i,c]=C(0),p=!e&&!r;ae(()=>{if(!p)return;const F=setInterval(()=>{o(N=>(N+1)%ft.length)},200),_=setInterval(()=>{c(N=>(N+1)%yt.length)},400);return()=>{clearInterval(F),clearInterval(_)}},[p]);const g=ur.trimEnd().split(`
17
- `),m=Math.max(...g.map(gt)),f=ft[s];let O=ue,x="\u25CF",U=q;return e?(O=P,x="\u2717",U=M):r&&(O=je,x="\u2713",U=je),j(w,{flexDirection:"column",paddingX:n,children:[l(w,{flexDirection:"column",children:g.map((F,_)=>{const N=gt(F),S=_===0||_===g.length-1,$=m-N+mr-(S?1:0),Z=_===f;return j(d,{color:P,children:[F," ".repeat($),Z?l(d,{color:O,children:x}):" "]},_)})}),a&&j(d,{color:U,children:[t,p?yt[i]:""]})]})},"ScaffoldingAnimation"),gr=[{id:"generate-files",label:"Generate project"},{id:"setup-linter",label:"Setup linter"},{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"}],bt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function fr(t,e,r){if(!t)return r.map(s=>({stage:s,status:"pending"}));if(t==="complete")return r.map(s=>({stage:s,status:e?"failed":"completed"}));const n=r.map(s=>s.id).indexOf(t);return r.map((s,o)=>o<n?{stage:s,status:e?"failed":"completed"}:o===n?{stage:s,status:e?"failed":"active"}:e&&o>n?{stage:s,status:"pending"}:e?{stage:s,status:"failed"}:{stage:s,status:"pending"})}u(fr,"getStages");function yr(t,e){switch(t){case"completed":return"\u2713";case"active":return e;case"failed":return"\u2717";case"pending":return"\u25CB";default:return t}}u(yr,"statusIcon");function br(t){switch(t){case"completed":return je;case"active":return ue;case"failed":return P;case"pending":return ve;default:return t}}u(br,"statusColor");function wr(t){return t===void 0?"":` (${t}%)`}u(wr,"formatPercentage");function jr(t){return t?.message?t.message:"Installing dependencies..."}u(jr,"getInstallMessage");const wt=u(({currentStage:t,generationMessage:e,installProgress:r,isError:a,skippedStages:n=[]})=>{const s=W(()=>gr.filter(m=>!n.includes(m.id)),[n]),o=W(()=>fr(t,a,s),[t,a,s]),[i,c]=C(0),p=t==="complete"&&!a;ae(()=>{if(a||p)return;const m=setInterval(()=>{c(f=>(f+1)%bt.length)},80);return()=>clearInterval(m)},[a,p]);const g=bt[i]??"\u280B";return j(w,{flexDirection:"column",paddingX:2,children:[l(w,{marginBottom:1,children:l(hr,{showProgressText:!1,paddingX:0,isError:a,isComplete:p})}),l(w,{flexDirection:"column",rowGap:0,children:o.map(m=>{const f=m.status==="active",O=f&&m.stage.id==="install-dependencies",x=r?.percentage,U=16,F=x===void 0?0:Math.round(x/100*U),_=U-F;return j(w,{flexDirection:"column",children:[j(w,{children:[j(d,{bold:f,color:br(m.status),children:[yr(m.status,g)," ",m.stage.label]}),O?l(d,{children:x===void 0?null:j(L,{children:[l(d,{color:ue,children:wr(x)})," ",l(d,{color:ue,children:"\u2588".repeat(F)}),l(d,{color:pe,children:"\u2591".repeat(_)})]})}):null]}),O?l(w,{marginLeft:4,children:l(d,{color:q,children:jr(r)})}):null]},m.stage.id)})}),!a&&t===null?l(w,{marginTop:1,children:l(d,{color:q,children:e})}):null,p?l(w,{marginTop:1,children:l(d,{color:je,children:e})}):null,a?l(w,{marginTop:1,flexDirection:"column",children:e.split(`
18
- `).map((m,f)=>l(d,{color:m.startsWith(" ")?q:P,children:m},f))}):null]})},"InstallationProgress"),Qe=u(({action:t="select",showBack:e=!1})=>j(d,{children:[t==="select"||t==="multi-select"?l(d,{color:q,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,l(d,{color:q,children:t==="confirm"?j(L,{children:[l(d,{color:M,children:"Enter "}),"to confirm"]}):t==="multi-select"?j(L,{children:[l(d,{color:M,children:"Space "}),"to toggle \u2022",l(d,{color:M,children:" Enter "}),"to confirm"]}):j(L,{children:[l(d,{color:M,children:"Enter "}),"to select"]})}),j(d,{color:q,children:[e?j(L,{children:[" ","\u2022",l(d,{color:M,children:" Ctrl+B "}),"to go back"]}):"",j(L,{children:[" ","\u2022",l(d,{color:M,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),jt=u(({architecture:t,projectName:e,packageManager:r,isGitInitialized:a,dependenciesInstalled:n,outputDir:s})=>l(w,{flexDirection:"column",children:j(w,{flexDirection:"column",marginTop:1,children:[l(d,{color:je,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),j(w,{marginTop:1,children:[l(d,{color:M,children:"Project: "}),l(d,{color:H,bold:!0,children:e})]}),j(w,{children:[l(d,{color:M,children:"Architecture: "}),l(d,{color:H,bold:!0,children:t})]}),s?j(w,{children:[l(d,{color:M,children:"Location: "}),l(d,{color:H,bold:!0,children:s})]}):null,a?l(w,{marginTop:1,children:l(d,{color:q,children:"Git repository initialized"})}):null,j(w,{flexDirection:"column",borderStyle:"round",borderColor:P,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[l(d,{color:M,bold:!0,children:"\u{1F680} NEXT STEPS"}),l(w,{height:1}),l(d,{color:M,children:"1. Move into the project directory:"}),l(d,{color:H,bold:!0,children:` cd ${e}`}),l(w,{height:1}),n?l(w,{children:l(d,{color:q,children:"2. Dependencies already installed"})}):j(L,{children:[l(d,{color:M,children:"2. Install dependencies:"}),l(d,{color:H,bold:!0,children:` ${r} install`})]}),l(w,{height:1}),j(d,{color:M,children:["3."," Start development server:"]}),l(d,{color:H,bold:!0,children:` ${r} run dev`})]}),l(w,{marginTop:1,children:l(d,{color:q,children:"(Press enter to exit)"})})]})}),"DoneStep"),vr=100,_e=u(t=>{const e=Je(0);le((r,a)=>{if(a.upArrow||a.downArrow||a.leftArrow||a.rightArrow||r==="k"||r==="j"||r==="h"||r==="l"){const s=Date.now();if(s-e.current<vr)return;e.current=s}t(r,a)})},"useArrowSelect"),oe=u(({initialSelected:t,onConfirm:e,onChange:r,options:a,prompt:n,minified:s=!1})=>{const o=W(()=>new Set(a.map(k=>k.value)),[a]),i=T(k=>k.filter(I=>o.has(I)),[o]),[c,p]=C(0),[g,m]=C(()=>i(t)),f=Je(g);f.current=g;const O=Je(r);O.current=r,ae(()=>{const k=i(t);m(k),p(0),O.current?.(k)},[t,i]);const x=T(k=>g.includes(k),[g]),U=T(k=>{const I=a[k];I&&m(D=>{const V=D.includes(I.value)?D.filter(ee=>ee!==I.value):[...D,I.value];return f.current=V,r?.(V),V})},[a,r]),F=T(()=>{e(f.current)},[e]),_=a.length>16,N=_?Math.ceil(a.length/2):a.length;_e((k,I)=>{I.upArrow||k==="k"?p(D=>(D-1+a.length)%a.length):I.downArrow||k==="j"?p(D=>(D+1)%a.length):_&&(I.leftArrow||k==="h")?p(D=>(D-N+a.length)%a.length):_&&(I.rightArrow||k==="l")?p(D=>(D+N)%a.length):I.return?F():(k===" "||k==="x")&&U(c)});const S=g.length,$=u((k,I)=>{const D=x(k.value),V=I===c,ee=D?"\u25CF":"\u25CB";return j(w,{flexDirection:"column",children:[l(d,{children:V?j(L,{children:[l(d,{color:P,children:"> "}),l(d,{color:D?P:q,children:`${ee} `}),l(d,{color:D?P:M,children:k.label})]}):j(L,{children:[l(d,{color:D?P:q,children:` ${ee}`}),l(d,{color:ve,children:` ${k.label}`})]})}),V&&!_?j(d,{color:q,children:[" ",k.description]}):null]},k.value)},"renderOption");let Z;return _||(Z=s?0:1),j(w,{flexDirection:"column",children:[l(d,{color:q,children:n}),l(d,{color:ue,children:S===0?"No options selected yet \u2014 pick what you need":`${S} selected`}),l(w,{marginTop:1,flexDirection:_?"row":"column",rowGap:Z,columnGap:_?4:void 0,overflow:"hidden",children:_?j(L,{children:[l(w,{flexDirection:"column",rowGap:s?0:1,flexGrow:1,flexBasis:0,children:a.slice(0,N).map((k,I)=>$(k,I))}),l(w,{flexDirection:"column",rowGap:s?0:1,flexGrow:1,flexBasis:0,children:a.slice(N).map((k,I)=>$(k,I+N))})]}):a.map((k,I)=>$(k,I))})]})},"MultiSelectStep"),vt="my-nest-app",St=64,Sr=/^[a-z][a-z0-9-]*$/u;function ne(t){return t.trim()||vt}u(ne,"resolveProjectName");function ze(t){const e=t.trim();return e?e.length>St?`Project name must be at most ${St} characters`:Sr.test(e)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}u(ze,"validateProjectName");const kt=u(({error:t,onChange:e,onSubmit:r,value:a})=>(le((n,s)=>{s.return&&r()}),j(w,{flexDirection:"column",children:[l(d,{color:q,children:"Enter a name for your project"}),j(w,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[l(d,{color:M,children:"Project name:"}),l(er,{placeholder:vt,value:a,onChange:e})]}),t?l(d,{color:P,children:t}):null]})),"ProjectNameStep"),Y=u(({onConfirm:t,options:e,prompt:r,initialValue:a})=>{const[n,s]=C(()=>{const i=e.findIndex(c=>c.value===a);return Math.max(i,0)});ae(()=>{const i=e.findIndex(c=>c.value===a);s(Math.max(i,0))},[a,e]);const o=T(()=>{const i=e[n];i&&t(i.value)},[t,e,n]);return _e((i,c)=>{c.upArrow||i==="k"?s(p=>(p-1+e.length)%e.length):c.downArrow||i==="j"?s(p=>(p+1)%e.length):c.return&&o()}),j(w,{flexDirection:"column",children:[l(d,{color:q,children:r}),l(w,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((i,c)=>{const p=c===n;return j(w,{flexDirection:"column",children:[l(d,{children:p?j(L,{children:[l(d,{color:P,children:"> "}),l(d,{color:P,children:i.label})]}):l(d,{color:ve,children:` ${i.label}`})}),p?l(d,{color:q,children:i.description}):null]},i.value)})})]})},"SingleSelectStep"),At=[{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"}],Tt=[{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"}],Pt=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],Et=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",label:"Monorepo (Turborepo)",value:"monorepo"}],Rt=[{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"}],Ye=[{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"}],Xe=[{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"}],Ke=[{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 (Code first)",value:"graphql"}],Ze=[{description:"No authentication scaffolding",label:"None",value:"none"},{description:"Flexible authentication \u2014 stateless (OAuth 2 JWE session) when no database, ORM-backed (JWT Authorization Bearer) 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"}],et=[{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"},{description:"Scaffold a Todo CRUD module example (GraphQL only)",label:"Todo Example",value:"todo-example"}],qt=[{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:"Modern OpenAPI documentation UI",label:"Scalar UI (Recommended)",value:"scalar-ui"}],kr=[{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"}],xt=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],Ar=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],Tr=[{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"}],Pr=[{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"}],Er=[{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"}],Rr=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],qr={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"},xr=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","installing","done"];function Ir(t){return t.includes("mongodb")}u(Ir,"databaseIncludesMongodb");function tt(t){return t.length===0}u(tt,"databaseIsEmpty");function Ge(t){return t.includes("rest")||t.includes("trpc")}u(Ge,"hasApiLayer");function De(t){return tt(t)}u(De,"shouldSkipOrmStep");function Te(t){return xr.filter(e=>!(e==="orm"&&De(t.database)||e==="auth"&&!Ge(t.api)||e==="microservices"&&t.architecture!=="nest-gateway"||(e==="ultraciteEditors"||e==="ultraciteAgents"||e==="ultraciteHooks"||e==="ultraciteInstallSkill")&&(!t.addons.includes("ultracite")||t.formatter==="none")))}u(Te,"getVisibleSteps");const It=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function Pe(t){return It.includes(t)}u(Pe,"isUltraciteSubStep");function Cr(t,e){if(!Pe(t))return null;const r=It.filter(i=>Te(e).includes(i)),a=r.indexOf(t);if(a===-1)return null;const n=r.length,s=a+1,o=Math.round(s/n*100);return{current:s,percent:o,total:n}}u(Cr,"getUltraciteSubStepInfo");function rt(t){return Te(t).filter(e=>e!=="installing"&&e!=="done"&&!Pe(e)).length}u(rt,"getTotalSteps");function Or(t,e){const r=Te(e).filter(s=>s!=="installing"&&s!=="done");if(t==="installing"||t==="done")return rt(e);if(Pe(t)){const s=r.indexOf("addons");return s===-1?1:s+1}const n=r.filter(s=>!Pe(s)).indexOf(t);return n===-1?1:n+1}u(Or,"getDisplayStepNumber");function _r(t,e){const r=Te(e),a=r.indexOf(t);return a===-1||a>=r.length-1?null:r[a+1]??null}u(_r,"getNextStepId");function zr(t,e){const r=Te(e),a=r.indexOf(t);return a<=0?null:r[a-1]??null}u(zr,"getPreviousStepId");function Gr(t){return t==="monorepo"?Rt:Rt.filter(e=>e.value!=="nest-gateway")}u(Gr,"filterArchitectureOptions");function Ct(t){return Ir(t)?Xe.filter(e=>e.value!=="drizzle"):Xe}u(Ct,"filterOrmOptions");function Dr(t){return t.includes("drizzle")?Ye.filter(e=>e.value!=="mongodb"):Ye}u(Dr,"filterDatabaseOptions");function Mr(t){return tt(t)?Ze.filter(e=>e.value!=="better-auth"):Ze}u(Mr,"filterAuthOptions");function Nr(t){return tt(t)?Ke.filter(e=>e.value!=="graphql"):Ke}u(Nr,"filterApiOptions");function Lr(t,e){return e.includes("drizzle")?t.filter(r=>r!=="mongodb"):t}u(Lr,"sanitizeDatabaseForOrm");function Ot(t){return"nest-api"}u(Ot,"defaultArchitecture");function _t(t,e){if(De(e))return[];const r=new Set(Ct(e).map(a=>a.value));return t.filter(a=>r.has(a))}u(_t,"sanitizeOrmForDatabase");function me(t,e){return t.find(r=>r.value===e)?.label??e}u(me,"labelFor");function he(t,e){return e.length===0?"None":e.map(r=>me(t,r)).join(", ")}u(he,"labelsFor");const Fr=u(({onConfirm:t,state:e})=>{le((n,s)=>{s.return&&t()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},a=[{label:"Project",value:ne(e.projectName)},{label:"Package manager",value:e.packageManager?me(At,e.packageManager):"\u2014"},{label:"Formatter",value:e.formatter?me(Tt,e.formatter):"\u2014"},{label:"HTTP provider",value:e.httpProvider?me(Pt,e.httpProvider):"\u2014"},{label:"Project type",value:e.projectType?me(Et,e.projectType):"\u2014"},{label:"Architecture",value:e.architecture?r[e.architecture]??e.architecture:"\u2014"},{label:"Database",value:he(Ye,e.database)}];return De(e.database)||a.push({label:"ORM",value:he(Xe,e.orm)}),a.push({label:"API layer",value:he(Ke,e.api)}),e.architecture==="nest-gateway"&&a.push({label:"Microservices",value:he([{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)}),Ge(e.api)&&a.push({label:"Auth",value:e.auth?me(Ze,e.auth):"\u2014"}),a.push({label:"Extras",value:he(et,e.extras)},{label:"Addons",value:he(qt,e.addons)},{label:"Git",value:e.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:e.installDependencies==="yes"?"Install":"Skip"}),j(L,{children:[l(w,{flexDirection:"column",marginBottom:1,children:j(d,{children:[l(d,{color:P,children:"\u2726 "}),l(d,{color:H,children:"Review your selections"})]})}),l(w,{flexDirection:"column",rowGap:0,overflow:"hidden",children:a.map(n=>j(w,{flexDirection:"row",columnGap:1,children:[l(d,{color:Zt,children:`${n.label}:`}),l(d,{color:ue,children:n.value})]},n.label))})]})},"SummaryStep"),Me=tr({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:de.string().pipe(de.coerce.number()).default(95),NEST_ARCH_BETA_MODE:de.enum(["true","false"]).default("false").transform(t=>t==="true"),NEST_ARCH_SCHEMA_URL:de.string().default("./schema.json"),NEST_ARCH_VERSION:de.string().default("0.0.1"),NODE_ENV:de.enum(["development","production","test"]).default("development")}});function st(t){return t.length===0?"\u2014":t.join(", ")}u(st,"formatList");const Ur=u(({state:t,stepId:e})=>{const{stdout:r}=We(),a=r.columns||r.getWindowSize?.()[0]||80,n=Math.min(Me.APP_MAX_WIDTH,a-4),s=[];if(e!=="projectName"&&t.projectName.trim()&&s.push(ne(t.projectName)),t.packageManager&&s.push(t.packageManager),t.httpProvider&&s.push(t.httpProvider),t.projectType&&s.push(t.projectType==="monorepo"?"Monorepo":"Single"),t.architecture){const c={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};s.push(c[t.architecture]??t.architecture)}if(t.database.length>0&&s.push(st(t.database)),t.orm.length>0&&s.push(st(t.orm)),t.api.length>0&&s.push(st(t.api)),t.auth&&s.push(t.auth),t.extras.length>0&&s.push(`+${t.extras.length} extras`),t.addons.length>0&&!Pe(e)&&s.push(`+${t.addons.length} addons`),t.initGit&&s.push(t.initGit==="yes"?"git init":"no git"),s.length===0)return j(d,{children:[l(d,{color:P,children:"\u25C6 "}),l(d,{color:P,children:"Create a new NestJS project"})]});const[o,...i]=s;return j(L,{children:[j(d,{children:[l(d,{color:P,children:"\u25C6 "}),l(d,{color:P,children:"Create a new NestJS project"})]}),e!=="summary"&&l(w,{borderStyle:"single",borderColor:pe,width:n,children:j(d,{children:[l(d,{children:"Project Name: "}),l(d,{color:P,children:o}),l(d,{color:q,children:" Selected: "}),i.length>0?l(d,{color:q,children:`${i.filter(c=>c!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),$r=u(({displayStep:t,stepId:e,subProgress:r,totalSteps:a})=>j(w,{paddingLeft:2,paddingTop:e==="summary"?2:1,marginBottom:1,children:[l(d,{color:M,children:"Create project"}),l(d,{color:q,children:` \u2014 step ${t}/${a}`}),r?l(d,{color:H,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):l(d,{color:H,children:` \xB7 ${qr[e]}`})]}),"WizardTitle$1"),at=Q(mt(),".nestarch"),ot=Q(at,"last-used.json");function Br(){try{if(!Se(ot))return null;const t=rr(ot,"utf-8");return JSON.parse(t)}catch{return null}}u(Br,"getLastUsedConfig");function zt(t){try{Se(at)||sr(at,{recursive:!0}),ar(ot,JSON.stringify(t,null,2),"utf-8")}catch{}}u(zt,"saveLastUsedConfig");function Wr(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,a=r.toLocaleString("en-US",{month:"short"}),n=r.getDate(),s=r.getFullYear(),o=`${a} ${n}, ${s}`;return`${e.join(", ")} (last used ${o})`}u(Wr,"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(J.registerHelper("eq",(r,a)=>r===a),J.registerHelper("ne",(r,a)=>r!==a),J.registerHelper("lt",(r,a)=>r<a),J.registerHelper("gt",(r,a)=>r>a),J.registerHelper("and",(r,a)=>r&&a),J.registerHelper("or",(r,a)=>r||a),J.registerHelper("includes",(r,a)=>Array.isArray(r)?r.includes(a):typeof r=="string"?r.includes(String(a)):!1),J.registerHelper("uppercase",r=>r?.toUpperCase?.()),J.registerHelper("lowercase",r=>r?.toLowerCase?.()),J.registerHelper("capitalize",r=>r?r.charAt(0).toUpperCase()+r.slice(1):""),J.registerHelper("camelCase",r=>r?.split("-").map((a,n)=>n===0?a.toLowerCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")),J.registerHelper("pascalCase",r=>r?.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")),J.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),e)for(const[r,a]of Object.entries(e))J.registerHelper(r,a)}async loadTemplate(e){const r=e;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const a=v.join(this.templatesDir,e),n=await K.readFile(a,"utf-8"),s=J.compile(n);return this.cacheEnabled&&(this.cache[r]=s),s}async renderTemplate(e,r){return(await this.loadTemplate(e))(r.context)}async renderToFile(e,r,a){return{content:await this.renderTemplate(e,a),filePath:r,isBinary:!1}}clearCache(){this.cache={}}getCacheStats(){return{enabled:this.cacheEnabled,size:Object.keys(this.cache).length}}}class Jr{static{u(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(e){this.baseDir=e}getBaseDir(){return this.baseDir}async writeFile(e,r={}){const a=v.join(this.baseDir,e.filePath),n=v.dirname(a);try{await K.mkdir(n,{recursive:!0});let s=!1;try{await K.stat(a),s=!0}catch{s=!1}if(s&&!r.overwrite)return{backed:!1,error:"File already exists and overwrite is disabled",filePath:a,written:!1};let o=!1;if(s&&r.createBackups&&!r.dryRun){const i=`${a}.bak`;await K.copyFile(a,i),o=!0}return r.dryRun||(await K.writeFile(a,e.content,"utf-8"),this.writtenFiles.add(a)),{backed:o,filePath:a,written:!r.dryRun}}catch(s){return{backed:!1,error:s instanceof Error?s.message:"Unknown error",filePath:a,written:!1}}}writeFiles(e,r={}){return Promise.all(e.map(a=>this.writeFile(a,r)))}async fileExists(e){const r=v.join(this.baseDir,e);try{return await K.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(e,r){const a=[],n=v.join(this.baseDir,e),s=v.join(this.baseDir,r);await K.mkdir(s,{recursive:!0});const o=await K.readdir(n,{withFileTypes:!0});for(const i of o){const c=v.join(n,i.name),p=v.join(s,i.name);if(i.isDirectory()){const g=await this.copyDirectory(v.relative(this.baseDir,c),v.relative(this.baseDir,p));a.push(...g)}else{const g=await K.readFile(c,"utf-8");await K.writeFile(p,g,"utf-8"),a.push(p),this.writtenFiles.add(p)}}return a}}const Ne=He(ir);async function Hr(t){await Ne("git",["init"],{cwd:t})}u(Hr,"gitInit");async function Gt(t){await Ne("git",["add","."],{cwd:t})}u(Gt,"gitAddAll");async function Dt(t,e){await Ne("git",["commit","--no-verify","-m",e],{cwd:t})}u(Dt,"gitCommit");async function Vr(t){try{const{stdout:e}=await Ne("git",["diff","--cached","--name-only"],{cwd:t});return e.trim().length>0}catch{return!1}}u(Vr,"gitHasStagedChanges");async function Qr(t){try{return await or(Q(t,".git")),!0}catch{return!1}}u(Qr,"gitDirectoryExists");const Yr=He(ht),Xr={bun:["Bun is not installed or not found in your PATH.",""," Install Bun: https://bun.sh",""," Then restart your terminal and try again."].join(`
16
+ `,dr=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"),gt=u(t=>{let e=0;for(const r of t){const a=r.codePointAt(0)??0;e+=dr(a)?2:1}return e},"getDisplayWidth"),mr=2,ft=[0,1,2,3,2,1],bt=["",".","..","..."],hr=u(({message:t="Scaffolding your project",isError:e=!1,isComplete:r=!1,showProgressText:a=!0,paddingX:n=2})=>{const[s,o]=O(0),[i,l]=O(0),p=!e&&!r;ae(()=>{if(!p)return;const L=setInterval(()=>{o(F=>(F+1)%ft.length)},200),C=setInterval(()=>{l(F=>(F+1)%bt.length)},400);return()=>{clearInterval(L),clearInterval(C)}},[p]);const h=ur.trimEnd().split(`
17
+ `),d=Math.max(...h.map(gt)),j=ft[s];let I=de,M="\u25CF",$=q;return e?(I=P,M="\u2717",$=N):r&&(I=Se,M="\u2713",$=Se),w(y,{flexDirection:"column",paddingX:n,children:[c(y,{flexDirection:"column",children:h.map((L,C)=>{const F=gt(L),S=C===0||C===h.length-1,U=d-F+mr-(S?1:0),Z=C===j;return w(m,{color:P,children:[L," ".repeat(U),Z?c(m,{color:I,children:M}):" "]},C)})}),a&&w(m,{color:$,children:[t,p?bt[i]:""]})]})},"ScaffoldingAnimation"),gr=[{id:"generate-files",label:"Generate project"},{id:"install-agent-skills",label:"Install agent skills"},{id:"setup-linter",label:"Setup linter"},{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"}],yt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function fr(t,e,r){if(!t)return r.map(s=>({stage:s,status:"pending"}));if(t==="complete")return r.map(s=>({stage:s,status:e?"failed":"completed"}));const n=r.map(s=>s.id).indexOf(t);return r.map((s,o)=>o<n?{stage:s,status:e?"failed":"completed"}:o===n?{stage:s,status:e?"failed":"active"}:e&&o>n?{stage:s,status:"pending"}:e?{stage:s,status:"failed"}:{stage:s,status:"pending"})}u(fr,"getStages");function br(t,e){switch(t){case"completed":return"\u2713";case"active":return e;case"failed":return"\u2717";case"pending":return"\u25CB";default:return t}}u(br,"statusIcon");function yr(t){switch(t){case"completed":return Se;case"active":return de;case"failed":return P;case"pending":return oe;default:return t}}u(yr,"statusColor");function wr(t){return t===void 0?"":` (${t}%)`}u(wr,"formatPercentage");function jr(t){return t?.message?t.message:"Installing dependencies..."}u(jr,"getInstallMessage");const wt=u(({currentStage:t,generationMessage:e,installProgress:r,isError:a,skippedStages:n=[]})=>{const s=J(()=>gr.filter(d=>!n.includes(d.id)),[n]),o=J(()=>fr(t,a,s),[t,a,s]),[i,l]=O(0),p=t==="complete"&&!a;ae(()=>{if(a||p)return;const d=setInterval(()=>{l(j=>(j+1)%yt.length)},80);return()=>clearInterval(d)},[a,p]);const h=yt[i]??"\u280B";return w(y,{flexDirection:"column",paddingX:2,children:[c(y,{marginBottom:1,children:c(hr,{showProgressText:!1,paddingX:0,isError:a,isComplete:p})}),c(y,{flexDirection:"column",rowGap:0,children:o.map(d=>{const j=d.status==="active",I=j&&d.stage.id==="install-dependencies",M=r?.percentage,$=16,L=M===void 0?0:Math.round(M/100*$),C=$-L;return w(y,{flexDirection:"column",children:[w(y,{children:[w(m,{bold:j,color:yr(d.status),children:[br(d.status,h)," ",d.stage.label]}),I?c(m,{children:M===void 0?null:w(D,{children:[c(m,{color:de,children:wr(M)})," ",c(m,{color:de,children:"\u2588".repeat(L)}),c(m,{color:ue,children:"\u2591".repeat(C)})]})}):null]}),I?c(y,{marginLeft:4,children:c(m,{color:q,children:jr(r)})}):null]},d.stage.id)})}),!a&&t===null?c(y,{marginTop:1,children:c(m,{color:q,children:e})}):null,p?c(y,{marginTop:1,children:c(m,{color:Se,children:e})}):null,a?c(y,{marginTop:1,flexDirection:"column",children:e.split(`
18
+ `).map((d,j)=>c(m,{color:d.startsWith(" ")?q:P,children:d},j))}):null]})},"InstallationProgress"),Ye=u(({action:t="select",showBack:e=!1})=>w(m,{children:[t==="select"||t==="multi-select"?c(m,{color:q,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,c(m,{color:q,children:t==="confirm"?w(D,{children:[c(m,{color:N,children:"Enter "}),"to confirm"]}):t==="multi-select"?w(D,{children:[c(m,{color:N,children:"Space "}),"to toggle \u2022",c(m,{color:N,children:" Enter "}),"to confirm"]}):w(D,{children:[c(m,{color:N,children:"Enter "}),"to select"]})}),w(m,{color:q,children:[e?w(D,{children:[" ","\u2022",c(m,{color:N,children:" Ctrl+B "}),"to go back"]}):"",w(D,{children:[" ","\u2022",c(m,{color:N,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),jt=u(({architecture:t,projectName:e,packageManager:r,isGitInitialized:a,dependenciesInstalled:n,outputDir:s})=>c(y,{flexDirection:"column",children:w(y,{flexDirection:"column",marginTop:1,children:[c(m,{color:Se,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),w(y,{marginTop:1,children:[c(m,{color:N,children:"Project: "}),c(m,{color:W,bold:!0,children:e})]}),w(y,{children:[c(m,{color:N,children:"Architecture: "}),c(m,{color:W,bold:!0,children:t})]}),s?w(y,{children:[c(m,{color:N,children:"Location: "}),c(m,{color:W,bold:!0,children:s})]}):null,a?c(y,{marginTop:1,children:c(m,{color:q,children:"Git repository initialized"})}):null,w(y,{flexDirection:"column",borderStyle:"round",borderColor:P,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[c(m,{color:N,bold:!0,children:"\u{1F680} NEXT STEPS"}),c(y,{height:1}),c(m,{color:N,children:"1. Move into the project directory:"}),c(m,{color:W,bold:!0,children:` cd ${e}`}),c(y,{height:1}),n?c(y,{children:c(m,{color:q,children:"2. Dependencies already installed"})}):w(D,{children:[c(m,{color:N,children:"2. Install dependencies:"}),c(m,{color:W,bold:!0,children:` ${r} install`})]}),c(y,{height:1}),w(m,{color:N,children:["3."," Start development server:"]}),c(m,{color:W,bold:!0,children:` ${r} run dev`})]}),c(y,{marginTop:1,children:c(m,{color:q,children:"(Press enter to exit)"})})]})}),"DoneStep"),vr=100,ze=u(t=>{const e=We(0);pe((r,a)=>{if(a.upArrow||a.downArrow||a.leftArrow||a.rightArrow||r==="k"||r==="j"||r==="h"||r==="l"){const s=Date.now();if(s-e.current<vr)return;e.current=s}t(r,a)})},"useArrowSelect"),ne=u(({initialSelected:t,onConfirm:e,onChange:r,options:a,prompt:n,minified:s=!1})=>{const o=J(()=>new Set(a.map(k=>k.value)),[a]),i=T(k=>k.filter(x=>o.has(x)),[o]),[l,p]=O(0),[h,d]=O(()=>i(t)),j=We(h);j.current=h;const I=We(r);I.current=r,ae(()=>{const k=i(t);d(k),p(0),I.current?.(k)},[t,i]);const M=T(k=>h.includes(k),[h]),$=T(k=>{const x=a[k];x&&d(z=>{const V=z.includes(x.value)?z.filter(ee=>ee!==x.value):[...z,x.value];return j.current=V,r?.(V),V})},[a,r]),L=T(()=>{e(j.current)},[e]),C=a.length>16,F=C?Math.ceil(a.length/2):a.length;ze((k,x)=>{x.upArrow||k==="k"?p(z=>(z-1+a.length)%a.length):x.downArrow||k==="j"?p(z=>(z+1)%a.length):C&&(x.leftArrow||k==="h")?p(z=>(z-F+a.length)%a.length):C&&(x.rightArrow||k==="l")?p(z=>(z+F)%a.length):x.return?L():(k===" "||k==="x")&&$(l)});const S=h.length,U=u((k,x)=>{const z=M(k.value),V=x===l,ee=z?"\u25CF":"\u25CB";return w(y,{flexDirection:"column",children:[c(m,{children:V?w(D,{children:[c(m,{color:P,children:"> "}),c(m,{color:z?P:q,children:`${ee} `}),c(m,{color:z?P:N,children:k.label})]}):w(D,{children:[c(m,{color:z?P:q,children:` ${ee}`}),c(m,{color:oe,children:` ${k.label}`})]})}),V&&!C?w(m,{color:q,children:[" ",k.description]}):null]},k.value)},"renderOption");let Z;return C||(Z=s?0:1),w(y,{flexDirection:"column",children:[c(m,{color:q,children:n}),c(m,{color:de,children:S===0?"No options selected yet \u2014 pick what you need":`${S} selected`}),c(y,{marginTop:1,flexDirection:C?"row":"column",rowGap:Z,columnGap:C?4:void 0,overflow:"hidden",children:C?w(D,{children:[c(y,{flexDirection:"column",rowGap:s?0:1,flexGrow:1,flexBasis:0,children:a.slice(0,F).map((k,x)=>U(k,x))}),c(y,{flexDirection:"column",rowGap:s?0:1,flexGrow:1,flexBasis:0,children:a.slice(F).map((k,x)=>U(k,x+F))})]}):a.map((k,x)=>U(k,x))})]})},"MultiSelectStep"),vt="my-nest-app",St=64,Sr=/^[a-z][a-z0-9-]*$/u;function ie(t){return t.trim()||vt}u(ie,"resolveProjectName");function De(t){const e=t.trim();return e?e.length>St?`Project name must be at most ${St} characters`:Sr.test(e)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}u(De,"validateProjectName");const kt=u(({error:t,onChange:e,onSubmit:r,value:a})=>(pe((n,s)=>{s.return&&r()}),w(y,{flexDirection:"column",children:[c(m,{color:q,children:"Enter a name for your project"}),w(y,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[c(m,{color:N,children:"Project name:"}),c(er,{placeholder:vt,value:a,onChange:e})]}),t?c(m,{color:P,children:t}):null]})),"ProjectNameStep"),he=tr({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:me.string().pipe(me.coerce.number()).default(95),NEST_ARCH_BETA_MODE:me.enum(["true","false"]).default("false").transform(t=>t==="true"),NEST_ARCH_SCHEMA_URL:me.string().default("./schema.json"),NEST_ARCH_VERSION:me.string().default("0.0.1"),NODE_ENV:me.enum(["development","production","test"]).default("development")}}),Y=u(({onConfirm:t,options:e,prompt:r,initialValue:a})=>{const[n,s]=O(()=>{const i=e.findIndex(l=>l.value===a);return Math.max(i,0)});ae(()=>{const i=e.findIndex(l=>l.value===a);s(Math.max(i,0))},[a,e]);const o=T(()=>{const i=e[n];i&&i.devOnly!==(he.NODE_ENV==="production")&&t(i.value)},[t,e,n]);return ze((i,l)=>{l.upArrow||i==="k"?s(p=>(p-1+e.length)%e.length):l.downArrow||i==="j"?s(p=>(p+1)%e.length):l.return&&o()}),w(y,{flexDirection:"column",children:[c(m,{color:q,children:r}),c(y,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((i,l)=>{const p=l===n;return w(y,{flexDirection:"column",children:[c(m,{children:p?c(D,{children:i.devOnly===(he.NODE_ENV==="production")?w(D,{children:[c(m,{color:oe,children:"> "}),w(m,{color:oe,children:[i.label,". (Comming soon)"]})]}):w(D,{children:[c(m,{color:P,children:"> "}),c(m,{color:P,children:i.label})]})}):c(m,{color:oe,children:` ${i.label}`})}),p?c(m,{color:q,children:i.description}):null]},i.value)})})]})},"SingleSelectStep"),At=[{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"}],Tt=[{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"}],Pt=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],Et=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",devOnly:!0,label:"Monorepo (Turborepo)",value:"monorepo"}],Rt=[{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"}],Xe=[{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:"Better SQLite",value:"sqlite"},{description:"Document database",label:"MongoDB",value:"mongodb"}],Ke=[{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"}],Ze=[{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 (Code first)",value:"graphql"}],et=[{description:"No authentication scaffolding",label:"None",value:"none"},{description:"Flexible authentication \u2014 stateless (OAuth 2 JWE session) when no database, ORM-backed (JWT Authorization Bearer) 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"}],tt=[{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"},{description:"Scaffold a Todo CRUD module example (GraphQL only)",label:"Todo Example",value:"todo-example"}],qt=[{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:"Modern OpenAPI documentation UI",label:"Scalar UI (Recommended)",value:"scalar-ui"}],kr=[{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"}],xt=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],Ar=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],Tr=[{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"}],Pr=[{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"}],Er=[{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"}],Rr=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],qr={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"},xr=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","installing","done"];function Ir(t){return t.includes("mongodb")}u(Ir,"databaseIncludesMongodb");function rt(t){return t.length===0}u(rt,"databaseIsEmpty");function Me(t){return t.includes("rest")||t.includes("trpc")}u(Me,"hasApiLayer");function Ne(t){return rt(t)}u(Ne,"shouldSkipOrmStep");function Pe(t){return xr.filter(e=>!(e==="orm"&&Ne(t.database)||e==="auth"&&!Me(t.api)||e==="microservices"&&t.architecture!=="nest-gateway"||(e==="ultraciteEditors"||e==="ultraciteAgents"||e==="ultraciteHooks"||e==="ultraciteInstallSkill")&&(!t.addons.includes("ultracite")||t.formatter==="none")))}u(Pe,"getVisibleSteps");const It=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function Ee(t){return It.includes(t)}u(Ee,"isUltraciteSubStep");function Or(t,e){if(!Ee(t))return null;const r=It.filter(i=>Pe(e).includes(i)),a=r.indexOf(t);if(a===-1)return null;const n=r.length,s=a+1,o=Math.round(s/n*100);return{current:s,percent:o,total:n}}u(Or,"getUltraciteSubStepInfo");function st(t){return Pe(t).filter(e=>e!=="installing"&&e!=="done"&&!Ee(e)).length}u(st,"getTotalSteps");function Cr(t,e){const r=Pe(e).filter(s=>s!=="installing"&&s!=="done");if(t==="installing"||t==="done")return st(e);if(Ee(t)){const s=r.indexOf("addons");return s===-1?1:s+1}const n=r.filter(s=>!Ee(s)).indexOf(t);return n===-1?1:n+1}u(Cr,"getDisplayStepNumber");function _r(t,e){const r=Pe(e),a=r.indexOf(t);return a===-1||a>=r.length-1?null:r[a+1]??null}u(_r,"getNextStepId");function Gr(t,e){const r=Pe(e),a=r.indexOf(t);return a<=0?null:r[a-1]??null}u(Gr,"getPreviousStepId");function zr(t){return t==="monorepo"?Rt:Rt.filter(e=>e.value!=="nest-gateway")}u(zr,"filterArchitectureOptions");function Ot(t){return Ir(t)?Ke.filter(e=>e.value!=="drizzle"):Ke}u(Ot,"filterOrmOptions");function Dr(t){return t.includes("drizzle")?Xe.filter(e=>e.value!=="mongodb"):Xe}u(Dr,"filterDatabaseOptions");function Mr(t){return rt(t)?et.filter(e=>e.value!=="better-auth"):et}u(Mr,"filterAuthOptions");function Nr(t){return rt(t)?Ze.filter(e=>e.value!=="graphql"):Ze}u(Nr,"filterApiOptions");function Fr(t,e){return e.includes("drizzle")?t.filter(r=>r!=="mongodb"):t}u(Fr,"sanitizeDatabaseForOrm");function Ct(t){return"nest-api"}u(Ct,"defaultArchitecture");function _t(t,e){if(Ne(e))return[];const r=new Set(Ot(e).map(a=>a.value));return t.filter(a=>r.has(a))}u(_t,"sanitizeOrmForDatabase");function ge(t,e){return t.find(r=>r.value===e)?.label??e}u(ge,"labelFor");function fe(t,e){return e.length===0?"None":e.map(r=>ge(t,r)).join(", ")}u(fe,"labelsFor");const Lr=u(({onConfirm:t,state:e})=>{pe((n,s)=>{s.return&&t()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},a=[{label:"Project",value:ie(e.projectName)},{label:"Package manager",value:e.packageManager?ge(At,e.packageManager):"\u2014"},{label:"Formatter",value:e.formatter?ge(Tt,e.formatter):"\u2014"},{label:"HTTP provider",value:e.httpProvider?ge(Pt,e.httpProvider):"\u2014"},{label:"Project type",value:e.projectType?ge(Et,e.projectType):"\u2014"},{label:"Architecture",value:e.architecture?r[e.architecture]??e.architecture:"\u2014"},{label:"Database",value:fe(Xe,e.database)}];return Ne(e.database)||a.push({label:"ORM",value:fe(Ke,e.orm)}),a.push({label:"API layer",value:fe(Ze,e.api)}),e.architecture==="nest-gateway"&&a.push({label:"Microservices",value:fe([{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)}),Me(e.api)&&a.push({label:"Auth",value:e.auth?ge(et,e.auth):"\u2014"}),a.push({label:"Extras",value:fe(tt,e.extras)},{label:"Addons",value:fe(qt,e.addons)},{label:"Git",value:e.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:e.installDependencies==="yes"?"Install":"Skip"}),w(D,{children:[c(y,{flexDirection:"column",marginBottom:1,children:w(m,{children:[c(m,{color:P,children:"\u2726 "}),c(m,{color:W,children:"Review your selections"})]})}),c(y,{flexDirection:"column",rowGap:0,overflow:"hidden",children:a.map(n=>w(y,{flexDirection:"row",columnGap:1,children:[c(m,{color:Zt,children:`${n.label}:`}),c(m,{color:de,children:n.value})]},n.label))})]})},"SummaryStep");function at(t){return t.length===0?"\u2014":t.join(", ")}u(at,"formatList");const $r=u(({state:t,stepId:e})=>{const{stdout:r}=He(),a=r.columns||r.getWindowSize?.()[0]||80,n=Math.min(he.APP_MAX_WIDTH,a-4),s=[];if(e!=="projectName"&&t.projectName.trim()&&s.push(ie(t.projectName)),t.packageManager&&s.push(t.packageManager),t.httpProvider&&s.push(t.httpProvider),t.projectType&&s.push(t.projectType==="monorepo"?"Monorepo":"Single"),t.architecture){const l={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};s.push(l[t.architecture]??t.architecture)}if(t.database.length>0&&s.push(at(t.database)),t.orm.length>0&&s.push(at(t.orm)),t.api.length>0&&s.push(at(t.api)),t.auth&&s.push(t.auth),t.extras.length>0&&s.push(`+${t.extras.length} extras`),t.addons.length>0&&!Ee(e)&&s.push(`+${t.addons.length} addons`),t.initGit&&s.push(t.initGit==="yes"?"git init":"no git"),s.length===0)return w(m,{children:[c(m,{color:P,children:"\u25C6 "}),c(m,{color:P,children:"Create a new NestJS project"})]});const[o,...i]=s;return w(D,{children:[w(m,{children:[c(m,{color:P,children:"\u25C6 "}),c(m,{color:P,children:"Create a new NestJS project"})]}),e!=="summary"&&c(y,{borderStyle:"single",borderColor:ue,width:n,children:w(m,{children:[c(m,{children:"Project Name: "}),c(m,{color:P,children:o}),c(m,{color:q,children:" Selected: "}),i.length>0?c(m,{color:q,children:`${i.filter(l=>l!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),Ur=u(({displayStep:t,stepId:e,subProgress:r,totalSteps:a})=>w(y,{paddingLeft:2,paddingTop:e==="summary"?2:1,marginBottom:1,children:[c(m,{color:N,children:"Create project"}),c(m,{color:q,children:` \u2014 step ${t}/${a}`}),r?c(m,{color:W,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):c(m,{color:W,children:` \xB7 ${qr[e]}`})]}),"WizardTitle$1"),ot=Q(ht(),".nestarch"),nt=Q(ot,"last-used.json");function Br(){try{if(!ke(nt))return null;const t=rr(nt,"utf-8");return JSON.parse(t)}catch{return null}}u(Br,"getLastUsedConfig");function Gt(t){try{ke(ot)||sr(ot,{recursive:!0}),ar(nt,JSON.stringify(t,null,2),"utf-8")}catch{}}u(Gt,"saveLastUsedConfig");function Jr(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,a=r.toLocaleString("en-US",{month:"short"}),n=r.getDate(),s=r.getFullYear(),o=`${a} ${n}, ${s}`;return`${e.join(", ")} (last used ${o})`}u(Jr,"buildLastUsedDescription");const Hr=[{label:"NestJS Best Practices",name:"nestjs-best-practices",repo:"kadajett/agent-nestjs-skills",when:u(()=>!0,"when")},{label:"Prisma CLI",name:"prisma-cli",repo:"prisma/skills",when:u(t=>t.orm.includes("prisma"),"when")},{label:"Prisma Client API",name:"prisma-client-api",repo:"prisma/skills",when:u(t=>t.orm.includes("prisma"),"when")},{label:"Prisma Database Setup",name:"prisma-database-setup",repo:"prisma/skills",when:u(t=>t.orm.includes("prisma"),"when")},{label:"Prisma NestJS Patterns",name:"prisma-nestjs-patterns",repo:"davidcastagnetoa/skills",when:u(t=>t.orm.includes("prisma"),"when")},{label:"NestJS TypeORM Integration",name:"nestjs-typeorm-integration",repo:"vong3432/vibemark",when:u(t=>t.orm.includes("typeorm"),"when")},{label:"Better Auth Best Practices",name:"better-auth-best-practices",repo:"better-auth/skills",when:u(t=>t.auth==="better-auth"||t.auth==="better-auth:stateless","when")},{label:"JWT Security",name:"jwt-security",repo:"mindrally/skills",when:u(t=>t.auth!=="none","when")},{label:"Turborepo",name:"turborepo",repo:"vercel/turborepo",when:u(t=>t.projectType==="monorepo","when")},{label:"Ultracite",name:"ultracite",repo:"haydenbleasel/ultracite",when:u(t=>t.addons.includes("ultracite"),"when")}];function Wr(t){return Hr.filter(e=>e.when(t))}u(Wr,"resolveSkills");const Vr=_e(Ve);function Qr(t){return`npx skills add ${`https://github.com/${t.repo}`} --skill ${t.name}`}u(Qr,"buildCommand");async function Yr(t,e){const r={failed:[],installed:[]};if(!e.addons.includes("agent-skills"))return r;const a=Wr(e);for(const n of a)try{const s=Qr(n);await Vr(s,{cwd:t,maxBuffer:4*1024*1024,timeout:6e4}),r.installed.push(n.name)}catch(s){const o=s instanceof Error?s.message:"Unknown error";r.failed.push({error:o,name:n.name})}return r}u(Yr,"installAgentSkills");class pt{static{u(this,"TemplateEngine")}cache={};cacheEnabled;templatesDir;constructor(e,r={}){this.templatesDir=e,this.cacheEnabled=r.cache??!0,pt.registerHelpers(r.helpers)}static registerHelpers(e){if(H.registerHelper("eq",(r,a)=>r===a),H.registerHelper("ne",(r,a)=>r!==a),H.registerHelper("lt",(r,a)=>r<a),H.registerHelper("gt",(r,a)=>r>a),H.registerHelper("and",(...r)=>(r.pop(),r.every(Boolean))),H.registerHelper("or",(...r)=>(r.pop(),r.some(Boolean))),H.registerHelper("includes",(r,a)=>Array.isArray(r)?r.includes(a):typeof r=="string"?r.includes(String(a)):!1),H.registerHelper("uppercase",r=>r?.toUpperCase?.()),H.registerHelper("lowercase",r=>r?.toLowerCase?.()),H.registerHelper("capitalize",r=>r?r.charAt(0).toUpperCase()+r.slice(1):""),H.registerHelper("camelCase",r=>r?.split("-").map((a,n)=>n===0?a.toLowerCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")),H.registerHelper("pascalCase",r=>r?.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")),H.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),e)for(const[r,a]of Object.entries(e))H.registerHelper(r,a)}async loadTemplate(e){const r=e;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const a=v.join(this.templatesDir,e),n=await K.readFile(a,"utf-8"),s=H.compile(n);return this.cacheEnabled&&(this.cache[r]=s),s}async renderTemplate(e,r){return(await this.loadTemplate(e))(r.context)}async renderToFile(e,r,a){return{content:await this.renderTemplate(e,a),filePath:r,isBinary:!1}}clearCache(){this.cache={}}getCacheStats(){return{enabled:this.cacheEnabled,size:Object.keys(this.cache).length}}}class Xr{static{u(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(e){this.baseDir=e}getBaseDir(){return this.baseDir}async writeFile(e,r={}){const a=v.join(this.baseDir,e.filePath),n=v.dirname(a);try{await K.mkdir(n,{recursive:!0});let s=!1;try{await K.stat(a),s=!0}catch{s=!1}if(s&&!r.overwrite)return{backed:!1,error:"File already exists and overwrite is disabled",filePath:a,written:!1};let o=!1;if(s&&r.createBackups&&!r.dryRun){const i=`${a}.bak`;await K.copyFile(a,i),o=!0}return r.dryRun||(await K.writeFile(a,e.content,"utf-8"),this.writtenFiles.add(a)),{backed:o,filePath:a,written:!r.dryRun}}catch(s){return{backed:!1,error:s instanceof Error?s.message:"Unknown error",filePath:a,written:!1}}}writeFiles(e,r={}){return Promise.all(e.map(a=>this.writeFile(a,r)))}async fileExists(e){const r=v.join(this.baseDir,e);try{return await K.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(e,r){const a=[],n=v.join(this.baseDir,e),s=v.join(this.baseDir,r);await K.mkdir(s,{recursive:!0});const o=await K.readdir(n,{withFileTypes:!0});for(const i of o){const l=v.join(n,i.name),p=v.join(s,i.name);if(i.isDirectory()){const h=await this.copyDirectory(v.relative(this.baseDir,l),v.relative(this.baseDir,p));a.push(...h)}else{const h=await K.readFile(l,"utf-8");await K.writeFile(p,h,"utf-8"),a.push(p),this.writtenFiles.add(p)}}return a}}const Fe=_e(or);async function Kr(t){await Fe("git",["init"],{cwd:t})}u(Kr,"gitInit");async function zt(t){await Fe("git",["add","."],{cwd:t})}u(zt,"gitAddAll");async function Dt(t,e){await Fe("git",["commit","--no-verify","-m",e],{cwd:t})}u(Dt,"gitCommit");async function Zr(t){try{const{stdout:e}=await Fe("git",["diff","--cached","--name-only"],{cwd:t});return e.trim().length>0}catch{return!1}}u(Zr,"gitHasStagedChanges");async function es(t){try{return await nr(Q(t,".git")),!0}catch{return!1}}u(es,"gitDirectoryExists");const Mt=_e(Ve),ts={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
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
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
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 Kr(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(Kr,"getFormatterCommand");function Zr(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="EINVAL")}u(Zr,"isPackageManagerNotFoundError");async function es(t,e){const r=Kr(t);try{return await Yr(r,{cwd:e,timeout:12e4}),{success:!0}}catch(a){return Zr(a)?{error:Xr[t],success:!1}:{success:!0}}}u(es,"runFormatter");const ts=He(ht);function rs(t,e){const r=e.join(" ");switch(t){case"pnpm":return`pnpm dlx ${r}`;case"yarn":return`yarn dlx ${r}`;case"bun":return`bunx ${r}`;default:return`npx --yes ${r}`}}u(rs,"buildUltraciteInitCommand");function ss(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(ss,"mapFormatterToLinter");async function as(t){const e=Q(t,"package.json");try{const a=await Ce(e,"utf-8"),n=JSON.parse(a);n.devDependencies&&(n.devDependencies=Object.fromEntries(Object.entries(n.devDependencies).filter(([s])=>!s.startsWith("stylelint")))),await ke(e,`${JSON.stringify(n,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 a of r){const n=Q(t,a);Se(n)&&await nr(n,{force:!0})}}u(as,"removeStylelint");async function os(t,e){const r=ss(e.formatter);if(r==="none")return{message:"Skipping ultracite init (no formatter selected)",success:!0};const a=[];e.addons.includes("husky")&&a.push("husky");const n=["ultracite","init","--quiet","--skip-install","--pm",e.packageManager,"--linter",r,"--frameworks","nestjs"];a.length>0&&n.push("--integrations",...a),e.addons.includes("ultracite")&&(e.ultraciteEditors.length>0&&n.push("--editors",...e.ultraciteEditors),e.ultraciteAgents.length>0&&n.push("--agents",...e.ultraciteAgents),e.ultraciteHooks.length>0&&n.push("--hooks",...e.ultraciteHooks),e.ultraciteInstallSkill==="yes"&&n.push("--install-skill"));const s=rs(e.packageManager,n);try{return await ts(s,{cwd:t,timeout:12e4}),e.formatter==="eslint-prettier-no-stylelint"&&await as(t),{message:"Ultracite setup completed",success:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(o&&typeof o=="object"&&"stderr"in o){const c=o.stderr?.trim();c&&(i=`${i}
24
- ${c}`)}return{message:`Ultracite setup failed: ${i}`,success:!1}}}u(os,"runUltraciteInit");class ns{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 a=[];try{const n=await K.readdir(e,{withFileTypes:!0});for(const s of n){if(!s.isFile())continue;const{name:o}=s,i=v.extname(o);if(i===".hbs"){const c=v.basename(o,i),p={description:`Template: ${c}`,format:"handlebars",id:c,name:c.replaceAll(/[-_]/gu," "),optional:o.startsWith("_"),path:v.join(v.relative(v.dirname(e),e),o)};a.push(p),this.registerTemplate(p)}}if(r&&a.length>0){const s={description:`Templates from ${e}`,id:r,name:r,templates:a};this.registerGroup(s)}}catch(n){console.error(`Failed to load templates from ${e}:`,n)}return a}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function fo(t,e,r){}u(fo,"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/ban-ts-comment":"off","typescript/consistent-type-imports":"off","typescript/no-extraneous-class":"off","typescript/no-non-null-assertion":"off","typescript/parameter-properties":"off","unicorn/no-static-only-class":"off"}};async function is(t){const e=Q(t,"oxlint.config.ts");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}let a=r;/import vitest from "ultracite\/oxlint\/vitest"/u.test(r)||(a=a.replace(/(import nestjs from "ultracite\/oxlint\/nestjs";)/u,`$1
25
- import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(nt.oxlint).map(([o,i])=>{const c=Array.isArray(i)?JSON.stringify(i):`"${i}"`;return` "${o}": ${c}`}).join(`,
26
- `),s=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);a=a.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(o,i)=>{const c=i.includes("vitest"),p=i.includes("ignorePatterns"),g=i.includes("rules:"),m=i.includes("overrides:");let f=i;return c||(f=f.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(O,x,U,F)=>{const _=U.trimEnd(),N=!_.endsWith(",");return`${x}${_}${N?",":""}
22
+ `)};function rs(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(rs,"getFormatterCommand");function ss(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="EINVAL")}u(ss,"isPackageManagerNotFoundError");async function as(t,e){const r=rs(t);try{return await Mt(r,{cwd:e,timeout:12e4}),await Mt(r,{cwd:e,timeout:12e4}),{success:!0}}catch(a){return ss(a)?{error:ts[t],success:!1}:{success:!0}}}u(as,"runFormatter");const os=_e(Ve);function ns(t,e){const r=e.join(" ");switch(t){case"pnpm":return`pnpm dlx ${r}`;case"yarn":return`yarn dlx ${r}`;case"bun":return`bunx ${r}`;default:return`npx --yes ${r}`}}u(ns,"buildUltraciteInitCommand");function is(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(is,"mapFormatterToLinter");async function cs(t){const e=Q(t,"package.json");try{const a=await Ge(e,"utf-8"),n=JSON.parse(a);n.devDependencies&&(n.devDependencies=Object.fromEntries(Object.entries(n.devDependencies).filter(([s])=>!s.startsWith("stylelint")))),await Ae(e,`${JSON.stringify(n,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 a of r){const n=Q(t,a);ke(n)&&await ir(n,{force:!0})}}u(cs,"removeStylelint");async function ls(t,e){const r=is(e.formatter);if(r==="none")return{message:"Skipping ultracite init (no formatter selected)",success:!0};const a=[];e.addons.includes("husky")&&a.push("husky");const n=["ultracite","init","--quiet","--skip-install","--pm",e.packageManager,"--linter",r,"--frameworks","nestjs"];a.length>0&&n.push("--integrations",...a),e.addons.includes("ultracite")&&(e.ultraciteEditors.length>0&&n.push("--editors",...e.ultraciteEditors),e.ultraciteAgents.length>0&&n.push("--agents",...e.ultraciteAgents),e.ultraciteHooks.length>0&&n.push("--hooks",...e.ultraciteHooks),e.ultraciteInstallSkill==="yes"&&n.push("--install-skill"));const s=ns(e.packageManager,n);try{return await os(s,{cwd:t,timeout:12e4}),e.formatter==="eslint-prettier-no-stylelint"&&await cs(t),{message:"Ultracite setup completed",success:!0}}catch(o){let i=o instanceof Error?o.message:String(o);if(o&&typeof o=="object"&&"stderr"in o){const l=o.stderr?.trim();l&&(i=`${i}
24
+ ${l}`)}return{message:`Ultracite setup failed: ${i}`,success:!1}}}u(ls,"runUltraciteInit");class ps{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 a=[];try{const n=await K.readdir(e,{withFileTypes:!0});for(const s of n){if(!s.isFile())continue;const{name:o}=s,i=v.extname(o);if(i===".hbs"){const l=v.basename(o,i),p={description:`Template: ${l}`,format:"handlebars",id:l,name:l.replaceAll(/[-_]/gu," "),optional:o.startsWith("_"),path:v.join(v.relative(v.dirname(e),e),o)};a.push(p),this.registerTemplate(p)}}if(r&&a.length>0){const s={description:`Templates from ${e}`,id:r,name:r,templates:a};this.registerGroup(s)}}catch(n){console.error(`Failed to load templates from ${e}:`,n)}return a}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function Ro(t,e,r){}u(Ro,"log");const it={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/ban-ts-comment":"off","typescript/consistent-type-imports":"off","typescript/no-extraneous-class":"off","typescript/no-non-null-assertion":"off","typescript/parameter-properties":"off","unicorn/no-static-only-class":"off"}};async function us(t){const e=Q(t,"oxlint.config.ts");let r;try{r=await Ge(e,"utf-8"),`${e}`}catch{return}let a=r;/import vitest from "ultracite\/oxlint\/vitest"/u.test(r)||(a=a.replace(/(import nestjs from "ultracite\/oxlint\/nestjs";)/u,`$1
25
+ import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(it.oxlint).map(([o,i])=>{const l=Array.isArray(i)?JSON.stringify(i):`"${i}"`;return` "${o}": ${l}`}).join(`,
26
+ `),s=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);a=a.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(o,i)=>{const l=i.includes("vitest"),p=i.includes("ignorePatterns"),h=i.includes("rules:"),d=i.includes("overrides:");let j=i;return l||(j=j.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(I,M,$,L)=>{const C=$.trimEnd(),F=!C.endsWith(",");return`${M}${C}${F?",":""}
27
27
  vitest,
28
- ${F.trimStart()}`})),p||(f=f.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
29
- ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**"],`)),m||(f=`${f} overrides: [
28
+ ${L.trimStart()}`})),p||(j=j.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
29
+ ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**"],`)),d||(j=`${j} overrides: [
30
30
  {
31
31
  files: ["**/*.{test,spec}.{ts,tsx,js,jsx}"],
32
32
  plugins: ["vitest"],
@@ -35,64 +35,61 @@ import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(nt.oxlin
35
35
  },
36
36
  },
37
37
  ],
38
- `),g||(f=`${f} rules: {
38
+ `),h||(j=`${j} rules: {
39
39
  ${n},
40
40
  },
41
- `),`export default defineConfig({${f}});`});try{await ke(e,a,"utf-8"),`${e}`}catch{}}u(is,"injectOxlintRules");async function cs(t){const e=Q(t,"biome.jsonc");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}const a=nt.biome,n=r.includes('"linter"'),s=r.includes('"rules"');if(n&&s){const o=Object.entries(a).flatMap(([c,p])=>Object.entries(p).map(([g,m])=>` "${c}": {
42
- "${g}": "${m}"
41
+ `),`export default defineConfig({${j}});`});try{await Ae(e,a,"utf-8"),`${e}`}catch{}}u(us,"injectOxlintRules");async function ds(t){const e=Q(t,"biome.jsonc");let r;try{r=await Ge(e,"utf-8"),`${e}`}catch{return}const a=it.biome,n=r.includes('"linter"'),s=r.includes('"rules"');if(n&&s){const o=Object.entries(a).flatMap(([l,p])=>Object.entries(p).map(([h,d])=>` "${l}": {
42
+ "${h}": "${d}"
43
43
  }`)).join(`,
44
- `),i=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(c,p,g,m)=>{const f=g.trim().endsWith(",")?"":",";return`${p}${g}${f}
44
+ `),i=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(l,p,h,d)=>{const j=h.trim().endsWith(",")?"":",";return`${p}${h}${j}
45
45
  ${o}
46
- ${m}`});try{await ke(e,i,"utf-8"),`${e}`}catch{}}else{const i=` "linter": {
46
+ ${d}`});try{await Ae(e,i,"utf-8"),`${e}`}catch{}}else{const i=` "linter": {
47
47
  "rules": {
48
- ${Object.entries(a).map(([p,g])=>{const m=Object.entries(g).map(([f,O])=>` "${f}": "${O}"`).join(`,
48
+ ${Object.entries(a).map(([p,h])=>{const d=Object.entries(h).map(([j,I])=>` "${j}": "${I}"`).join(`,
49
49
  `);return` "${p}": {
50
- ${m}
50
+ ${d}
51
51
  }`}).join(`,
52
52
  `)}
53
53
  }
54
- }`,c=r.replace(/(\}\s*)$/u,p=>`,
54
+ }`,l=r.replace(/(\}\s*)$/u,p=>`,
55
55
  ${i}
56
- ${p}`);try{await ke(e,c,"utf-8"),`${e}`}catch{}}}u(cs,"injectBiomeRules");async function ls(t){const e=Q(t,"eslint.config.mjs");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}if(r.includes("rules:"))return;const a=Object.entries(nt.eslint).map(([s,o])=>{const i=Array.isArray(o)?JSON.stringify(o):`"${o}"`;return` "${s}": ${i}`}).join(`,
56
+ ${p}`);try{await Ae(e,l,"utf-8"),`${e}`}catch{}}}u(ds,"injectBiomeRules");async function ms(t){const e=Q(t,"eslint.config.mjs");let r;try{r=await Ge(e,"utf-8"),`${e}`}catch{return}if(r.includes("rules:"))return;const a=Object.entries(it.eslint).map(([s,o])=>{const i=Array.isArray(o)?JSON.stringify(o):`"${o}"`;return` "${s}": ${i}`}).join(`,
57
57
  `),n=r.replace(/\];?$/u,` {
58
58
  rules: {
59
59
  ${a},
60
60
  },
61
61
  },
62
- ];`);try{await ke(e,n,"utf-8"),`${e}`}catch{}}u(ls,"injectEslintRules");async function ps(t,e){switch(e){case"oxlint-oxfmt":return await is(t),{success:!0};case"biome":return await cs(t),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await ls(t),{success:!0};default:return{message:"No injection needed",success:!0}}}u(ps,"injectUltraciteRules");function us(t){const e=[`pnpm create nest-arch@latest ${t.projectName}`,`--package-manager ${t.packageManager}`,`--http-provider ${t.httpProvider}`,`--project-type ${t.projectType}`,`--architecture ${t.architecture}`,`--database ${t.database.length>0?t.database.join(" "):"none"}`,`--orm ${t.orm.length>0?t.orm.join(" "):"none"}`,`--api ${t.api.length>0?t.api.join(" "):"none"}`,`--auth ${t.auth}`,`--extras ${t.extras.length>0?t.extras.join(" "):"none"}`,`--microservices ${t.microservices.length>0?t.microservices.join(" "):"none"}`,`--addons ${t.addons.length>0?t.addons.join(" "):"none"}`,`--formatter ${t.formatter}`,`--install-dependencies ${t.installDependencies?"yes":"no"}`,t.initGit?"--git":"--no-git"];return t.addons.includes("ultracite")&&(t.ultraciteEditors.length>0&&e.push(`--ultracite-editors ${t.ultraciteEditors.join(" ")}`),t.ultraciteAgents.length>0&&e.push(`--ultracite-agents ${t.ultraciteAgents.join(" ")}`),t.ultraciteHooks.length>0&&e.push(`--ultracite-hooks ${t.ultraciteHooks.join(" ")}`),e.push(`--ultracite-install-skill ${t.ultraciteInstallSkill}`)),e.join(" ")}u(us,"buildReproducibleCommand");function ds(t){return{$schema:Me.NEST_ARCH_SCHEMA_URL,addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth,createdAt:new Date().toISOString(),database:t.database,description:t.description,extras:t.extras,formatter:t.formatter,httpProvider:t.httpProvider,initGit:t.initGit,installDependencies:t.installDependencies,microservices:t.microservices,orm:t.orm,packageManager:t.packageManager,projectName:t.projectName,projectType:t.projectType,reproducibleCommand:us(t),ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill,version:Me.NEST_ARCH_VERSION}}u(ds,"buildMetadata");function ms(t){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(`
63
- `)+JSON.stringify(t,null,2)}
64
- `}u(ms,"serializeMetadata");function hs(){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","todo-example"]},type:"array"},formatter:{enum:["biome","eslint-prettier-stylelint","eslint-prettier-no-stylelint","oxlint-oxfmt","none"]},httpProvider:{enum:["express","fastify"]},initGit:{type:"boolean"},installDependencies:{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"},ultraciteAgents:{items:{enum:["universal","claude","codex","jules","replit","devin","lovable","zencoder","ona","openclaw","continue","snowflake-cortex","deepagents","qoder","kimi-cli","mcpjam","mux","pi","adal","copilot","cline","amp","aider","firebase-studio","open-hands","gemini","junie","augmentcode","kilo-code","goose","roo-code","warp","droid","opencode","crush","qwen","amazon-q-cli","firebender","cursor-cli","mistral-vibe","vercel"]},type:"array"},ultraciteEditors:{items:{enum:["universal","vscode","cursor","windsurf","antigravity","kiro","trae","void","bob","codebuddy","zed"]},type:"array"},ultraciteHooks:{items:{enum:["cursor","windsurf","codebuddy","claude","copilot"]},type:"array"},ultraciteInstallSkill:{enum:["yes","no"]},version:{type:"string"}},required:["version","createdAt","reproducibleCommand","projectName","packageManager","httpProvider","projectType","architecture","database","orm","api","auth","extras","microservices","addons","initGit","formatter","installDependencies","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"],title:"NestArchMetadata",type:"object"},null,2)}
65
- `}u(hs,"buildSchemaContent");const gs="single-project/architecture/nest-api",fs="single-project/architecture/nest-gateway",ys="single-project/architecture/nest-microservice",bs="monorepo/root",ws="monorepo/apps/api-gateway",js="monorepo/packages",vs="addons/husky",Ss="extras/docker",ks="extras/swagger",As="extras/database",Ts="monorepo/packages/db",Ps="feature/graphql/todo-example",Es="monorepo/feature/graphql/todo-example",Rs="feature/rest/todo-example",qs="monorepo/feature/rest/todo-example",xs=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[gs]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[fs]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[ys]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[bs,ws,js]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[vs]},{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[Ss]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[ks]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[As]},{conditions:{api:["rest"],projectType:"single"},id:"feature-rest",name:"REST API templates (single)",priority:3,templateGroups:["feature/rest"]},{conditions:{api:["rest"],projectType:"monorepo"},id:"monorepo-feature-rest",name:"REST API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/rest"]},{conditions:{api:["trpc"],projectType:"single"},id:"feature-trpc",name:"tRPC API templates (single)",priority:3,templateGroups:["feature/trpc"]},{conditions:{api:["trpc"],projectType:"monorepo"},id:"monorepo-feature-trpc",name:"tRPC API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/trpc"]},{conditions:{api:["graphql"],projectType:"single"},id:"feature-graphql",name:"GraphQL API templates (single)",priority:3,templateGroups:["feature/graphql"]},{conditions:{api:["graphql"],projectType:"monorepo"},id:"monorepo-feature-graphql",name:"GraphQL API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/graphql"]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[Ts]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"single"},id:"extra-todo-example",name:"Todo Example (single, graphql)",priority:5,templateGroups:[Ps]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-todo-example",name:"Todo Example (monorepo, graphql)",priority:5,templateGroups:[Es]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"single"},id:"extra-rest-todo-example",name:"REST Todo Example (single)",priority:5,templateGroups:[Rs]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-rest-todo-example",name:"REST Todo Example (monorepo)",priority:5,templateGroups:[qs]}];function Is(t){t.registerAll(xs)}u(Is,"initializeTemplateMappings");class Ue{static{u(this,"TemplateMapper")}mappings=[];register(e){this.mappings.push(e),this.mappings.sort((r,a)=>(a.priority??0)-(r.priority??0))}registerAll(e){for(const r of e)this.register(r)}resolve(e){const r=[];for(const o of this.mappings)Ue.matches(o.conditions,e)&&r.push(o);const a=[],n={},s=[];for(const o of r){for(const i of o.templateGroups)a.includes(i)||a.push(i);Object.assign(n,o.extraVariables),s.push(o.id)}return{extraVariables:n,matchedMappings:s,templateGroups:a}}findFirst(e){return this.mappings.find(r=>Ue.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(a=>r.database.includes(a))||e.orm!==void 0&&!e.orm.some(a=>r.orm.includes(a))||e.api!==void 0&&!e.api.some(a=>r.api.includes(a))||e.extras!==void 0&&!e.extras.some(a=>r.extras.includes(a))||e.addons!==void 0&&!e.addons.some(a=>r.addons.includes(a))||e.microservices!==void 0&&!e.microservices.some(a=>r.microservices.includes(a)))}}function Cs(t){return t.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}u(Cs,"toKebabCase");function Os(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toLowerCase())}u(Os,"toCamelCase");function _s(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toUpperCase())}u(_s,"toPascalCase");function zs(t){const e=t.database.includes("postgresql"),r=t.database.includes("mysql"),a=t.database.includes("sqlite"),n=t.database.includes("mongodb"),s=t.orm.includes("prisma"),o=t.orm.includes("typeorm"),i=t.orm.includes("drizzle"),c=t.database.length>0&&!s&&!o&&!i;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],graphqlPlayground:t.api.includes("graphql"),hasAuth:t.auth!=="none",hasBetterAuthWithoutRest:(t.auth==="better-auth"||t.auth==="better-auth:stateless")&&!t.api.includes("rest"),hasDatabase:t.database.length>0,hasGraphql:t.api.includes("graphql"),hasMongodb:n,hasMysql:r,hasOrm:t.orm.length>0,hasPostgres:e,hasRest:t.api.includes("rest"),hasSqlite:a,hasTodoExample:t.extras.includes("todo-example"),hasTrpc:t.api.includes("trpc"),hasTrpcAndAuth:t.api.includes("trpc")&&t.auth!=="none",httpProvider:t.httpProvider,initGit:t.initGit,isBetterAuth:t.auth==="better-auth"||t.auth==="better-auth:stateless",isBun:t.packageManager==="bun",isMonorepo:t.projectType==="monorepo",isNpm:t.packageManager==="npm",isPassportAuth:t.auth==="passport",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:Os(t.projectName),projectNameKebab:Cs(t.projectName),projectNamePascalCase:_s(t.projectName),projectType:t.projectType,shouldImportAuthModule:t.auth!=="none"&&(t.api.includes("rest")||t.api.includes("graphql")),supportsCatalog:["pnpm","yarn","bun"].includes(t.packageManager),swagger:t.extras.includes("swagger"),trpcGeneratePath:t.projectType==="monorepo"?"../../packages/shared/src/trpc/@generated":"src/libs/trpc/@generated",useDrizzle:i,usePrisma:s,useRawSql:c,useSwaggerScalar:t.extras.includes("swagger")&&t.addons.includes("scalar-ui"),useTypeorm:o,year:new Date().getFullYear()}}u(zs,"buildTemplateVariables");function Gs(t,e){return{...t,...e}}u(Gs,"mergeTemplateExtras");class Ds{static{u(this,"BetterAuthGenerator")}project;config;constructor(e,r){this.project=e,this.config=r}generate(e){const r=this.config.orm??[],a=this.config.database??[],n=a.length>0,s=this.config.skipModule??!1;if(!n){this.generateStateless(e,s);return}const o=r.includes("prisma"),i=r.includes("drizzle"),c=r.includes("typeorm");o?(this.generatePrisma(e,a),s||this.generateModule(e,"prisma")):i?(this.generateDrizzle(e,a),s||this.generateModule(e,"drizzle")):c?(this.generateNative(e,a),s||this.generateTypeormModule(e,a)):(this.generateNative(e,a),s||this.generateModule(e,"raw.sql"))}generateAuthOnly(e){const r=this.config.database??[];if(!(r.length>0)){this.generateStateless(e,!0);return}const n=this.config.orm??[],s=n.includes("prisma"),o=n.includes("drizzle"),i=n.includes("typeorm");s?this.generatePrisma(e,r):o?this.generateDrizzle(e,r):i?this.generateNative(e,r):this.generateNative(e,r)}generatePrisma(e,r){const a=r.includes("postgresql"),n=r.includes("mysql");let s;a?s="postgresql":n?s="mysql":s="sqlite";let o,i,c;a?(o="PrismaPg",i="@prisma/adapter-pg",c="new PrismaPg({ connectionString: '' })"):n?(o="PrismaMySql",i="@prisma/adapter-mysql2",c="new PrismaMySql({ uri: '' })"):(o="PrismaBetterSqlite3",i="@prisma/adapter-better-sqlite3",c="new PrismaBetterSqlite3({ url: ':memory:' })");const p=this.config.extras?.includes("swagger"),g=[`import { ${o} } from "${i}";`,'import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";','import { PrismaClient } from "../database/orm/prisma/generated/client.js";',...p?['import { openAPI } from "better-auth/plugins";']:[],"","export function createAuth(prisma: PrismaClient) {"," return betterAuth({",` database: prismaAdapter(prisma, { provider: "${s}" }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...p?[" plugins: [openAPI()],"]:[]," });","}","","// 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 = ${c};`," 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"],m=v.join(e,"auth.ts");this.project.createSourceFile(m,g.join(`
66
- `),{overwrite:!0})}generateDrizzle(e,r){const a=r.includes("postgresql"),n=r.includes("mysql"),s=r.includes("sqlite");let o,i,c,p,g,m;a?(o='import { drizzle } from "drizzle-orm/node-postgres";',i='import { Pool } from "pg";',c="NodePgDatabase",p="pg",g='new Pool({ connectionString: "" })',m="drizzle({ client: pool, schema })"):n?(o='import { drizzle } from "drizzle-orm/mysql2";',i='import mysql from "mysql2/promise";',c="MySql2Database",p="mysql",g='mysql.createPool({ uri: "" })',m="drizzle({ client: pool, schema })"):(o='import { drizzle } from "drizzle-orm/better-sqlite3";',i='import Database from "better-sqlite3";',c="BetterSqlite3Database",p="sqlite",g='new Database(":memory:")',m="drizzle({ client: sqliteDb, schema })");const f=this.config.extras?.includes("swagger"),O=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',o,i,'import * as schema from "../database/orm/drizzle/schema.js";',...f?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(db: ${c}<typeof schema>) {`," return betterAuth({",` database: drizzleAdapter(db, { provider: "${p}", usePlural: true }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...f?[" plugins: [openAPI()],"]:[]," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",s?` const sqliteDb = ${g};`:` const pool = ${g};`,...s?[` 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"],x=v.join(e,"auth.ts");this.project.createSourceFile(x,O.join(`
62
+ ];`);try{await Ae(e,n,"utf-8"),`${e}`}catch{}}u(ms,"injectEslintRules");async function hs(t,e){switch(e){case"oxlint-oxfmt":return await us(t),{success:!0};case"biome":return await ds(t),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await ms(t),{success:!0};default:return{message:"No injection needed",success:!0}}}u(hs,"injectUltraciteRules");const gs="single-project/architecture/nest-api",fs="single-project/architecture/nest-gateway",bs="single-project/architecture/nest-microservice",ys="monorepo/root",ws="monorepo/apps/api-gateway",js="monorepo/packages",vs="addons/husky",Ss="extras/docker",ks="extras/swagger",As="extras/database",Ts="monorepo/packages/db",Ps="feature/graphql/todo-example",Es="monorepo/feature/graphql/todo-example",Nt="feature/rest/todo-example",Ft="monorepo/feature/rest/todo-example",Rs=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[gs]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[fs]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[bs]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[ys,ws,js]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[vs]},{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[Ss]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[ks]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[As]},{conditions:{api:["rest"],projectType:"single"},id:"feature-rest",name:"REST API templates (single)",priority:3,templateGroups:["feature/rest"]},{conditions:{api:["rest"],projectType:"monorepo"},id:"monorepo-feature-rest",name:"REST API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/rest"]},{conditions:{api:["trpc"],projectType:"single"},id:"feature-trpc",name:"tRPC API templates (single)",priority:3,templateGroups:["feature/trpc"]},{conditions:{api:["trpc"],projectType:"monorepo"},id:"monorepo-feature-trpc",name:"tRPC API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/trpc"]},{conditions:{api:["graphql"],projectType:"single"},id:"feature-graphql",name:"GraphQL API templates (single)",priority:3,templateGroups:["feature/graphql"]},{conditions:{api:["graphql"],projectType:"monorepo"},id:"monorepo-feature-graphql",name:"GraphQL API templates (monorepo)",priority:3,templateGroups:["monorepo/feature/graphql"]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[Ts]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"single"},id:"extra-todo-example",name:"Todo Example (single, graphql)",priority:5,templateGroups:[Ps]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-todo-example",name:"Todo Example (monorepo, graphql)",priority:5,templateGroups:[Es]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"single"},id:"extra-rest-todo-example",name:"REST Todo Example (single)",priority:5,templateGroups:[Nt]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-rest-todo-example",name:"REST Todo Example (monorepo)",priority:5,templateGroups:[Ft]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"single"},id:"extra-trpc-todo-example",name:"tRPC Todo Example (single)",priority:5,templateGroups:[Nt]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-trpc-todo-example",name:"tRPC Todo Example (monorepo)",priority:5,templateGroups:[Ft]}];function qs(t){t.registerAll(Rs)}u(qs,"initializeTemplateMappings");class Ue{static{u(this,"TemplateMapper")}mappings=[];register(e){this.mappings.push(e),this.mappings.sort((r,a)=>(a.priority??0)-(r.priority??0))}registerAll(e){for(const r of e)this.register(r)}resolve(e){const r=[];for(const o of this.mappings)Ue.matches(o.conditions,e)&&r.push(o);const a=[],n={},s=[];for(const o of r){for(const i of o.templateGroups)a.includes(i)||a.push(i);Object.assign(n,o.extraVariables),s.push(o.id)}return{extraVariables:n,matchedMappings:s,templateGroups:a}}findFirst(e){return this.mappings.find(r=>Ue.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(a=>r.database.includes(a))||e.orm!==void 0&&!e.orm.some(a=>r.orm.includes(a))||e.api!==void 0&&!e.api.some(a=>r.api.includes(a))||e.extras!==void 0&&!e.extras.some(a=>r.extras.includes(a))||e.addons!==void 0&&!e.addons.some(a=>r.addons.includes(a))||e.microservices!==void 0&&!e.microservices.some(a=>r.microservices.includes(a)))}}function xs(t){return t.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}u(xs,"toKebabCase");function Is(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toLowerCase())}u(Is,"toCamelCase");function Os(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toUpperCase())}u(Os,"toPascalCase");function Cs(t){const e=t.database.includes("postgresql"),r=t.database.includes("mysql"),a=t.database.includes("sqlite"),n=t.database.includes("mongodb"),s=t.orm.includes("prisma"),o=t.orm.includes("typeorm"),i=t.orm.includes("drizzle"),l=t.database.length>0&&!s&&!o&&!i;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],graphqlPlayground:t.api.includes("graphql"),hasAuth:t.auth!=="none",hasBetterAuthWithoutRest:(t.auth==="better-auth"||t.auth==="better-auth:stateless")&&!t.api.includes("rest"),hasDatabase:t.database.length>0,hasGraphql:t.api.includes("graphql"),hasMongodb:n,hasMysql:r,hasOrm:t.orm.length>0,hasPostgres:e,hasRest:t.api.includes("rest"),hasSqlite:a,hasTodoExample:t.extras.includes("todo-example"),hasTrpc:t.api.includes("trpc"),hasTrpcAndAuth:t.api.includes("trpc")&&t.auth!=="none",httpProvider:t.httpProvider,initGit:t.initGit,isBetterAuth:t.auth==="better-auth"||t.auth==="better-auth:stateless",isBun:t.packageManager==="bun",isMonorepo:t.projectType==="monorepo",isNpm:t.packageManager==="npm",isPassportAuth:t.auth==="passport",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:Is(t.projectName),projectNameKebab:xs(t.projectName),projectNamePascalCase:Os(t.projectName),projectType:t.projectType,shouldImportAuthModule:t.auth!=="none"&&(t.api.includes("rest")||t.api.includes("graphql")),supportsCatalog:["pnpm","yarn","bun"].includes(t.packageManager),swagger:t.extras.includes("swagger"),trpcGeneratePath:t.projectType==="monorepo"?"../../packages/shared/src/trpc/@generated":"src/libs/trpc/@generated",useDrizzle:i,usePrisma:s,useRawSql:l,useSwaggerScalar:t.extras.includes("swagger")&&t.addons.includes("scalar-ui"),useTypeorm:o,year:new Date().getFullYear()}}u(Cs,"buildTemplateVariables");function _s(t,e){return{...t,...e}}u(_s,"mergeTemplateExtras");class Gs{static{u(this,"BetterAuthGenerator")}project;config;constructor(e,r){this.project=e,this.config=r}generate(e){const r=this.config.orm??[],a=this.config.database??[],n=a.length>0,s=this.config.skipModule??!1;if(!n){this.generateStateless(e,s);return}const o=r.includes("prisma"),i=r.includes("drizzle"),l=r.includes("typeorm");o?(this.generatePrisma(e,a),s||this.generateModule(e,"prisma")):i?(this.generateDrizzle(e,a),s||this.generateModule(e,"drizzle")):l?(this.generateNative(e,a),s||this.generateTypeormModule(e,a)):(this.generateNative(e,a),s||this.generateModule(e,"raw.sql"))}generateAuthOnly(e){const r=this.config.database??[];if(!(r.length>0)){this.generateStateless(e,!0);return}const n=this.config.orm??[],s=n.includes("prisma"),o=n.includes("drizzle"),i=n.includes("typeorm");s?this.generatePrisma(e,r):o?this.generateDrizzle(e,r):i?this.generateNative(e,r):this.generateNative(e,r)}generatePrisma(e,r){const a=r.includes("postgresql"),n=r.includes("mysql");let s;a?s="postgresql":n?s="mysql":s="sqlite";let o,i,l;a?(o="PrismaPg",i="@prisma/adapter-pg",l="new PrismaPg({ connectionString: '' })"):n?(o="PrismaMariaDb",i="@prisma/adapter-mariadb",l="new PrismaMariaDb('')"):(o="PrismaBetterSqlite3",i="@prisma/adapter-better-sqlite3",l="new PrismaBetterSqlite3({ url: ':memory:' })");const p=this.config.extras?.includes("swagger"),h=[`import { ${o} } from "${i}";`,'import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";','import { PrismaClient } from "../database/orm/prisma/generated/client.js";',...p?['import { openAPI } from "better-auth/plugins";']:[],"","export function createAuth(prisma: PrismaClient) {"," return betterAuth({",` database: prismaAdapter(prisma, { provider: "${s}" }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...p?[" plugins: [openAPI()],"]:[]," });","}","","// 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"],d=v.join(e,"auth.ts");this.project.createSourceFile(d,h.join(`
63
+ `),{overwrite:!0})}generateDrizzle(e,r){const a=r.includes("postgresql"),n=r.includes("mysql"),s=r.includes("sqlite");let o,i,l,p,h,d;a?(o='import { drizzle } from "drizzle-orm/node-postgres";',i='import { Pool } from "pg";',l="NodePgDatabase",p="pg",h='new Pool({ connectionString: "" })',d="drizzle({ client: pool, schema })"):n?(o='import { drizzle } from "drizzle-orm/mysql2";',i='import mysql from "mysql2/promise";',l="MySql2Database",p="mysql",h='mysql.createPool({ uri: "" })',d="drizzle({ client: pool, schema })"):(o='import { drizzle } from "drizzle-orm/better-sqlite3";',i='import Database from "better-sqlite3";',l="BetterSqlite3Database",p="sqlite",h='new Database(":memory:")',d="drizzle({ client: sqliteDb, schema })");const j=this.config.extras?.includes("swagger"),I=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',o,i,'import * as schema from "../database/orm/drizzle/schema.js";',...j?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(db: ${l}<typeof schema>) {`," return betterAuth({",` database: drizzleAdapter(db, { provider: "${p}", usePlural: true }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...j?[" plugins: [openAPI()],"]:[]," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",s?` const sqliteDb = ${h};`:` const pool = ${h};`,...s?[` const db = ${d};`]:[` const db = ${d};`]," 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"],M=v.join(e,"auth.ts");this.project.createSourceFile(M,I.join(`
67
64
  `),{overwrite:!0})}generateNative(e,r){const a=r.includes("postgresql"),n=r.includes("mysql");let s,o,i;a?(s=`import { Pool } from "pg";
68
65
  `,o="Pool",i='new Pool({ connectionString: "" })'):n?(s=`import { createPool } from "mysql2";
69
66
  `,o="ReturnType<typeof createPool>",i='createPool({ uri: "" })'):(s=`import Database from "better-sqlite3";
70
- `,o="Database.Database",i='new Database(":memory:")');const c=this.config.extras?.includes("swagger"),p=['import { betterAuth } from "better-auth";',s.trim(),...c?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(pool: ${o}) {`," return betterAuth({"," database: pool,"," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...c?[" plugins: [openAPI()],"]:[]," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",` const pool = ${i};`," 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"],g=v.join(e,"auth.ts");this.project.createSourceFile(g,p.join(`
67
+ `,o="Database.Database",i='new Database(":memory:")');const l=this.config.extras?.includes("swagger"),p=['import { betterAuth } from "better-auth";',s.trim(),...l?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(pool: ${o}) {`," return betterAuth({"," database: pool,"," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...l?[" plugins: [openAPI()],"]:[]," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",` const pool = ${i};`," 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"],h=v.join(e,"auth.ts");this.project.createSourceFile(h,p.join(`
71
68
  `),{overwrite:!0})}generateStateless(e,r=!1){const a=this.config.extras?.includes("swagger"),n=['import { betterAuth } from "better-auth";',...a?['import { openAPI } from "better-auth/plugins";']:[],"","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 },",...a?[" plugins: [openAPI()],"]:[],"});",""].join(`
72
69
  `),s=v.join(e,"auth.ts");this.project.createSourceFile(s,n,{overwrite:!0}),r||this.generateStatelessModule(e)}generateModule(e,r){const a=['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 {}",""],n=v.join(e,"auth.module.ts");this.project.createSourceFile(n,a.join(`
73
- `),{overwrite:!0})}generateTypeormModule(e,r){const a=r.includes("postgresql"),n=r.includes("mysql");let s,o;a?(s='import { Pool } from "pg";',o="new Pool({ connectionString: process.env.POSTGRES_URL! })"):n?(s='import { createPool } from "mysql2";',o="createPool({ uri: process.env.MYSQL_URL! })"):(s='import Database from "better-sqlite3";',o='new Database(process.env.SQLITE_PATH ?? ":memory:")');const i=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',s,'import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," useFactory: () => ({",` auth: createAuth(${o}),`," }),"," }),"," ],","})","export class AuthModule {}",""],c=v.join(e,"auth.module.ts");this.project.createSourceFile(c,i.join(`
70
+ `),{overwrite:!0})}generateTypeormModule(e,r){const a=r.includes("postgresql"),n=r.includes("mysql");let s,o;a?(s='import { Pool } from "pg";',o="new Pool({ connectionString: process.env.POSTGRES_URL! })"):n?(s='import { createPool } from "mysql2";',o="createPool({ uri: process.env.MYSQL_URL! })"):(s='import Database from "better-sqlite3";',o='new Database(process.env.SQLITE_PATH ?? ":memory:")');const i=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',s,'import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," useFactory: () => ({",` auth: createAuth(${o}),`," }),"," }),"," ],","})","export class AuthModule {}",""],l=v.join(e,"auth.module.ts");this.project.createSourceFile(l,i.join(`
74
71
  `),{overwrite:!0})}generateStatelessModule(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 {}",""],a=v.join(e,"auth.module.ts");this.project.createSourceFile(a,r.join(`
75
- `),{overwrite:!0})}}class Ms{static{u(this,"PassportAuthGenerator")}project;config;constructor(e,r){this.project=e,this.config=r}generate(e){(this.config.database?.length??0)>0?this.generateDbAuth(e):this.generateStatelessAuth(e)}generateStatelessAuth(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(`
72
+ `),{overwrite:!0})}}class zs{static{u(this,"PassportAuthGenerator")}project;config;constructor(e,r){this.project=e,this.config=r}generate(e){(this.config.database?.length??0)>0?this.generateDbAuth(e):this.generateStatelessAuth(e)}generateStatelessAuth(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(`
76
73
  `),a=v.join(e,"strategies/jwt.strategy.ts");this.project.createSourceFile(a,r,{overwrite:!0});const n=v.join(e,"auth.service.ts"),s=this.project.createSourceFile(n,"",{overwrite:!0});s.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),s.addImportDeclaration({moduleSpecifier:"@nestjs/jwt",namedImports:["JwtService"]}),s.addClass({ctors:[{parameters:[{decorators:[{name:"Inject"}],isReadonly:!0,name:"jwtService",scope:cr.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 o=["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
- `),i=v.join(e,"auth.controller.ts");this.project.createSourceFile(i,o,{overwrite:!0}),this.generateDecorators(e),this.generateGuard(e);const c=['import { Module } from "@nestjs/common";','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 { RestAuthGuard } from "./guards/rest-auth.guard.js";','import { RestOptionalAuthGuard } from "./guards/rest-optional-auth.guard.js";','import { RestRolesGuard } from "./guards/rest-roles.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,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],"," exports: ["," AuthService,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],","})","export class AuthModule {}",""].join(`
78
- `),p=v.join(e,"auth.module.ts");this.project.createSourceFile(p,c,{overwrite:!0})}generateDbAuth(e){const r=this.config.orm??[],a=r.includes("prisma"),n=r.includes("typeorm"),s=r.includes("drizzle"),o=(this.config.api??[]).includes("graphql"),i=(this.config.extras??[]).includes("swagger");this.generatePasswordService(e),this.generateDbAuthService(e,{useDrizzle:s,usePrisma:a,useTypeorm:n}),this.generateLoginSchema(e),this.generateSignupSchema(e),this.generateRefreshTokenSchema(e),this.generateJwtDto(e),o&&(this.generateLoginInput(e),this.generateSignupInput(e),this.generateRefreshTokenInput(e)),this.generateDbJwtStrategy(e),this.generateDbRestGuard(e),o&&this.generateDbGqlGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e),o&&(this.generateGqlOptionalAuthGuard(e),this.generateGqlRolesGuard(e)),this.generateDbController(e,i),o&&(this.generateTokenModel(e),this.generateAuthModel(e),this.generateAuthResolver(e)),this.generateDecorators(e),this.generateDbModule(e,{hasGraphql:o,useTypeorm:n})}generatePasswordService(e){const r=['import { Injectable } from "@nestjs/common";','import { hash, compare } from "bcrypt";',"","@Injectable()","export class PasswordService {"," private readonly saltRounds = 10;",""," validatePassword(password: string, hashedPassword: string): Promise<boolean> {"," return compare(password, hashedPassword);"," }",""," hashPassword(password: string): Promise<string> {"," return hash(password, this.saltRounds);"," }","}",""].join(`
79
- `);this.project.createSourceFile(v.join(e,"password.service.ts"),r,{overwrite:!0})}generateDbAuthService(e,r){const{usePrisma:a,useTypeorm:n}=r,s=["import {"," ConflictException,"," Injectable,"," NotFoundException,"," UnauthorizedException,",'} from "@nestjs/common";','import { JwtService } from "@nestjs/jwt";','import { env } from "../config/env.js";','import { PasswordService } from "./password.service.js";'];let o,i,c,p,g;a?(o='import { DbService } from "../database/db.service.js";',i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
80
- `),c=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const user = await this.db.prisma.user.create({"," data: {"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," },"," });"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
74
+ `),i=v.join(e,"auth.controller.ts");this.project.createSourceFile(i,o,{overwrite:!0}),this.generateDecorators(e),this.generateGuard(e);const l=['import { Module } from "@nestjs/common";','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 { RestAuthGuard } from "./guards/rest-auth.guard.js";','import { RestOptionalAuthGuard } from "./guards/rest-optional-auth.guard.js";','import { RestRolesGuard } from "./guards/rest-roles.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,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],"," exports: ["," AuthService,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],","})","export class AuthModule {}",""].join(`
75
+ `),p=v.join(e,"auth.module.ts");this.project.createSourceFile(p,l,{overwrite:!0})}generateDbAuth(e){const r=this.config.orm??[],a=r.includes("prisma"),n=r.includes("typeorm"),s=r.includes("drizzle"),o=(this.config.api??[]).includes("graphql"),i=(this.config.extras??[]).includes("swagger");this.generatePasswordService(e),this.generateDbAuthService(e,{useDrizzle:s,usePrisma:a,useTypeorm:n}),this.generateLoginSchema(e),this.generateSignupSchema(e),this.generateRefreshTokenSchema(e),this.generateJwtDto(e),o&&(this.generateLoginInput(e),this.generateSignupInput(e),this.generateRefreshTokenInput(e)),this.generateDbJwtStrategy(e),this.generateDbRestGuard(e),o&&this.generateDbGqlGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e),o&&(this.generateGqlOptionalAuthGuard(e),this.generateGqlRolesGuard(e)),this.generateDbController(e,i),o&&(this.generateTokenModel(e),this.generateAuthModel(e),this.generateAuthResolver(e)),this.generateDecorators(e),this.generateDbModule(e,{hasGraphql:o,useTypeorm:n})}generatePasswordService(e){const r=['import { Injectable } from "@nestjs/common";','import { hash, compare } from "bcrypt";',"","@Injectable()","export class PasswordService {"," private readonly saltRounds = 10;",""," validatePassword(password: string, hashedPassword: string): Promise<boolean> {"," return compare(password, hashedPassword);"," }",""," hashPassword(password: string): Promise<string> {"," return hash(password, this.saltRounds);"," }","}",""].join(`
76
+ `);this.project.createSourceFile(v.join(e,"password.service.ts"),r,{overwrite:!0})}generateDbAuthService(e,r){const{usePrisma:a,useTypeorm:n}=r,s=["import {"," ConflictException,"," Injectable,"," NotFoundException,"," UnauthorizedException,",'} from "@nestjs/common";','import { JwtService } from "@nestjs/jwt";','import { env } from "../config/env.js";','import { PasswordService } from "./password.service.js";'];let o,i,l,p,h;a?(o='import { DbService } from "../database/db.service.js";',i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
77
+ `),l=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const user = await this.db.prisma.user.create({"," data: {"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," },"," });"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
81
78
  `),p=["const user = await this.db.prisma.user.findUnique({"," where: { email },","});"].join(`
82
- `),g=["return this.db.prisma.user.findUnique({ where: { id: userId } });"].join(`
79
+ `),h=["return this.db.prisma.user.findUnique({ where: { id: userId } });"].join(`
83
80
  `)):n?(o=['import { InjectRepository } from "@nestjs/typeorm";','import { Repository } from "typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";'].join(`
84
81
  `),i=[" @InjectRepository(UserEntity)"," private readonly userRepository: Repository<UserEntity>,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
85
- `),c=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const user = this.userRepository.create({"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER" as never,'," });"," await this.userRepository.save(user);"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
82
+ `),l=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const user = this.userRepository.create({"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER" as never,'," });"," await this.userRepository.save(user);"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
86
83
  `),p=["const user = await this.userRepository.findOne({"," where: { email },","});"].join(`
87
- `),g=["return this.userRepository.findOne({ where: { id: userId } });"].join(`
84
+ `),h=["return this.userRepository.findOne({ where: { id: userId } });"].join(`
88
85
  `)):(o=['import { DbService } from "../database/db.service.js";','import { users } from "../database/orm/drizzle/schema.js";','import { eq } from "drizzle-orm";'].join(`
89
86
  `),i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
90
- `),c=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const [user] = await this.db.sql.getClient()"," .insert(users)"," .values({"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," })"," .returning();"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
87
+ `),l=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const [user] = await this.db.sql.getClient()"," .insert(users)"," .values({"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," })"," .returning();"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
91
88
  `),p=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.email, email))"," .limit(1);"].join(`
92
- `),g=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.id, userId))"," .limit(1);","return user ?? null;"].join(`
93
- `));const m=[s.join(`
94
- `),"",o,"",'import type { SignupInput } from "./dto/signup.input.js";',"","interface TokenPayload {"," accessToken: string;"," refreshToken: string;","}","","@Injectable()","export class AuthService {"," constructor(",i," ) {}",""," async createUser(payload: SignupInput): Promise<TokenPayload> {",c," }",""," async login("," email: string,"," password: string"," ): Promise<TokenPayload> {",p," if (!user) {",' throw new NotFoundException("No user found for email: " + email);'," }"," const passwordValid = await this.passwordService.validatePassword("," password,"," user.password"," );"," if (!passwordValid) {",' throw new UnauthorizedException("Invalid password");'," }"," return this.generateTokens({ userId: user.id });"," }",""," validateUser(userId: string) {",` ${g}`," }",""," getUserFromToken(token: string) {"," try {"," const payload = this.jwtService.decode<{ userId: string }>(token);"," if (!payload?.userId) return null;"," return this.validateUser(payload.userId);"," } catch {"," return null;"," }"," }",""," generateTokens(payload: {"," userId: string;"," }): TokenPayload {"," return {"," accessToken: this.generateAccessToken(payload),"," refreshToken: this.generateRefreshToken(payload),"," };"," }",""," private generateAccessToken(payload: {"," userId: string;"," }): string {"," return this.jwtService.sign(payload);"," }",""," private generateRefreshToken(payload: {"," userId: string;"," }): string {"," return this.jwtService.sign(payload, {",' expiresIn: "7d",'," secret: env.JWT_REFRESH_SECRET,"," });"," }",""," refreshToken(token: string) {"," try {"," const { userId } = this.jwtService.verify<{ userId: string }>("," token,"," { secret: env.JWT_REFRESH_SECRET }"," );"," return this.generateTokens({ userId });"," } catch {"," throw new UnauthorizedException();"," }"," }","}",""].join(`
95
- `);this.project.createSourceFile(v.join(e,"auth.service.ts"),m,{overwrite:!0})}generateLoginSchema(e){const r=['import { z } from "zod";',"","export const loginSchema = z.object({"," email: z.email(),"," password: z.string().min(8),","});",""].join(`
89
+ `),h=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.id, userId))"," .limit(1);","return user ?? null;"].join(`
90
+ `));const d=[s.join(`
91
+ `),"",o,"",'import type { SignupInput } from "./dto/signup.input.js";',"","interface TokenPayload {"," accessToken: string;"," refreshToken: string;","}","","@Injectable()","export class AuthService {"," constructor(",i," ) {}",""," async createUser(payload: SignupInput): Promise<TokenPayload> {",l," }",""," async login("," email: string,"," password: string"," ): Promise<TokenPayload> {",p," if (!user) {",' throw new NotFoundException("No user found for email: " + email);'," }"," const passwordValid = await this.passwordService.validatePassword("," password,"," user.password"," );"," if (!passwordValid) {",' throw new UnauthorizedException("Invalid password");'," }"," return this.generateTokens({ userId: user.id });"," }",""," validateUser(userId: string) {",` ${h}`," }",""," getUserFromToken(token: string) {"," try {"," const payload = this.jwtService.decode<{ userId: string }>(token);"," if (!payload?.userId) return null;"," return this.validateUser(payload.userId);"," } catch {"," return null;"," }"," }",""," generateTokens(payload: {"," userId: string;"," }): TokenPayload {"," return {"," accessToken: this.generateAccessToken(payload),"," refreshToken: this.generateRefreshToken(payload),"," };"," }",""," private generateAccessToken(payload: {"," userId: string;"," }): string {"," return this.jwtService.sign(payload);"," }",""," private generateRefreshToken(payload: {"," userId: string;"," }): string {"," return this.jwtService.sign(payload, {",' expiresIn: "7d",'," secret: env.JWT_REFRESH_SECRET,"," });"," }",""," refreshToken(token: string) {"," try {"," const { userId } = this.jwtService.verify<{ userId: string }>("," token,"," { secret: env.JWT_REFRESH_SECRET }"," );"," return this.generateTokens({ userId });"," } catch {"," throw new UnauthorizedException();"," }"," }","}",""].join(`
92
+ `);this.project.createSourceFile(v.join(e,"auth.service.ts"),d,{overwrite:!0})}generateLoginSchema(e){const r=['import { z } from "zod";',"","export const loginSchema = z.object({"," email: z.email(),"," password: z.string().min(8),","});",""].join(`
96
93
  `);this.project.createSourceFile(v.join(e,"schemas/login.schema.ts"),r,{overwrite:!0})}generateSignupSchema(e){const r=['import { z } from "zod";',"","export const signupSchema = z.object({"," email: z.email(),"," firstname: z.string().optional(),"," lastname: z.string().optional(),"," password: z"," .string()",' .min(8, "Password must be at least 8 characters")',' .regex(/[A-Z]/u, "Password must contain an uppercase letter")',' .regex(/[a-z]/u, "Password must contain a lowercase letter")',' .regex(/[0-9]/u, "Password must contain a number")',' .regex(/[^A-Za-z0-9]/u, "Password must contain a special character"),',"});",""].join(`
97
94
  `);this.project.createSourceFile(v.join(e,"schemas/signup.schema.ts"),r,{overwrite:!0})}generateRefreshTokenSchema(e){const r=['import { z } from "zod";',"","export const refreshTokenSchema = z.object({"," token: z.string().min(1),","});",""].join(`
98
95
  `);this.project.createSourceFile(v.join(e,"schemas/refresh-token.schema.ts"),r,{overwrite:!0})}generateJwtDto(e){const r=["export interface JwtDto {"," userId: string;"," iat: number;"," exp: number;","}",""].join(`
@@ -106,33 +103,36 @@ ${a},
106
103
  `);this.project.createSourceFile(v.join(e,"guards/rest-optional-auth.guard.ts"),r,{overwrite:!0})}generateGqlOptionalAuthGuard(e){const r=['import { ExecutionContext, Injectable } from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class GqlOptionalAuthGuard extends AuthGuard("jwt") {'," getRequest(context: ExecutionContext) {"," const ctx = GqlExecutionContext.create(context);"," return ctx.getContext().req;"," }",""," handleRequest<TUser>(err: Error | null, user: TUser): TUser | null {"," if (err || !user) {"," return null;"," }"," return user;"," }","}",""].join(`
107
104
  `);this.project.createSourceFile(v.join(e,"guards/gql-optional-auth.guard.ts"),r,{overwrite:!0})}generateRestRolesGuard(e){const r=["import {"," Injectable,"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class RestRolesGuard extends AuthGuard("jwt") {'," constructor(private readonly roles: string[]) {"," super();"," }",""," handleRequest<TUser extends { role: string }>("," err: Error | null,"," user: TUser"," ): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," if (!this.roles.includes(user.role)) {",' throw new ForbiddenException("Insufficient permissions");'," }"," return user;"," }","}",""].join(`
108
105
  `);this.project.createSourceFile(v.join(e,"guards/rest-roles.guard.ts"),r,{overwrite:!0})}generateGqlRolesGuard(e){const r=["import {"," ExecutionContext,"," Injectable,"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class GqlRolesGuard extends AuthGuard("jwt") {'," constructor(private readonly roles: string[]) {"," super();"," }",""," getRequest(context: ExecutionContext) {"," const ctx = GqlExecutionContext.create(context);"," return ctx.getContext().req;"," }",""," handleRequest<TUser extends { role: string }>("," err: Error | null,"," user: TUser"," ): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," if (!this.roles.includes(user.role)) {",' throw new ForbiddenException("Insufficient permissions");'," }"," return user;"," }","}",""].join(`
109
- `);this.project.createSourceFile(v.join(e,"guards/gql-roles.guard.ts"),r,{overwrite:!0})}generateDbController(e,r){const a=r?["import {"," ApiCreatedResponse,"," ApiOperation,"," ApiTags,"," ApiUnauthorizedResponse,",'} from "@nestjs/swagger";']:[],n=[];r&&n.push('@ApiTags("Auth")');const s=[];r&&s.push(' @ApiOperation({ summary: "/api/auth/signup" })'," @ApiCreatedResponse({ description: 'User registered successfully' })");const o=[];r&&o.push(' @ApiOperation({ summary: "/api/auth/login" })'," @ApiCreatedResponse({ description: 'User logged in successfully' })"," @ApiUnauthorizedResponse({ description: 'Invalid credentials' })");const i=[];r&&i.push(' @ApiOperation({ summary: "/api/auth/refresh" })');const c=['import { Body, Controller, Post } from "@nestjs/common";',...a,"",'import { AuthService } from "./auth.service.js";','import { LoginInput } from "./dto/login.input.js";','import { RefreshTokenInput } from "./dto/refresh-token.input.js";','import { SignupInput } from "./dto/signup.input.js";',"",...n,'@Controller("auth")',"export class AuthController {"," constructor(private readonly auth: AuthService) {}","",' @Post("signup")',...s," signup(@Body({ schema: SignupInput.schema }) data: SignupInput) {"," data.email = data.email.toLowerCase();"," return this.auth.createUser(data);"," }","",' @Post("login")',...o," login(@Body({ schema: LoginInput.schema }) { email, password }: LoginInput) {"," return this.auth.login(email.toLowerCase(), password);"," }","",' @Post("refresh")',...i," refreshToken("," @Body({ schema: RefreshTokenInput.schema }) { token }: RefreshTokenInput"," ) {"," return this.auth.refreshToken(token);"," }","}",""];this.project.createSourceFile(v.join(e,"auth.controller.ts"),c.join(`
106
+ `);this.project.createSourceFile(v.join(e,"guards/gql-roles.guard.ts"),r,{overwrite:!0})}generateDbController(e,r){const a=r?["import {"," ApiCreatedResponse,"," ApiOperation,"," ApiTags,"," ApiUnauthorizedResponse,",'} from "@nestjs/swagger";']:[],n=[];r&&n.push('@ApiTags("Auth")');const s=[];r&&s.push(' @ApiOperation({ summary: "/api/auth/signup" })'," @ApiCreatedResponse({ description: 'User registered successfully' })");const o=[];r&&o.push(' @ApiOperation({ summary: "/api/auth/login" })'," @ApiCreatedResponse({ description: 'User logged in successfully' })"," @ApiUnauthorizedResponse({ description: 'Invalid credentials' })");const i=[];r&&i.push(' @ApiOperation({ summary: "/api/auth/refresh" })');const l=['import { Body, Controller, Post } from "@nestjs/common";',...a,"",'import { AuthService } from "./auth.service.js";','import { LoginInput } from "./dto/login.input.js";','import { RefreshTokenInput } from "./dto/refresh-token.input.js";','import { SignupInput } from "./dto/signup.input.js";',"",...n,'@Controller("auth")',"export class AuthController {"," constructor(private readonly auth: AuthService) {}","",' @Post("signup")',...s," signup(@Body({ schema: SignupInput.schema }) data: SignupInput) {"," data.email = data.email.toLowerCase();"," return this.auth.createUser(data);"," }","",' @Post("login")',...o," login(@Body({ schema: LoginInput.schema }) { email, password }: LoginInput) {"," return this.auth.login(email.toLowerCase(), password);"," }","",' @Post("refresh")',...i," refreshToken("," @Body({ schema: RefreshTokenInput.schema }) { token }: RefreshTokenInput"," ) {"," return this.auth.refreshToken(token);"," }","}",""];this.project.createSourceFile(v.join(e,"auth.controller.ts"),l.join(`
110
107
  `),{overwrite:!0})}generateTokenModel(e){const r=['import { Field, ObjectType } from "@nestjs/graphql";','import { GraphQLJWT } from "graphql-scalars";',"","@ObjectType()","export class Token {"," @Field(() => GraphQLJWT, { description: 'JWT access token' })"," accessToken: string;",""," @Field(() => GraphQLJWT, { description: 'JWT refresh token' })"," refreshToken: string;","}",""].join(`
111
108
  `);this.project.createSourceFile(v.join(e,"models/token.model.ts"),r,{overwrite:!0})}generateAuthModel(e){const r=['import { Field, ObjectType } from "@nestjs/graphql";',"",'import { User } from "../../graphql/models/user.model.js";','import { Token } from "./token.model.js";',"","@ObjectType()","export class Auth extends Token {"," @Field(() => User)"," user: User;","}",""].join(`
112
109
  `);this.project.createSourceFile(v.join(e,"models/auth.model.ts"),r,{overwrite:!0})}generateAuthResolver(e){const r=['import { StandardSchemaValidationPipe, UsePipes } from "@nestjs/common";',"import {"," Resolver,"," Mutation,"," Args,"," Parent,"," ResolveField,",'} from "@nestjs/graphql";',"",'import { User } from "../../graphql/models/user.model.js";','import { AuthService } from "./auth.service.js";','import { LoginInput } from "./dto/login.input.js";','import { RefreshTokenInput } from "./dto/refresh-token.input.js";','import { SignupInput } from "./dto/signup.input.js";','import { Auth } from "./models/auth.model.js";','import { Token } from "./models/token.model.js";',"","@UsePipes(new StandardSchemaValidationPipe())","@Resolver(() => Auth)","export class AuthResolver {"," constructor(private readonly auth: AuthService) {}",""," @Mutation(() => Auth)"," async signup(@Args('data') data: SignupInput) {"," data.email = data.email.toLowerCase();"," const { accessToken, refreshToken } = await this.auth.createUser("," data"," );"," return { accessToken, refreshToken };"," }",""," @Mutation(() => Auth)"," async login("," @Args('data') { email, password }: LoginInput"," ) {"," const { accessToken, refreshToken } = await this.auth.login("," email.toLowerCase(),"," password"," );"," return { accessToken, refreshToken };"," }",""," @Mutation(() => Token)"," refreshToken(@Args() { token }: RefreshTokenInput) {"," return this.auth.refreshToken(token);"," }",""," @ResolveField('user', () => User)"," user(@Parent() auth: Auth) {"," return this.auth.getUserFromToken(auth.accessToken);"," }","}",""].join(`
113
- `);this.project.createSourceFile(v.join(e,"auth.resolver.ts"),r,{overwrite:!0})}generateDbModule(e,r){const{hasGraphql:a,useTypeorm:n}=r,s=['import { Module } from "@nestjs/common";','import { JwtModule } from "@nestjs/jwt";','import { PassportModule } from "@nestjs/passport";',"",'import { env } from "../config/env.js";','import { AuthController } from "./auth.controller.js";','import { AuthService } from "./auth.service.js";','import { RestAuthGuard } from "./guards/rest-auth.guard.js";','import { RestOptionalAuthGuard } from "./guards/rest-optional-auth.guard.js";','import { RestRolesGuard } from "./guards/rest-roles.guard.js";','import { PasswordService } from "./password.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";'];a&&(s.push('import { AuthResolver } from "./auth.resolver.js";'),s.push('import { GqlAuthGuard } from "./guards/gql-auth.guard.js";'),s.push('import { GqlOptionalAuthGuard } from "./guards/gql-optional-auth.guard.js";'),s.push('import { GqlRolesGuard } from "./guards/gql-roles.guard.js";')),n&&s.push('import { TypeOrmModule } from "@nestjs/typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";');const o=n?" TypeOrmModule.forFeature([UserEntity]),":"",i=[" AuthService,"," JwtStrategy,"," PasswordService,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"];a&&(i.push(" GqlAuthGuard,"),i.push(" GqlOptionalAuthGuard,"),i.push(" GqlRolesGuard,"),i.push(" AuthResolver,"));const c=[" RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"];a&&(c.push(" GqlAuthGuard,"),c.push(" GqlOptionalAuthGuard,"),c.push(" GqlRolesGuard,"));const p=[...s,"","@Module({"," controllers: [AuthController],"," exports: [",c.join(`
110
+ `);this.project.createSourceFile(v.join(e,"auth.resolver.ts"),r,{overwrite:!0})}generateDbModule(e,r){const{hasGraphql:a,useTypeorm:n}=r,s=['import { Module } from "@nestjs/common";','import { JwtModule } from "@nestjs/jwt";','import { PassportModule } from "@nestjs/passport";',"",'import { env } from "../config/env.js";','import { AuthController } from "./auth.controller.js";','import { AuthService } from "./auth.service.js";','import { RestAuthGuard } from "./guards/rest-auth.guard.js";','import { RestOptionalAuthGuard } from "./guards/rest-optional-auth.guard.js";','import { RestRolesGuard } from "./guards/rest-roles.guard.js";','import { PasswordService } from "./password.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";'];a&&(s.push('import { AuthResolver } from "./auth.resolver.js";'),s.push('import { GqlAuthGuard } from "./guards/gql-auth.guard.js";'),s.push('import { GqlOptionalAuthGuard } from "./guards/gql-optional-auth.guard.js";'),s.push('import { GqlRolesGuard } from "./guards/gql-roles.guard.js";')),n&&s.push('import { TypeOrmModule } from "@nestjs/typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";');const o=n?" TypeOrmModule.forFeature([UserEntity]),":"",i=[" AuthService,"," JwtStrategy,"," PasswordService,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"];a&&(i.push(" GqlAuthGuard,"),i.push(" GqlOptionalAuthGuard,"),i.push(" GqlRolesGuard,"),i.push(" AuthResolver,"));const l=[" RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"];a&&(l.push(" GqlAuthGuard,"),l.push(" GqlOptionalAuthGuard,"),l.push(" GqlRolesGuard,"));const p=[...s,"","@Module({"," controllers: [AuthController],"," exports: [",l.join(`
114
111
  `)," ],"," imports: [",' PassportModule.register({ defaultStrategy: "jwt" }),'," JwtModule.register({"," secret: env.JWT_ACCESS_SECRET,",' signOptions: { expiresIn: "15m" },'," }),",o," ],"," providers: [",i.join(`
115
112
  `)," ],","})","export class AuthModule {}",""];this.project.createSourceFile(v.join(e,"auth.module.ts"),p.join(`
116
113
  `),{overwrite:!0})}generateDecorators(e){const r=v.join(e,"decorators"),a=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const CurrentUser = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user;"," }",");",""].join(`
117
114
  `);this.project.createSourceFile(v.join(r,"current-user.decorator.ts"),a,{overwrite:!0});const n=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";',"","export const UserEntity = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const gqlCtx = GqlExecutionContext.create(ctx);"," return gqlCtx.getContext().req.user;"," }",");",""].join(`
118
115
  `);this.project.createSourceFile(v.join(r,"user.decorator.ts"),n,{overwrite:!0});const s=['export { CurrentUser } from "./current-user.decorator.js";','export { UserEntity } from "./user.decorator.js";',""].join(`
119
- `);this.project.createSourceFile(v.join(r,"index.ts"),s,{overwrite:!0})}generateGuard(e){this.generateDbRestGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e)}}class Ns{static{u(this,"AuthModuleGenerator")}project;config;passportGen;betterAuthGen;constructor(e){this.config=e,this.project=new lr,this.passportGen=new Ms(this.project,e),this.betterAuthGen=new Ds(this.project,e)}generate(){const e=`${this.config.outputDir}/auth`,r=this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy;r==="passport"?this.passportGen.generate(e):r==="better-auth"&&this.betterAuthGen.generate(e)}generateAuthOnly(){const e=`${this.config.outputDir}/auth`;(this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy)==="better-auth"&&this.betterAuthGen.generateAuthOnly(e)}async save(){await this.project.save()}}class Mt{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 a=this.getPreset(r);return a?a.architectures.includes(e.architecture):!1}}async function Nt(t,e,r){const a=[];for(const n of r)try{if(n==="auth"){const s=t.api.includes("rest"),o=new Ns({api:t.api,database:t.database,extras:t.extras,orm:t.orm,outputDir:`${e}/src`,skipModule:!s&&(t.auth==="better-auth"||t.auth==="better-auth:stateless"),strategy:t.auth});await(s||t.auth==="passport"?o.generate():o.generateAuthOnly()),await o.save(),a.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${n} not yet implemented`)}catch(s){a.push({error:s instanceof Error?s.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return a}u(Nt,"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=[],a=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 s of r)e.push(` - ${s}`)}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: ${a}_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: ${a}_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: ${a}_db`),e.push(" ports:"),e.push(' - "27017:27017"'),e.push(" volumes:"),e.push(" - mongo_data:/data/db")),t.database.some(s=>["postgresql","mysql","mongodb"].includes(s))&&(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(`
116
+ `);this.project.createSourceFile(v.join(r,"index.ts"),s,{overwrite:!0})}generateGuard(e){this.generateDbRestGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e)}}class Ds{static{u(this,"AuthModuleGenerator")}project;config;passportGen;betterAuthGen;constructor(e){this.config=e,this.project=new lr,this.passportGen=new zs(this.project,e),this.betterAuthGen=new Gs(this.project,e)}generate(){const e=`${this.config.outputDir}/auth`,r=this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy;r==="passport"?this.passportGen.generate(e):r==="better-auth"&&this.betterAuthGen.generate(e)}generateAuthOnly(){const e=`${this.config.outputDir}/auth`;(this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy)==="better-auth"&&this.betterAuthGen.generateAuthOnly(e)}async save(){await this.project.save()}}class Ms{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 a=this.getPreset(r);return a?a.architectures.includes(e.architecture):!1}}async function Ns(t,e,r){const a=[];for(const n of r)try{if(n==="auth"){const s=t.api.includes("rest"),o=new Ds({api:t.api,database:t.database,extras:t.extras,orm:t.orm,outputDir:`${e}/src`,skipModule:!s&&(t.auth==="better-auth"||t.auth==="better-auth:stateless"),strategy:t.auth});await(s||t.auth==="passport"?o.generate():o.generateAuthOnly()),await o.save(),a.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${n} not yet implemented`)}catch(s){a.push({error:s instanceof Error?s.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return a}u(Ns,"executePresetGenerators");function Fs(t){const e=["services:",` ${t.projectName}:`," build:"," context: ."," dockerfile: Dockerfile"," ports:",` - "${t.httpProvider==="fastify"?"3001:3001":"3000:3000"}"`," environment:"," - NODE_ENV=development"],r=[],a=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 s of r)e.push(` - ${s}`)}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: ${a}_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.7.1"),e.push(" environment:"),e.push(" MYSQL_ROOT_PASSWORD: mysql"),e.push(` MYSQL_DATABASE: ${a}_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: ${a}_db`),e.push(" ports:"),e.push(' - "27017:27017"'),e.push(" volumes:"),e.push(" - mongo_data:/data/db")),t.database.some(s=>["postgresql","mysql","mongodb"].includes(s))&&(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(`
120
117
  `)}
121
- `}u(Lt,"generateDockerCompose");const Ls={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:{"@apollo/server":"^4.11.0","@as-integrations/fastify":"^2.1.0","@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":"^11.0.0","@nestjs/microservices":"next","@nestjs/passport":"^11.0.0","@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-api-reference":"^1.2.4","@t3-oss/env-core":"^0.13.11","@thallesp/nestjs-better-auth":"^2.6.1","@trpc/client":"^11.18.0","@trpc/openapi":"^11.18.0-alpha","@trpc/server":"^11.18.0",amqplib:"^0.10.5",bcrypt:"^5.1.1","better-auth":"^1.6.17","better-sqlite3":"^12.19.0",dotenv:"^17.2.2","drizzle-graphql":"^0.0.1","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-trpc":"^2.11.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","typeorm-relations-graphql":"^3.0.0",zod:"^4.4.3"},devDependencies:{"@nestjs/cli":"next","@nestjs/schematics":"next","@nestjs/testing":"next","@types/amqplib":"^0.10.6","@types/bcrypt":"^5.0.2","@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 Ls}u(Ft,"loadReference");function h(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(h,"getDependencyVersion");function Fs(){return{...Ft().catalog}}u(Fs,"getCatalogDependencies");const Us=[{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:".env.example",src:"base/.env.example.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/config/env.ts",src:"single-project/shared/config/env.ts.hbs"}],$s={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},Bs={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},Ws=[{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:"test/app.e2e-spec.ts",src:"base/test/app.e2e-spec.ts.hbs"}],Js=[{dest:"src/api/todo/todo.controller.ts",src:"feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs"},{dest:"src/api/todo/dto/create-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/create-todo.dto.ts.hbs"},{dest:"src/api/todo/dto/update-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/update-todo.dto.ts.hbs"}],Hs=[{dest:"apps/api-gateway/src/api/todo/todo.controller.ts",src:"feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/dto/create-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/create-todo.dto.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/dto/update-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/update-todo.dto.ts.hbs"}],Vs=[{dest:"src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"},{dest:"src/libs/trpc/scripts/fix-trpc-generated.mjs",src:"base/src/libs/trpc/scripts/fix-trpc-generated.mjs.hbs"},{dest:"src/libs/trpc/scripts/watch-trpc.mjs",src:"base/src/libs/trpc/scripts/watch-trpc.mjs.hbs"}],Qs=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],Ys=[{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"}],Xs=[{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"}],Ks=[{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"}]},Ut=[{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"}],ea="package.json",ta=[{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.service.ts",src:"monorepo/apps/api-gateway/src/app.service.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"}],ra=[{dest:"apps/api-gateway/src/app.controller.ts",src:"monorepo/apps/api-gateway/src/app.controller.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"}],sa=[{dest:"src/graphql/graphql.module.ts",src:"feature/graphql/src/graphql/graphql.module.ts.hbs"},{dest:"src/graphql/models/base.model.ts",src:"feature/graphql/src/graphql/models/base.model.ts.hbs"},{dest:"src/graphql/models/user.model.ts",src:"feature/graphql/src/graphql/models/user.model.ts.hbs"},{dest:"src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts",src:"feature/graphql/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts.hbs"},{dest:"src/graphql/orm/drizzle/drizzle-graphql.module.ts",src:"feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs"}],aa=[{dest:"src/graphql/dto/create-todo.input.ts",src:"feature/graphql/src/graphql/dto/create-todo.input.ts.hbs"},{dest:"src/graphql/dto/update-todo.input.ts",src:"feature/graphql/src/graphql/dto/update-todo.input.ts.hbs"},{dest:"src/graphql/models/todo.model.ts",src:"feature/graphql/src/graphql/models/todo.model.ts.hbs"},{dest:"src/graphql/resolvers/todo.resolver.ts",src:"feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs"}],oa=[{dest:"apps/api-gateway/src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"apps/api-gateway/src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"apps/api-gateway/src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/scripts/fix-trpc-generated.mjs",src:"base/src/libs/trpc/scripts/fix-trpc-generated.mjs.hbs"},{dest:"apps/api-gateway/src/libs/trpc/scripts/watch-trpc.mjs",src:"base/src/libs/trpc/scripts/watch-trpc.mjs.hbs"}],na=[{dest:"apps/api-gateway/src/graphql/graphql.module.ts",src:"monorepo/feature/graphql/src/graphql/graphql.module.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/base.model.ts",src:"monorepo/feature/graphql/src/graphql/models/base.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/user.model.ts",src:"monorepo/feature/graphql/src/graphql/models/user.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts",src:"monorepo/feature/graphql/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts.hbs"},{dest:"apps/api-gateway/src/graphql/orm/drizzle/drizzle-graphql.module.ts",src:"monorepo/feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs"}],ia=[{dest:"apps/api-gateway/src/graphql/dto/create-todo.input.ts",src:"monorepo/feature/graphql/src/graphql/dto/create-todo.input.ts.hbs"},{dest:"apps/api-gateway/src/graphql/dto/update-todo.input.ts",src:"monorepo/feature/graphql/src/graphql/dto/update-todo.input.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/todo.model.ts",src:"monorepo/feature/graphql/src/graphql/models/todo.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/resolvers/todo.resolver.ts",src:"monorepo/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs"}],ca=[{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"}],$t={"addons/husky":Qs,"extras/database":Xs,"extras/docker":Ys,"extras/swagger":[],"feature/graphql":sa,"feature/graphql/todo-example":aa,"feature/rest":Ws,"feature/rest/todo-example":Js,"feature/trpc":Vs,"monorepo/apps/api-gateway":ta,"monorepo/feature/graphql":na,"monorepo/feature/graphql/todo-example":ia,"monorepo/feature/rest":ra,"monorepo/feature/rest/todo-example":Hs,"monorepo/feature/trpc":oa,"monorepo/packages":ca,"monorepo/packages/db":Ks,"monorepo/root":Ut};function Bt(t,e,r){t.auth==="passport"?(e["@nestjs/jwt"]=h("@nestjs/jwt"),e["@nestjs/passport"]=h("@nestjs/passport"),e.passport=h("passport"),e["passport-jwt"]=h("passport-jwt"),r["@types/passport-jwt"]=h("@types/passport-jwt"),t.database.length>0&&(e.bcrypt=h("bcrypt"),r["@types/bcrypt"]=h("@types/bcrypt"),t.orm.includes("typeorm")&&(e["@nestjs/typeorm"]=h("@nestjs/typeorm"),e.typeorm=h("typeorm")))):(t.auth==="better-auth"||t.auth==="better-auth:stateless")&&(e["better-auth"]=h("better-auth"),e["@thallesp/nestjs-better-auth"]=h("@thallesp/nestjs-better-auth"),t.orm.includes("drizzle")&&(e["@better-auth/drizzle-adapter"]=h("@better-auth/drizzle-adapter")));for(const a of t.api)a==="graphql"?(e["@nestjs/graphql"]=h("@nestjs/graphql"),e["@nestjs/apollo"]=h("@nestjs/apollo"),e.graphql=h("graphql"),e["@apollo/server"]=h("@apollo/server"),t.httpProvider==="fastify"?e["@as-integrations/fastify"]=h("@as-integrations/fastify"):e["@as-integrations/express5"]=h("@as-integrations/express5"),t.auth==="passport"&&(e["graphql-scalars"]=h("graphql-scalars")),t.orm.includes("typeorm")&&(e["typeorm-relations-graphql"]=h("typeorm-relations-graphql")),t.orm.includes("drizzle")&&(e["drizzle-graphql"]=h("drizzle-graphql"))):a==="trpc"&&(e["@trpc/server"]=h("@trpc/server"),e["@trpc/client"]=h("@trpc/client"),e["@trpc/openapi"]=h("@trpc/openapi"),e["nestjs-trpc"]=h("nestjs-trpc"));t.extras.includes("swagger")&&(e["@nestjs/swagger"]=h("@nestjs/swagger"),t.addons.includes("scalar-ui")&&(e["@scalar/nestjs-api-reference"]=h("@scalar/nestjs-api-reference"))),t.extras.includes("health-check")&&(e["@nestjs/terminus"]=h("@nestjs/terminus")),t.extras.includes("rate-limiting")&&(e["@nestjs/throttler"]=h("@nestjs/throttler"));for(const a of t.microservices)a==="redis"?e.ioredis=h("ioredis"):a==="mqtt"?e.mqtt=h("mqtt"):a==="nats"?e.nats=h("nats"):a==="rabbitmq"?(e.amqplib=h("amqplib"),r["@types/amqplib"]=h("@types/amqplib")):a==="kafka"?e.kafkajs=h("kafkajs"):a==="grpc"&&(e["@grpc/grpc-js"]=h("@grpc/grpc-js"),e["@grpc/proto-loader"]=h("@grpc/proto-loader"));t.addons.includes("nestjs-zod")&&(e["nestjs-zod"]=h("nestjs-zod"))}u(Bt,"addConditionalDependencies");function Wt(t,e,r){const a=t.orm.includes("prisma"),n=t.orm.includes("drizzle"),s=t.orm.includes("typeorm"),o=t.database.length>0&&!a&&!n&&!s;for(const i of t.orm)i==="prisma"?(e["@prisma/client"]=h("@prisma/client"),r.prisma=h("prisma"),t.database.includes("postgresql")&&(e["@prisma/adapter-pg"]=h("@prisma/adapter-pg")),t.database.includes("mysql")&&(e["@prisma/adapter-mysql2"]=h("@prisma/adapter-mysql2")),t.database.includes("sqlite")&&(e["@prisma/adapter-better-sqlite3"]=h("@prisma/adapter-better-sqlite3"))):i==="typeorm"?(e.typeorm=h("typeorm"),e["@nestjs/typeorm"]=h("@nestjs/typeorm"),t.database.includes("postgresql")&&(e.pg=h("pg"),r["@types/pg"]=h("@types/pg"))):i==="drizzle"&&(e["drizzle-orm"]=h("drizzle-orm"),r["drizzle-kit"]=h("drizzle-kit"));t.database.includes("postgresql")&&n&&(e.pg=h("pg"),r["@types/pg"]=h("@types/pg")),t.database.includes("mysql")&&n&&(e.mysql2=h("mysql2")),t.database.includes("sqlite")&&n&&(e["better-sqlite3"]=h("better-sqlite3"),r["@types/better-sqlite3"]=h("@types/better-sqlite3")),t.database.includes("mongodb")&&o&&(e.mongodb=h("mongodb"))}u(Wt,"addDatabaseDependencies");async function la(t,e,r,a,n,s){try{const o=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":h("@nestjs/common"),"@nestjs/core":h("@nestjs/core"),[o]:h(o),"@t3-oss/env-core":h("@t3-oss/env-core"),dotenv:h("dotenv"),"reflect-metadata":h("reflect-metadata"),rxjs:h("rxjs"),zod:h("zod")},c={"@nestjs/cli":h("@nestjs/cli"),"@nestjs/schematics":h("@nestjs/schematics"),"@nestjs/testing":h("@nestjs/testing"),"@types/node":h("@types/node"),"@types/supertest":h("@types/supertest"),"@vitest/coverage-v8":h("@vitest/coverage-v8"),"source-map-support":h("source-map-support"),supertest:h("supertest"),typescript:h("typescript"),vitest:h("vitest")};t.httpProvider==="express"&&(c["@types/express"]=h("@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"};Bt(t,i,c),Wt(t,i,c),t.addons.includes("ultracite")&&(c.ultracite=h("ultracite"),p.check="ultracite check",p.fix="ultracite fix"),t.addons.includes("husky")&&(c.husky=h("husky"),p.prepare="husky"),t.orm.includes("prisma")&&(p["prisma:generate"]="prisma generate",p["prisma:format"]="prisma format",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.api.includes("trpc")&&(p["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o src/libs/trpc/@generated && node src/libs/trpc/scripts/fix-trpc-generated.mjs",p["trpc:watch"]="node src/libs/trpc/scripts/watch-trpc.mjs"),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 g={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:p,dependencies:i,devDependencies:c},m=JSON.stringify(g,null,2),f=await r.writeFile({content:m,filePath:"package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});f.written&&n.push(f.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate package.json: ${i}`),console.error("Failed to generate package.json:",o)}}u(la,"generateSingleProjectPackageJson");async function pa(t,e,r,a,n,s){try{const o={build:"turbo build","check-types":"turbo check-types",dev:"turbo dev"},i={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},c={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:h("turbo"),typescript:"catalog:"};t.addons.includes("ultracite")&&(o.check="ultracite check"),t.addons.includes("husky")&&(c.husky=h("husky"),o.prepare="husky");const g={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",...g?{packageManager:g}:{},...t.packageManager==="bun"?{catalog:Fs()}:{},scripts:o,dependencies:i,devDependencies:c},f=JSON.stringify(m,null,2),O=await r.writeFile({content:f,filePath:ea,isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});O.written&&n.push(O.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo root package.json: ${i}`),console.error("Failed to generate monorepo root package.json:",o)}}u(pa,"generateMonorepoRootPackageJson");async function ua(t,e,r,a,n,s){try{const o=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":h("@nestjs/common"),"@nestjs/core":h("@nestjs/core"),[o]:h(o),"@repo/env":"workspace:*","reflect-metadata":h("reflect-metadata"),rxjs:h("rxjs"),zod:"catalog:"};t.database.length>0&&(i["@repo/db"]="workspace:*");const c={"@nestjs/cli":h("@nestjs/cli"),"@nestjs/schematics":h("@nestjs/schematics"),"@nestjs/testing":h("@nestjs/testing"),"@repo/config":"workspace:*","@types/node":"catalog:","@types/supertest":h("@types/supertest"),"@vitest/coverage-v8":h("@vitest/coverage-v8"),"source-map-support":h("source-map-support"),supertest:h("supertest"),typescript:"catalog:",vitest:h("vitest")};t.httpProvider==="express"&&(c["@types/express"]=h("@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"};Bt(t,i,c),t.addons.includes("ultracite")&&(c.ultracite=h("ultracite"),p.check="ultracite check",p.fix="ultracite fix"),t.addons.includes("husky")&&(c.husky=h("husky"),p.prepare="husky"),t.api.includes("trpc")&&(p["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated && node src/libs/trpc/scripts/fix-trpc-generated.mjs",p["trpc:watch"]="node src/libs/trpc/scripts/watch-trpc.mjs");const g={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:p,dependencies:i,devDependencies:c},m=JSON.stringify(g,null,2),f=await r.writeFile({content:m,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});f.written&&n.push(f.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo app package.json: ${i}`),console.error("Failed to generate monorepo app package.json:",o)}}u(ua,"generateMonorepoAppPackageJson");async function da(t,e,r,a,n,s){try{const o={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:"},i={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:"catalog:"};Wt(t,o,i);const c={};t.orm.includes("prisma")&&(c["prisma:generate"]="prisma generate",c["prisma:format"]="prisma format",c["prisma:push"]="prisma db push",c["prisma:studio"]="prisma studio",c["prisma:migrate"]="prisma migrate dev",c["prisma:migrate:deploy"]="prisma migrate deploy",c.postinstall="prisma generate"),t.orm.includes("drizzle")&&(c["db:generate"]="drizzle-kit generate",c["db:migrate"]="drizzle-kit migrate",c["db:studio"]="drizzle-kit studio",c["db:push"]="drizzle-kit push"),t.orm.includes("typeorm")&&(c["typeorm:run"]="typeorm-ts esm migration:run -d src/database/orm/typeorm/data-source.ts",c["typeorm:revert"]="typeorm-ts esm migration:revert -d src/database/orm/typeorm/data-source.ts",c["typeorm:generate"]="typeorm-ts esm migration:generate -d src/database/orm/typeorm/data-source.ts",c["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(c).length>0?{scripts:c}:{},dependencies:o,devDependencies:i},g=JSON.stringify(p,null,2),m=await r.writeFile({content:g,filePath:"packages/db/package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});m.written&&n.push(m.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo db package.json: ${i}`),console.error("Failed to generate monorepo db package.json:",o)}}u(da,"generateMonorepoDbPackageJson");class ma{static{u(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(e,r){this.options=r,this.fileWriter=new Jr(e),this.templateEngine=new lt(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new ns,this.mapper=new Ue,Is(this.mapper)}getMapper(){return this.mapper}async generate(e){const r=Date.now(),a=[],n=[];try{const s=this.mapper.resolve(e);let o=zs(e);o=Gs(o,s.extraVariables),o.hasUltracite=e.addons.includes("ultracite"),o.hasHusky=e.addons.includes("husky"),await(e.projectType==="monorepo"?this.generateMonorepo(e,o,s.templateGroups,a,n):this.generateSingleProject(e,o,s.templateGroups,a,n));const i=Date.now()-r,c=n.length===0;return c&&await this.generateMetadata(e,o,a,n),console.log(`\u2705 Project generated in ${i}ms`),{error:c&&n.length===0?void 0:n.join(`
122
- `),filesCount:a.length,generatedFiles:a,success:c&&n.length===0}}catch(s){return{error:s instanceof Error?s.message:"Unknown error",filesCount:0,generatedFiles:a,success:!1}}}async generateSingleProject(e,r,a,n,s){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite},i=[...Us];r.packageManager==="pnpm"?i.push($s):r.packageManager==="yarn"&&i.push(Bs),await la(e,r,this.fileWriter,o,n,s);for(const c of i)await this.renderAndWrite(c.src,c.dest,r,n,s);e.extras.includes("swagger")&&await this.renderAndWrite("extras/swagger/create-docs.ts.hbs",e.projectType==="monorepo"?"apps/api-gateway/src/docs/create-docs.ts":"src/docs/create-docs.ts",r,n,s);for(const c of a){if(c==="monorepo/packages/db")continue;const p=Zs[c];if(p){for(const x of p)x.dest==="package.json"||x.dest==="pnpm-workspace.yaml"||x.dest===".yarnrc.yml"||await this.renderAndWrite(x.src,x.dest,r,n,s);continue}const g=$t[c];if(!g)continue;const m=c==="extras/database"||c==="monorepo/packages/db"?this.filterDatabaseTemplates(g,r):g,f=c==="feature/trpc"?this.filterTrpcTemplates(m,r):m,O=c==="feature/graphql"?this.filterGraphqlTemplates(f,r):f;for(const x of O)x.dest==="docker-compose.yml"&&e.database.length>0||await this.renderAndWrite(x.src,x.dest,r,n,s)}if(e.extras.includes("docker")&&e.database.length>0){const c=Lt(e),p=await this.fileWriter.writeFile({content:c,filePath:"docker-compose.yml",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});p.written&&n.push(p.filePath)}if(e.orm.includes("prisma")&&(await this.generatePrismaSchema(e,n,s),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,n,s)),e.orm.includes("drizzle")&&await this.generateDrizzleConfig(e,n,s),e.auth!=="none"){const c=Mt.composeGenerators(e),p=await Nt(e,this.fileWriter.getBaseDir(),c);for(const g of p)!g.success&&g.error&&s.push(g.error)}}async generateMonorepo(e,r,a,n,s){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await pa(e,r,this.fileWriter,o,n,s),await ua(e,r,this.fileWriter,o,n,s),e.database.length>0&&await da(e,r,this.fileWriter,o,n,s);for(const i of a){if(i==="monorepo/root"){for(const f of Ut)await this.renderAndWrite(f.src,f.dest,r,n,s);r.packageManager==="pnpm"?await this.renderAndWrite("monorepo/root/pnpm-workspace.yaml.hbs","pnpm-workspace.yaml",r,n,s):r.packageManager==="yarn"&&await this.renderAndWrite("monorepo/root/.yarnrc.yml.hbs",".yarnrc.yml",r,n,s);continue}const c=$t[i];if(!c)continue;const p=i==="extras/database"||i==="monorepo/packages/db"?this.filterDatabaseTemplates(c,r):c,g=i==="monorepo/feature/trpc"?this.filterTrpcTemplates(p,r):p,m=i==="monorepo/feature/graphql"?this.filterGraphqlTemplates(g,r):g;for(const f of m)f.dest!=="packages/db/package.json"&&(f.dest==="docker-compose.yml"&&e.database.length>0||await this.renderAndWrite(f.src,f.dest,r,n,s))}if(e.extras.includes("swagger")&&await this.renderAndWrite("extras/swagger/create-docs.ts.hbs","apps/api-gateway/src/docs/create-docs.ts",r,n,s),e.extras.includes("docker")&&e.database.length>0){const i=Lt(e),c=await this.fileWriter.writeFile({content:i,filePath:"docker-compose.yml",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});c.written&&n.push(c.filePath)}if(e.orm.includes("prisma")&&(await this.generatePrismaSchema(e,n,s),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,n,s)),e.orm.includes("drizzle")&&await this.generateDrizzleConfig(e,n,s),e.auth!=="none"){const i=Mt.composeGenerators(e),c=await Nt(e,this.fileWriter.getBaseDir(),i);for(const p of c)!p.success&&p.error&&s.push(p.error)}}async generateMetadata(e,r,a,n){try{const s=ds(e),o=ms(s),i=await this.fileWriter.writeFile({content:o,filePath:"nest-arch.jsonc",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});i.written&&a.push(i.filePath);const c=hs(),p=await this.fileWriter.writeFile({content:c,filePath:"schema.json",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});p.written&&a.push(p.filePath)}catch(s){const o=s instanceof Error?s.message:String(s);n.push(`Failed to generate nest-arch.jsonc/schema.json: ${o}`)}}filterGraphqlTemplates(e,r){const a=!!r.useTypeorm,n=!!r.usePrisma,s=!!r.useDrizzle;return e.filter(o=>{const{dest:i}=o;return i.includes("orm/typeorm")?a:i.includes("orm/prisma")?n:i.includes("orm/drizzle")?s:!0})}filterTrpcTemplates(e,r){const a=!!r.hasTrpcAndAuth;return e.filter(n=>n.dest.includes("libs/trpc/protected.ts")||n.dest.includes("libs/trpc/inner.context.ts")||n.dest.includes("libs/middlewares/auth.trpc.middleware.ts")?a:!0)}filterDatabaseTemplates(e,r){const a=!!r.usePrisma,n=!!r.useTypeorm,s=!!r.useDrizzle,o=!!r.useRawSql,i=!!r.hasPostgres,c=!!r.hasMysql,p=!!r.hasSqlite,g=!!r.hasMongodb;return e.filter(m=>{const{dest:f}=m;return f.includes("prisma-sql.adapter")?a&&(i||c||p):f.includes("prisma-mongo.adapter")?a&&g:f.includes("typeorm-sql.adapter")?n&&(i||c||p):f.includes("orm/typeorm/data-source")||f.includes("entities/")?n:f.includes("drizzle-sql.adapter")?s:f.includes("raw-sql.adapter")?o&&(i||c||p):f.includes("raw-mongo.adapter")?o&&g:f.includes("orm/drizzle/schema")?s:!0})}async generatePrismaSchema(e,r,a){let n="postgresql";e.database.includes("mysql")?n="mysql":e.database.includes("sqlite")?n="sqlite":e.database.includes("mongodb")&&(n="mongodb");const s=["generator client {",' provider = "prisma-client"',' output = "./generated"',"}","","datasource db {",` provider = "${n}"`,"}",""],o=e.extras.includes("todo-example");e.auth==="passport"&&e.database.length>0&&s.push("enum Role {"," ADMIN"," USER","}","","model User {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," email String @unique"," password String"," firstname String?"," lastname String?"," role Role @default(USER)",...o?[" todos Todo[]",""]:[""],' @@map("user")',"}",""),o&&e.database.length>0&&(e.auth==="none"?s.push("model Todo {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)","",' @@map("todo")',"}",""):s.push("model Todo {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)"," authorId String?"," author User? @relation(fields: [authorId], references: [id])","",' @@map("todo")',"}",""));const i=s.join(`
123
- `);try{const c=await this.fileWriter.writeFile({content:i,filePath:"src/database/orm/prisma/schema.prisma",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});c.written&&r.push(c.filePath)}catch(c){const p=c instanceof Error?c.message:String(c);a.push(`Failed to generate src/database/orm/prisma/schema.prisma: ${p}`)}}async generateDrizzleConfig(e,r,a){let n="postgresql";e.database.includes("mysql")?n="mysql":e.database.includes("sqlite")&&(n="sqlite");const s=e.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",o=s.replace("/schema.ts","/migrations");let i="process.env.POSTGRES_URL!";e.database.includes("mysql")?i="process.env.MYSQL_URL!":e.database.includes("sqlite")&&(i="process.env.SQLITE_PATH!");const c=[e.formatter==="oxlint-oxfmt"?"// oxlint-disable typescript/no-non-null-assertion":"","import 'dotenv/config';","import { defineConfig } from 'drizzle-kit';","","export default defineConfig({"," dbCredentials: {",` url: ${i},`," },",` dialect: '${n}',`,` out: '${o}',`,` schema: '${s}',`,"});",""].join(`
124
- `);try{const p=await this.fileWriter.writeFile({content:c,filePath:"drizzle.config.ts",isBinary:!1},{dryRun:this.options.dryRun,overwrite:this.options.overwrite});p.written&&r.push(p.filePath)}catch(p){const g=p instanceof Error?p.message:String(p);a.push(`Failed to generate drizzle.config.ts: ${g}`)}}async renderAndWrite(e,r,a,n,s){try{const o=await this.templateEngine.renderToFile(e,r,{context:a}),i=await this.fileWriter.writeFile(o,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});i.written&&n.push(i.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate ${r}: ${i}`),console.error(`Failed to generate ${r}:`,o)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}const ha=/Resolved|Resolving/iu,ga=/Downloaded?|downloaded/iu,fa=/Link(ed|ing)/iu,ya=/saved (to )?(lockfile|bun)/iu;function ba(t){const e=[],r=t.split(`
125
- `);for(const a of r){const n=a.trim();if(n){if(ha.test(n)){e.push({message:"Resolving packages...",phase:"resolve"});continue}if(ga.test(n)){e.push({message:"Downloading...",phase:"download"});continue}if(fa.test(n)){e.push({message:"Linking packages...",phase:"link"});continue}if(n.includes("packages installed")){e.push({message:n,percentage:100,phase:"link"});continue}if(ya.test(n)){e.push({message:"Saving lockfile...",phase:"postinstall"});continue}(n.includes("[script]")||n.includes("postinstall"))&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}}return e}u(ba,"parseBunText");class wa{static{u(this,"BunInstaller")}async install(e,r,a){const n=Oe("bun install",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";const o=u(c=>{const p=c.toString();s+=p;const g=ba(p);for(const m of g)r?.(m)},"handleData");n.stderr.on("data",o),n.stdout.on("data",o);const[i]=await Promise.race([re(n,"close"),re(n,"error").then(([c])=>{const p=c;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(`
126
- `)):new Error(p.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`bun install exited with code ${i}`)}}const ja=/^(\d+)\/(\d+)\s+resolving/iu,va=/^(\d+)\/(\d+)\s+extract:/iu,Sa=/^(\d+)\/(\d+)\s+(\S+)/iu,ka=/^(\d+)ms\s+(.*)/iu;function Aa(t){const e=[],r=t.split(`
127
- `);for(const a of r){const n=a.trim();if(n.includes("resolving")){const s=ja.exec(n);s?e.push({completed:Number(s[1]),message:"Resolving packages...",percentage:Math.round(Number(s[1])/Number(s[2])*100),phase:"resolve",total:Number(s[2])}):e.push({message:"Resolving packages...",phase:"resolve"});continue}if(n.includes("extract:")||n.includes("http fetch")){const s=va.exec(n)||Sa.exec(n);s?e.push({completed:Number(s[1]),message:"Downloading...",percentage:Math.round(Number(s[1])/Number(s[2])*100),phase:"download",total:Number(s[2])}):e.push({message:"Downloading...",phase:"download"});continue}if(n.includes("timing")){const s=ka.exec(n);if(s){const o=s[2]??"";o.includes("build")?e.push({message:"Building dependencies...",phase:"build"}):o.includes("link")&&e.push({message:"Linking packages...",phase:"link"})}continue}n.includes("postinstall")&&!n.includes("timing")&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}return e}u(Aa,"parseNpmText");class Ta{static{u(this,"NpmInstaller")}async install(e,r,a){const n=Oe("npm install --loglevel silly",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";const o=u(c=>{const p=c.toString();s+=p;const g=Aa(p);for(const m of g)r?.(m)},"handleData");n.stderr.on("data",o),n.stdout.on("data",()=>{});const[i]=await Promise.race([re(n,"close"),re(n,"error").then(([c])=>{const p=c;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(`
128
- `)):new Error(p.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`npm install exited with code ${i}`)}}function Pa(t,e){const r=e?.status,a=e?.progress;switch(r){case"resolving":return{message:"Resolving packages...",percentage:a??0,phase:"resolve"};case"downloading":case"fetching":return{message:"Downloading...",percentage:a??e?.progress,phase:"download"};case"linking":return{message:"Linking packages...",percentage:a??0,phase:"link"};case"build":return{message:"Building dependencies...",percentage:a??0,phase:"build"};default:return{message:r||"Installing dependencies...",percentage:a??0,phase:"download"}}}u(Pa,"mapPnpmStage");function Ea(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(Ea,"mapPnpmStat");function Ra(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(Ra,"mapPnpmFetching");function qa(t){if(!t.type)return null;switch(t.type){case"stage":{const e=t.data?.stage;return e?Pa(e,t.data):null}case"stat":return Ea(t.data);case"fetching":return Ra(t);case"warning":case"error":return{message:t.message??t.type,phase:"download"};default:return null}}u(qa,"parsePnpmLine");class xa{static{u(this,"PnpmInstaller")}async install(e,r,a){const n=Oe("pnpm install --reporter ndjson",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";n.stdout.on("data",i=>{const c=i.toString().split(`
129
- `).filter(Boolean);for(const p of c)try{const g=JSON.parse(p),m=qa(g);m&&r&&r(m)}catch{}}),n.stderr.on("data",i=>{s+=i.toString()});const[o]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const c=i;throw c.code==="ENOENT"||c.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(`
130
- `)):new Error(c.message)})]);if(o===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`pnpm install exited with code ${o}`)}}function Ia(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,a=e?.total;return r!==void 0&&a!==void 0?{completed:r,message:"Processing...",percentage:Math.round(r/a*100),phase:"download",total:a}: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(Ia,"parseYarnLine");class Ca{static{u(this,"YarnInstaller")}async install(e,r,a){const n=Oe("yarn install --json",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";n.stdout.on("data",i=>{const c=i.toString().split(`
131
- `).filter(Boolean);for(const p of c)try{const g=JSON.parse(p),m=Ia(g);m&&r&&r(m)}catch{}}),n.stderr.on("data",i=>{s+=i.toString()});const[o]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const c=i;throw c.code==="ENOENT"||c.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(`
132
- `)):new Error(c.message)})]);if(o===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`yarn install exited with code ${o}`)}}function Oa(t){switch(t){case"pnpm":return new xa;case"npm":return new Ta;case"yarn":return new Ca;case"bun":return new wa;default:throw new Error(`Unhandled package manager: ${t}`)}}u(Oa,"createPackageInstaller");class _a{static{u(this,"ProjectPipeline")}outputDir;generatorOptions;constructor(e,r){this.outputDir=e,this.generatorOptions=r}async execute(e,r){const a=[],n=[],s=u(m=>{r?.onStageChange?.(m)},"emitStage"),o=u(m=>{a.push(m)},"addPhase");s("generate-files");const i=new ma(this.outputDir,this.generatorOptions);try{const m=await i.generate(e);if(n.push(...m.generatedFiles),!m.success)return o({error:m.error,phase:"generate-files",success:!1}),this.buildResult(!1,a,n);o({phase:"generate-files",success:!0})}catch(m){return o({error:m instanceof Error?m.message:String(m),phase:"generate-files",success:!1}),this.buildResult(!1,a,n)}if(e.formatter!=="none"){s("setup-linter");try{const m=await os(this.outputDir,e);if(!m.success)return o({error:m.message,phase:"setup-linter",success:!1}),this.buildResult(!1,a,n);const f=await ps(this.outputDir,e.formatter);if(!f.success)return o({error:f.message??"Rule injection failed",phase:"setup-linter",success:!1}),this.buildResult(!1,a,n);o({phase:"setup-linter",success:!0})}catch(m){return o({error:m instanceof Error?m.message:String(m),phase:"setup-linter",success:!1}),this.buildResult(!1,a,n)}}else o({phase:"setup-linter",skipped:!0,success:!0});if(e.initGit){s("initialize-git");try{await Qr(this.outputDir)||await Hr(this.outputDir),o({phase:"initialize-git",success:!0})}catch(m){o({error:m instanceof Error?m.message:String(m),phase:"initialize-git",success:!1})}if(a[2]?.success){s("initial-commit");try{await Gt(this.outputDir),await Dt(this.outputDir,"Initial project scaffold"),o({phase:"initial-commit",success:!0})}catch(m){o({error:m instanceof Error?m.message:String(m),phase:"initial-commit",success:!1})}}else o({phase:"initial-commit",skipped:!0,success:!0})}else o({phase:"initialize-git",skipped:!0,success:!0}),o({phase:"initial-commit",skipped:!0,success:!0});let c=!1;if(e.installDependencies){s("install-dependencies");try{await Oa(e.packageManager).install(this.outputDir,f=>{r?.onInstallProgress?.(f)}),c=!0,o({phase:"install-dependencies",success:!0})}catch(m){o({error:m instanceof Error?m.message:String(m),phase:"install-dependencies",success:!1})}}else o({phase:"install-dependencies",skipped:!0,success:!0});if(c&&e.formatter!=="none"){s("run-formatter");try{const m=await es(e.packageManager,this.outputDir);m.success?o({phase:"run-formatter",success:!0}):o({error:m.error,phase:"run-formatter",success:!1})}catch(m){o({error:m instanceof Error?m.message:String(m),phase:"run-formatter",success:!1})}}else o({phase:"run-formatter",skipped:!0,success:!0});const{5:p}=a;if(e.initGit&&p?.success&&!p.skipped){s("formatter-commit");try{await Gt(this.outputDir),await Vr(this.outputDir)&&await Dt(this.outputDir,"Apply formatter"),o({phase:"formatter-commit",success:!0})}catch(m){o({error:m instanceof Error?m.message:String(m),phase:"formatter-commit",success:!1})}}else o({phase:"formatter-commit",skipped:!0,success:!0});s("complete");const g=a.every(m=>m.success||m.skipped);return this.buildResult(g,a,n)}buildResult(e,r,a){return{generatedFiles:a,outputDir:this.outputDir,phases:r,success:e}}}function za(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(za,"buildGeneratorContext");function Le(t){return Me.NEST_ARCH_BETA_MODE?Q(mt(),"test-projects",t):Q(process.cwd(),t)}u(Le,"getOutputDir");function Ga(){const t=import.meta.dirname;if(t){const r=Q(t,"templates");if(Se(r))return r}return Q(t??process.cwd(),"..","..","..","..","packages","core","templates")}u(Ga,"getTemplatesDir");async function Jt(t,e){const r=Le(t.projectName),a=za(t),n=Ga(),s=new _a(r,{cacheTemplates:!0,templatesDir:n});try{const o=await s.execute(a,e),i={"formatter-commit":"Commit formatting","generate-files":"Generate project","initial-commit":"Initial commit","initialize-git":"Initialize Git","install-dependencies":"Install dependencies","run-formatter":"Run formatter","setup-linter":"Setup linter"},c=o.phases.filter(p=>!p.success&&!p.skipped&&p.error).map(p=>`${i[p.phase]||p.phase} failed:
133
- ${p.error}`);return c.length>0?{message:c.join(`
118
+ `}u(Fs,"generateDockerCompose");async function Ls(t,e,r,a,n){let s="postgresql";e.database.includes("mysql")?s="mysql":e.database.includes("sqlite")&&(s="sqlite");const o=e.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",i=o.replace("/schema.ts","/migrations");let l="process.env.POSTGRES_URL!";e.database.includes("mysql")?l="process.env.MYSQL_URL!":e.database.includes("sqlite")&&(l="process.env.SQLITE_PATH!");const p=[e.formatter==="oxlint-oxfmt"?"// oxlint-disable typescript/no-non-null-assertion":"","import 'dotenv/config';","import { defineConfig } from 'drizzle-kit';","","export default defineConfig({"," dbCredentials: {",` url: ${l},`," },",` dialect: '${s}',`,` out: '${i}',`,` schema: '${o}',`,"});",""].join(`
119
+ `);try{const h=await t.writeFile({content:p,filePath:"drizzle.config.ts",isBinary:!1},r);h.written&&a.push(h.filePath)}catch(h){const d=h instanceof Error?h.message:String(h);n.push(`Failed to generate drizzle.config.ts: ${d}`)}}u(Ls,"generateDrizzleConfig");function $s(t){const e=[`pnpm create nest-arch@latest ${t.projectName}`,`--package-manager ${t.packageManager}`,`--http-provider ${t.httpProvider}`,`--project-type ${t.projectType}`,`--architecture ${t.architecture}`,`--database ${t.database.length>0?t.database.join(" "):"none"}`,`--orm ${t.orm.length>0?t.orm.join(" "):"none"}`,`--api ${t.api.length>0?t.api.join(" "):"none"}`,`--auth ${t.auth}`,`--extras ${t.extras.length>0?t.extras.join(" "):"none"}`,`--microservices ${t.microservices.length>0?t.microservices.join(" "):"none"}`,`--addons ${t.addons.length>0?t.addons.join(" "):"none"}`,`--formatter ${t.formatter}`,`--install-dependencies ${t.installDependencies?"yes":"no"}`,t.initGit?"--git":"--no-git"];return t.addons.includes("ultracite")&&(t.ultraciteEditors.length>0&&e.push(`--ultracite-editors ${t.ultraciteEditors.join(" ")}`),t.ultraciteAgents.length>0&&e.push(`--ultracite-agents ${t.ultraciteAgents.join(" ")}`),t.ultraciteHooks.length>0&&e.push(`--ultracite-hooks ${t.ultraciteHooks.join(" ")}`),e.push(`--ultracite-install-skill ${t.ultraciteInstallSkill}`)),e.join(" ")}u($s,"buildReproducibleCommand");function Us(t){return{$schema:he.NEST_ARCH_SCHEMA_URL,addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth,createdAt:new Date().toISOString(),database:t.database,description:t.description,extras:t.extras,formatter:t.formatter,httpProvider:t.httpProvider,initGit:t.initGit,installDependencies:t.installDependencies,microservices:t.microservices,orm:t.orm,packageManager:t.packageManager,projectName:t.projectName,projectType:t.projectType,reproducibleCommand:$s(t),ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill,version:he.NEST_ARCH_VERSION}}u(Us,"buildMetadata");function Bs(t){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(`
120
+ `)+JSON.stringify(t,null,2)}
121
+ `}u(Bs,"serializeMetadata");function Js(){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","todo-example"]},type:"array"},formatter:{enum:["biome","eslint-prettier-stylelint","eslint-prettier-no-stylelint","oxlint-oxfmt","none"]},httpProvider:{enum:["express","fastify"]},initGit:{type:"boolean"},installDependencies:{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"},ultraciteAgents:{items:{enum:["universal","claude","codex","jules","replit","devin","lovable","zencoder","ona","openclaw","continue","snowflake-cortex","deepagents","qoder","kimi-cli","mcpjam","mux","pi","adal","copilot","cline","amp","aider","firebase-studio","open-hands","gemini","junie","augmentcode","kilo-code","goose","roo-code","warp","droid","opencode","crush","qwen","amazon-q-cli","firebender","cursor-cli","mistral-vibe","vercel"]},type:"array"},ultraciteEditors:{items:{enum:["universal","vscode","cursor","windsurf","antigravity","kiro","trae","void","bob","codebuddy","zed"]},type:"array"},ultraciteHooks:{items:{enum:["cursor","windsurf","codebuddy","claude","copilot"]},type:"array"},ultraciteInstallSkill:{enum:["yes","no"]},version:{type:"string"}},required:["version","createdAt","reproducibleCommand","projectName","packageManager","httpProvider","projectType","architecture","database","orm","api","auth","extras","microservices","addons","initGit","formatter","installDependencies","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"],title:"NestArchMetadata",type:"object"},null,2)}
122
+ `}u(Js,"buildSchemaContent");async function Hs(t,e,r,a,n){try{const s=Us(e),o=Bs(s),i=await t.writeFile({content:o,filePath:"nest-arch.jsonc",isBinary:!1},r);i.written&&a.push(i.filePath);const l=Js(),p=await t.writeFile({content:l,filePath:"schema.json",isBinary:!1},r);p.written&&a.push(p.filePath)}catch(s){const o=s instanceof Error?s.message:String(s);n.push(`Failed to generate nest-arch.jsonc/schema.json: ${o}`)}}u(Hs,"generateMetadata");const Ws={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:{"@apollo/server":"^4.11.0","@as-integrations/fastify":"^2.1.0","@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":"^11.0.0","@nestjs/microservices":"next","@nestjs/passport":"^11.0.0","@nestjs/platform-express":"next","@nestjs/platform-fastify":"next","@nestjs/swagger":"next","@nestjs/terminus":"next","@nestjs/throttler":"next","@nestjs/typeorm":"11.0.1","@prisma/adapter-better-sqlite3":"^7.8.0","@prisma/adapter-mariadb":"^7.8.0","@prisma/adapter-pg":"^7.8.0","@prisma/adapter-ppg":"^7.8.0","@prisma/client":"^7.8.0","@scalar/nestjs-api-reference":"^1.2.6","@t3-oss/env-core":"^0.13.11","@thallesp/nestjs-better-auth":"^2.6.1","@trpc/client":"^11.18.0","@trpc/openapi":"^11.18.0-alpha","@trpc/server":"^11.18.0",amqplib:"^0.10.5",bcrypt:"^5.1.1","better-auth":"^1.6.17","better-sqlite3":"^12.11.1",dotenv:"^17.2.2","drizzle-graphql":"^0.8.5","drizzle-orm":"^0.45.2",graphql:"^16.14.2",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-trpc":"^2.12.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","typeorm-relations-graphql":"^3.0.0",zod:"^4.4.3"},devDependencies:{"@nestjs/cli":"next","@nestjs/schematics":"next","@nestjs/testing":"next","@types/amqplib":"^0.10.6","@types/bcrypt":"^5.0.2","@types/better-sqlite3":"^7.6.13","@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.56.0",oxlint:"^1.71.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 Lt(){return Ws}u(Lt,"loadReference");function g(t){const e=Lt(),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 Vs(){return{...Lt().catalog}}u(Vs,"getCatalogDependencies");const Qs=[{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:".env.example",src:"base/.env.example.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/config/env.ts",src:"single-project/shared/config/env.ts.hbs"}],Ys={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},Xs={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},Ks=[{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:"test/app.e2e-spec.ts",src:"base/test/app.e2e-spec.ts.hbs"}],Zs=[{dest:"src/api/todo/todo.controller.ts",src:"feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs"},{dest:"src/api/todo/todo.service.ts",src:"feature/rest/todo-example/src/api/todo/todo.service.ts.hbs"},{dest:"src/api/todo/todo.module.ts",src:"feature/rest/todo-example/src/api/todo/todo.module.ts.hbs"},{dest:"src/api/todo/todo.router.ts",src:"feature/rest/todo-example/src/api/todo/todo.router.ts.hbs"},{dest:"src/api/todo/dto/create-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/create-todo.dto.ts.hbs"},{dest:"src/api/todo/dto/update-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/update-todo.dto.ts.hbs"}],ea=[{dest:"apps/api-gateway/src/api/todo/todo.controller.ts",src:"feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/todo.service.ts",src:"feature/rest/todo-example/src/api/todo/todo.service.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/todo.module.ts",src:"feature/rest/todo-example/src/api/todo/todo.module.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/todo.router.ts",src:"feature/rest/todo-example/src/api/todo/todo.router.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/dto/create-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/create-todo.dto.ts.hbs"},{dest:"apps/api-gateway/src/api/todo/dto/update-todo.dto.ts",src:"feature/rest/todo-example/src/api/todo/dto/update-todo.dto.ts.hbs"}],ta=[{dest:"src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"}],ra=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],sa=[{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"}],aa=[{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"}],oa=[{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"}],$t={"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"}]},Ut=[{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"}],na="package.json",ia=[{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.service.ts",src:"monorepo/apps/api-gateway/src/app.service.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"}],ca=[{dest:"apps/api-gateway/src/app.controller.ts",src:"monorepo/apps/api-gateway/src/app.controller.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"}],la=[{dest:"src/graphql/graphql.module.ts",src:"feature/graphql/src/graphql/graphql.module.ts.hbs"},{dest:"src/graphql/models/base.model.ts",src:"feature/graphql/src/graphql/models/base.model.ts.hbs"},{dest:"src/graphql/models/user.model.ts",src:"feature/graphql/src/graphql/models/user.model.ts.hbs"},{dest:"src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts",src:"feature/graphql/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts.hbs"},{dest:"src/graphql/orm/drizzle/drizzle-graphql.module.ts",src:"feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs"}],pa=[{dest:"src/graphql/dto/create-todo.input.ts",src:"feature/graphql/src/graphql/dto/create-todo.input.ts.hbs"},{dest:"src/graphql/dto/update-todo.input.ts",src:"feature/graphql/src/graphql/dto/update-todo.input.ts.hbs"},{dest:"src/graphql/models/todo.model.ts",src:"feature/graphql/src/graphql/models/todo.model.ts.hbs"},{dest:"src/graphql/resolvers/todo.resolver.ts",src:"feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs"}],ua=[{dest:"apps/api-gateway/src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"apps/api-gateway/src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"apps/api-gateway/src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"}],da=[{dest:"apps/api-gateway/src/graphql/graphql.module.ts",src:"monorepo/feature/graphql/src/graphql/graphql.module.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/base.model.ts",src:"monorepo/feature/graphql/src/graphql/models/base.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/user.model.ts",src:"monorepo/feature/graphql/src/graphql/models/user.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts",src:"monorepo/feature/graphql/src/graphql/orm/typeorm/typeorm-graphql-relations.helper.ts.hbs"},{dest:"apps/api-gateway/src/graphql/orm/drizzle/drizzle-graphql.module.ts",src:"monorepo/feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs"}],ma=[{dest:"apps/api-gateway/src/graphql/dto/create-todo.input.ts",src:"monorepo/feature/graphql/src/graphql/dto/create-todo.input.ts.hbs"},{dest:"apps/api-gateway/src/graphql/dto/update-todo.input.ts",src:"monorepo/feature/graphql/src/graphql/dto/update-todo.input.ts.hbs"},{dest:"apps/api-gateway/src/graphql/models/todo.model.ts",src:"monorepo/feature/graphql/src/graphql/models/todo.model.ts.hbs"},{dest:"apps/api-gateway/src/graphql/resolvers/todo.resolver.ts",src:"monorepo/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs"}],ha=[{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"}],ga={"addons/husky":ra,"extras/database":aa,"extras/docker":sa,"extras/swagger":[],"feature/graphql":la,"feature/graphql/todo-example":pa,"feature/rest":Ks,"feature/rest/todo-example":Zs,"feature/trpc":ta,"monorepo/apps/api-gateway":ia,"monorepo/feature/graphql":da,"monorepo/feature/graphql/todo-example":ma,"monorepo/feature/rest":ca,"monorepo/feature/rest/todo-example":ea,"monorepo/feature/trpc":ua,"monorepo/packages":ha,"monorepo/packages/db":oa,"monorepo/root":Ut};function Bt(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&&(e.bcrypt=g("bcrypt"),r["@types/bcrypt"]=g("@types/bcrypt"),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 a of t.api)a==="graphql"?(e["@nestjs/graphql"]=g("@nestjs/graphql"),e["@nestjs/apollo"]=g("@nestjs/apollo"),e.graphql=g("graphql"),e["@apollo/server"]=g("@apollo/server"),t.httpProvider==="fastify"?e["@as-integrations/fastify"]=g("@as-integrations/fastify"):e["@as-integrations/express5"]=g("@as-integrations/express5"),t.auth==="passport"&&(e["graphql-scalars"]=g("graphql-scalars")),t.orm.includes("typeorm")&&(e["typeorm-relations-graphql"]=g("typeorm-relations-graphql")),t.orm.includes("drizzle")&&(e["drizzle-graphql"]=g("drizzle-graphql"))):a==="trpc"&&(e["@trpc/server"]=g("@trpc/server"),e["@trpc/client"]=g("@trpc/client"),e["@trpc/openapi"]=g("@trpc/openapi"),e["nestjs-trpc"]=g("nestjs-trpc"));t.extras.includes("swagger")&&(e["@nestjs/swagger"]=g("@nestjs/swagger"),t.addons.includes("scalar-ui")&&(e["@scalar/nestjs-api-reference"]=g("@scalar/nestjs-api-reference"))),t.extras.includes("health-check")&&(e["@nestjs/terminus"]=g("@nestjs/terminus")),t.extras.includes("rate-limiting")&&(e["@nestjs/throttler"]=g("@nestjs/throttler"));for(const a of t.microservices)a==="redis"?e.ioredis=g("ioredis"):a==="mqtt"?e.mqtt=g("mqtt"):a==="nats"?e.nats=g("nats"):a==="rabbitmq"?(e.amqplib=g("amqplib"),r["@types/amqplib"]=g("@types/amqplib")):a==="kafka"?e.kafkajs=g("kafkajs"):a==="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"))}u(Bt,"addConditionalDependencies");function Jt(t,e,r){const a=t.orm.includes("prisma"),n=t.orm.includes("drizzle"),s=t.orm.includes("typeorm"),o=t.database.length>0&&!a&&!n&&!s;for(const i of t.orm)i==="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-mariadb"]=g("@prisma/adapter-mariadb")),t.database.includes("sqlite")&&(e["@prisma/adapter-better-sqlite3"]=g("@prisma/adapter-better-sqlite3"))):i==="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"))):i==="drizzle"&&(e["drizzle-orm"]=g("drizzle-orm"),r["drizzle-kit"]=g("drizzle-kit"));t.database.includes("postgresql")&&n&&(e.pg=g("pg"),r["@types/pg"]=g("@types/pg")),t.database.includes("mysql")&&n&&(e.mysql2=g("mysql2")),t.database.includes("sqlite")&&n&&(e["better-sqlite3"]=g("better-sqlite3"),r["@types/better-sqlite3"]=g("@types/better-sqlite3")),t.database.includes("mongodb")&&o&&(e.mongodb=g("mongodb"))}u(Jt,"addDatabaseDependencies");async function fa(t,e,r,a,n,s){try{const o=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":g("@nestjs/common"),"@nestjs/core":g("@nestjs/core"),[o]:g(o),"@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"};Bt(t,i,l),Jt(t,i,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:format"]="prisma format",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.api.includes("trpc")&&(p["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o src/libs/trpc/@generated",p["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o src/libs/trpc/@generated"),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:i,devDependencies:l},d=JSON.stringify(h,null,2),j=await r.writeFile({content:d,filePath:"package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});j.written&&n.push(j.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate package.json: ${i}`),console.error("Failed to generate package.json:",o)}}u(fa,"generateSingleProjectPackageJson");async function ba(t,e,r,a,n,s){try{const o={build:"turbo build","check-types":"turbo check-types",dev:"turbo dev"},i={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},l={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:g("turbo"),typescript:"catalog:"};t.addons.includes("ultracite")&&(o.check="ultracite check"),t.addons.includes("husky")&&(l.husky=g("husky"),o.prepare="husky");const h={bun:"bun@1.3.14",npm:void 0,pnpm:"pnpm@11.6.0",yarn:"yarn@4.6.0"}[t.packageManager],d={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:Vs()}:{},scripts:o,dependencies:i,devDependencies:l},j=JSON.stringify(d,null,2),I=await r.writeFile({content:j,filePath:na,isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});I.written&&n.push(I.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo root package.json: ${i}`),console.error("Failed to generate monorepo root package.json:",o)}}u(ba,"generateMonorepoRootPackageJson");async function ya(t,e,r,a,n,s){try{const o=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":g("@nestjs/common"),"@nestjs/core":g("@nestjs/core"),[o]:g(o),"@repo/env":"workspace:*","reflect-metadata":g("reflect-metadata"),rxjs:g("rxjs"),zod:"catalog:"};t.database.length>0&&(i["@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"};Bt(t,i,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.api.includes("trpc")&&(p["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated",p["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated");const h={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:p,dependencies:i,devDependencies:l},d=JSON.stringify(h,null,2),j=await r.writeFile({content:d,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});j.written&&n.push(j.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo app package.json: ${i}`),console.error("Failed to generate monorepo app package.json:",o)}}u(ya,"generateMonorepoAppPackageJson");async function wa(t,e,r,a,n,s){try{const o={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:"},i={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:"catalog:"};Jt(t,o,i);const l={};t.orm.includes("prisma")&&(l["prisma:generate"]="prisma generate",l["prisma:format"]="prisma format",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:o,devDependencies:i},h=JSON.stringify(p,null,2),d=await r.writeFile({content:h,filePath:"packages/db/package.json",isBinary:!1},{dryRun:a.dryRun,overwrite:a.overwrite});d.written&&n.push(d.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate monorepo db package.json: ${i}`),console.error("Failed to generate monorepo db package.json:",o)}}u(wa,"generateMonorepoDbPackageJson");async function ja(t,e,r,a,n){let s="postgresql";e.database.includes("mysql")?s="mysql":e.database.includes("sqlite")?s="sqlite":e.database.includes("mongodb")&&(s="mongodb");const o=["generator client {",' provider = "prisma-client"',' output = "./generated"',"}","","datasource db {",` provider = "${s}"`,"}",""],i=e.extras.includes("todo-example");e.auth==="passport"&&e.database.length>0&&o.push("enum Role {"," ADMIN"," USER","}","","model User {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," email String @unique"," password String"," firstname String?"," lastname String?"," role Role @default(USER)",...i?[" todos Todo[]",""]:[""],' @@map("user")',"}",""),i&&e.database.length>0&&(e.auth==="none"?o.push("model Todo {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)","",' @@map("todo")',"}",""):o.push("model Todo {"," id String @id @default(cuid())"," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)"," authorId String?"," author User? @relation(fields: [authorId], references: [id])","",' @@map("todo")',"}",""));const l=o.join(`
123
+ `);try{const p=await t.writeFile({content:l,filePath:"src/database/orm/prisma/schema.prisma",isBinary:!1},r);p.written&&a.push(p.filePath)}catch(p){const h=p instanceof Error?p.message:String(p);n.push(`Failed to generate src/database/orm/prisma/schema.prisma: ${h}`)}}u(ja,"generatePrismaSchema");function va(t,e){const r=!!e.usePrisma,a=!!e.useTypeorm,n=!!e.useDrizzle,s=!!e.useRawSql,o=!!e.hasPostgres,i=!!e.hasMysql,l=!!e.hasSqlite,p=!!e.hasMongodb;return t.filter(h=>{const{dest:d}=h;return d.includes("prisma-sql.adapter")?r&&(o||i||l):d.includes("prisma-mongo.adapter")?r&&p:d.includes("typeorm-sql.adapter")?a&&(o||i||l):d.includes("orm/typeorm/data-source")||d.includes("entities/")?a:d.includes("drizzle-sql.adapter")?n:d.includes("raw-sql.adapter")?s&&(o||i||l):d.includes("raw-mongo.adapter")?s&&p:d.includes("orm/drizzle/schema")?n:!0})}u(va,"filterDatabaseTemplates");function Sa(t,e){const r=!!e.hasTrpcAndAuth;return t.filter(a=>a.dest.includes("libs/trpc/protected.ts")||a.dest.includes("libs/trpc/inner.context.ts")||a.dest.includes("libs/middlewares/auth.trpc.middleware.ts")?r:!0)}u(Sa,"filterTrpcTemplates");function ka(t,e){const r=!!e.useTypeorm,a=!!e.usePrisma,n=!!e.useDrizzle;return t.filter(s=>{const{dest:o}=s;return o.includes("orm/typeorm")?r:o.includes("orm/prisma")?a:o.includes("orm/drizzle")?n:!0})}u(ka,"filterGraphqlTemplates");function Aa(t,e){const r=!!e.hasTrpc,a=!!e.hasRest;return t.filter(n=>n.dest.includes("todo.router.ts")?r:n.dest.includes("todo.controller.ts")?a:!0)}u(Aa,"filterTodoTemplates");class Ta{static{u(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(e,r){this.options=r,this.fileWriter=new Xr(e),this.templateEngine=new pt(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new ps,this.mapper=new Ue,qs(this.mapper)}getMapper(){return this.mapper}async generate(e){const r=Date.now(),a=[],n=[];try{const s=this.mapper.resolve(e);let o=Cs(e);o=_s(o,s.extraVariables),o.hasUltracite=e.addons.includes("ultracite"),o.hasHusky=e.addons.includes("husky"),o.hasAgentSkills=e.addons.includes("agent-skills"),await(e.projectType==="monorepo"?this.generateMonorepo.bind(this):this.generateSingleProject.bind(this))(e,o,s.templateGroups,a,n);const l=Date.now()-r,p=n.length===0;if(p){const h={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await Hs(this.fileWriter,e,h,a,n)}return console.log(`\u2705 Project generated in ${l}ms`),{error:p&&n.length===0?void 0:n.join(`
124
+ `),filesCount:a.length,generatedFiles:a,success:p&&n.length===0}}catch(s){return{error:s instanceof Error?s.message:"Unknown error",filesCount:0,generatedFiles:a,success:!1}}}async generateSingleProject(e,r,a,n,s){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite},i=[...Qs];r.packageManager==="pnpm"?i.push(Ys):r.packageManager==="yarn"&&i.push(Xs),await fa(e,r,this.fileWriter,o,n,s);for(const l of i)await this.renderAndWrite(l.src,l.dest,r,n,s);await this.processTemplateGroups(e,r,a,n,s),await this.processPostTemplateSteps(e,r,n,s)}async generateMonorepo(e,r,a,n,s){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await ba(e,r,this.fileWriter,o,n,s),await ya(e,r,this.fileWriter,o,n,s),e.database.length>0&&await wa(e,r,this.fileWriter,o,n,s),await this.processTemplateGroups(e,r,a,n,s),await this.processPostTemplateSteps(e,r,n,s)}async processTemplateGroups(e,r,a,n,s){const o=e.projectType==="monorepo",i=o?"monorepo/":"";for(const l of a){if(!o&&$t[l]){const d=$t[l];for(const j of d)j.dest==="package.json"||j.dest==="pnpm-workspace.yaml"||j.dest===".yarnrc.yml"||await this.renderAndWrite(j.src,j.dest,r,n,s);continue}if(o&&l==="monorepo/root"){for(const d of Ut)await this.renderAndWrite(d.src,d.dest,r,n,s);r.packageManager==="pnpm"?await this.renderAndWrite("monorepo/root/pnpm-workspace.yaml.hbs","pnpm-workspace.yaml",r,n,s):r.packageManager==="yarn"&&await this.renderAndWrite("monorepo/root/.yarnrc.yml.hbs",".yarnrc.yml",r,n,s);continue}if(!o&&l==="monorepo/packages/db")continue;const p=ga[l];if(!p)continue;let h=p;(l==="extras/database"||l==="monorepo/packages/db")&&(h=va(h,r)),l===`${i}feature/trpc`&&(h=Sa(h,r)),l===`${i}feature/graphql`&&(h=ka(h,r)),l===`${i}feature/rest/todo-example`&&(h=Aa(h,r));for(const d of h)o&&d.dest==="packages/db/package.json"||d.dest==="docker-compose.yml"&&e.database.length>0||await this.renderAndWrite(d.src,d.dest,r,n,s)}}async processPostTemplateSteps(e,r,a,n){const s={dryRun:this.options.dryRun,overwrite:this.options.overwrite},o=e.projectType==="monorepo"?"apps/api-gateway/src/docs/create-docs.ts":"src/docs/create-docs.ts";if(e.extras.includes("swagger")&&await this.renderAndWrite("extras/swagger/create-docs.ts.hbs",o,r,a,n),e.extras.includes("docker")&&e.database.length>0){const i=Fs(e),l=await this.fileWriter.writeFile({content:i,filePath:"docker-compose.yml",isBinary:!1},s);l.written&&a.push(l.filePath)}if(e.orm.includes("prisma")&&(await ja(this.fileWriter,e,s,a,n),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,a,n)),e.orm.includes("drizzle")&&await Ls(this.fileWriter,e,s,a,n),e.auth!=="none"){const i=Ms.composeGenerators(e),l=await Ns(e,this.fileWriter.getBaseDir(),i);for(const p of l)!p.success&&p.error&&n.push(p.error)}}async renderAndWrite(e,r,a,n,s){try{const o=await this.templateEngine.renderToFile(e,r,{context:a}),i=await this.fileWriter.writeFile(o,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});i.written&&n.push(i.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);s.push(`Failed to generate ${r}: ${i}`),console.error(`Failed to generate ${r}:`,o)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}const Pa=/Resolved|Resolving/iu,Ea=/Downloaded?|downloaded/iu,Ra=/Link(ed|ing)/iu,qa=/saved (to )?(lockfile|bun)/iu;function xa(t){const e=[],r=t.split(`
125
+ `);for(const a of r){const n=a.trim();if(n){if(Pa.test(n)){e.push({message:"Resolving packages...",phase:"resolve"});continue}if(Ea.test(n)){e.push({message:"Downloading...",phase:"download"});continue}if(Ra.test(n)){e.push({message:"Linking packages...",phase:"link"});continue}if(n.includes("packages installed")){e.push({message:n,percentage:100,phase:"link"});continue}if(qa.test(n)){e.push({message:"Saving lockfile...",phase:"postinstall"});continue}(n.includes("[script]")||n.includes("postinstall"))&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}}return e}u(xa,"parseBunText");class Ia{static{u(this,"BunInstaller")}async install(e,r,a){const n=Ce("bun install",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";const o=u(l=>{const p=l.toString();s+=p;const h=xa(p);for(const d of h)r?.(d)},"handleData");n.stderr.on("data",o),n.stdout.on("data",o);const[i]=await Promise.race([re(n,"close"),re(n,"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(`
126
+ `)):new Error(p.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`bun install exited with code ${i}`)}}const Oa=/^(\d+)\/(\d+)\s+resolving/iu,Ca=/^(\d+)\/(\d+)\s+extract:/iu,_a=/^(\d+)\/(\d+)\s+(\S+)/iu,Ga=/^(\d+)ms\s+(.*)/iu;function za(t){const e=[],r=t.split(`
127
+ `);for(const a of r){const n=a.trim();if(n.includes("resolving")){const s=Oa.exec(n);s?e.push({completed:Number(s[1]),message:"Resolving packages...",percentage:Math.round(Number(s[1])/Number(s[2])*100),phase:"resolve",total:Number(s[2])}):e.push({message:"Resolving packages...",phase:"resolve"});continue}if(n.includes("extract:")||n.includes("http fetch")){const s=Ca.exec(n)||_a.exec(n);s?e.push({completed:Number(s[1]),message:"Downloading...",percentage:Math.round(Number(s[1])/Number(s[2])*100),phase:"download",total:Number(s[2])}):e.push({message:"Downloading...",phase:"download"});continue}if(n.includes("timing")){const s=Ga.exec(n);if(s){const o=s[2]??"";o.includes("build")?e.push({message:"Building dependencies...",phase:"build"}):o.includes("link")&&e.push({message:"Linking packages...",phase:"link"})}continue}n.includes("postinstall")&&!n.includes("timing")&&e.push({message:"Running postinstall scripts...",phase:"postinstall"})}return e}u(za,"parseNpmText");class Da{static{u(this,"NpmInstaller")}async install(e,r,a){const n=Ce("npm install --loglevel silly",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";const o=u(l=>{const p=l.toString();s+=p;const h=za(p);for(const d of h)r?.(d)},"handleData");n.stderr.on("data",o),n.stdout.on("data",()=>{});const[i]=await Promise.race([re(n,"close"),re(n,"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(`
128
+ `)):new Error(p.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`npm install exited with code ${i}`)}}function Ma(t,e){const r=e?.status,a=e?.progress;switch(r){case"resolving":return{message:"Resolving packages...",percentage:a??0,phase:"resolve"};case"downloading":case"fetching":return{message:"Downloading...",percentage:a??e?.progress,phase:"download"};case"linking":return{message:"Linking packages...",percentage:a??0,phase:"link"};case"build":return{message:"Building dependencies...",percentage:a??0,phase:"build"};default:return{message:r||"Installing dependencies...",percentage:a??0,phase:"download"}}}u(Ma,"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 Fa(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(Fa,"mapPnpmFetching");function La(t){if(!t.type)return null;switch(t.type){case"stage":{const e=t.data?.stage;return e?Ma(e,t.data):null}case"stat":return Na(t.data);case"fetching":return Fa(t);case"warning":case"error":return{message:t.message??t.type,phase:"download"};default:return null}}u(La,"parsePnpmLine");class $a{static{u(this,"PnpmInstaller")}async install(e,r,a){const n=Ce("pnpm install --reporter ndjson",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";n.stdout.on("data",i=>{const l=i.toString().split(`
129
+ `).filter(Boolean);for(const p of l)try{const h=JSON.parse(p),d=La(h);d&&r&&r(d)}catch{}}),n.stderr.on("data",i=>{s+=i.toString()});const[o]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const l=i;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(`
130
+ `)):new Error(l.message)})]);if(o===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`pnpm install exited with code ${o}`)}}function Ua(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,a=e?.total;return r!==void 0&&a!==void 0?{completed:r,message:"Processing...",percentage:Math.round(r/a*100),phase:"download",total:a}: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(Ua,"parseYarnLine");class Ba{static{u(this,"YarnInstaller")}async install(e,r,a){const n=Ce("yarn install --json",[],{cwd:e,shell:!0,signal:a,stdio:["ignore","pipe","pipe"]});let s="";n.stdout.on("data",i=>{const l=i.toString().split(`
131
+ `).filter(Boolean);for(const p of l)try{const h=JSON.parse(p),d=Ua(h);d&&r&&r(d)}catch{}}),n.stderr.on("data",i=>{s+=i.toString()});const[o]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const l=i;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(`
132
+ `)):new Error(l.message)})]);if(o===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(s.trim()||`yarn install exited with code ${o}`)}}function Ja(t){switch(t){case"pnpm":return new $a;case"npm":return new Da;case"yarn":return new Ba;case"bun":return new Ia;default:throw new Error(`Unhandled package manager: ${t}`)}}u(Ja,"createPackageInstaller");class Ha{static{u(this,"ProjectPipeline")}outputDir;generatorOptions;constructor(e,r){this.outputDir=e,this.generatorOptions=r}async execute(e,r){const a=[],n=[],s=u(d=>{r?.onStageChange?.(d)},"emitStage"),o=u(d=>{a.push(d)},"addPhase");s("generate-files");const i=new Ta(this.outputDir,this.generatorOptions);try{const d=await i.generate(e);if(n.push(...d.generatedFiles),!d.success)return o({error:d.error,phase:"generate-files",success:!1}),this.buildResult(!1,a,n);o({phase:"generate-files",success:!0})}catch(d){return o({error:d instanceof Error?d.message:String(d),phase:"generate-files",success:!1}),this.buildResult(!1,a,n)}if(e.addons.includes("agent-skills")){s("install-agent-skills");try{const d=await Yr(this.outputDir,e);if(d.failed.length>0){const j=d.failed.map(I=>`${I.name}: ${I.error}`).join(", ");o({error:j,phase:"install-agent-skills",success:!0})}else o({phase:"install-agent-skills",success:!0})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"install-agent-skills",success:!0})}}else o({phase:"install-agent-skills",skipped:!0,success:!0});if(e.formatter!=="none"){s("setup-linter");try{const d=await ls(this.outputDir,e);if(!d.success)return o({error:d.message,phase:"setup-linter",success:!1}),this.buildResult(!1,a,n);const j=await hs(this.outputDir,e.formatter);if(!j.success)return o({error:j.message??"Rule injection failed",phase:"setup-linter",success:!1}),this.buildResult(!1,a,n);o({phase:"setup-linter",success:!0})}catch(d){return o({error:d instanceof Error?d.message:String(d),phase:"setup-linter",success:!1}),this.buildResult(!1,a,n)}}else o({phase:"setup-linter",skipped:!0,success:!0});if(e.initGit){s("initialize-git");try{await es(this.outputDir)||await Kr(this.outputDir),o({phase:"initialize-git",success:!0})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"initialize-git",success:!1})}if(a[2]?.success){s("initial-commit");try{await zt(this.outputDir),await Dt(this.outputDir,"Initial project scaffold"),o({phase:"initial-commit",success:!0})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"initial-commit",success:!1})}}else o({phase:"initial-commit",skipped:!0,success:!0})}else o({phase:"initialize-git",skipped:!0,success:!0}),o({phase:"initial-commit",skipped:!0,success:!0});let l=!1;if(e.installDependencies){s("install-dependencies");try{await Ja(e.packageManager).install(this.outputDir,j=>{r?.onInstallProgress?.(j)}),l=!0,o({phase:"install-dependencies",success:!0})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"install-dependencies",success:!1})}}else o({phase:"install-dependencies",skipped:!0,success:!0});if(l&&e.formatter!=="none"){s("run-formatter");try{const d=await as(e.packageManager,this.outputDir);d.success?o({phase:"run-formatter",success:!0}):o({error:d.error,phase:"run-formatter",success:!1})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"run-formatter",success:!1})}}else o({phase:"run-formatter",skipped:!0,success:!0});const{5:p}=a;if(e.initGit&&p?.success&&!p.skipped){s("formatter-commit");try{await zt(this.outputDir),await Zr(this.outputDir)&&await Dt(this.outputDir,"Apply formatter"),o({phase:"formatter-commit",success:!0})}catch(d){o({error:d instanceof Error?d.message:String(d),phase:"formatter-commit",success:!1})}}else o({phase:"formatter-commit",skipped:!0,success:!0});s("complete");const h=a.every(d=>d.success||d.skipped);return this.buildResult(h,a,n)}buildResult(e,r,a){return{generatedFiles:a,outputDir:this.outputDir,phases:r,success:e}}}function Wa(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(Wa,"buildGeneratorContext");function Le(t){return he.NEST_ARCH_BETA_MODE?Q(ht(),"test-projects",t):Q(process.cwd(),t)}u(Le,"getOutputDir");function Va(){const t=import.meta.dirname;if(t){const r=Q(t,"templates");if(ke(r))return r}return Q(t??process.cwd(),"..","..","..","..","packages","core","templates")}u(Va,"getTemplatesDir");async function Ht(t,e){const r=Le(t.projectName),a=Wa(t),n=Va(),s=new Ha(r,{cacheTemplates:!0,templatesDir:n});try{const o=await s.execute(a,e),i={"formatter-commit":"Commit formatting","generate-files":"Generate project","initial-commit":"Initial commit","initialize-git":"Initialize Git","install-dependencies":"Install dependencies","run-formatter":"Run formatter","setup-linter":"Setup linter"},l=o.phases.filter(p=>!p.success&&!p.skipped&&p.error).map(p=>`${i[p.phase]||p.phase} failed:
133
+ ${p.error}`);return l.length>0?{message:l.join(`
134
134
 
135
- `),outputDir:r,success:!1}:{message:`Project created with ${o.generatedFiles.length} files`,outputDir:r,success:!0}}catch(o){return{message:`Failed to generate project: ${o instanceof Error?o.message:String(o)}`,outputDir:r,success:!1}}}u(Jt,"generateProject");const Da=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 Ht(t){return!t.packageManager||!t.formatter||!t.httpProvider||!t.projectType||!t.architecture||!t.initGit||!t.installDependencies?null:{addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth??"none",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:De(t.database)?[]:t.orm,packageManager:t.packageManager,projectName:ne(t.projectName),projectType:t.projectType,ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill??"no"}}u(Ht,"buildResult");const Ma=u(({onBack:t,onExit:e,onStepChange:r})=>{const[a,n]=C("projectName"),[s,o]=C(Da),[i,c]=C(null),[p,g]=C(null),[m,f]=C(null),[O,x]=C(null),U=W(()=>rt(s),[s]),F=W(()=>Or(a,s),[a,s]),_=W(()=>Cr(a,s),[a,s]),N=W(()=>{const b=new Set;return s.initGit==="no"&&(b.add("initialize-git"),b.add("initial-commit")),s.installDependencies==="no"&&b.add("install-dependencies"),(s.formatter==="none"||s.installDependencies==="no")&&(b.add("setup-linter"),b.add("run-formatter")),(s.initGit==="no"||b.has("run-formatter"))&&b.add("formatter-commit"),[...b]},[s.initGit,s.installDependencies,s.formatter]);ut(()=>{if(!p||p.isError)return;const b=Ht(s);b&&zt(b),n("done"),r?.("done")},[p,s,r]);const S=T(b=>{const y=_r(a,b);y&&(n(y),r?.(y))},[a,r]),$=T(()=>{const b=zr(a,s);if(b){n(b),r?.(b);return}t()},[t,s,a,r]),Z=T(()=>{const b=ze(s.projectName);if(b){c(b);return}const y=ne(s.projectName),G=Le(y);if(Se(G)){c(`Directory "${G}" already exists. Choose a different name or delete the existing directory.`);return}const A={...s,projectName:y};o(A),S(A)},[S,s]),k=T(b=>{const y={...s,packageManager:b};o(y),S(y)},[S,s]),I=T(b=>{const y={...s,formatter:b};o(y),S(y)},[S,s]),D=T(b=>{const y={...s,httpProvider:b};o(y),S(y)},[S,s]),V=T(b=>{const y=b==="single"&&s.architecture==="nest-gateway"?Ot():s.architecture??Ot(),G={...s,architecture:y,extras:b==="single"?s.extras.filter(A=>A!=="packages/shared"):s.extras,microservices:y==="nest-gateway"?s.microservices:[],projectType:b};o(G),S(G)},[S,s]),ee=T(b=>{const y={...s,architecture:b,microservices:b==="nest-gateway"?s.microservices:[]};o(y),S(y)},[S,s]),ge=T(b=>{const y=b==="none"?[]:[b],G=_t(s.orm,y),A=y.length===0,B={...s,api:A?s.api.filter(we=>we!=="graphql"):s.api,auth:A&&s.auth==="better-auth"?null:s.auth,database:y,orm:G};o(B),S(B)},[S,s]),fe=T(b=>{const y=b==="none"?[]:[b],G=Lr(s.database,y),A={...s,database:G,orm:_t(y,G)};o(A),S(A)},[S,s]),ye=T(b=>{const y=Ge(b),G={...s,addons:y?s.addons:s.addons.filter(A=>A!=="scalar-ui"),api:b,auth:y?s.auth:null,extras:y?s.extras:s.extras.filter(A=>A==="docker"||A==="packages/shared")};o(G),S(G)},[S,s]),be=T(b=>{const y={...s,auth:b};o(y),S(y)},[S,s]),ie=T(b=>{const y=b.includes("swagger"),G={...s,addons:y?s.addons:s.addons.filter(A=>A!=="scalar-ui"),extras:b};o(G),S(G)},[S,s]),Ee=W(()=>{const b=s.projectType==="monorepo"?et:et.filter(y=>y.value!=="packages/shared");return Ge(s.api)?b:b.filter(y=>y.value==="docker"||y.value==="packages/shared")},[s.projectType,s.api]),E=T(b=>{const y={...s,microservices:b};o(y),S(y)},[S,s]),X=T(b=>{const y={...s,addons:b};o(y),S(y)},[S,s]),ce=T(b=>{const y={...s,ultraciteEditors:b};o(y),S(y)},[S,s]),te=T(b=>{const y={...s,ultraciteAgents:b};o(y),S(y)},[S,s]),z=T(b=>{const y={...s,ultraciteHooks:b};o(y),S(y)},[S,s]),se=T(b=>{const y={...s,ultraciteInstallSkill:b};o(y),S(y)},[S,s]),$e=T(b=>{const y={...s,initGit:b};o(y),S(y)},[S,s]),R=T(b=>{const y={...s,installDependencies:b};o(y),S(y)},[S,s]),Re=T(async()=>{const b=Ht(s);if(b){n("installing"),r?.("installing");try{const y=await Jt(b,{onInstallProgress:u(G=>{x(G)},"onInstallProgress"),onStageChange:u(G=>{f(G)},"onStageChange")});g({isError:!y.success,message:y.message})}catch(y){g({isError:!0,message:`Error: ${y instanceof Error?y.message:String(y)}`})}}},[s,r]),Be=T(()=>{n("summary"),r?.("summary"),g(null)},[r]),qe=W(()=>a==="projectName"||a==="summary"?"confirm":a==="database"||a==="orm"||a==="apiLayer"||a==="extras"||a==="microservices"||a==="addons"||a==="ultraciteEditors"||a==="ultraciteAgents"||a==="ultraciteHooks"?"select":a==="installing"&&p?.isError?"confirm":"select",[a,p?.isError]);return{architectureOpts:W(()=>Gr(s.projectType),[s.projectType]),currentStage:m,displayStep:F,extrasStepOptions:Ee,generationStatus:p,goBack:$,handleAddons:X,handleApi:ye,handleArchitecture:ee,handleAuth:be,handleDatabase:ge,handleExtras:ie,handleFormatter:I,handleHttpProvider:D,handleInitGit:$e,handleInstallDependencies:R,handleMicroservices:E,handleOrm:fe,handlePackageManager:k,handleProjectNameSubmit:Z,handleProjectType:V,handleRetry:Be,handleSummaryConfirm:Re,handleUltraciteAgents:te,handleUltraciteEditors:ce,handleUltraciteHooks:z,handleUltraciteInstallSkill:se,installProgress:O,projectNameError:i,setProjectNameError:c,setState:o,skippedStages:N,state:s,statusAction:qe,stepId:a,subProgress:_,totalSteps:U}},"useCreateProjectWizard"),Na=u(({onBack:t,onDone:e,onExit:r,onStepChange:a})=>{const{architectureOpts:n,currentStage:s,displayStep:o,extrasStepOptions:i,generationStatus:c,goBack:p,handleProjectNameSubmit:g,handlePackageManager:m,handleFormatter:f,handleHttpProvider:O,handleProjectType:x,handleArchitecture:U,handleDatabase:F,handleOrm:_,handleApi:N,handleAuth:S,handleExtras:$,handleMicroservices:Z,handleAddons:k,handleUltraciteEditors:I,handleUltraciteAgents:D,handleUltraciteHooks:V,handleUltraciteInstallSkill:ee,handleInitGit:ge,handleInstallDependencies:fe,handleRetry:ye,handleSummaryConfirm:be,installProgress:ie,projectNameError:Ee,setProjectNameError:E,setState:X,skippedStages:ce,statusAction:te,stepId:z,subProgress:se,totalSteps:$e,state:R}=Ma({onBack:t,onExit:r,onStepChange:a}),[Re,Be]=C([]),[qe]=C([]),pt=W(()=>qt.filter(A=>!(A.value==="ultracite"&&R.formatter==="none"||A.value==="scalar-ui"&&!R.extras.includes("swagger"))),[R.formatter,R.extras]),b=W(()=>{let A=R;return z==="addons"&&(A={...A,addons:Re}),z==="database"&&(A={...A,database:qe}),rt(A)},[z,R,Re,qe,$e]);ae(()=>{z==="done"&&e()},[z,e]),le((A,B)=>{if(B.ctrl&&A==="c"){r();return}if(B.ctrl&&A==="b"&&z!=="done"){p();return}if(z==="done"&&B.return){r();return}z==="installing"&&c?.isError&&B.return&&ye()});const y=u(()=>{switch(z){case"projectName":return l(kt,{error:Ee,onChange:u(A=>{X(B=>({...B,projectName:A})),E(ze(A))},"onChange"),onSubmit:g,value:R.projectName});case"packageManager":return l(Y,{onConfirm:m,options:At,prompt:"Choose a package manager"},"packageManager");case"formatter":return l(Y,{onConfirm:f,options:Tt,prompt:"Choose a formatter-linter (with ultracite preset) setup"},"formatter");case"httpProvider":return l(Y,{onConfirm:O,options:Pt,prompt:"Choose an HTTP provider"},"httpProvider");case"projectType":return l(Y,{onConfirm:x,options:Et,prompt:"Choose a project layout"},"projectType");case"architecture":return l(Y,{onConfirm:U,options:n,prompt:"Choose an application architecture"},"architecture");case"database":{const B=[{description:"Skip database scaffolding for now",label:"No database",value:"none"},...Dr(R.orm)];return l(Y,{initialValue:R.database[0]??"none",onConfirm:F,options:B,prompt:"Select a database for your project (optional)"},"database")}case"orm":{const A=Ct(R.database),we=[{description:"Use plain database access without an ORM",label:"No ORM",value:"none"},...A];return l(Y,{initialValue:R.orm[0]??"none",onConfirm:_,options:we,prompt:"Select an ORM to include"},"orm")}case"apiLayer":{const A=R.architecture==="nest-api"&&R.api.length===0?["rest"]:R.api,B=Nr(R.database);return l(oe,{initialSelected:A,onConfirm:N,options:B,prompt:"Select API layers (optional)"},"apiLayer")}case"auth":{const A=Mr(R.database);return l(Y,{onConfirm:S,options:A,prompt:"Choose an authentication strategy"},"auth")}case"extras":return l(oe,{initialSelected:R.extras,onConfirm:$,options:i,prompt:"Select extras (optional)"},"extras");case"microservices":return l(oe,{initialSelected:R.microservices,onConfirm:Z,options:kr,prompt:"Select microservice communication protocols"},"microservices");case"addons":return l(oe,{initialSelected:R.addons,onConfirm:k,onChange:Be,options:pt,prompt:"Select addons (optional)"},"addons");case"ultraciteEditors":return l(oe,{initialSelected:R.ultraciteEditors,onConfirm:I,options:Tr,prompt:"Select Ultracite editors",minified:!0},"ultraciteEditors");case"ultraciteAgents":return l(oe,{initialSelected:R.ultraciteAgents,onConfirm:D,options:Pr,prompt:"Select Ultracite agents",minified:!0},"ultraciteAgents");case"ultraciteHooks":return l(oe,{initialSelected:R.ultraciteHooks,onConfirm:V,options:Er,prompt:"Select Ultracite hooks"},"ultraciteHooks");case"ultraciteInstallSkill":return l(Y,{onConfirm:ee,options:Rr,prompt:"Install Ultracite skill?"},"ultraciteInstallSkill");case"initGit":return l(Y,{onConfirm:ge,options:xt,prompt:"Initialize a git repository?"},"initGit");case"installDependencies":return l(Y,{onConfirm:fe,options:Ar,prompt:"Install dependencies?"},"installDependencies");case"summary":return l(Fr,{onConfirm:be,state:R});case"installing":return j(w,{flexDirection:"column",children:[l(wt,{currentStage:s,generationMessage:c?.message??"Scaffolding your project",installProgress:ie,isError:c?.isError??!1,packageManager:R.packageManager??void 0,skippedStages:ce}),c?.isError?l(w,{marginTop:1,children:j(d,{color:q,children:["Press ",l(d,{color:P,children:"Enter"})," to go back to Summary and retry, or ",l(d,{color:q,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const A=ne(R.projectName),B=R.initGit==="yes",we=Le(A),Qt=R.installDependencies==="yes";return l(jt,{architecture:R.architecture||"nest-api",projectName:A,packageManager:R.packageManager||"pnpm",dependenciesInstalled:Qt,isGitInitialized:B,outputDir:we})}default:return null}},"renderStep"),G=z!=="installing"&&z!=="done";return j(w,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[G?j(L,{children:[l(Ur,{state:R,stepId:z}),l(w,{height:0}),l($r,{displayStep:o,stepId:z,subProgress:se??void 0,totalSteps:b}),l(w,{height:2})]}):null,y(),l(w,{flexGrow:1}),G?j(L,{children:[l(Ae,{}),l(w,{height:1}),l(Qe,{action:te,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),it=` _ _ ___ ___ _____ _ ___ ___ _ _
135
+ `),outputDir:r,success:!1}:{message:`Project created with ${o.generatedFiles.length} files`,outputDir:r,success:!0}}catch(o){return{message:`Failed to generate project: ${o instanceof Error?o.message:String(o)}`,outputDir:r,success:!1}}}u(Ht,"generateProject");const Qa=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 Wt(t){return!t.packageManager||!t.formatter||!t.httpProvider||!t.projectType||!t.architecture||!t.initGit||!t.installDependencies?null:{addons:t.addons,api:t.api,architecture:t.architecture,auth:t.auth??"none",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:Ne(t.database)?[]:t.orm,packageManager:t.packageManager,projectName:ie(t.projectName),projectType:t.projectType,ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill??"no"}}u(Wt,"buildResult");const Ya=u(({onBack:t,onExit:e,onStepChange:r})=>{const[a,n]=O("projectName"),[s,o]=O(Qa),[i,l]=O(null),[p,h]=O(null),[d,j]=O(null),[I,M]=O(null),$=J(()=>st(s),[s]),L=J(()=>Cr(a,s),[a,s]),C=J(()=>Or(a,s),[a,s]),F=J(()=>{const b=new Set;return s.initGit==="no"&&(b.add("initialize-git"),b.add("initial-commit")),s.installDependencies==="no"&&b.add("install-dependencies"),(s.formatter==="none"||s.installDependencies==="no")&&(b.add("setup-linter"),b.add("run-formatter")),(s.initGit==="no"||b.has("run-formatter"))&&b.add("formatter-commit"),s.addons.includes("agent-skills")||b.add("install-agent-skills"),[...b]},[s.initGit,s.installDependencies,s.formatter,s.addons]);dt(()=>{if(!p||p.isError)return;const b=Wt(s);b&&Gt(b),n("done"),r?.("done")},[p,s,r]);const S=T(b=>{const f=_r(a,b);f&&(n(f),r?.(f))},[a,r]),U=T(()=>{const b=Gr(a,s);if(b){n(b),r?.(b);return}t()},[t,s,a,r]),Z=T(()=>{const b=De(s.projectName);if(b){l(b);return}const f=ie(s.projectName),G=Le(f);if(ke(G)){l(`Directory "${G}" already exists. Choose a different name or delete the existing directory.`);return}const A={...s,projectName:f};o(A),S(A)},[S,s]),k=T(b=>{const f={...s,packageManager:b};o(f),S(f)},[S,s]),x=T(b=>{const f={...s,formatter:b};o(f),S(f)},[S,s]),z=T(b=>{const f={...s,httpProvider:b};o(f),S(f)},[S,s]),V=T(b=>{const f=b==="single"&&s.architecture==="nest-gateway"?Ct():s.architecture??Ct(),G={...s,architecture:f,extras:b==="single"?s.extras.filter(A=>A!=="packages/shared"):s.extras,microservices:f==="nest-gateway"?s.microservices:[],projectType:b};o(G),S(G)},[S,s]),ee=T(b=>{const f={...s,architecture:b,microservices:b==="nest-gateway"?s.microservices:[]};o(f),S(f)},[S,s]),be=T(b=>{const f=b==="none"?[]:[b],G=_t(s.orm,f),A=f.length===0,B={...s,api:A?s.api.filter(ve=>ve!=="graphql"):s.api,auth:A&&s.auth==="better-auth"?null:s.auth,database:f,orm:G};o(B),S(B)},[S,s]),ye=T(b=>{const f=b==="none"?[]:[b],G=Fr(s.database,f),A={...s,database:G,orm:_t(f,G)};o(A),S(A)},[S,s]),we=T(b=>{const f=Me(b),G={...s,addons:f?s.addons:s.addons.filter(A=>A!=="scalar-ui"),api:b,auth:f?s.auth:null,extras:f?s.extras:s.extras.filter(A=>A==="docker"||A==="packages/shared")};o(G),S(G)},[S,s]),je=T(b=>{const f={...s,auth:b};o(f),S(f)},[S,s]),ce=T(b=>{const f=b.includes("swagger"),G={...s,addons:f?s.addons:s.addons.filter(A=>A!=="scalar-ui"),extras:b};o(G),S(G)},[S,s]),Re=J(()=>{const b=s.projectType==="monorepo"?tt:tt.filter(f=>f.value!=="packages/shared");return Me(s.api)?b:b.filter(f=>f.value==="docker"||f.value==="packages/shared")},[s.projectType,s.api]),E=T(b=>{const f={...s,microservices:b};o(f),S(f)},[S,s]),X=T(b=>{const f={...s,addons:b};o(f),S(f)},[S,s]),le=T(b=>{const f={...s,ultraciteEditors:b};o(f),S(f)},[S,s]),te=T(b=>{const f={...s,ultraciteAgents:b};o(f),S(f)},[S,s]),_=T(b=>{const f={...s,ultraciteHooks:b};o(f),S(f)},[S,s]),se=T(b=>{const f={...s,ultraciteInstallSkill:b};o(f),S(f)},[S,s]),Be=T(b=>{const f={...s,initGit:b};o(f),S(f)},[S,s]),R=T(b=>{const f={...s,installDependencies:b};o(f),S(f)},[S,s]),qe=T(async()=>{const b=Wt(s);if(b){n("installing"),r?.("installing");try{const f=await Ht(b,{onInstallProgress:u(G=>{M(G)},"onInstallProgress"),onStageChange:u(G=>{j(G)},"onStageChange")});h({isError:!f.success,message:f.message})}catch(f){h({isError:!0,message:`Error: ${f instanceof Error?f.message:String(f)}`})}}},[s,r]),Je=T(()=>{n("summary"),r?.("summary"),h(null)},[r]),xe=J(()=>a==="projectName"||a==="summary"?"confirm":a==="database"||a==="orm"||a==="apiLayer"||a==="extras"||a==="microservices"||a==="addons"||a==="ultraciteEditors"||a==="ultraciteAgents"||a==="ultraciteHooks"?"select":a==="installing"&&p?.isError?"confirm":"select",[a,p?.isError]);return{architectureOpts:J(()=>zr(s.projectType),[s.projectType]),currentStage:d,displayStep:L,extrasStepOptions:Re,generationStatus:p,goBack:U,handleAddons:X,handleApi:we,handleArchitecture:ee,handleAuth:je,handleDatabase:be,handleExtras:ce,handleFormatter:x,handleHttpProvider:z,handleInitGit:Be,handleInstallDependencies:R,handleMicroservices:E,handleOrm:ye,handlePackageManager:k,handleProjectNameSubmit:Z,handleProjectType:V,handleRetry:Je,handleSummaryConfirm:qe,handleUltraciteAgents:te,handleUltraciteEditors:le,handleUltraciteHooks:_,handleUltraciteInstallSkill:se,installProgress:I,projectNameError:i,setProjectNameError:l,setState:o,skippedStages:F,state:s,statusAction:xe,stepId:a,subProgress:C,totalSteps:$}},"useCreateProjectWizard"),Xa=u(({onBack:t,onDone:e,onExit:r,onStepChange:a})=>{const{architectureOpts:n,currentStage:s,displayStep:o,extrasStepOptions:i,generationStatus:l,goBack:p,handleProjectNameSubmit:h,handlePackageManager:d,handleFormatter:j,handleHttpProvider:I,handleProjectType:M,handleArchitecture:$,handleDatabase:L,handleOrm:C,handleApi:F,handleAuth:S,handleExtras:U,handleMicroservices:Z,handleAddons:k,handleUltraciteEditors:x,handleUltraciteAgents:z,handleUltraciteHooks:V,handleUltraciteInstallSkill:ee,handleInitGit:be,handleInstallDependencies:ye,handleRetry:we,handleSummaryConfirm:je,installProgress:ce,projectNameError:Re,setProjectNameError:E,setState:X,skippedStages:le,statusAction:te,stepId:_,subProgress:se,totalSteps:Be,state:R}=Ya({onBack:t,onExit:r,onStepChange:a}),[qe,Je]=O([]),[xe]=O([]),ut=J(()=>qt.filter(A=>!(A.value==="ultracite"&&R.formatter==="none"||A.value==="scalar-ui"&&!R.extras.includes("swagger"))),[R.formatter,R.extras]),b=J(()=>{let A=R;return _==="addons"&&(A={...A,addons:qe}),_==="database"&&(A={...A,database:xe}),st(A)},[_,R,qe,xe,Be]);ae(()=>{_==="done"&&e()},[_,e]),pe((A,B)=>{if(B.ctrl&&A==="c"){r();return}if(B.ctrl&&A==="b"&&_!=="done"){p();return}if(_==="done"&&B.return){r();return}_==="installing"&&l?.isError&&B.return&&we()});const f=u(()=>{switch(_){case"projectName":return c(kt,{error:Re,onChange:u(A=>{X(B=>({...B,projectName:A})),E(De(A))},"onChange"),onSubmit:h,value:R.projectName});case"packageManager":return c(Y,{onConfirm:d,options:At,prompt:"Choose a package manager"},"packageManager");case"formatter":return c(Y,{onConfirm:j,options:Tt,prompt:"Choose a formatter-linter (with ultracite preset) setup"},"formatter");case"httpProvider":return c(Y,{onConfirm:I,options:Pt,prompt:"Choose an HTTP provider"},"httpProvider");case"projectType":return c(Y,{onConfirm:M,options:Et,prompt:"Choose a project layout"},"projectType");case"architecture":return c(Y,{onConfirm:$,options:n,prompt:"Choose an application architecture"},"architecture");case"database":{const B=[{description:"Skip database scaffolding for now",label:"No database",value:"none"},...Dr(R.orm)];return c(Y,{initialValue:R.database[0]??"none",onConfirm:L,options:B,prompt:"Select a database for your project (optional)"},"database")}case"orm":{const A=Ot(R.database),ve=[{description:"Use plain database access without an ORM",label:"No ORM",value:"none"},...A];return c(Y,{initialValue:R.orm[0]??"none",onConfirm:C,options:ve,prompt:"Select an ORM to include"},"orm")}case"apiLayer":{const A=R.architecture==="nest-api"&&R.api.length===0?["rest"]:R.api,B=Nr(R.database);return c(ne,{initialSelected:A,onConfirm:F,options:B,prompt:"Select API layers (optional)"},"apiLayer")}case"auth":{const A=Mr(R.database);return c(Y,{onConfirm:S,options:A,prompt:"Choose an authentication strategy"},"auth")}case"extras":return c(ne,{initialSelected:R.extras,onConfirm:U,options:i,prompt:"Select extras (optional)"},"extras");case"microservices":return c(ne,{initialSelected:R.microservices,onConfirm:Z,options:kr,prompt:"Select microservice communication protocols"},"microservices");case"addons":return c(ne,{initialSelected:R.addons,onConfirm:k,onChange:Je,options:ut,prompt:"Select addons (optional)"},"addons");case"ultraciteEditors":return c(ne,{initialSelected:R.ultraciteEditors,onConfirm:x,options:Tr,prompt:"Select Ultracite editors",minified:!0},"ultraciteEditors");case"ultraciteAgents":return c(ne,{initialSelected:R.ultraciteAgents,onConfirm:z,options:Pr,prompt:"Select Ultracite agents",minified:!0},"ultraciteAgents");case"ultraciteHooks":return c(ne,{initialSelected:R.ultraciteHooks,onConfirm:V,options:Er,prompt:"Select Ultracite hooks"},"ultraciteHooks");case"ultraciteInstallSkill":return c(Y,{onConfirm:ee,options:Rr,prompt:"Install Ultracite skill?"},"ultraciteInstallSkill");case"initGit":return c(Y,{onConfirm:be,options:xt,prompt:"Initialize a git repository?"},"initGit");case"installDependencies":return c(Y,{onConfirm:ye,options:Ar,prompt:"Install dependencies?"},"installDependencies");case"summary":return c(Lr,{onConfirm:je,state:R});case"installing":return w(y,{flexDirection:"column",children:[c(wt,{currentStage:s,generationMessage:l?.message??"Scaffolding your project",installProgress:ce,isError:l?.isError??!1,packageManager:R.packageManager??void 0,skippedStages:le}),l?.isError?c(y,{marginTop:1,children:w(m,{color:q,children:["Press ",c(m,{color:P,children:"Enter"})," to go back to Summary and retry, or ",c(m,{color:q,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const A=ie(R.projectName),B=R.initGit==="yes",ve=Le(A),Qt=R.installDependencies==="yes";return c(jt,{architecture:R.architecture||"nest-api",projectName:A,packageManager:R.packageManager||"pnpm",dependenciesInstalled:Qt,isGitInitialized:B,outputDir:ve})}default:return null}},"renderStep"),G=_!=="installing"&&_!=="done";return w(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[G?w(D,{children:[c($r,{state:R,stepId:_}),c(y,{height:0}),c(Ur,{displayStep:o,stepId:_,subProgress:se??void 0,totalSteps:b}),c(y,{height:2})]}):null,f(),c(y,{flexGrow:1}),G?w(D,{children:[c(Te,{}),c(y,{height:1}),c(Ye,{action:te,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),ct=` _ _ ___ ___ _____ _ ___ ___ _ _
136
136
  | \\| | __/ __|_ _| /_\\ | _ \\/ __| || |
137
137
  | .\` | _|\\__ \\ | | / _ \\| / (__| __ |
138
- |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,La=12,Fa=4,Vt=u(({onlyCat:t=!1})=>{const{stdout:e}=We(),r=e.columns||e.getWindowSize?.()[0]||80,a=e.rows||e.getWindowSize?.()[1]||24;return t?a<15||r<20?l(w,{flexDirection:"column",alignItems:"center",children:l(d,{bold:!0,color:P,children:dt})}):l(w,{flexDirection:"column",alignItems:"center",children:l(d,{color:P,children:Ve})}):a<15||r<38?j(w,{flexDirection:"column",alignItems:"center",rowGap:0,children:[l(d,{bold:!0,color:P,children:dt}),l(d,{color:q,children:xe}),l(d,{color:H,children:Ie})]}):a<15+Fa||r<55?j(w,{flexDirection:"column",alignItems:"center",rowGap:0,children:[l(d,{color:P,children:it}),l(d,{color:q,children:xe}),l(d,{color:H,children:Ie})]}):a<15+La||r<80?j(w,{flexDirection:"column",alignItems:"center",rowGap:0,children:[l(d,{color:P,children:Ve}),l(d,{color:P,children:it}),l(d,{color:q,children:xe}),l(d,{color:H,children:Ie})]}):j(w,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[l(d,{color:P,children:Ve}),j(w,{flexDirection:"column",children:[l(d,{color:P,children:it}),j(d,{color:q,children:[" ",xe]}),j(d,{color:H,children:[" ",Ie]})]})]})},"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"},Ua=u(({onSelect:t,options:e})=>{const[r,a]=C(0),n=T(()=>{const s=e[r];s&&!s.disabled&&t(s)},[t,e,r]);return _e((s,o)=>{o.upArrow||s==="k"?a(i=>Math.max(0,i-1)):o.downArrow||s==="j"?a(i=>Math.min(e.length-1,i+1)):o.return&&n()}),j(w,{flexDirection:"column",children:[l(d,{color:q,children:"Choose a project preset"}),l(w,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((s,o)=>j(w,{flexDirection:"column",children:[l(d,{children:o===r?j(L,{children:[l(d,{color:s.disabled?pe:P,children:"> "}),l(d,{color:s.disabled?pe:P,children:s.name})]}):l(d,{color:s.disabled?pe:ve,children:` ${s.name}`})}),o===r&&s.description?l(d,{color:q,children:s.description}):null]},s.name))})]})},"PresetStep"),$a={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},Ba=u(({step:t})=>j(d,{children:[l(d,{color:P,children:"\u2727 "}),l(d,{color:M,children:$a[t]})]}),"WizardTitle"),Wa=u(({onBack:t,onDone:e,onExit:r,onStepChange:a})=>{const[n,s]=C("preset"),[o,i]=C(""),[c,p]=C(null),[g,m]=C(null),[f,O]=C(null),[x,U]=C(null),[F,_]=C(null),[N,S]=C("");ae(()=>{n==="done"&&e()},[n,e]);const $=W(()=>Br(),[]),Z=W(()=>{const E=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return $?E.push({description:Wr($),name:"Last Used"}):E.push({description:"",disabled:!0,name:"Last Used"}),E},[$]),[k,I]=C(ct),D=W(()=>{const E=new Set;return g==="no"&&(E.add("initialize-git"),E.add("initial-commit")),k.installDependencies==="no"&&E.add("install-dependencies"),(k.formatter==="none"||k.installDependencies==="no")&&(E.add("setup-linter"),E.add("run-formatter")),(g==="no"||E.has("run-formatter"))&&E.add("formatter-commit"),[...E]},[g,k]),V=T(()=>{switch(n){case"projectName":{s("preset"),a?.("preset"),p(null);return}case"initGit":{s("projectName"),a?.("projectName");return}default:t()}},[t,n,a]),ee=T(E=>{if(E.name==="Last Used"&&$){const{projectName:X,initGit:ce,...te}=$;I(te)}else E.name==="API Gateway"?I({...ct,architecture:"nest-gateway",projectType:"monorepo"}):I(ct);s("projectName"),a?.("projectName")},[$,a]),ge=T(E=>{i(E),p(ze(E))},[]),fe=T(()=>{const E=ze(o);if(E){p(E);return}s("initGit"),a?.("initGit")},[o,a]),ye=T(async E=>{m(E);const X=ne(o),ce=Le(X);S(ce),s("installing"),a?.("installing");const te={...k,initGit:E,projectName:X};try{const z=await Jt(te,{onInstallProgress:u(se=>{_(se)},"onInstallProgress"),onStageChange:u(se=>{U(se)},"onStageChange")});O({isError:!z.success,message:z.message}),z.success&&zt(te)}catch(z){O({isError:!0,message:`Error: ${z instanceof Error?z.message:String(z)}`})}},[o,k,a]);ut(()=>{f&&!f.isError&&(s("done"),a?.("done"))},[f,a]),le((E,X)=>{if(X.ctrl&&E==="c"){r();return}if(X.ctrl&&E==="b"&&n!=="done"){V();return}n==="done"&&X.return&&r()});const be=W(()=>n==="projectName"?"confirm":"select",[n]),ie=n!=="installing"&&n!=="done";return j(w,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[ie?j(L,{children:[l(Vt,{}),l(Ae,{}),l(w,{height:1}),l(Ba,{step:n}),l(w,{height:2})]}):null,u(()=>{switch(n){case"preset":return l(Ua,{onSelect:ee,options:Z});case"projectName":return l(kt,{error:c,onChange:ge,onSubmit:fe,value:o});case"initGit":return l(Y,{onConfirm:ye,options:xt,prompt:"Initialize a git repository?"});case"installing":return j(w,{flexDirection:"column",children:[l(wt,{currentStage:x,generationMessage:f?.message??"Scaffolding your project",installProgress:F,isError:f?.isError??!1,skippedStages:D}),f?.isError?l(w,{marginTop:1,children:j(d,{color:q,children:["Press ",l(d,{color:P,children:"Enter"})," to go back to Summary and retry, or ",l(d,{color:q,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const E=ne(o);return l(jt,{architecture:k.architecture||"nest-api",projectName:E,packageManager:k.packageManager||"pnpm",dependenciesInstalled:k.installDependencies==="yes",isGitInitialized:g==="yes",outputDir:N})}default:return null}},"renderStep")(),l(w,{flexGrow:1}),ie?j(L,{children:[l(Ae,{}),l(w,{height:1}),l(Qe,{action:be,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),Fe=[{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"}],Ja=u(({onSelect:t})=>{const[e,r]=C(0),a=T(()=>{const o=Fe[e]??null;o?.disabled||t(e,o)},[t,e]),n=[];for(let o=0;o<Fe.length;o+=1)Fe[o].disabled||n.push(o);const s=n.indexOf(e);return _e((o,i)=>{if(i.upArrow||o==="k"){const c=n[s-1];c!==void 0&&r(c)}else if(i.downArrow||o==="j"){const c=n[s+1];c!==void 0&&r(c)}else i.return&&a()}),j(w,{flexDirection:"column",children:[l(d,{color:q,children:" What would you like to do?"}),l(w,{marginTop:1,flexDirection:"column",rowGap:1,children:Fe.map((o,i)=>l(d,{children:i===e&&!o.disabled?j(L,{children:[l(d,{color:P,children:"> "}),l(d,{color:P,children:o.name})]}):l(d,{color:ve,children:` ${o.name}`})},o.name))})]})},"MainMenu"),Ha=u(()=>j(d,{children:[l(d,{color:P,children:"\u2727 "}),l(d,{color:M,children:" Welcome to "}),l(d,{color:P,children:"Nest Arch"}),l(d,{color:M,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),Va=u(({onCreateProject:t,onExit:e,onUsePreset:r})=>{const a=T(async()=>{const s="https://github.com/Angel-Mario";try{await pr(s,{wait:!1})}catch{}},[]),n=T((s,o)=>{o?.name==="Exit"?e():o?.name==="Create a new NestJS project"?t():o?.name==="Use a project preset"?r():o?.name==="View documentation"&&a()},[t,e,r,a]);return le((s,o)=>{o.ctrl&&s==="c"&&e()}),j(w,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[l(Vt,{}),l(Ae,{}),l(w,{height:1}),l(Ha,{}),l(w,{height:2}),l(Ja,{onSelect:n}),l(w,{flexGrow:1}),l(Ae,{borderTop:!1}),l(w,{height:1}),l(Qe,{})]})},"WelcomeScreen"),Qa=u(({onDone:t})=>{const[e,r]=C("welcome"),{stdout:a}=We(),{exit:n}=Kt(),[s,o]=C(a?.rows??24);ae(()=>{if(!a)return;const f=u(()=>{o(a.rows)},"handleResize");return a.on("resize",f),()=>{a.off("resize",f)}},[a]);const i=T(()=>{n()},[n]),c=T(()=>{r("preset-wizard")},[]),p=T(()=>{r("create-wizard")},[]),g=T(()=>{r("welcome")},[]);return l(w,{height:s,flexDirection:"column",children:u(()=>e==="create-wizard"?l(Na,{onBack:g,onDone:t,onExit:i}):e==="preset-wizard"?l(Wa,{onBack:g,onDone:t,onExit:i}):l(Va,{onCreateProject:p,onExit:i,onUsePreset:c}),"renderScreen")()})},"App");async function Ya(){process.stdout.write("\x1B[?1049h");let t=!1;try{await Xt(l(Qa,{onDone:u(()=>{process.stdout.write("\x1B[?1049l"),t=!0},"onDone")})).waitUntilExit()}finally{t||process.stdout.write("\x1B[?1049l")}}u(Ya,"main");try{await Ya()}catch(t){console.error("Error:",t),process.exit(1)}
138
+ |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,Ka=12,Za=4,Vt=u(({onlyCat:t=!1})=>{const{stdout:e}=He(),r=e.columns||e.getWindowSize?.()[0]||80,a=e.rows||e.getWindowSize?.()[1]||24;return t?a<15||r<20?c(y,{flexDirection:"column",alignItems:"center",children:c(m,{bold:!0,color:P,children:mt})}):c(y,{flexDirection:"column",alignItems:"center",children:c(m,{color:P,children:Qe})}):a<15||r<38?w(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(m,{bold:!0,color:P,children:mt}),c(m,{color:q,children:Ie}),c(m,{color:W,children:Oe})]}):a<15+Za||r<55?w(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(m,{color:P,children:ct}),c(m,{color:q,children:Ie}),c(m,{color:W,children:Oe})]}):a<15+Ka||r<80?w(y,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(m,{color:P,children:Qe}),c(m,{color:P,children:ct}),c(m,{color:q,children:Ie}),c(m,{color:W,children:Oe})]}):w(y,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[c(m,{color:P,children:Qe}),w(y,{flexDirection:"column",children:[c(m,{color:P,children:ct}),w(m,{color:q,children:[" ",Ie]}),w(m,{color:W,children:[" ",Oe]})]})]})},"Header"),lt={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"},eo=u(({onSelect:t,options:e})=>{const[r,a]=O(0),n=T(()=>{const s=e[r];s&&!s.disabled&&t(s)},[t,e,r]);return ze((s,o)=>{o.upArrow||s==="k"?a(i=>Math.max(0,i-1)):o.downArrow||s==="j"?a(i=>Math.min(e.length-1,i+1)):o.return&&n()}),w(y,{flexDirection:"column",children:[c(m,{color:q,children:"Choose a project preset"}),c(y,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((s,o)=>w(y,{flexDirection:"column",children:[c(m,{children:o===r?w(D,{children:[c(m,{color:s.disabled?ue:P,children:"> "}),c(m,{color:s.disabled?ue:P,children:s.name})]}):c(m,{color:s.disabled?ue:oe,children:` ${s.name}`})}),o===r&&s.description?c(m,{color:q,children:s.description}):null]},s.name))})]})},"PresetStep"),to={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},ro=u(({step:t})=>w(m,{children:[c(m,{color:P,children:"\u2727 "}),c(m,{color:N,children:to[t]})]}),"WizardTitle"),so=u(({onBack:t,onDone:e,onExit:r,onStepChange:a})=>{const[n,s]=O("preset"),[o,i]=O(""),[l,p]=O(null),[h,d]=O(null),[j,I]=O(null),[M,$]=O(null),[L,C]=O(null),[F,S]=O("");ae(()=>{n==="done"&&e()},[n,e]);const U=J(()=>Br(),[]),Z=J(()=>{const E=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return U?E.push({description:Jr(U),name:"Last Used"}):E.push({description:"",disabled:!0,name:"Last Used"}),E},[U]),[k,x]=O(lt),z=J(()=>{const E=new Set;return h==="no"&&(E.add("initialize-git"),E.add("initial-commit")),k.installDependencies==="no"&&E.add("install-dependencies"),(k.formatter==="none"||k.installDependencies==="no")&&(E.add("setup-linter"),E.add("run-formatter")),(h==="no"||E.has("run-formatter"))&&E.add("formatter-commit"),k.addons.includes("agent-skills")||E.add("install-agent-skills"),[...E]},[h,k]),V=T(()=>{switch(n){case"projectName":{s("preset"),a?.("preset"),p(null);return}case"initGit":{s("projectName"),a?.("projectName");return}default:t()}},[t,n,a]),ee=T(E=>{if(E.name==="Last Used"&&U){const{projectName:X,initGit:le,...te}=U;x(te)}else E.name==="API Gateway"?x({...lt,architecture:"nest-gateway",projectType:"monorepo"}):x(lt);s("projectName"),a?.("projectName")},[U,a]),be=T(E=>{i(E),p(De(E))},[]),ye=T(()=>{const E=De(o);if(E){p(E);return}s("initGit"),a?.("initGit")},[o,a]),we=T(async E=>{d(E);const X=ie(o),le=Le(X);S(le),s("installing"),a?.("installing");const te={...k,initGit:E,projectName:X};try{const _=await Ht(te,{onInstallProgress:u(se=>{C(se)},"onInstallProgress"),onStageChange:u(se=>{$(se)},"onStageChange")});I({isError:!_.success,message:_.message}),_.success&&Gt(te)}catch(_){I({isError:!0,message:`Error: ${_ instanceof Error?_.message:String(_)}`})}},[o,k,a]);dt(()=>{j&&!j.isError&&(s("done"),a?.("done"))},[j,a]),pe((E,X)=>{if(X.ctrl&&E==="c"){r();return}if(X.ctrl&&E==="b"&&n!=="done"){V();return}n==="done"&&X.return&&r()});const je=J(()=>n==="projectName"?"confirm":"select",[n]),ce=n!=="installing"&&n!=="done";return w(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[ce?w(D,{children:[c(Vt,{}),c(Te,{}),c(y,{height:1}),c(ro,{step:n}),c(y,{height:2})]}):null,u(()=>{switch(n){case"preset":return c(eo,{onSelect:ee,options:Z});case"projectName":return c(kt,{error:l,onChange:be,onSubmit:ye,value:o});case"initGit":return c(Y,{onConfirm:we,options:xt,prompt:"Initialize a git repository?"});case"installing":return w(y,{flexDirection:"column",children:[c(wt,{currentStage:M,generationMessage:j?.message??"Scaffolding your project",installProgress:L,isError:j?.isError??!1,skippedStages:z}),j?.isError?c(y,{marginTop:1,children:w(m,{color:q,children:["Press ",c(m,{color:P,children:"Enter"})," to go back to Summary and retry, or ",c(m,{color:q,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const E=ie(o);return c(jt,{architecture:k.architecture||"nest-api",projectName:E,packageManager:k.packageManager||"pnpm",dependenciesInstalled:k.installDependencies==="yes",isGitInitialized:h==="yes",outputDir:F})}default:return null}},"renderStep")(),c(y,{flexGrow:1}),ce?w(D,{children:[c(Te,{}),c(y,{height:1}),c(Ye,{action:je,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),$e=[{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"}],ao=u(({onSelect:t})=>{const[e,r]=O(0),a=T(()=>{const o=$e[e]??null;o?.disabled||t(e,o)},[t,e]),n=[];for(let o=0;o<$e.length;o+=1)$e[o].disabled||n.push(o);const s=n.indexOf(e);return ze((o,i)=>{if(i.upArrow||o==="k"){const l=n[s-1];l!==void 0&&r(l)}else if(i.downArrow||o==="j"){const l=n[s+1];l!==void 0&&r(l)}else i.return&&a()}),w(y,{flexDirection:"column",children:[c(m,{color:q,children:" What would you like to do?"}),c(y,{marginTop:1,flexDirection:"column",rowGap:1,children:$e.map((o,i)=>c(m,{children:i===e&&!o.disabled?w(D,{children:[c(m,{color:P,children:"> "}),c(m,{color:P,children:o.name})]}):c(m,{color:oe,children:` ${o.name}`})},o.name))})]})},"MainMenu"),oo=u(()=>w(m,{children:[c(m,{color:P,children:"\u2727 "}),c(m,{color:N,children:" Welcome to "}),c(m,{color:P,children:"Nest Arch"}),c(m,{color:N,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),no=u(({onCreateProject:t,onExit:e,onUsePreset:r})=>{const a=T(async()=>{const s="https://github.com/Angel-Mario";try{await pr(s,{wait:!1})}catch{}},[]),n=T((s,o)=>{o?.name==="Exit"?e():o?.name==="Create a new NestJS project"?t():o?.name==="Use a project preset"?r():o?.name==="View documentation"&&a()},[t,e,r,a]);return pe((s,o)=>{o.ctrl&&s==="c"&&e()}),w(y,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[c(Vt,{}),c(Te,{}),c(y,{height:1}),c(oo,{}),c(y,{height:2}),c(ao,{onSelect:n}),c(y,{flexGrow:1}),c(Te,{borderTop:!1}),c(y,{height:1}),c(Ye,{})]})},"WelcomeScreen"),io=u(({onDone:t})=>{const[e,r]=O("welcome"),{stdout:a}=He(),{exit:n}=Kt(),[s,o]=O(a?.rows??24);ae(()=>{if(!a)return;const j=u(()=>{o(a.rows)},"handleResize");return a.on("resize",j),()=>{a.off("resize",j)}},[a]);const i=T(()=>{n()},[n]),l=T(()=>{r("preset-wizard")},[]),p=T(()=>{r("create-wizard")},[]),h=T(()=>{r("welcome")},[]);return c(y,{height:s,flexDirection:"column",children:u(()=>e==="create-wizard"?c(Xa,{onBack:h,onDone:t,onExit:i}):e==="preset-wizard"?c(so,{onBack:h,onDone:t,onExit:i}):c(no,{onCreateProject:p,onExit:i,onUsePreset:l}),"renderScreen")()})},"App");async function co(){process.stdout.write("\x1B[?1049h");let t=!1;try{await Xt(c(io,{onDone:u(()=>{process.stdout.write("\x1B[?1049l"),t=!0},"onDone")})).waitUntilExit()}finally{t||process.stdout.write("\x1B[?1049l")}}u(co,"main");try{await co()}catch(t){console.error("Error:",t),process.exit(1)}