@nest-arch/tui 0.2.8 → 0.4.0

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 (70) hide show
  1. package/README.md +20 -42
  2. package/dist/cli.js +1 -1
  3. package/dist/constants-C3xmDWeK.js +1 -0
  4. package/dist/index.js +297 -84
  5. package/dist/templates/base/.env.example.hbs +4 -2
  6. package/dist/templates/base/.env.hbs +4 -2
  7. package/dist/templates/base/.gitignore.hbs +2 -1
  8. package/dist/templates/base/.yarnrc.yml.hbs +0 -5
  9. package/dist/templates/base/README.md.hbs +33 -5
  10. package/dist/templates/base/nest-cli.json.hbs +2 -1
  11. package/dist/templates/base/pnpm-workspace.yaml.hbs +9 -0
  12. package/dist/templates/base/prisma.config.ts.hbs +32 -6
  13. package/dist/templates/base/src/app.controller.spec.ts.hbs +3 -11
  14. package/dist/templates/base/src/app.controller.ts.hbs +2 -2
  15. package/dist/templates/base/src/app.module.ts.hbs +8 -4
  16. package/dist/templates/base/src/app.router.ts.hbs +2 -2
  17. package/dist/templates/base/src/database/adapters/interfaces/db-adapter.interface.ts.hbs +7 -0
  18. package/dist/templates/base/src/database/adapters/mongo/prisma-mongo.adapter.ts.hbs +25 -1
  19. package/dist/templates/base/src/database/adapters/mongo/raw-mongo.adapter.ts.hbs +17 -12
  20. package/dist/templates/base/src/database/adapters/sql/drizzle-sql.adapter.ts.hbs +9 -0
  21. package/dist/templates/base/src/database/adapters/sql/prisma-sql.adapter.ts.hbs +7 -4
  22. package/dist/templates/base/src/database/adapters/sql/raw-sql.adapter.ts.hbs +37 -0
  23. package/dist/templates/base/src/database/adapters/sql/typeorm-sql.adapter.ts.hbs +8 -3
  24. package/dist/templates/base/src/database/db.module.ts.hbs +32 -35
  25. package/dist/templates/base/src/database/db.service.ts.hbs +40 -6
  26. package/dist/templates/base/src/database/entities/todo.entity.ts.hbs +12 -7
  27. package/dist/templates/base/src/database/index.ts.hbs +1 -0
  28. package/dist/templates/base/src/database/orm/drizzle/schema.ts.hbs +47 -5
  29. package/dist/templates/base/src/database/orm/typeorm/data-source.ts.hbs +12 -4
  30. package/dist/templates/base/src/libs/trpc/error.handler.ts.hbs +1 -1
  31. package/dist/templates/base/src/main.ts.hbs +21 -6
  32. package/dist/templates/base/test/app.e2e-spec.ts.hbs +208 -6
  33. package/dist/templates/base/test/bootstrap.e2e-spec.ts.hbs +74 -0
  34. package/dist/templates/base/tsconfig.build.json.hbs +2 -0
  35. package/dist/templates/base/vitest.config.e2e.ts.hbs +4 -3
  36. package/dist/templates/base/vitest.config.ts.hbs +4 -3
  37. package/dist/templates/base/yarn.lock.hbs +1 -0
  38. package/dist/templates/extras/docker/Dockerfile.hbs +4 -1
  39. package/dist/templates/extras/swagger/create-docs.ts.hbs +4 -19
  40. package/dist/templates/feature/graphql/src/graphql/graphql.module.ts.hbs +8 -1
  41. package/dist/templates/feature/graphql/src/graphql/models/todo.model.ts.hbs +4 -0
  42. package/dist/templates/feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs +4 -3
  43. package/dist/templates/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs +51 -0
  44. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs +3 -1
  45. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.module.ts.hbs +1 -3
  46. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.service.ts.hbs +98 -32
  47. package/dist/templates/monorepo/apps/api-gateway/package.json.hbs +0 -1
  48. package/dist/templates/monorepo/apps/api-gateway/src/app.controller.spec.ts.hbs +1 -1
  49. package/dist/templates/monorepo/apps/api-gateway/test/app.e2e-spec.ts.hbs +20 -1
  50. package/dist/templates/monorepo/apps/api-gateway/tsconfig.build.json.hbs +2 -1
  51. package/dist/templates/monorepo/apps/api-gateway/vitest.config.e2e.ts.hbs +3 -2
  52. package/dist/templates/monorepo/apps/api-gateway/vitest.config.ts.hbs +3 -2
  53. package/dist/templates/monorepo/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs +9 -0
  54. package/dist/templates/monorepo/packages/env/src/api-gateway.ts.hbs +9 -3
  55. package/dist/templates/monorepo/root/.gitignore.hbs +1 -0
  56. package/dist/templates/monorepo/root/pnpm-workspace.yaml.hbs +9 -0
  57. package/dist/templates/monorepo/root/tsconfig.json.hbs +1 -1
  58. package/dist/templates/monorepo/root/turbo.json.hbs +2 -0
  59. package/dist/templates/single-project/architecture/nest-api/.env.hbs +3 -1
  60. package/dist/templates/single-project/architecture/nest-api/package.json.hbs +0 -1
  61. package/dist/templates/single-project/architecture/nest-api/src/main.ts.hbs +20 -5
  62. package/dist/templates/single-project/architecture/nest-microservice/.env.hbs +18 -0
  63. package/dist/templates/single-project/architecture/nest-microservice/proto/app.proto.hbs +13 -0
  64. package/dist/templates/single-project/architecture/nest-microservice/src/app.controller.ts.hbs +14 -1
  65. package/dist/templates/single-project/architecture/nest-microservice/src/app.service.ts.hbs +4 -0
  66. package/dist/templates/single-project/architecture/nest-microservice/src/main.ts.hbs +13 -2
  67. package/dist/templates/single-project/architecture/nest-microservice/test/microservice.e2e-spec.ts.hbs +64 -0
  68. package/dist/templates/single-project/shared/config/env.ts.hbs +27 -3
  69. package/package.json +5 -2
  70. package/dist/constants-Cgtoxhmd.js +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var rr=Object.defineProperty;var l=(t,e)=>rr(t,"name",{value:e,configurable:!0});import{jsx as c,jsxs as y,Fragment as N}from"react/jsx-runtime";import{Box as f,Text as u,useInput as le,useStdout as Qe,render as sr,useApp as ar}from"ink";import{useState as O,useEffect as ae,useMemo as J,useRef as qe,useCallback as R,useLayoutEffect as mt}from"react";import{COLOR_DIVIDER as pe,COLOR_RED as P,COLOR_WARM as de,COLOR_DIM as E,COLOR_FG as L,COLOR_SUCCESS as we,COLOR_DIMMER as oe,COLOR_ACCENT as W,COLOR_WARM_SECONDARY as or,APP_NAME as ht,APP_TAGLINE as xe,APP_VERSION as Ie}from"./constants-Cgtoxhmd.js";import nr from"ink-text-input";import{createEnv as ir}from"@t3-oss/env-nextjs";import{z as ue}from"zod";import{existsSync as je,readFileSync as cr,mkdirSync as lr,writeFileSync as pr}from"node:fs";import{homedir as gt}from"node:os";import w,{join as Y}from"node:path";import{exec as Ye,execFile as dr,spawn as Oe}from"node:child_process";import{promisify as _e}from"node:util";import Z,{access as ur,readFile as Ce,writeFile as ve,rm as mr}from"node:fs/promises";import H from"handlebars";import{Scope as hr,Project as gr}from"ts-morph";import{once as re}from"node:events";import fr from"open";const Se=l(({borderTop:t=!0})=>c(f,{borderStyle:"single",borderBottom:!t,borderLeft:!1,borderRight:!1,borderTop:t,borderColor:pe,height:1,width:"full"}),"Divider"),yr=` \uFF0Fl\u3001
1
+ var _o=Object.defineProperty;var c=(e,t)=>_o(e,"name",{value:t,configurable:!0});import{jsx as d,jsxs as w,Fragment as V}from"react/jsx-runtime";import{Box as v,Text as h,useInput as Re,useStdout as Ut,render as xo,useApp as To}from"ink";import{useState as $,useEffect as ye,useMemo as X,useRef as at,useCallback as N,useLayoutEffect as Wr}from"react";import{COLOR_DIVIDER as Oe,COLOR_RED as z,COLOR_WARM as _e,COLOR_DIM as O,COLOR_FG as H,COLOR_SUCCESS as Ue,COLOR_DIMMER as xe,COLOR_ACCENT as ie,COLOR_WARM_SECONDARY as Ao,APP_NAME as Kr,APP_TAGLINE as ot,APP_VERSION as Ce}from"./constants-C3xmDWeK.js";import Eo from"ink-text-input";import{createEnv as Po}from"@t3-oss/env-nextjs";import{z as he}from"zod";import{exec as Lt,execFile as Io,spawn as it}from"node:child_process";import{promisify as ct}from"node:util";import me,{access as zo,readFile as De,writeFile as be,mkdir as Ro}from"node:fs/promises";import j,{join as ee,dirname as Oo}from"node:path";import ae from"handlebars";import{Scope as Qr,Project as Yr}from"ts-morph";import{once as ve}from"node:events";import{existsSync as lt,readFileSync as Co,mkdirSync as Do,writeFileSync as No}from"node:fs";import{homedir as pt}from"node:os";import qo from"open";import{valid as $o,gt as Mo}from"semver";const Le=c(({borderTop:e=!0})=>d(v,{borderStyle:"single",borderBottom:!e,borderLeft:!1,borderRight:!1,borderTop:e,borderColor:Oe,height:1,width:"full"}),"Divider"),Fo=` \uFF0Fl\u3001
2
2
  \uFF08\uFF9F\uFF64 \uFF61\uFF17
3
3
  l\u3001\uFF9E ~\u30FD
4
4
  \u3058\u3057(_,)\u30CE
5
- `,Xe=` ,-. _,---._ __ /\\
5
+ `,Jt=` ,-. _,---._ __ /\\
6
6
  / ) .-' \`./ / \\
7
7
  ( ( ,' \` / /|
8
8
  \\ \`-" \\'\\ / |
@@ -13,19 +13,40 @@ var rr=Object.defineProperty;var l=(t,e)=>rr(t,"name",{value:e,configurable:!0})
13
13
  | | ( | Toolkit | /
14
14
  ) | \\ \`.___________|/
15
15
  \`--' \`--'
16
- `,br=l(t=>t>=4352&&t<=4447||t>=9001&&t<=9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=131072&&t<=196605||t>=196608&&t<=262141,"isFullwidthCodePoint"),ft=l(t=>{let e=0;for(const r of t){const s=r.codePointAt(0)??0;e+=br(s)?2:1}return e},"getDisplayWidth"),wr=2,yt=[0,1,2,3,2,1],bt=["",".","..","..."],jr=l(({message:t="Scaffolding your project",isError:e=!1,isComplete:r=!1,showProgressText:s=!0,paddingX:n=2})=>{const[o,a]=O(0),[i,d]=O(0),p=!e&&!r;ae(()=>{if(!p)return;const F=setInterval(()=>{a($=>($+1)%yt.length)},200),_=setInterval(()=>{d($=>($+1)%bt.length)},400);return()=>{clearInterval(F),clearInterval(_)}},[p]);const m=yr.trimEnd().split(`
17
- `),g=Math.max(...m.map(ft)),b=yt[o];let q=de,M="\u25CF",U=E;return e?(q=P,M="\u2717",U=L):r&&(q=we,M="\u2713",U=we),y(f,{flexDirection:"column",paddingX:n,children:[c(f,{flexDirection:"column",children:m.map((F,_)=>{const $=ft(F),D=_===0||_===m.length-1,B=g-$+wr-(D?1:0),z=_===b;return y(u,{color:P,children:[F," ".repeat(B),z?c(u,{color:q,children:M}):" "]},_)})}),s&&y(u,{color:U,children:[t,p?bt[i]:""]})]})},"ScaffoldingAnimation"),vr=[{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"}],wt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Sr(t,e,r){if(!t)return r.map(o=>({stage:o,status:"pending"}));if(t==="complete")return r.map(o=>({stage:o,status:e?"failed":"completed"}));const n=r.map(o=>o.id).indexOf(t);return r.map((o,a)=>a<n?{stage:o,status:e?"failed":"completed"}:a===n?{stage:o,status:e?"failed":"active"}:e&&a>n?{stage:o,status:"pending"}:e?{stage:o,status:"failed"}:{stage:o,status:"pending"})}l(Sr,"getStages");function kr(t,e){switch(t){case"completed":return"\u2713";case"active":return e;case"failed":return"\u2717";case"pending":return"\u25CB";default:return t}}l(kr,"statusIcon");function Ar(t){switch(t){case"completed":return we;case"active":return de;case"failed":return P;case"pending":return oe;default:return t}}l(Ar,"statusColor");function Pr(t){return t===void 0?"":` (${t}%)`}l(Pr,"formatPercentage");function Tr(t){return t?.message?t.message:"Installing dependencies..."}l(Tr,"getInstallMessage");const jt=l(({currentStage:t,generationMessage:e,installProgress:r,isError:s,skippedStages:n=[]})=>{const o=J(()=>vr.filter(g=>!n.includes(g.id)),[n]),a=J(()=>Sr(t,s,o),[t,s,o]),[i,d]=O(0),p=t==="complete"&&!s;ae(()=>{if(s||p)return;const g=setInterval(()=>{d(b=>(b+1)%wt.length)},80);return()=>clearInterval(g)},[s,p]);const m=wt[i]??"\u280B";return y(f,{flexDirection:"column",paddingX:2,children:[c(f,{marginBottom:1,children:c(jr,{showProgressText:!1,paddingX:0,isError:s,isComplete:p})}),c(f,{flexDirection:"column",rowGap:0,children:a.map(g=>{const b=g.status==="active",q=b&&g.stage.id==="install-dependencies",M=r?.percentage,U=16,F=M===void 0?0:Math.round(M/100*U),_=U-F;return y(f,{flexDirection:"column",children:[y(f,{children:[y(u,{bold:b,color:Ar(g.status),children:[kr(g.status,m)," ",g.stage.label]}),q?c(u,{children:M===void 0?null:y(N,{children:[c(u,{color:de,children:Pr(M)})," ",c(u,{color:de,children:"\u2588".repeat(F)}),c(u,{color:pe,children:"\u2591".repeat(_)})]})}):null]}),q?c(f,{marginLeft:4,children:c(u,{color:E,children:Tr(r)})}):null]},g.stage.id)})}),!s&&t===null?c(f,{marginTop:1,children:c(u,{color:E,children:e})}):null,p?c(f,{marginTop:1,children:c(u,{color:we,children:e})}):null,s?c(f,{marginTop:1,flexDirection:"column",children:e.split(`
18
- `).map((g,b)=>c(u,{color:g.startsWith(" ")?E:P,children:g},b))}):null]})},"InstallationProgress"),Ke=l(({action:t="select",showBack:e=!1})=>y(u,{children:[t==="select"||t==="multi-select"?c(u,{color:E,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,c(u,{color:E,children:t==="confirm"?y(N,{children:[c(u,{color:L,children:"Enter "}),"to confirm"]}):t==="multi-select"?y(N,{children:[c(u,{color:L,children:"Space "}),"to toggle \u2022",c(u,{color:L,children:" Enter "}),"to confirm"]}):y(N,{children:[c(u,{color:L,children:"Enter "}),"to select"]})}),y(u,{color:E,children:[e?y(N,{children:[" ","\u2022",c(u,{color:L,children:" Ctrl+B "}),"to go back"]}):"",y(N,{children:[" ","\u2022",c(u,{color:L,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),vt=l(({architecture:t,projectName:e,packageManager:r,isGitInitialized:s,dependenciesInstalled:n,outputDir:o})=>c(f,{flexDirection:"column",children:y(f,{flexDirection:"column",marginTop:1,children:[c(u,{color:we,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),y(f,{marginTop:1,children:[c(u,{color:L,children:"Project: "}),c(u,{color:W,bold:!0,children:e})]}),y(f,{children:[c(u,{color:L,children:"Architecture: "}),c(u,{color:W,bold:!0,children:t})]}),o?y(f,{children:[c(u,{color:L,children:"Location: "}),c(u,{color:W,bold:!0,children:o})]}):null,s?c(f,{marginTop:1,children:c(u,{color:E,children:"Git repository initialized"})}):null,y(f,{flexDirection:"column",borderStyle:"round",borderColor:P,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[c(u,{color:L,bold:!0,children:"\u{1F680} NEXT STEPS"}),c(f,{height:1}),c(u,{color:L,children:"1. Move into the project directory:"}),c(u,{color:W,bold:!0,children:` cd ${e}`}),c(f,{height:1}),n?c(f,{children:c(u,{color:E,children:"2. Dependencies already installed"})}):y(N,{children:[c(u,{color:L,children:"2. Install dependencies:"}),c(u,{color:W,bold:!0,children:` ${r} install`})]}),c(f,{height:1}),y(u,{color:L,children:["3."," Start development server:"]}),c(u,{color:W,bold:!0,children:` ${r} run dev`})]}),c(f,{marginTop:1,children:c(u,{color:E,children:"(Press enter to exit)"})})]})}),"DoneStep"),Er=100,De=l(t=>{const e=qe(0);le((r,s)=>{if(s.upArrow||s.downArrow||s.leftArrow||s.rightArrow||r==="k"||r==="j"||r==="h"||r==="l"){const o=Date.now();if(o-e.current<Er)return;e.current=o}t(r,s)})},"useArrowSelect"),Rr=l(({initialSelected:t,onConfirm:e,onChange:r,options:s,prompt:n,minified:o=!1})=>{const a=J(()=>new Set(s.map(v=>v.value)),[s]),i=R(v=>v.filter(I=>a.has(I)),[a]),[d,p]=O(0),[m,g]=O(()=>i(t)),b=qe(m);b.current=m;const q=qe(r);q.current=r,ae(()=>{const v=i(t);g(v),p(0),q.current?.(v)},[t,i]);const M=R(v=>m.includes(v),[m]),U=R(v=>{const I=s[v];I&&g(G=>{const V=G.includes(I.value)?G.filter(ee=>ee!==I.value):[...G,I.value];return b.current=V,r?.(V),V})},[s,r]),F=R(()=>{e(b.current)},[e]),_=s.length>16,$=_?Math.ceil(s.length/2):s.length;De((v,I)=>{I.upArrow||v==="k"?p(G=>(G-1+s.length)%s.length):I.downArrow||v==="j"?p(G=>(G+1)%s.length):_&&(I.leftArrow||v==="h")?p(G=>(G-$+s.length)%s.length):_&&(I.rightArrow||v==="l")?p(G=>(G+$)%s.length):I.return?F():(v===" "||v==="x")&&U(d)});const D=m.length,B=l((v,I)=>{const G=M(v.value),V=I===d,ee=G?"\u25CF":"\u25CB";return y(f,{flexDirection:"column",children:[c(u,{children:V?y(N,{children:[c(u,{color:P,children:"> "}),c(u,{color:G?P:E,children:`${ee} `}),c(u,{color:G?P:L,children:v.label})]}):y(N,{children:[c(u,{color:G?P:E,children:` ${ee}`}),c(u,{color:oe,children:` ${v.label}`})]})}),V&&!_?y(u,{color:E,children:[" ",v.description]}):null]},v.value)},"renderOption");let z;return _||(z=o?0:1),y(f,{flexDirection:"column",children:[c(u,{color:E,children:n}),c(u,{color:de,children:D===0?"No options selected yet \u2014 pick what you need":`${D} selected`}),c(f,{marginTop:1,flexDirection:_?"row":"column",rowGap:z,columnGap:_?4:void 0,overflow:"hidden",children:_?y(N,{children:[c(f,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice(0,$).map((v,I)=>B(v,I))}),c(f,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice($).map((v,I)=>B(v,I+$))})]}):s.map((v,I)=>B(v,I))})]})},"MultiSelectStep"),St="my-nest-app",kt=64,qr=/^[a-z][a-z0-9-]*$/u;function ne(t){return t.trim()||St}l(ne,"resolveProjectName");function Me(t){const e=t.trim();return e?e.length>kt?`Project name must be at most ${kt} characters`:qr.test(e)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}l(Me,"validateProjectName");const At=l(({error:t,onChange:e,onSubmit:r,value:s})=>(le((n,o)=>{o.return&&r()}),y(f,{flexDirection:"column",children:[c(u,{color:E,children:"Enter a name for your project"}),y(f,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[c(u,{color:L,children:"Project name:"}),c(nr,{placeholder:St,value:s,onChange:e})]}),t?c(u,{color:P,children:t}):null]})),"ProjectNameStep"),ke=ir({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:ue.string().pipe(ue.coerce.number()).default(95),NEST_ARCH_BETA_MODE:ue.enum(["true","false"]).default("false").transform(t=>t==="true"),NEST_ARCH_SCHEMA_URL:ue.string().default("./schema.json"),NEST_ARCH_VERSION:ue.string().default("0.0.1"),NODE_ENV:ue.enum(["development","production","test"]).default("development")}}),Ge=l(({onConfirm:t,options:e,prompt:r,initialValue:s})=>{const[n,o]=O(()=>{const i=e.findIndex(d=>d.value===s);return Math.max(i,0)});ae(()=>{const i=e.findIndex(d=>d.value===s);o(Math.max(i,0))},[s,e]);const a=R(()=>{const i=e[n];i&&i.devOnly!==(ke.NODE_ENV==="production")&&t(i.value)},[t,e,n]);return De((i,d)=>{d.upArrow||i==="k"?o(p=>(p-1+e.length)%e.length):d.downArrow||i==="j"?o(p=>(p+1)%e.length):d.return&&a()}),y(f,{flexDirection:"column",children:[c(u,{color:E,children:r}),c(f,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((i,d)=>{const p=d===n;return y(f,{flexDirection:"column",children:[c(u,{children:p?c(N,{children:i.devOnly===(ke.NODE_ENV==="production")?y(N,{children:[c(u,{color:oe,children:"> "}),y(u,{color:oe,children:[i.label,". (Comming soon)"]})]}):y(N,{children:[c(u,{color:P,children:"> "}),c(u,{color:P,children:i.label})]})}):c(u,{color:oe,children:` ${i.label}`})}),p?c(u,{color:E,children:i.description}):null]},i.value)})})]})},"SingleSelectStep"),Pt=[{description:"Fast, disk-efficient package manager (recommended)",label:"pnpm",value:"pnpm"},{description:"Default Node.js package manager",label:"npm",value:"npm"},{description:"Classic alternative with workspaces support",label:"yarn",value:"yarn"},{description:"A superfast Node.js-compatible package manager",label:"bun",value:"bun"}],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"}],Et=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],Rt=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",devOnly:!0,label:"Monorepo (Turborepo)",value:"monorepo"}],qt=[{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"}],Ze=[{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"}],et=[{description:"Type-safe ORM with schema and migrations",label:"Prisma",value:"prisma"},{description:"Decorator-based ORM for TypeScript",label:"TypeORM",value:"typeorm"},{description:"Lightweight SQL ORM <insert MongoDB unsupported joke here>",label:"Drizzle",value:"drizzle"}],tt=[{description:"RESTful HTTP endpoints",label:"REST",value:"rest"},{description:"End-to-end typesafe APIs",label:"tRPC",value:"trpc"},{description:"GraphQL schema and resolvers",label:"GraphQL (Code first)",value:"graphql"}],rt=[{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"}],st=[{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"},{description:"Latest TypeScript compiler \u2014 faster checking and new language features (default: TypeScript 6)",label:"TypeScript 7",value:"typescript-7"}],xt=[{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"}],xr=[{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"}],It=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],Ir=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],Or=[{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"}],_r=[{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"}],Cr=[{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"}],Dr=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],Mr={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"},Gr=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","installing","done"];function zr(t){return t.includes("mongodb")}l(zr,"databaseIncludesMongodb");function at(t){return t.length===0}l(at,"databaseIsEmpty");function ze(t){return t.includes("rest")||t.includes("trpc")}l(ze,"hasApiLayer");function Ne(t){return at(t)}l(Ne,"shouldSkipOrmStep");function Ae(t){return Gr.filter(e=>!(e==="orm"&&Ne(t.database)||e==="auth"&&!ze(t.api)||e==="microservices"&&t.architecture!=="nest-gateway"||(e==="ultraciteEditors"||e==="ultraciteAgents"||e==="ultraciteHooks"||e==="ultraciteInstallSkill")&&(!t.addons.includes("ultracite")||t.formatter==="none")))}l(Ae,"getVisibleSteps");const Ot=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function Pe(t){return Ot.includes(t)}l(Pe,"isUltraciteSubStep");function Nr(t,e){if(!Pe(t))return null;const r=Ot.filter(i=>Ae(e).includes(i)),s=r.indexOf(t);if(s===-1)return null;const n=r.length,o=s+1,a=Math.round(o/n*100);return{current:o,percent:a,total:n}}l(Nr,"getUltraciteSubStepInfo");function ot(t){return Ae(t).filter(e=>e!=="installing"&&e!=="done"&&!Pe(e)).length}l(ot,"getTotalSteps");function Fr(t,e){const r=Ae(e).filter(o=>o!=="installing"&&o!=="done");if(t==="installing"||t==="done")return ot(e);if(Pe(t)){const o=r.indexOf("addons");return o===-1?1:o+1}const n=r.filter(o=>!Pe(o)).indexOf(t);return n===-1?1:n+1}l(Fr,"getDisplayStepNumber");function Lr(t,e){const r=Ae(e),s=r.indexOf(t);return s===-1||s>=r.length-1?null:r[s+1]??null}l(Lr,"getNextStepId");function $r(t,e){const r=Ae(e),s=r.indexOf(t);return s<=0?null:r[s-1]??null}l($r,"getPreviousStepId");function Ur(t){return t==="monorepo"?qt:qt.filter(e=>e.value!=="nest-gateway")}l(Ur,"filterArchitectureOptions");function _t(t){return zr(t)?et.filter(e=>e.value!=="drizzle"):et}l(_t,"filterOrmOptions");function Br(t){return t.includes("drizzle")?Ze.filter(e=>e.value!=="mongodb"):Ze}l(Br,"filterDatabaseOptions");function Jr(t){return at(t)?rt.filter(e=>e.value!=="better-auth"):rt}l(Jr,"filterAuthOptions");function Hr(t){return at(t)?tt.filter(e=>e.value!=="graphql"):tt}l(Hr,"filterApiOptions");function Wr(t,e){return e.includes("drizzle")?t.filter(r=>r!=="mongodb"):t}l(Wr,"sanitizeDatabaseForOrm");function Ct(t){return"nest-api"}l(Ct,"defaultArchitecture");function Dt(t,e){if(Ne(e))return[];const r=new Set(_t(e).map(s=>s.value));return t.filter(s=>r.has(s))}l(Dt,"sanitizeOrmForDatabase");function me(t,e){return t.find(r=>r.value===e)?.label??e}l(me,"labelFor");function he(t,e){return e.length===0?"None":e.map(r=>me(t,r)).join(", ")}l(he,"labelsFor");const Vr=l(({onConfirm:t,state:e})=>{le((n,o)=>{o.return&&t()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},s=[{label:"Project",value:ne(e.projectName)},{label:"Package manager",value:e.packageManager?me(Pt,e.packageManager):"\u2014"},{label:"Formatter",value:e.formatter?me(Tt,e.formatter):"\u2014"},{label:"HTTP provider",value:e.httpProvider?me(Et,e.httpProvider):"\u2014"},{label:"Project type",value:e.projectType?me(Rt,e.projectType):"\u2014"},{label:"Architecture",value:e.architecture?r[e.architecture]??e.architecture:"\u2014"},{label:"Database",value:he(Ze,e.database)}];return Ne(e.database)||s.push({label:"ORM",value:he(et,e.orm)}),s.push({label:"API layer",value:he(tt,e.api)}),e.architecture==="nest-gateway"&&s.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)}),ze(e.api)&&s.push({label:"Auth",value:e.auth?me(rt,e.auth):"\u2014"}),s.push({label:"Extras",value:he(st,e.extras)},{label:"Addons",value:he(xt,e.addons)},{label:"Git",value:e.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:e.installDependencies==="yes"?"Install":"Skip"}),y(N,{children:[c(f,{flexDirection:"column",marginBottom:1,children:y(u,{children:[c(u,{color:P,children:"\u2726 "}),c(u,{color:W,children:"Review your selections"})]})}),c(f,{flexDirection:"column",rowGap:0,overflow:"hidden",children:s.map(n=>y(f,{flexDirection:"row",columnGap:1,children:[c(u,{color:or,children:`${n.label}:`}),c(u,{color:de,children:n.value})]},n.label))})]})},"SummaryStep");function Fe(t){return t.length===0?"\u2014":t.join(", ")}l(Fe,"formatList");const Qr=l(({state:t,stepId:e})=>{const{stdout:r}=Qe(),s=r.columns||r.getWindowSize?.()[0]||80,n=Math.min(ke.APP_MAX_WIDTH,s-4),o=[];if(e!=="projectName"&&t.projectName.trim()&&o.push(ne(t.projectName)),t.packageManager&&o.push(t.packageManager),t.httpProvider&&o.push(t.httpProvider),t.projectType&&o.push(t.projectType==="monorepo"?"Monorepo":"Single"),t.architecture){const d={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};o.push(d[t.architecture]??t.architecture)}if(t.database.length>0&&o.push(Fe(t.database)),t.orm.length>0&&o.push(Fe(t.orm)),t.api.length>0&&o.push(Fe(t.api)),t.auth&&o.push(t.auth),t.formatter){const d={biome:"Biome",none:"No formatter","oxlint-oxfmt":"Oxlint+Oxfmt"};o.push(d[t.formatter]??t.formatter)}if(t.microservices.length>0&&o.push(Fe(t.microservices)),t.installDependencies&&o.push(t.installDependencies==="yes"?"install: yes":"install: no"),t.extras.length>0&&o.push(`+${t.extras.length} extras`),t.addons.length>0&&!Pe(e)&&o.push(`+${t.addons.length} addons`),t.initGit&&o.push(t.initGit==="yes"?"git init":"no git"),o.length===0)return y(u,{children:[c(u,{color:P,children:"\u25C6 "}),c(u,{color:P,children:"Create a new NestJS project"})]});const[a,...i]=o;return y(N,{children:[y(u,{children:[c(u,{color:P,children:"\u25C6 "}),c(u,{color:P,children:"Create a new NestJS project"})]}),e!=="summary"&&c(f,{borderStyle:"single",borderColor:pe,width:n,children:y(u,{children:[c(u,{children:"Project Name: "}),c(u,{color:P,children:a}),c(u,{color:E,children:" Selected: "}),i.length>0?c(u,{color:E,children:`${i.filter(d=>d!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),Yr=l(({displayStep:t,stepId:e,subProgress:r,totalSteps:s})=>y(f,{paddingLeft:2,paddingTop:e==="summary"?2:1,marginBottom:1,children:[c(u,{color:L,children:"Create project"}),c(u,{color:E,children:` \u2014 step ${t}/${s}`}),r?c(u,{color:W,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):c(u,{color:W,children:` \xB7 ${Mr[e]}`})]}),"WizardTitle$1"),nt=Y(gt(),".nestarch"),it=Y(nt,"last-used.json");function Xr(){try{if(!je(it))return null;const t=cr(it,"utf-8");return JSON.parse(t)}catch{return null}}l(Xr,"getLastUsedConfig");function Mt(t){try{je(nt)||lr(nt,{recursive:!0}),pr(it,JSON.stringify(t,null,2),"utf-8")}catch{}}l(Mt,"saveLastUsedConfig");function Kr(t){const e=[t.packageManager];t.httpProvider&&e.push(t.httpProvider),t.api.length>0&&e.push(t.api.join(", ")),t.projectType&&e.push(t.projectType);const r=new Date,s=r.toLocaleString("en-US",{month:"short"}),n=r.getDate(),o=r.getFullYear(),a=`${s} ${n}, ${o}`;return`${e.join(", ")} (last used ${a})`}l(Kr,"buildLastUsedDescription");const Zr=[{label:"NestJS Best Practices",name:"nestjs-best-practices",repo:"kadajett/agent-nestjs-skills",when:l(()=>!0,"when")},{label:"Prisma CLI",name:"prisma-cli",repo:"prisma/skills",when:l(t=>t.orm.includes("prisma"),"when")},{label:"Prisma Client API",name:"prisma-client-api",repo:"prisma/skills",when:l(t=>t.orm.includes("prisma"),"when")},{label:"Prisma Database Setup",name:"prisma-database-setup",repo:"prisma/skills",when:l(t=>t.orm.includes("prisma"),"when")},{label:"Prisma NestJS Patterns",name:"prisma-nestjs-patterns",repo:"davidcastagnetoa/skills",when:l(t=>t.orm.includes("prisma"),"when")},{label:"NestJS TypeORM Integration",name:"nestjs-typeorm-integration",repo:"vong3432/vibemark",when:l(t=>t.orm.includes("typeorm"),"when")},{label:"Better Auth Best Practices",name:"better-auth-best-practices",repo:"better-auth/skills",when:l(t=>t.auth==="better-auth"||t.auth==="better-auth:stateless","when")},{label:"JWT Security",name:"jwt-security",repo:"mindrally/skills",when:l(t=>t.auth!=="none","when")},{label:"Turborepo",name:"turborepo",repo:"vercel/turborepo",when:l(t=>t.projectType==="monorepo","when")},{label:"Ultracite",name:"ultracite",repo:"haydenbleasel/ultracite",when:l(t=>t.addons.includes("ultracite"),"when")}];function es(t){return Zr.filter(e=>e.when(t))}l(es,"resolveSkills");const ts=_e(Ye);function rs(t){return`npx skills add ${`https://github.com/${t.repo}`} --skill ${t.name}`}l(rs,"buildCommand");async function ss(t,e){const r={failed:[],installed:[]};if(!e.addons.includes("agent-skills"))return r;const s=es(e);for(const n of s)try{const o=rs(n);await ts(o,{cwd:t,maxBuffer:4*1024*1024,timeout:6e4}),r.installed.push(n.name)}catch(o){const a=o instanceof Error?o.message:"Unknown error";r.failed.push({error:a,name:n.name})}return r}l(ss,"installAgentSkills");class dt{static{l(this,"TemplateEngine")}cache={};cacheEnabled;templatesDir;constructor(e,r={}){this.templatesDir=e,this.cacheEnabled=r.cache??!0,dt.registerHelpers(r.helpers)}static registerHelpers(e){if(H.registerHelper("eq",(r,s)=>r===s),H.registerHelper("ne",(r,s)=>r!==s),H.registerHelper("lt",(r,s)=>r<s),H.registerHelper("gt",(r,s)=>r>s),H.registerHelper("and",(...r)=>(r.pop(),r.every(Boolean))),H.registerHelper("or",(...r)=>(r.pop(),r.some(Boolean))),H.registerHelper("includes",(r,s)=>Array.isArray(r)?r.includes(s):typeof r=="string"?r.includes(String(s)):!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((s,n)=>n===0?s.toLowerCase():s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),H.registerHelper("pascalCase",r=>r?.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),H.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),e)for(const[r,s]of Object.entries(e))H.registerHelper(r,s)}async loadTemplate(e){const r=e;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const s=w.join(this.templatesDir,e),n=await Z.readFile(s,"utf-8"),o=H.compile(n);return this.cacheEnabled&&(this.cache[r]=o),o}async renderTemplate(e,r){return(await this.loadTemplate(e))(r.context)}async renderToFile(e,r,s){return{content:await this.renderTemplate(e,s),filePath:r,isBinary:!1}}clearCache(){this.cache={}}getCacheStats(){return{enabled:this.cacheEnabled,size:Object.keys(this.cache).length}}}class as{static{l(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(e){this.baseDir=e}getBaseDir(){return this.baseDir}async writeFile(e,r={}){const s=w.join(this.baseDir,e.filePath),n=w.dirname(s);try{await Z.mkdir(n,{recursive:!0});let o=!1;try{await Z.stat(s),o=!0}catch{o=!1}if(o&&!r.overwrite)return{backed:!1,error:"File already exists and overwrite is disabled",filePath:s,written:!1};let a=!1;if(o&&r.createBackups&&!r.dryRun){const i=`${s}.bak`;await Z.copyFile(s,i),a=!0}return r.dryRun||(await Z.writeFile(s,e.content,"utf-8"),this.writtenFiles.add(s)),{backed:a,filePath:s,written:!r.dryRun}}catch(o){return{backed:!1,error:o instanceof Error?o.message:"Unknown error",filePath:s,written:!1}}}writeFiles(e,r={}){return Promise.all(e.map(s=>this.writeFile(s,r)))}async fileExists(e){const r=w.join(this.baseDir,e);try{return await Z.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(e,r){const s=[],n=w.join(this.baseDir,e),o=w.join(this.baseDir,r);await Z.mkdir(o,{recursive:!0});const a=await Z.readdir(n,{withFileTypes:!0});for(const i of a){const d=w.join(n,i.name),p=w.join(o,i.name);if(i.isDirectory()){const m=await this.copyDirectory(w.relative(this.baseDir,d),w.relative(this.baseDir,p));s.push(...m)}else{const m=await Z.readFile(d,"utf-8");await Z.writeFile(p,m,"utf-8"),s.push(p),this.writtenFiles.add(p)}}return s}}const Le=_e(dr);async function os(t){await Le("git",["init"],{cwd:t})}l(os,"gitInit");async function Gt(t){await Le("git",["add","."],{cwd:t})}l(Gt,"gitAddAll");async function zt(t,e){await Le("git",["commit","--no-verify","-m",e],{cwd:t})}l(zt,"gitCommit");async function ns(t){try{const{stdout:e}=await Le("git",["diff","--cached","--name-only"],{cwd:t});return e.trim().length>0}catch{return!1}}l(ns,"gitHasStagedChanges");async function is(t){try{return await ur(Y(t,".git")),!0}catch{return!1}}l(is,"gitDirectoryExists");const Nt=_e(Ye),cs={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
+ `,Go=c(e=>e>=4352&&e<=4447||e>=9001&&e<=9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=196605||e>=196608&&e<=262141,"isFullwidthCodePoint"),Xr=c(e=>{let t=0;for(const r of e){const s=r.codePointAt(0)??0;t+=Go(s)?2:1}return t},"getDisplayWidth"),Uo=2,es=[0,1,2,3,2,1],ts=["",".","..","..."],Lo=c(({message:e="Scaffolding your project",isError:t=!1,isComplete:r=!1,showProgressText:s=!0,paddingX:n=2})=>{const[o,a]=$(0),[i,p]=$(0),u=!t&&!r;ye(()=>{if(!u)return;const M=setInterval(()=>{a(B=>(B+1)%es.length)},200),W=setInterval(()=>{p(B=>(B+1)%ts.length)},400);return()=>{clearInterval(M),clearInterval(W)}},[u]);const m=Fo.trimEnd().split(`
17
+ `),g=Math.max(...m.map(Xr)),b=es[o];let S=_e,P="\u25CF",T=O;return t?(S=z,P="\u2717",T=H):r&&(S=Ue,P="\u2713",T=Ue),w(v,{flexDirection:"column",paddingX:n,children:[d(v,{flexDirection:"column",children:m.map((M,W)=>{const B=Xr(M),F=W===0||W===m.length-1,se=g-B+Uo-(F?1:0),L=W===b;return w(h,{color:z,children:[M," ".repeat(se),L?d(h,{color:S,children:P}):" "]},W)})}),s&&w(h,{color:T,children:[e,u?ts[i]:""]})]})},"ScaffoldingAnimation"),Jo=[{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"}],rs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Bo(e,t,r){if(!e)return r.map(o=>({stage:o,status:"pending"}));if(e==="complete")return r.map(o=>({stage:o,status:t?"failed":"completed"}));const n=r.map(o=>o.id).indexOf(e);return r.map((o,a)=>a<n?{stage:o,status:t?"failed":"completed"}:a===n?{stage:o,status:t?"failed":"active"}:t&&a>n?{stage:o,status:"pending"}:t?{stage:o,status:"failed"}:{stage:o,status:"pending"})}c(Bo,"getStages");function Zo(e,t){switch(e){case"completed":return"\u2713";case"active":return t;case"failed":return"\u2717";case"pending":return"\u25CB";default:return e}}c(Zo,"statusIcon");function Vo(e){switch(e){case"completed":return Ue;case"active":return _e;case"failed":return z;case"pending":return xe;default:return e}}c(Vo,"statusColor");function Ho(e){return e===void 0?"":` (${e}%)`}c(Ho,"formatPercentage");function Wo(e){return e?.message?e.message:"Installing dependencies..."}c(Wo,"getInstallMessage");const ss=c(({currentStage:e,generationMessage:t,installProgress:r,isError:s,skippedStages:n=[]})=>{const o=X(()=>Jo.filter(g=>!n.includes(g.id)),[n]),a=X(()=>Bo(e,s,o),[e,s,o]),[i,p]=$(0),u=e==="complete"&&!s;ye(()=>{if(s||u)return;const g=setInterval(()=>{p(b=>(b+1)%rs.length)},80);return()=>clearInterval(g)},[s,u]);const m=rs[i]??"\u280B";return w(v,{flexDirection:"column",paddingX:2,children:[d(v,{marginBottom:1,children:d(Lo,{showProgressText:!1,paddingX:0,isError:s,isComplete:u})}),d(v,{flexDirection:"column",rowGap:0,children:a.map(g=>{const b=g.status==="active",S=b&&g.stage.id==="install-dependencies",P=r?.percentage,T=16,M=P===void 0?0:Math.round(P/100*T),W=T-M;return w(v,{flexDirection:"column",children:[w(v,{children:[w(h,{bold:b,color:Vo(g.status),children:[Zo(g.status,m)," ",g.stage.label]}),S?d(h,{children:P===void 0?null:w(V,{children:[d(h,{color:_e,children:Ho(P)})," ",d(h,{color:_e,children:"\u2588".repeat(M)}),d(h,{color:Oe,children:"\u2591".repeat(W)})]})}):null]}),S?d(v,{marginLeft:4,children:d(h,{color:O,children:Wo(r)})}):null]},g.stage.id)})}),!s&&e===null?d(v,{marginTop:1,children:d(h,{color:O,children:t})}):null,u?d(v,{marginTop:1,children:d(h,{color:Ue,children:t})}):null,s?d(v,{marginTop:1,flexDirection:"column",children:t.split(`
18
+ `).map((g,b)=>d(h,{color:g.startsWith(" ")?O:z,children:g},b))}):null]})},"InstallationProgress"),Bt=c(({action:e="select",showBack:t=!1})=>w(h,{children:[e==="select"||e==="multi-select"?d(h,{color:O,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,d(h,{color:O,children:e==="confirm"?w(V,{children:[d(h,{color:H,children:"Enter "}),"to confirm"]}):e==="multi-select"?w(V,{children:[d(h,{color:H,children:"Space "}),"to toggle \u2022",d(h,{color:H,children:" Enter "}),"to confirm"]}):w(V,{children:[d(h,{color:H,children:"Enter "}),"to select"]})}),w(h,{color:O,children:[t?w(V,{children:[" ","\u2022",d(h,{color:H,children:" Ctrl+B "}),"to go back"]}):"",w(V,{children:[" ","\u2022",d(h,{color:H,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),ns=c(({architecture:e,projectName:t,packageManager:r,isGitInitialized:s,dependenciesInstalled:n,outputDir:o})=>d(v,{flexDirection:"column",children:w(v,{flexDirection:"column",marginTop:1,children:[d(h,{color:Ue,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),w(v,{marginTop:1,children:[d(h,{color:H,children:"Project: "}),d(h,{color:ie,bold:!0,children:t})]}),w(v,{children:[d(h,{color:H,children:"Architecture: "}),d(h,{color:ie,bold:!0,children:e})]}),o?w(v,{children:[d(h,{color:H,children:"Location: "}),d(h,{color:ie,bold:!0,children:o})]}):null,s?d(v,{marginTop:1,children:d(h,{color:O,children:"Git repository initialized"})}):null,w(v,{flexDirection:"column",borderStyle:"round",borderColor:z,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[d(h,{color:H,bold:!0,children:"\u{1F680} NEXT STEPS"}),d(v,{height:1}),d(h,{color:H,children:"1. Move into the project directory:"}),d(h,{color:ie,bold:!0,children:` cd ${t}`}),d(v,{height:1}),n?d(v,{children:d(h,{color:O,children:"2. Dependencies already installed"})}):w(V,{children:[d(h,{color:H,children:"2. Install dependencies:"}),d(h,{color:ie,bold:!0,children:` ${r} install`})]}),d(v,{height:1}),w(h,{color:H,children:["3."," Start development server:"]}),d(h,{color:ie,bold:!0,children:` ${r} run dev`})]}),d(v,{marginTop:1,children:d(h,{color:O,children:"(Press enter to exit)"})})]})}),"DoneStep"),Ko=100,ut=c(e=>{const t=at(0);Re((r,s)=>{if(s.upArrow||s.downArrow||s.leftArrow||s.rightArrow||r==="k"||r==="j"||r==="h"||r==="l"){const o=Date.now();if(o-t.current<Ko)return;t.current=o}e(r,s)})},"useArrowSelect"),Qo=c(({initialSelected:e,onConfirm:t,onChange:r,options:s,prompt:n,minified:o=!1,exclusiveValue:a})=>{const i=X(()=>new Set(s.map(I=>I.value)),[s]),p=N(I=>I.filter(q=>i.has(q)),[i]),[u,m]=$(0),[g,b]=$(()=>p(e)),S=at(g);S.current=g;const P=at(r);P.current=r,ye(()=>{const I=p(e);b(I),m(0),P.current?.(I)},[e,p]);const T=N(I=>g.includes(I),[g]),M=N(I=>{const q=s[I];q&&b(Z=>{let ne;return Z.includes(q.value)?ne=Z.filter(ce=>ce!==q.value):q.value===a?ne=[q.value]:ne=[...Z.filter(ce=>ce!==a),q.value],S.current=ne,r?.(ne),ne})},[s,r,a]),W=N(()=>{t(S.current)},[t]),B=s.length>16,F=B?Math.ceil(s.length/2):s.length;ut((I,q)=>{q.upArrow||I==="k"?m(Z=>(Z-1+s.length)%s.length):q.downArrow||I==="j"?m(Z=>(Z+1)%s.length):B&&(q.leftArrow||I==="h")?m(Z=>(Z-F+s.length)%s.length):B&&(q.rightArrow||I==="l")?m(Z=>(Z+F)%s.length):q.return?W():(I===" "||I==="x")&&M(u)});const se=g.length,L=c((I,q)=>{const Z=T(I.value),ne=q===u,ce=Z?"\u25CF":"\u25CB";return w(v,{flexDirection:"column",children:[d(h,{children:ne?w(V,{children:[d(h,{color:z,children:"> "}),d(h,{color:Z?z:O,children:`${ce} `}),d(h,{color:Z?z:H,children:I.label})]}):w(V,{children:[d(h,{color:Z?z:O,children:` ${ce}`}),d(h,{color:xe,children:` ${I.label}`})]})}),ne&&!B?w(h,{color:O,children:[" ",I.description]}):null]},I.value)},"renderOption");let K;return B||(K=o?0:1),w(v,{flexDirection:"column",children:[d(h,{color:O,children:n}),d(h,{color:_e,children:se===0?"No options selected yet \u2014 pick what you need":`${se} selected`}),d(v,{marginTop:1,flexDirection:B?"row":"column",rowGap:K,columnGap:B?4:void 0,overflow:"hidden",children:B?w(V,{children:[d(v,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice(0,F).map((I,q)=>L(I,q))}),d(v,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice(F).map((I,q)=>L(I,q+F))})]}):s.map((I,q)=>L(I,q))})]})},"MultiSelectStep"),as="my-nest-app",os=64,Yo=/^[a-z][a-z0-9-]*$/u;function Te(e){return e.trim()||as}c(Te,"resolveProjectName");function dt(e){const t=e.trim();return t?t.length>os?`Project name must be at most ${os} characters`:Yo.test(t)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}c(dt,"validateProjectName");const is=c(({error:e,onChange:t,onSubmit:r,value:s})=>(Re((n,o)=>{o.return&&r()}),w(v,{flexDirection:"column",children:[d(h,{color:O,children:"Enter a name for your project"}),w(v,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[d(h,{color:H,children:"Project name:"}),d(Eo,{placeholder:as,value:s,onChange:t})]}),e?d(h,{color:z,children:e}):null]})),"ProjectNameStep"),mt=Po({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:he.string().pipe(he.coerce.number()).default(95),NEST_ARCH_BETA_MODE:he.enum(["true","false"]).default("false").transform(e=>e==="true"),NEST_ARCH_SCHEMA_URL:he.string().default("./schema.json"),NEST_ARCH_VERSION:he.string().default("0.0.1"),NODE_ENV:he.enum(["development","production","test"]).default("development")}}),Je=c(({onConfirm:e,options:t,prompt:r,initialValue:s})=>{const[n,o]=$(()=>{const i=t.findIndex(p=>p.value===s);return Math.max(i,0)});ye(()=>{const i=t.findIndex(p=>p.value===s);o(Math.max(i,0))},[s,t]);const a=N(()=>{const i=t[n];i&&!(i.devOnly&&mt.NODE_ENV==="production")&&e(i.value)},[e,t,n]);return ut((i,p)=>{p.upArrow||i==="k"?o(u=>(u-1+t.length)%t.length):p.downArrow||i==="j"?o(u=>(u+1)%t.length):p.return&&a()}),w(v,{flexDirection:"column",children:[d(h,{color:O,children:r}),d(v,{marginTop:1,flexDirection:"column",rowGap:1,children:t.map((i,p)=>{const u=p===n;return w(v,{flexDirection:"column",children:[d(h,{children:u?d(V,{children:i.devOnly&&mt.NODE_ENV==="production"?w(V,{children:[d(h,{color:xe,children:"> "}),w(h,{color:xe,children:[i.label,". (Comming soon)"]})]}):w(V,{children:[d(h,{color:z,children:"> "}),d(h,{color:z,children:i.label})]})}):d(h,{color:xe,children:` ${i.label}`})}),u?d(h,{color:O,children:i.description}):null]},i.value)})})]})},"SingleSelectStep"),cs=[{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"}],ls=[{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"}],ps=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],us=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",devOnly:!0,label:"Monorepo (Turborepo)",value:"monorepo"}],ds=[{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"}],Zt=[{description:"Native MongoDB with Express/REST (no ORM or authentication)",label:"MongoDB",value:"mongodb"},{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"}],ms=[{description:"Prisma 7 with schema and migrations for PostgreSQL, MySQL, and SQLite",label:"Prisma",value:"prisma"},{description:"Decorator-based ORM for TypeScript",label:"TypeORM",value:"typeorm"},{description:"Lightweight SQL ORM (SQL only)",label:"Drizzle",value:"drizzle"}],hs=[{description:"Classic Prisma ORM with driver adapters for PostgreSQL, MySQL, and SQLite",label:"Prisma 7",value:"7"}],fs=[{description:"Express with PostgreSQL/Prisma 7 (no authentication)",label:"GraphQL",value:"graphql"},{description:"RESTful HTTP endpoints",label:"REST",value:"rest"},{description:"End-to-end typesafe APIs",label:"tRPC",value:"trpc"}],gs=[{description:"Express/REST with PostgreSQL/Prisma 7",label:"Passport",value:"passport"},{description:"No authentication scaffolding",label:"None",value:"none"},{description:"Database-backed sessions with native PostgreSQL, Prisma 7/PostgreSQL, or Drizzle/SQLite",label:"Better Auth",value:"better-auth"}],Vt=[{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 example for a supported API/database combination",label:"Todo Example",value:"todo-example"},{description:"Latest TypeScript compiler \u2014 faster checking and new language features (default: TypeScript 6)",label:"TypeScript 7",value:"typescript-7"}],ys=[{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"}],Xo=[{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"}],bs=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],ei=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],ti=[{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"}],ri=[{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"}],si=[{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"}],ni=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],ai={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",prismaVersion:"Prisma version",projectName:"Project name",projectType:"Project type",summary:"Summary",ultraciteAgents:"Ultracite agents",ultraciteEditors:"Ultracite editors",ultraciteHooks:"Ultracite hooks",ultraciteInstallSkill:"Ultracite skill"};var oi=Object.defineProperty,l=c((e,t)=>oi(e,"name",{value:t,configurable:!0}),"c");const ii=[{label:"NestJS Best Practices",name:"nestjs-best-practices",repo:"kadajett/agent-nestjs-skills",when:l(()=>!0,"when")},{label:"Prisma CLI",name:"prisma-cli",repo:"prisma/skills",when:l(e=>e.orm.includes("prisma"),"when")},{label:"Prisma Client API",name:"prisma-client-api",repo:"prisma/skills",when:l(e=>e.orm.includes("prisma"),"when")},{label:"Prisma Database Setup",name:"prisma-database-setup",repo:"prisma/skills",when:l(e=>e.orm.includes("prisma"),"when")},{label:"Prisma NestJS Patterns",name:"prisma-nestjs-patterns",repo:"davidcastagnetoa/skills",when:l(e=>e.orm.includes("prisma"),"when")},{label:"NestJS TypeORM Integration",name:"nestjs-typeorm-integration",repo:"vong3432/vibemark",when:l(e=>e.orm.includes("typeorm"),"when")},{label:"Better Auth Best Practices",name:"better-auth-best-practices",repo:"better-auth/skills",when:l(e=>e.auth==="better-auth"||e.auth==="better-auth:stateless","when")},{label:"JWT Security",name:"jwt-security",repo:"mindrally/skills",when:l(e=>e.auth!=="none","when")},{label:"Turborepo",name:"turborepo",repo:"vercel/turborepo",when:l(e=>e.projectType==="monorepo","when")},{label:"Ultracite",name:"ultracite",repo:"haydenbleasel/ultracite",when:l(e=>e.addons.includes("ultracite"),"when")}];function vs(e){return ii.filter(t=>t.when(e))}c(vs,"Ie"),l(vs,"resolveSkills");const ci=ct(Lt);function ws(e){return`npx skills add ${`https://github.com/${e.repo}`} --skill ${e.name}`}c(ws,"_r"),l(ws,"buildCommand");async function js(e,t){const r={failed:[],installed:[]};if(!t.addons.includes("agent-skills"))return r;const s=vs(t);for(const n of s)try{const o=ws(n);await ci(o,{cwd:e,maxBuffer:4*1024*1024,timeout:6e4}),r.installed.push(n.name)}catch(o){const a=o instanceof Error?o.message:"Unknown error";r.failed.push({error:a,name:n.name})}return r}c(js,"Oe"),l(js,"installAgentSkills");class Vr{static{c(this,"ce")}static{l(this,"TemplateEngine")}cache={};cacheEnabled;templatesDir;constructor(t,r={}){this.templatesDir=t,this.cacheEnabled=r.cache??!0,Vr.registerHelpers(r.helpers)}static registerHelpers(t){if(ae.registerHelper("eq",(r,s)=>r===s),ae.registerHelper("ne",(r,s)=>r!==s),ae.registerHelper("lt",(r,s)=>r<s),ae.registerHelper("gt",(r,s)=>r>s),ae.registerHelper("and",(...r)=>(r.pop(),r.every(Boolean))),ae.registerHelper("or",(...r)=>(r.pop(),r.some(Boolean))),ae.registerHelper("includes",(r,s)=>Array.isArray(r)?r.includes(s):typeof r=="string"?r.includes(String(s)):!1),ae.registerHelper("uppercase",r=>r?.toUpperCase?.()),ae.registerHelper("lowercase",r=>r?.toLowerCase?.()),ae.registerHelper("capitalize",r=>r?r.charAt(0).toUpperCase()+r.slice(1):""),ae.registerHelper("camelCase",r=>r?.split("-").map((s,n)=>n===0?s.toLowerCase():s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),ae.registerHelper("pascalCase",r=>r?.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),ae.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),t)for(const[r,s]of Object.entries(t))ae.registerHelper(r,s)}async loadTemplate(t){const r=t;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const s=j.join(this.templatesDir,t),n=await me.readFile(s,"utf-8"),o=ae.compile(n);return this.cacheEnabled&&(this.cache[r]=o),o}async renderTemplate(t,r){return(await this.loadTemplate(t))(r.context)}async renderToFile(t,r,s){return{content:await this.renderTemplate(t,s),filePath:r,isBinary:!1}}clearCache(){this.cache={}}getCacheStats(){return{enabled:this.cacheEnabled,size:Object.keys(this.cache).length}}}class li{static{c(this,"$e")}static{l(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(t){this.baseDir=t}getBaseDir(){return this.baseDir}async writeFile(t,r={}){const s=j.join(this.baseDir,t.filePath),n=j.dirname(s);try{await me.mkdir(n,{recursive:!0});let o=!1;try{await me.stat(s),o=!0}catch{o=!1}if(o&&!r.overwrite)return{backed:!1,error:"File already exists and overwrite is disabled",filePath:s,written:!1};let a=!1;if(o&&r.createBackups&&!r.dryRun){const i=`${s}.bak`;await me.copyFile(s,i),a=!0}return r.dryRun||(await me.writeFile(s,t.content,"utf-8"),this.writtenFiles.add(s)),{backed:a,filePath:s,written:!r.dryRun}}catch(o){return{backed:!1,error:o instanceof Error?o.message:"Unknown error",filePath:s,written:!1}}}writeFiles(t,r={}){return Promise.all(t.map(s=>this.writeFile(s,r)))}async fileExists(t){const r=j.join(this.baseDir,t);try{return await me.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(t,r){const s=[],n=j.join(this.baseDir,t),o=j.join(this.baseDir,r);await me.mkdir(o,{recursive:!0});const a=await me.readdir(n,{withFileTypes:!0});for(const i of a){const p=j.join(n,i.name),u=j.join(o,i.name);if(i.isDirectory()){const m=await this.copyDirectory(j.relative(this.baseDir,p),j.relative(this.baseDir,u));s.push(...m)}else{const m=await me.readFile(p,"utf-8");await me.writeFile(u,m,"utf-8"),s.push(u),this.writtenFiles.add(u)}}return s}}const ht=ct(Io);async function Ht(e){await ht("git",["init"],{cwd:e})}c(Ht,"pe"),l(Ht,"gitInit");async function ft(e){await ht("git",["add","."],{cwd:e})}c(ft,"H"),l(ft,"gitAddAll");async function gt(e,t){await ht("git",["commit","--no-verify","-m",t],{cwd:e})}c(gt,"X"),l(gt,"gitCommit");async function Ss(e){try{const{stdout:t}=await ht("git",["diff","--cached","--name-only"],{cwd:e});return t.trim().length>0}catch{return!1}}c(Ss,"Ce"),l(Ss,"gitHasStagedChanges");async function Wt(e){try{return await zo(ee(e,".git")),!0}catch{return!1}}c(Wt,"le"),l(Wt,"gitDirectoryExists");class bd{static{c(this,"kr")}static{l(this,"GitInitializer")}baseDir;constructor(t){this.baseDir=t}async initGit(){try{return await Wt(this.baseDir)?{success:!0}:(await Ht(this.baseDir),await ft(this.baseDir),await gt(this.baseDir,"init"),{success:!0})}catch(t){return{error:t instanceof Error?t.message:String(t),success:!1}}}}const ks=ct(Lt),pi={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 ls(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}`)}}}l(ls,"getFormatterCommand");function ps(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="EINVAL")}l(ps,"isPackageManagerNotFoundError");async function ds(t,e){const r=ls(t);try{return await Nt(r,{cwd:e,timeout:12e4}),await Nt(r,{cwd:e,timeout:12e4}),{success:!0}}catch(s){return ps(s)?{error:cs[t],success:!1}:{success:!0}}}l(ds,"runFormatter");const us=_e(Ye);function ms(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}`}}l(ms,"buildUltraciteInitCommand");function hs(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"}}l(hs,"mapFormatterToLinter");async function gs(t){const e=Y(t,"package.json");try{const s=await Ce(e,"utf-8"),n=JSON.parse(s);n.devDependencies&&(n.devDependencies=Object.fromEntries(Object.entries(n.devDependencies).filter(([o])=>!o.startsWith("stylelint")))),await ve(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 s of r){const n=Y(t,s);je(n)&&await mr(n,{force:!0})}}l(gs,"removeStylelint");async function fs(t,e){const r=hs(e.formatter);if(r==="none")return{message:"Skipping ultracite init (no formatter selected)",success:!0};const s=[];e.addons.includes("husky")&&s.push("husky");const n=["ultracite","init","--quiet","--skip-install","--pm",e.packageManager,"--linter",r,"--frameworks","nestjs"];s.length>0&&n.push("--integrations",...s),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 o=ms(e.packageManager,n);try{return await us(o,{cwd:t,timeout:12e4}),e.formatter==="eslint-prettier-no-stylelint"&&await gs(t),{message:"Ultracite setup completed",success:!0}}catch(a){let i=a instanceof Error?a.message:String(a);if(a&&typeof a=="object"&&"stderr"in a){const d=a.stderr?.trim();d&&(i=`${i}
24
- ${d}`)}return{message:`Ultracite setup failed: ${i}`,success:!1}}}l(fs,"runUltraciteInit");class ys{static{l(this,"TemplateRegistry")}templates=new Map;groups=new Map;registerTemplate(e){this.templates.set(e.id,e)}registerTemplates(e){for(const r of e)this.registerTemplate(r)}registerGroup(e){this.groups.set(e.id,e);for(const r of e.templates)this.registerTemplate(r)}getTemplate(e){return this.templates.get(e)}getGroup(e){return this.groups.get(e)}getAllTemplates(){return[...this.templates.values()]}getAllGroups(){return[...this.groups.values()]}getTemplatesByGroup(e){return this.groups.get(e)?.templates||[]}getTemplatesByFormat(e){return[...this.templates.values()].filter(r=>r.format===e)}async loadFromDirectory(e,r){const s=[];try{const n=await Z.readdir(e,{withFileTypes:!0});for(const o of n){if(!o.isFile())continue;const{name:a}=o,i=w.extname(a);if(i===".hbs"){const d=w.basename(a,i),p={description:`Template: ${d}`,format:"handlebars",id:d,name:d.replaceAll(/[-_]/gu," "),optional:a.startsWith("_"),path:w.join(w.relative(w.dirname(e),e),a)};s.push(p),this.registerTemplate(p)}}if(r&&s.length>0){const o={description:`Templates from ${e}`,id:r,name:r,templates:s};this.registerGroup(o)}}catch(n){console.error(`Failed to load templates from ${e}:`,n)}return s}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function _o(t,e,r){}l(_o,"log");const ct={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 bs(t){const e=Y(t,"oxlint.config.ts");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}let s=r;/import vitest from "ultracite\/oxlint\/vitest"/u.test(r)||(s=s.replace(/(import nestjs from "ultracite\/oxlint\/nestjs";)/u,`$1
25
- import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(ct.oxlint).map(([a,i])=>{const d=Array.isArray(i)?JSON.stringify(i):`"${i}"`;return` "${a}": ${d}`}).join(`,
26
- `),o=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);s=s.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(a,i)=>{const d=i.includes("vitest"),p=i.includes("ignorePatterns"),m=i.includes("rules:"),g=i.includes("overrides:");let b=i;return d||(b=b.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(q,M,U,F)=>{const _=U.trimEnd(),$=!_.endsWith(",");return`${M}${_}${$?",":""}
22
+ `)};function _s(e){switch(e){case"pnpm":return"pnpm run format";case"npm":return"npm run format";case"yarn":return"yarn run format";case"bun":return"bun run format";default:{const t=e;throw new Error(`Unsupported package manager: ${t}`)}}}c(_s,"Tr"),l(_s,"getFormatterCommand");function xs(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="EINVAL")}c(xs,"Er"),l(xs,"isPackageManagerNotFoundError");async function Ts(e,t){const r=_s(e);try{return await ks(r,{cwd:t,timeout:12e4}),await ks(r,{cwd:t,timeout:12e4}),{success:!0}}catch(s){if(xs(s))return{error:pi[e],success:!1};const n=[s instanceof Error?s.message:String(s)];return s&&typeof s=="object"&&("stdout"in s&&typeof s.stdout=="string"&&n.push(s.stdout),"stderr"in s&&typeof s.stderr=="string"&&n.push(s.stderr)),{error:n.join(`
23
+ `),success:!1}}}c(Ts,"De"),l(Ts,"runFormatter");const Be={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":"^24.0.0",dotenv:"^17.2.2",typescript:"^6.0.2","typescript-7":"^7.0.0",zod:"^4.4.3"},dependencies:{"@apollo/server":"^5.5.1","@as-integrations/express5":"^1.1.2","@as-integrations/fastify":"^3.1.0","@better-auth/drizzle-adapter":"^1.2.0","@grpc/grpc-js":"^1.12.0","@grpc/proto-loader":"^0.7.13","@nats-io/transport-node":"^3.4.0","@nestjs/apollo":"^14.0.0","@nestjs/common":"^12.0.1","@nestjs/core":"^12.0.1","@nestjs/graphql":"^14.0.0","@nestjs/jwt":"^11.0.0","@nestjs/microservices":"^12.0.1","@nestjs/passport":"^11.0.0","@nestjs/platform-express":"^12.0.1","@nestjs/platform-fastify":"^12.0.1","@nestjs/swagger":"^12.0.1","@nestjs/terminus":"^12.0.0","@nestjs/throttler":"6.5.0","@nestjs/typeorm":"12.0.1","@prisma/adapter-better-sqlite3":"^7.10.0","@prisma/adapter-mariadb":"^7.10.0","@prisma/adapter-pg":"^7.10.0","@prisma/adapter-ppg":"^7.10.0","@prisma/client":"^7.10.0","@prisma/orm-mongo":"^8.0.0-rc.8","@prisma/orm-postgres":"^8.0.0-rc.8","@scalar/nestjs-api-reference":"^1.2.17","@t3-oss/env-core":"^0.13.11","@thallesp/nestjs-better-auth":"^2.8.0","@trpc/client":"^11.18.0","@trpc/openapi":"^11.18.0-alpha","@trpc/server":"^11.18.0","amqp-connection-manager":"^5.0.0",amqplib:"^0.10.5",bcrypt:"^6.0.0","better-auth":"^1.7.5","better-sqlite3":"^12.11.1",dotenv:"^17.2.2","drizzle-graphql":"^0.8.5","drizzle-orm":"^0.45.2",graphql:"^17.0.2","graphql-scalars":"^2.0.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.13.0","nestjs-zod":"^5.5.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","temporal-polyfill":"^1.0.4",typeorm:"^1.1.1","typeorm-relations-graphql":"^3.0.0",zod:"^4.5.4"},devDependencies:{"@nestjs/cli":"^12.0.0","@nestjs/mau":"^0.2.6","@nestjs/schematics":"^12.0.0","@nestjs/testing":"^12.0.1","@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.2","drizzle-kit":"^0.31.10",husky:"^9.1.7",oxfmt:"^0.66.0",oxlint:"^1.81.0",prettier:"^3.4.2",prisma:"^7.10.0","source-map-support":"^0.5.21",supertest:"^7.0.0",turbo:"^2.8.12",typescript:"^6.0.2","typescript-7":"^7.0.0",ultracite:"7.9.4",vitest:"^4.1.10"}};function As(e,t){const r=e.addons.includes("ultracite"),s={};return e.extras.includes("swagger")||Object.assign(s,{"@darraghor/nestjs-typed/api-method-should-specify-api-operation":"off","@darraghor/nestjs-typed/api-method-should-specify-api-response":"off","@darraghor/nestjs-typed/controllers-should-supply-api-tags":"off"}),e.auth==="none"&&(s["@darraghor/nestjs-typed/api-methods-should-be-guarded"]="off"),['import { defineConfig } from "eslint/config";','import ts from "@typescript-eslint/eslint-plugin";','import parser from "@typescript-eslint/parser";',...r?['import nestjs from "ultracite/eslint/nestjs";']:[],"","export default defineConfig([",` { ignores: ${JSON.stringify(t)} },`,` { files: ["**/*.ts"], languageOptions: { parser${r?", parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname }":""} }, plugins: { "@typescript-eslint": ts }, rules: ts.configs.recommended.rules },`,...r?[" // Only the backend preset: eslint/core imports frontend plugins."," { extends: [nestjs] },",` { files: ["**/*.ts"], rules: ${JSON.stringify(s)} },`," // Nest's per-class Logger intentionally uses the class name.",' { files: ["**/trpc/error.handler.ts"], rules: { "@darraghor/nestjs-typed/use-dependency-injection": "off" } },']:[],"]);",""].join(`
24
+ `)}c(As,"Ar"),l(As,"createEslintConfig");async function Es(e,t){const r=t.addons.includes("ultracite"),s=ee(e,"package.json"),n=JSON.parse(await De(s,"utf-8")),o=n.devDependencies??{},a=n.scripts??{},i={},p=["**/node_modules/**","**/dist/**","**/coverage/**","**/.turbo/**","**/generated/**","**/@generated/**","**/migrations/**"];if(r&&(o.ultracite=Be.devDependencies.ultracite),t.formatter==="biome")o["@biomejs/biome"]="2.5.3",i["biome.jsonc"]=JSON.stringify({...r?{extends:["ultracite/biome/core","ultracite/biome/nestjs"]}:{},files:{includes:["**",...p.map(u=>`!${u.replace(/\/\*\*$/u,"")}`)]},javascript:{parser:{unsafeParameterDecoratorsEnabled:!0}},linter:{enabled:!0,rules:{complexity:{noStaticOnlyClass:"off",noUselessConstructor:"off"},preset:"recommended",style:{useImportType:"off"}}}},null,2),a.check="biome check .",a.fix="biome check --write .",a.format="biome check --write --unsafe .";else if(t.formatter==="oxlint-oxfmt")o.oxlint=Be.devDependencies.oxlint,o.oxfmt=Be.devDependencies.oxfmt,i["oxlint.config.ts"]=`import { defineConfig } from "oxlint";
25
+ ${r?`import core from "ultracite/oxlint/core";
26
+ import nestjs from "ultracite/oxlint/nestjs";
27
+ `:""}export default defineConfig({
28
+ ${r?` extends: [core, nestjs],
29
+ `:` plugins: ["typescript", "unicorn", "oxc"],
30
+ `} ignorePatterns: ${JSON.stringify(p)},
31
+ });
32
+ `,r?i["oxfmt.config.ts"]=`import { defineConfig } from "oxfmt";
33
+ import core from "ultracite/oxfmt";
34
+
35
+ export default defineConfig({ ...core, ignorePatterns: ${JSON.stringify(p)} });
36
+ `:i[".oxfmtrc.json"]=JSON.stringify({ignorePatterns:p},null,2),a.check="oxlint && oxfmt --check .",a.fix="oxlint --fix && oxfmt --write .",a.format="oxlint --fix && oxfmt --write .";else{o.eslint="^10.0.0",o.prettier=Be.devDependencies.prettier,o["@typescript-eslint/parser"]="^8.62.1",o["@typescript-eslint/eslint-plugin"]="^8.62.1",r&&(o["@darraghor/eslint-plugin-nestjs-typed"]="^7.2.5"),i["eslint.config.mjs"]=As(t,p),i["prettier.config.mjs"]=r?`export { default } from "ultracite/prettier";
37
+ `:`export default {};
38
+ `,i[".prettierignore"]=`${p.join(`
39
+ `)}
40
+ `;const u='eslint "**/src/**/*.ts" "**/test/**/*.ts"';a.check=`${u} && prettier --check .`,a.fix=`${u} --fix && prettier --write .`,a.format=r?a.fix:"prettier --write .",t.formatter==="eslint-prettier-stylelint"&&(o.stylelint="^17.15.0",o["stylelint-config-standard"]="^40.0.0",i["stylelint.config.mjs"]=`export default { extends: ["stylelint-config-standard"] };
41
+ `,a.check+=' && stylelint "**/*.css" --allow-empty-input',a.fix+=' && stylelint "**/*.css" --fix --allow-empty-input')}n.devDependencies=o,n.scripts=a;for(const[u,m]of Object.entries(i))await be(ee(e,u),`${m.trim()}
42
+ `);await be(s,`${JSON.stringify(n,null,2)}
43
+ `)}c(Es,"Pr"),l(Es,"setupManualLinter");const ui=ct(Lt);function Ps(e,t){const r=t.join(" ");switch(e){case"pnpm":return`pnpm dlx ${r}`;case"yarn":return`yarn dlx ${r}`;case"bun":return`bunx ${r}`;default:return`npx --yes ${r}`}}c(Ps,"zr"),l(Ps,"buildUltraciteInitCommand");function Is(e){switch(e){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"}}c(Is,"Ir"),l(Is,"mapFormatterToLinter");async function zs(e,t){const r=Is(t.formatter);if(r==="none")return{message:"Skipping ultracite init (no formatter selected)",success:!0};if(!t.addons.includes("ultracite")||t.formatter==="eslint-prettier-no-stylelint"||t.formatter!=="eslint-prettier-stylelint"&&t.ultraciteAgents.length===0&&t.ultraciteEditors.length===0&&t.ultraciteHooks.length===0&&t.ultraciteInstallSkill==="no"&&!t.addons.includes("husky"))try{return await Es(e,t),{message:"Manual linter configuration completed",success:!0}}catch(a){return{message:String(a),success:!1}}const s=[];t.addons.includes("husky")&&s.push("husky");const n=["ultracite","init","--quiet","--skip-install","--pm",t.packageManager,"--linter",r,"--frameworks","nestjs"];s.length>0&&n.push("--integrations",...s),t.addons.includes("ultracite")&&(t.ultraciteEditors.length>0&&n.push("--editors",...t.ultraciteEditors),t.ultraciteAgents.length>0&&n.push("--agents",...t.ultraciteAgents),t.ultraciteHooks.length>0&&n.push("--hooks",...t.ultraciteHooks),t.ultraciteInstallSkill==="yes"&&n.push("--install-skill"));const o=Ps(t.packageManager,n);try{await ui(o,{cwd:e,timeout:12e4});const a=ee(e,"package.json"),i=JSON.parse(await De(a,"utf-8"));return i.scripts={...i.scripts,format:{biome:"biome format --write .",eslint:"prettier --write .",oxlint:"oxfmt --write ."}[r]},await be(a,`${JSON.stringify(i,null,2)}
44
+ `),{message:"Ultracite setup completed",success:!0}}catch(a){let i=a instanceof Error?a.message:String(a);if(a&&typeof a=="object"&&"stderr"in a){const p=a.stderr?.trim();p&&(i=`${i}
45
+ ${p}`)}return{message:`Ultracite setup failed: ${i}`,success:!1}}}c(zs,"Ne"),l(zs,"runUltraciteInit");class di{static{c(this,"Me")}static{l(this,"TemplateRegistry")}templates=new Map;groups=new Map;registerTemplate(t){this.templates.set(t.id,t)}registerTemplates(t){for(const r of t)this.registerTemplate(r)}registerGroup(t){this.groups.set(t.id,t);for(const r of t.templates)this.registerTemplate(r)}getTemplate(t){return this.templates.get(t)}getGroup(t){return this.groups.get(t)}getAllTemplates(){return[...this.templates.values()]}getAllGroups(){return[...this.groups.values()]}getTemplatesByGroup(t){return this.groups.get(t)?.templates||[]}getTemplatesByFormat(t){return[...this.templates.values()].filter(r=>r.format===t)}async loadFromDirectory(t,r){const s=[];try{const n=await me.readdir(t,{withFileTypes:!0});for(const o of n){if(!o.isFile())continue;const{name:a}=o,i=j.extname(a);if(i===".hbs"){const p=j.basename(a,i),u={description:`Template: ${p}`,format:"handlebars",id:p,name:p.replaceAll(/[-_]/gu," "),optional:a.startsWith("_"),path:j.join(j.relative(j.dirname(t),t),a)};s.push(u),this.registerTemplate(u)}}if(r&&s.length>0){const o={description:`Templates from ${t}`,id:r,name:r,templates:s};this.registerGroup(o)}}catch(n){console.error(`Failed to load templates from ${t}:`,n)}return s}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function mi(e,t,r){}c(mi,"Sc"),l(mi,"log");const Kt={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 Rs(e){const t=ee(e,"oxlint.config.ts");let r;try{r=await De(t,"utf-8"),`${t}`}catch{return}let s=r;/import vitest from "ultracite\/oxlint\/vitest"/u.test(r)||(s=s.replace(/(import nestjs from "ultracite\/oxlint\/nestjs";)/u,`$1
46
+ import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(Kt.oxlint).map(([a,i])=>{const p=Array.isArray(i)?JSON.stringify(i):`"${i}"`;return` "${a}": ${p}`}).join(`,
47
+ `),o=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);s=s.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(a,i)=>{const p=i.includes("vitest"),u=i.includes("ignorePatterns"),m=i.includes("rules:"),g=i.includes("overrides:");let b=i;return p||(b=b.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(S,P,T,M)=>{const W=T.trimEnd(),B=!W.endsWith(",");return`${P}${W}${B?",":""}
27
48
  vitest,
28
- ${F.trimStart()}`})),p||(b=b.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
49
+ ${M.trimStart()}`})),u||(b=b.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
29
50
  ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**"],`)),g||(b=`${b} overrides: [
30
51
  {
31
52
  files: ["**/*.{test,spec}.{ts,tsx,js,jsx}"],
@@ -38,101 +59,293 @@ import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(ct.oxlin
38
59
  `),m||(b=`${b} rules: {
39
60
  ${n},
40
61
  },
41
- `),`export default defineConfig({${b}});`});try{await ve(e,s,"utf-8"),`${e}`}catch{}}l(bs,"injectOxlintRules");async function ws(t){const e=Y(t,"biome.jsonc");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}const s=ct.biome,n=r.includes('"linter"'),o=r.includes('"rules"');if(n&&o){const a=Object.entries(s).flatMap(([d,p])=>Object.entries(p).map(([m,g])=>` "${d}": {
62
+ `),`export default defineConfig({${b}});`});try{await be(t,s,"utf-8"),`${t}`}catch{}}c(Rs,"Or"),l(Rs,"injectOxlintRules");async function Os(e){const t=ee(e,"biome.jsonc");let r;try{r=await De(t,"utf-8"),`${t}`}catch{return}const s=Kt.biome,n=r.includes('"linter"'),o=r.includes('"rules"');if(n&&o){const a=Object.entries(s).flatMap(([p,u])=>Object.entries(u).map(([m,g])=>` "${p}": {
42
63
  "${m}": "${g}"
43
64
  }`)).join(`,
44
- `),i=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(d,p,m,g)=>{const b=m.trim().endsWith(",")?"":",";return`${p}${m}${b}
65
+ `),i=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(p,u,m,g)=>{const b=m.trim().endsWith(",")?"":",";return`${u}${m}${b}
45
66
  ${a}
46
- ${g}`});try{await ve(e,i,"utf-8"),`${e}`}catch{}}else{const i=` "linter": {
67
+ ${g}`});try{await be(t,i,"utf-8"),`${t}`}catch{}}else{const a=` "linter": {
47
68
  "rules": {
48
- ${Object.entries(s).map(([p,m])=>{const g=Object.entries(m).map(([b,q])=>` "${b}": "${q}"`).join(`,
69
+ ${Object.entries(s).map(([p,u])=>{const m=Object.entries(u).map(([g,b])=>` "${g}": "${b}"`).join(`,
49
70
  `);return` "${p}": {
50
- ${g}
71
+ ${m}
51
72
  }`}).join(`,
52
73
  `)}
53
74
  }
54
- }`,d=r.replace(/(\}\s*)$/u,p=>`,
55
- ${i}
56
- ${p}`);try{await ve(e,d,"utf-8"),`${e}`}catch{}}}l(ws,"injectBiomeRules");async function js(t){const e=Y(t,"eslint.config.mjs");let r;try{r=await Ce(e,"utf-8"),`${e}`}catch{return}if(r.includes("rules:"))return;const s=Object.entries(ct.eslint).map(([o,a])=>{const i=Array.isArray(a)?JSON.stringify(a):`"${a}"`;return` "${o}": ${i}`}).join(`,
75
+ }`,i=r.replace(/(\}\s*)$/u,p=>`,
76
+ ${a}
77
+ ${p}`);try{await be(t,i,"utf-8"),`${t}`}catch{}}}c(Os,"$r"),l(Os,"injectBiomeRules");async function Cs(e){const t=ee(e,"eslint.config.mjs");let r;try{r=await De(t,"utf-8"),`${t}`}catch{return}if(r.includes("rules:"))return;const s=Object.entries(Kt.eslint).map(([o,a])=>{const i=Array.isArray(a)?JSON.stringify(a):`"${a}"`;return` "${o}": ${i}`}).join(`,
57
78
  `),n=r.replace(/\];?$/u,` {
58
79
  rules: {
59
80
  ${s},
60
81
  },
61
82
  },
62
- ];`);try{await ve(e,n,"utf-8"),`${e}`}catch{}}l(js,"injectEslintRules");async function vs(t,e){switch(e){case"oxlint-oxfmt":return await bs(t),{success:!0};case"biome":return await ws(t),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await js(t),{success:!0};default:return{message:"No injection needed",success:!0}}}l(vs,"injectUltraciteRules");const Ss="single-project/architecture/nest-api",ks="single-project/architecture/nest-gateway",As="single-project/architecture/nest-microservice",Ps="monorepo/root",Ts="monorepo/apps/api-gateway",Es="monorepo/packages",Rs="addons/husky",qs="extras/docker",xs="extras/swagger",Is="extras/database",Os="monorepo/packages/db",_s="feature/graphql/todo-example",Cs="monorepo/feature/graphql/todo-example",Ft="feature/rest/todo-example",Lt="monorepo/feature/rest/todo-example",Ds=[{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[qs]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[xs]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[Is]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[Os]},{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:{api:["graphql"],extras:["todo-example"],projectType:"single"},id:"extra-todo-example",name:"Todo Example (single, graphql)",priority:5,templateGroups:[_s]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-todo-example",name:"Todo Example (monorepo, graphql)",priority:5,templateGroups:[Cs]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"single"},id:"extra-rest-todo-example",name:"REST Todo Example (single)",priority:5,templateGroups:[Ft]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-rest-todo-example",name:"REST Todo Example (monorepo)",priority:5,templateGroups:[Lt]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"single"},id:"extra-trpc-todo-example",name:"tRPC Todo Example (single)",priority:5,templateGroups:[Ft]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-trpc-todo-example",name:"tRPC Todo Example (monorepo)",priority:5,templateGroups:[Lt]}],Ms=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[Ss]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[ks]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[As]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[Ps,Ts,Es]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[Rs]}],Gs=[...Ms,...Ds];function zs(t){t.registerAll(Gs)}l(zs,"initializeTemplateMappings");class Be{static{l(this,"TemplateMapper")}mappings=[];register(e){this.mappings.push(e),this.mappings.sort((r,s)=>(s.priority??0)-(r.priority??0))}registerAll(e){for(const r of e)this.register(r)}resolve(e){const r=[];for(const a of this.mappings)Be.matches(a.conditions,e)&&r.push(a);const s=[],n={},o=[];for(const a of r){for(const i of a.templateGroups)s.includes(i)||s.push(i);Object.assign(n,a.extraVariables),o.push(a.id)}return{extraVariables:n,matchedMappings:o,templateGroups:s}}findFirst(e){return this.mappings.find(r=>Be.matches(r.conditions,e))}getAll(){return[...this.mappings]}getById(e){return this.mappings.find(r=>r.id===e)}clear(){this.mappings=[]}static matches(e,r){return!(e.architecture!==void 0&&e.architecture!==r.architecture||e.projectType!==void 0&&e.projectType!==r.projectType||e.database!==void 0&&!e.database.some(s=>r.database.includes(s))||e.orm!==void 0&&!e.orm.some(s=>r.orm.includes(s))||e.api!==void 0&&!e.api.some(s=>r.api.includes(s))||e.extras!==void 0&&!e.extras.some(s=>r.extras.includes(s))||e.addons!==void 0&&!e.addons.some(s=>r.addons.includes(s))||e.microservices!==void 0&&!e.microservices.some(s=>r.microservices.includes(s)))}}function Ns(t){return t.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}l(Ns,"toKebabCase");function Fs(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toLowerCase())}l(Fs,"toCamelCase");function Ls(t){return t.replaceAll(/[-_\s](.)/gu,(e,r)=>r.toUpperCase()).replace(/^(.)/u,e=>e.toUpperCase())}l(Ls,"toPascalCase");function $s(t){const e=t.database.includes("postgresql"),r=t.database.includes("mysql"),s=t.database.includes("sqlite"),n=t.database.includes("mongodb"),o=t.orm.includes("prisma"),a=t.orm.includes("typeorm"),i=t.orm.includes("drizzle"),d=t.database.length>0&&!o&&!a&&!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:s,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:Fs(t.projectName),projectNameKebab:Ns(t.projectName),projectNamePascalCase:Ls(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:o,useRawSql:d,useSwaggerScalar:t.extras.includes("swagger")&&t.addons.includes("scalar-ui"),useTypeorm:a,useTypescript7:t.extras.includes("typescript-7"),year:new Date().getFullYear()}}l($s,"buildTemplateVariables");function Us(t,e){return{...t,...e}}l(Us,"mergeTemplateExtras");class Bs{static{l(this,"BetterAuthGenerator")}project;config;constructor(e,r){this.project=e,this.config=r}generate(e){const r=this.config.orm??[],s=this.config.database??[],n=s.length>0,o=this.config.skipModule??!1;if(!n){this.generateStateless(e,o);return}const a=r.includes("prisma"),i=r.includes("drizzle"),d=r.includes("typeorm");a?(this.generatePrisma(e,s),o||this.generateModule(e,"prisma")):i?(this.generateDrizzle(e,s),o||this.generateModule(e,"drizzle")):d?(this.generateNative(e,s),o||this.generateTypeormModule(e,s)):(this.generateNative(e,s),o||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??[],o=n.includes("prisma"),a=n.includes("drizzle"),i=n.includes("typeorm");o?this.generatePrisma(e,r):a?this.generateDrizzle(e,r):i?this.generateNative(e,r):this.generateNative(e,r)}generatePrisma(e,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o;s?o="postgresql":n?o="mysql":o="sqlite";let a,i,d;s?(a="PrismaPg",i="@prisma/adapter-pg",d="new PrismaPg({ connectionString: '' })"):n?(a="PrismaMariaDb",i="@prisma/adapter-mariadb",d="new PrismaMariaDb('')"):(a="PrismaBetterSqlite3",i="@prisma/adapter-better-sqlite3",d="new PrismaBetterSqlite3({ url: ':memory:' })");const p=this.config.extras?.includes("swagger"),m=[`import { ${a} } 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: "${o}" }),`," 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 = ${d};`," 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"],g=w.join(e,"auth.ts");this.project.createSourceFile(g,m.join(`
63
- `),{overwrite:!0})}generateDrizzle(e,r){const s=r.includes("postgresql"),n=r.includes("mysql"),o=r.includes("sqlite");let a,i,d,p,m,g;s?(a='import { drizzle } from "drizzle-orm/node-postgres";',i='import { Pool } from "pg";',d="NodePgDatabase",p="pg",m='new Pool({ connectionString: "" })',g="drizzle({ client: pool, schema })"):n?(a='import { drizzle } from "drizzle-orm/mysql2";',i='import mysql from "mysql2/promise";',d="MySql2Database",p="mysql",m='mysql.createPool({ uri: "" })',g="drizzle({ client: pool, schema })"):(a='import { drizzle } from "drizzle-orm/better-sqlite3";',i='import Database from "better-sqlite3";',d="BetterSqlite3Database",p="sqlite",m='new Database(":memory:")',g="drizzle({ client: sqliteDb, schema })");const b=this.config.extras?.includes("swagger"),q=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',a,i,'import * as schema from "../database/orm/drizzle/schema.js";',...b?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(db: ${d}<typeof schema>) {`," return betterAuth({",` database: drizzleAdapter(db, { provider: "${p}", usePlural: true }),`," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...b?[" plugins: [openAPI()],"]:[]," });","}","","// Lazily created \u2014 only initializes when CLI accesses auth.options","// This is for auth schema generation only, ignore this code","function createCliAuth() {",o?` const sqliteDb = ${m};`:` const pool = ${m};`,...o?[` const db = ${g};`]:[` const db = ${g};`]," 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=w.join(e,"auth.ts");this.project.createSourceFile(M,q.join(`
64
- `),{overwrite:!0})}generateNative(e,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o,a,i;s?(o=`import { Pool } from "pg";
65
- `,a="Pool",i='new Pool({ connectionString: "" })'):n?(o=`import { createPool } from "mysql2";
66
- `,a="ReturnType<typeof createPool>",i='createPool({ uri: "" })'):(o=`import Database from "better-sqlite3";
67
- `,a="Database.Database",i='new Database(":memory:")');const d=this.config.extras?.includes("swagger"),p=['import { betterAuth } from "better-auth";',o.trim(),...d?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(pool: ${a}) {`," return betterAuth({"," database: pool,"," emailAndPassword: { enabled: true },"," experimental: { joins: true },",...d?[" 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"],m=w.join(e,"auth.ts");this.project.createSourceFile(m,p.join(`
68
- `),{overwrite:!0})}generateStateless(e,r=!1){const s=this.config.extras?.includes("swagger"),n=['import { betterAuth } from "better-auth";',...s?['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 },",...s?[" plugins: [openAPI()],"]:[],"});",""].join(`
69
- `),o=w.join(e,"auth.ts");this.project.createSourceFile(o,n,{overwrite:!0}),r||this.generateStatelessModule(e)}generateModule(e,r){const s=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";','import { DbService } from "../database/db.service.js";','import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," inject: [DbService],"," useFactory: (db: DbService) => ({",` auth: createAuth(db.${r}),`," }),"," }),"," ],","})","export class AuthModule {}",""],n=w.join(e,"auth.module.ts");this.project.createSourceFile(n,s.join(`
70
- `),{overwrite:!0})}generateTypeormModule(e,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o,a;s?(o='import { Pool } from "pg";',a="new Pool({ connectionString: process.env.POSTGRES_URL! })"):n?(o='import { createPool } from "mysql2";',a="createPool({ uri: process.env.MYSQL_URL! })"):(o='import Database from "better-sqlite3";',a='new Database(process.env.SQLITE_PATH ?? ":memory:")');const i=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',o,'import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," useFactory: () => ({",` auth: createAuth(${a}),`," }),"," }),"," ],","})","export class AuthModule {}",""],d=w.join(e,"auth.module.ts");this.project.createSourceFile(d,i.join(`
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 {}",""],s=w.join(e,"auth.module.ts");this.project.createSourceFile(s,r.join(`
72
- `),{overwrite:!0})}}class Js{static{l(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(`
73
- `),s=w.join(e,"strategies/jwt.strategy.ts");this.project.createSourceFile(s,r,{overwrite:!0});const n=w.join(e,"auth.service.ts"),o=this.project.createSourceFile(n,"",{overwrite:!0});o.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),o.addImportDeclaration({moduleSpecifier:"@nestjs/jwt",namedImports:["JwtService"]}),o.addClass({ctors:[{parameters:[{decorators:[{name:"Inject"}],isReadonly:!0,name:"jwtService",scope:hr.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 a=["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(`
74
- `),i=w.join(e,"auth.controller.ts");this.project.createSourceFile(i,a,{overwrite:!0}),this.generateDecorators(e),this.generateGuard(e);const d=['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=w.join(e,"auth.module.ts");this.project.createSourceFile(p,d,{overwrite:!0})}generateDbAuth(e){const r=this.config.orm??[],s=r.includes("prisma"),n=r.includes("typeorm"),o=r.includes("drizzle"),a=(this.config.api??[]).includes("graphql"),i=(this.config.extras??[]).includes("swagger");this.generatePasswordService(e),this.generateDbAuthService(e,{useDrizzle:o,usePrisma:s,useTypeorm:n}),this.generateLoginSchema(e),this.generateSignupSchema(e),this.generateRefreshTokenSchema(e),this.generateJwtDto(e),a&&(this.generateLoginInput(e),this.generateSignupInput(e),this.generateRefreshTokenInput(e)),this.generateDbJwtStrategy(e),this.generateDbRestGuard(e),a&&this.generateDbGqlGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e),a&&(this.generateGqlOptionalAuthGuard(e),this.generateGqlRolesGuard(e)),this.generateDbController(e,i),a&&(this.generateTokenModel(e),this.generateAuthModel(e),this.generateAuthResolver(e)),this.generateDecorators(e),this.generateDbModule(e,{hasGraphql:a,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(w.join(e,"password.service.ts"),r,{overwrite:!0})}generateDbAuthService(e,r){const{usePrisma:s,useTypeorm:n}=r,o=["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 a,i,d,p,m;s?(a='import { DbService } from "../database/db.service.js";',i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
77
- `),d=[" 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(`
78
- `),p=["const user = await this.db.prisma.user.findUnique({"," where: { email },","});"].join(`
83
+ ];`);try{await be(t,n,"utf-8"),`${t}`}catch{}}c(Cs,"Cr"),l(Cs,"injectEslintRules");async function Ds(e,t){switch(t){case"oxlint-oxfmt":return await Rs(e),{success:!0};case"biome":return await Os(e),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await Cs(e),{success:!0};default:return{message:"No injection needed",success:!0}}}c(Ds,"Ue"),l(Ds,"injectUltraciteRules");const Qt={"better-auth-drizzle":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["drizzle"]},"better-auth-prisma":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"better-auth-stateless":{api:["rest"],auth:"better-auth:stateless",code:"better-auth-stateless",database:[],orm:[]},"graphql-prisma":{api:["graphql"],auth:"none",code:"graphql",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"microservice-grpc":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["grpc"],orm:[]},"microservice-kafka":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["kafka"],orm:[]},"microservice-mqtt":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["mqtt"],orm:[]},"microservice-nats":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["nats"],orm:[]},"microservice-rabbitmq":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["rabbitmq"],orm:[]},"microservice-redis":{api:["rest"],auth:"none",code:"microservice-transport",database:[],microservices:["redis"],orm:[]},"mongodb-native":{api:["rest"],auth:"none",code:"mongodb",database:["mongodb"],orm:[]},"passport-prisma":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"prisma8-postgres":{api:["rest"],auth:"none",code:"prisma-8",database:["postgresql"],orm:["prisma"],prismaVersion:"8"}};function Yt(e,t){const r=Qt[t];return e.projectType==="single"&&e.architecture===("microservices"in r?"nest-microservice":"nest-api")&&e.httpProvider==="express"&&JSON.stringify(e.microservices)===JSON.stringify("microservices"in r?r.microservices:[])&&e.auth===r.auth&&JSON.stringify(e.api)===JSON.stringify(r.api)&&JSON.stringify(e.database)===JSON.stringify(r.database)&&JSON.stringify(e.orm)===JSON.stringify(r.orm)&&e.prismaVersion===("prismaVersion"in r?r.prismaVersion:void 0)&&e.addons?.length===0&&(e.auth==="none"?e.extras?.every(s=>s==="todo-example"||"microservices"in r&&s==="docker")===!0:e.extras?.length===0)}c(Yt,"Fe"),l(Yt,"matchesCandidate");const hi=["better-auth-prisma","better-auth-drizzle","graphql-prisma","passport-prisma","mongodb-native","prisma8-postgres","better-auth-stateless","microservice-grpc","microservice-redis","microservice-kafka","microservice-mqtt","microservice-nats","microservice-rabbitmq"];function Ze(e){const t=[];return(e.database.length>1||e.orm.length>1)&&t.push({code:"multiple-database-adapters",kind:"unverified",message:"Select at most one database and one ORM; multiple adapter ownership is not implemented yet."}),e.orm.length>0&&e.database.length===0&&t.push({code:"orm-requires-database",kind:"invalid",message:"Select a database before selecting an ORM."}),e.orm.includes("prisma")&&e.database.length>0&&!e.prismaVersion&&t.push({code:"prisma-version-required",kind:"invalid",message:"Select Prisma 7 explicitly; implicit Prisma 8 generation is not supported."}),e.auth==="better-auth"&&(e.database.length===0?t.push({code:"better-auth-requires-database",kind:"invalid",message:"Database-backed Better Auth requires a database."}):(e.orm.length>0||e.database[0]!=="postgresql")&&t.push({code:"better-auth-adapter",kind:"unverified",message:"This Better Auth combination is unverified. Use native PostgreSQL, or a certified single-project Express/REST adapter profile without extras or addons (Prisma 7/PostgreSQL or Drizzle/SQLite)."})),e.database.includes("mongodb")&&t.push({code:"mongodb",kind:"unverified",message:"This MongoDB combination is unverified. Use native MongoDB with single-project Express/REST and no authentication; ORM and other API combinations remain gated."}),e.prismaVersion==="8"&&t.push({code:"prisma-8",kind:"unverified",message:"Prisma 8 generation is not supported yet; the generated contract has not passed clean-install runtime validation."}),e.api.includes("graphql")&&t.push({code:"graphql",kind:"unverified",message:"This GraphQL combination is unverified. Use single-project Express, PostgreSQL/Prisma 7, GraphQL only, no authentication, and no addons."}),e.auth==="passport"&&t.push({code:"passport",kind:"unverified",message:"This Passport combination is unverified. Use single-project Express/REST with PostgreSQL/Prisma 7 and no extras or addons."}),e.auth==="better-auth:stateless"&&t.push({code:"better-auth-stateless",kind:"unverified",message:"Stateless Better Auth generation is not supported yet; its issuer and session contract is still being defined."}),e.microservices.length>0&&t.push({code:"microservice-transport",kind:"unverified",message:"Redis, gRPC, and other transport generation is not supported yet; selecting a transport does not currently produce verified transport behavior."}),t.filter(({code:r})=>!hi.some(s=>Qt[s].code===r&&Yt(e,s)))}c(Ze,"Le"),l(Ze,"getUnsupportedSelections");function Ns(e,t){if(t&&!Yt(e,t))throw new Error(`Context does not match runtime certification profile: ${t}`);const r=Ze(e).filter(({code:s})=>!t||s!==Qt[t].code);if(r.length>0)throw new Error(r.map(({message:s})=>s).join(`
84
+ `))}c(Ns,"Ge"),l(Ns,"validateProjectContext");const fi="single-project/architecture/nest-api",gi="single-project/architecture/nest-gateway",yi="single-project/architecture/nest-microservice",bi="monorepo/root",vi="monorepo/apps/api-gateway",wi="monorepo/packages",ji="addons/husky",Si="extras/docker",ki="extras/swagger",_i="extras/database",xi="monorepo/packages/db",Ti="feature/graphql/todo-example",Ai="monorepo/feature/graphql/todo-example",qs="feature/rest/todo-example",$s="monorepo/feature/rest/todo-example",Ei=[{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[Si]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[ki]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[_i]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[xi]},{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:{api:["graphql"],extras:["todo-example"],projectType:"single"},id:"extra-todo-example",name:"Todo Example (single, graphql)",priority:5,templateGroups:[Ti]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-todo-example",name:"Todo Example (monorepo, graphql)",priority:5,templateGroups:[Ai]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"single"},id:"extra-rest-todo-example",name:"REST Todo Example (single)",priority:5,templateGroups:[qs]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-rest-todo-example",name:"REST Todo Example (monorepo)",priority:5,templateGroups:[$s]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"single"},id:"extra-trpc-todo-example",name:"tRPC Todo Example (single)",priority:5,templateGroups:[qs]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-trpc-todo-example",name:"tRPC Todo Example (monorepo)",priority:5,templateGroups:[$s]}],Pi=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[fi]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[gi]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[yi]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[bi,vi,wi]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[ji]}],Ms=[...Pi,...Ei];function Fs(e){e.registerAll(Ms)}c(Fs,"st"),l(Fs,"initializeTemplateMappings");function Ii(){return[...Ms]}c(Ii,"Lr"),l(Ii,"getPredefinedMappings");class qt{static{c(this,"B")}static{l(this,"TemplateMapper")}mappings=[];register(t){this.mappings.push(t),this.mappings.sort((r,s)=>(s.priority??0)-(r.priority??0))}registerAll(t){for(const r of t)this.register(r)}resolve(t){const r=[];for(const a of this.mappings)qt.matches(a.conditions,t)&&r.push(a);const s=[],n={},o=[];for(const a of r){for(const i of a.templateGroups)s.includes(i)||s.push(i);Object.assign(n,a.extraVariables),o.push(a.id)}return{extraVariables:n,matchedMappings:o,templateGroups:s}}findFirst(t){return this.mappings.find(r=>qt.matches(r.conditions,t))}getAll(){return[...this.mappings]}getById(t){return this.mappings.find(r=>r.id===t)}clear(){this.mappings=[]}static matches(t,r){return!(t.architecture!==void 0&&t.architecture!==r.architecture||t.projectType!==void 0&&t.projectType!==r.projectType||t.database!==void 0&&!t.database.some(s=>r.database.includes(s))||t.orm!==void 0&&!t.orm.some(s=>r.orm.includes(s))||t.api!==void 0&&!t.api.some(s=>r.api.includes(s))||t.extras!==void 0&&!t.extras.some(s=>r.extras.includes(s))||t.addons!==void 0&&!t.addons.some(s=>r.addons.includes(s))||t.microservices!==void 0&&!t.microservices.some(s=>r.microservices.includes(s)))}}function Gs(e){return e.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}c(Gs,"Gr"),l(Gs,"toKebabCase");function Us(e){return e.replaceAll(/[-_\s](.)/gu,(t,r)=>r.toUpperCase()).replace(/^(.)/u,t=>t.toLowerCase())}c(Us,"ot"),l(Us,"toCamelCase");function Ls(e){return e.replaceAll(/[-_\s](.)/gu,(t,r)=>r.toUpperCase()).replace(/^(.)/u,t=>t.toUpperCase())}c(Ls,"xr"),l(Ls,"toPascalCase");function Js(e){const t=e.database.includes("postgresql"),r=e.database.includes("mysql"),s=e.database.includes("sqlite"),n=e.database.includes("mongodb"),o=e.orm.includes("prisma"),a=e.orm.includes("typeorm"),i=e.orm.includes("drizzle"),p=e.database.length>0&&!o&&!a&&!i;return{addons:[...e.addons],apiType:e.api[0]??null,apis:[...e.api],architecture:e.architecture,auth:e.auth,databasePorts:{mongodb:27017,mysql:3306,postgres:5432},databaseType:e.database[0]??null,databases:[...e.database],description:e.description||"A NestJS application",docker:e.extras.includes("docker"),extras:[...e.extras],graphqlPlayground:e.api.includes("graphql"),hasAuth:e.auth!=="none",hasBetterAuthWithoutRest:(e.auth==="better-auth"||e.auth==="better-auth:stateless")&&!e.api.includes("rest"),hasDatabase:e.database.length>0,hasGraphql:e.api.includes("graphql"),hasMongodb:n,hasMysql:r,hasOrm:e.orm.length>0,hasPostgres:t,hasRest:e.api.includes("rest"),hasSqlite:s,hasTodoExample:e.extras.includes("todo-example"),hasTrpc:e.api.includes("trpc"),hasTrpcAndAuth:e.api.includes("trpc")&&e.auth!=="none",httpProvider:e.httpProvider,initGit:e.initGit,isBetterAuth:e.auth==="better-auth"||e.auth==="better-auth:stateless",isBun:e.packageManager==="bun",isMonorepo:e.projectType==="monorepo",isNpm:e.packageManager==="npm",isPassportAuth:e.auth==="passport",isPnpm:e.packageManager==="pnpm",isSingle:e.projectType==="single",isYarn:e.packageManager==="yarn",microservices:[...e.microservices],ormType:e.orm[0]??null,orms:[...e.orm],packageManager:e.packageManager,projectName:e.projectName,projectNameCamelCase:Us(e.projectName),projectNameKebab:Gs(e.projectName),projectNamePascalCase:Ls(e.projectName),projectType:e.projectType,shouldImportAuthModule:e.auth!=="none"&&(e.api.includes("rest")||e.api.includes("graphql")),supportsCatalog:["pnpm","yarn","bun"].includes(e.packageManager),swagger:e.extras.includes("swagger"),trpcGeneratePath:e.projectType==="monorepo"?"../../packages/shared/src/trpc/@generated":"src/libs/trpc/@generated",useDrizzle:i,usePrisma:o,isPrisma8:o&&(e.prismaVersion==="8"||n&&e.prismaVersion!=="7"||!e.prismaVersion&&!r&&!s),isPrisma7:o&&(e.prismaVersion==="7"||r||s||e.prismaVersion!=="8"&&!n),isPrismaMongo:o&&n&&(e.prismaVersion==="8"||e.prismaVersion!=="7"),isPrismaPostgres:o&&t&&(e.prismaVersion==="8"||!e.prismaVersion&&!r&&!s),useRawSql:p,useSwaggerScalar:e.extras.includes("swagger")&&e.addons.includes("scalar-ui"),useTypeorm:a,useTypescript7:e.extras.includes("typescript-7"),year:new Date().getFullYear()}}c(Js,"nt"),l(Js,"buildTemplateVariables");function Bs(e,t){return{...e,...t}}c(Bs,"at"),l(Bs,"mergeTemplateExtras");class zi{static{c(this,"Zr")}static{l(this,"BetterAuthGenerator")}project;config;environmentImport(){return`import { env } from "${this.config.envImport??"../config/env.js"}";`}constructor(t,r){this.project=t,this.config=r}generate(t){this.generateCliConfig(t);const r=this.config.orm??[],s=this.config.database??[],n=s.length>0,o=this.config.skipModule??!1;if(!n){this.generateStateless(t,o);return}const a=r.includes("prisma"),i=r.includes("drizzle"),p=r.includes("typeorm");a?(this.generatePrisma(t,s),o||this.generateModule(t,"prisma")):i?(this.generateDrizzle(t,s),o||this.generateModule(t,"drizzle")):p?(this.generateNative(t,s),o||this.generateTypeormModule(t,s)):(this.generateNative(t,s),o||this.generateModule(t,"raw.sql"))}generateAuthOnly(t){const r=this.config.database??[];if(!(r.length>0)){this.generateStateless(t,!0);return}const s=this.config.orm??[],n=s.includes("prisma"),o=s.includes("drizzle"),a=s.includes("typeorm");n?this.generatePrisma(t,r):o?this.generateDrizzle(t,r):a?this.generateNative(t,r):this.generateNative(t,r)}generateCliConfig(t){const r=this.config.orm??[];if(!r.includes("prisma")&&!r.includes("drizzle"))return;const s=r.includes("prisma"),n=s?"postgresql":"sqlite";s&&this.project.createSourceFile(j.resolve(t,"../../scripts/install-auth-schema.mjs"),['import { readFile, writeFile } from "node:fs/promises";','const schema = await readFile("auth-schema.prisma", "utf8");','const models = schema.replace(/^(?:generator|datasource)\\s+\\w+\\s*\\{[^}]*\\}/gmu, "").trim();','if (!models.includes("model User")) throw new Error("Auth CLI produced no User model");','await writeFile("src/database/orm/prisma/auth.prisma", models + "\\n");'].join(`
85
+ `),{overwrite:!0});const o=s?"prismaAdapter":"drizzleAdapter",a=s?"better-auth/adapters/prisma":"@better-auth/drizzle-adapter";this.project.createSourceFile(j.join(t,"auth.cli.ts"),['import { betterAuth } from "better-auth";',`import { ${o} } from "${a}";`,this.environmentImport(),"// Schema discovery needs adapter metadata, not a live database connection.","export const auth = betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,",` database: ${o}({} as never, { provider: "${n}" }),`," emailAndPassword: { enabled: true },","});"].join(`
86
+ `),{overwrite:!0})}generatePrisma(t,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o;s?o="postgresql":n?o="mysql":o="sqlite";const a=this.config.extras?.includes("swagger"),i=[this.environmentImport(),'import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";','import { PrismaClient } from "../database/orm/prisma/generated/client.js";',...a?['import { openAPI } from "better-auth/plugins";']:[],"","export function createAuth(prisma: PrismaClient) {"," return betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,",` database: prismaAdapter(prisma, { provider: "${o}" }),`," emailAndPassword: { enabled: true },",...a?[" plugins: [openAPI()],"]:[]," });","}","","export type UserSession = ReturnType<typeof createAuth>['$Infer']['Session'];"],p=j.join(t,"auth.ts");this.project.createSourceFile(p,i.join(`
87
+ `),{overwrite:!0})}generateDrizzle(t,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o,a,i;s?(o="NodePgDatabase",a="drizzle-orm/node-postgres",i="pg"):n?(o="MySql2Database",a="drizzle-orm/mysql2",i="mysql"):(o="BetterSQLite3Database",a="drizzle-orm/better-sqlite3",i="sqlite");const p=this.config.extras?.includes("swagger"),u=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',`import type { ${o} } from "${a}";`,this.environmentImport(),'import * as schema from "../database/orm/drizzle/schema.js";',...p?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(db: ${o}<typeof schema>) {`," return betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,",` database: drizzleAdapter(db, { provider: "${i}", schema }),`," emailAndPassword: { enabled: true },",...p?[" plugins: [openAPI()],"]:[]," });","}","","export type UserSession = ReturnType<typeof createAuth>['$Infer']['Session'];"],m=j.join(t,"auth.ts");this.project.createSourceFile(m,u.join(`
88
+ `),{overwrite:!0})}generateNative(t,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o,a,i;s?(o=`import { Pool } from "pg";
89
+ `,a="Pool",i="new Pool({ connectionString: env.POSTGRES_URL })"):n?(o=`import { createPool } from "mysql2";
90
+ `,a="ReturnType<typeof createPool>",i="createPool({ uri: env.MYSQL_URL })"):(o=`import Database from "better-sqlite3";
91
+ `,a="Database.Database",i="new Database(env.SQLITE_PATH)");const p=this.config.extras?.includes("swagger"),u=[this.environmentImport(),'import { betterAuth } from "better-auth";',o.trim(),...p?['import { openAPI } from "better-auth/plugins";']:[],"",`export function createAuth(pool: ${a}) {`," return betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,"," database: pool,"," emailAndPassword: { enabled: true },",...p?[" plugins: [openAPI()],"]:[]," });","}","","// Uses the same validated configuration for CLI migrations and runtime.","function createCliAuth() {",` const pool = ${i};`," return createAuth(pool);","}","","// Export concrete options so the CLI can discover the database configuration.","export const auth = createCliAuth();","export type UserSession = typeof auth.$Infer.Session;"],m=j.join(t,"auth.ts");this.project.createSourceFile(m,u.join(`
92
+ `),{overwrite:!0})}generateStateless(t,r=!1){const s=this.config.extras?.includes("swagger"),n=['import { betterAuth } from "better-auth";',this.environmentImport(),...s?['import { openAPI } from "better-auth/plugins";']:[],"","export const auth = betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,"," session: {"," cookieCache: {"," enabled: true,"," maxAge: 7 * 24 * 60 * 60, // 7 days",' strategy: "jwe",'," },"," },"," account: {"," storeAccountCookie: true,",' storeStateStrategy: "cookie",'," },",...s?[" plugins: [openAPI()],"]:[],"});",""].join(`
93
+ `),o=j.join(t,"auth.ts");this.project.createSourceFile(o,n,{overwrite:!0}),r||this.generateStatelessModule(t)}generateModule(t,r){const s=(this.config.orm??[]).some(a=>a==="prisma"||a==="drizzle");s&&this.project.createSourceFile(j.join(t,"profile.controller.ts"),['import { Controller, Get } from "@nestjs/common";','import { Session } from "@thallesp/nestjs-better-auth";','import type { UserSession } from "./auth.js";','@Controller("auth-profile")',"export class ProfileController {"," @Get()"," profile(@Session() session: UserSession) { return { id: session.user.id, email: session.user.email }; }","}"].join(`
94
+ `),{overwrite:!0});const n=['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";',...s?['import { ProfileController } from "./profile.controller.js";']:[],"","@Module({",...s?[" controllers: [ProfileController],"]:[]," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," inject: [DbService],"," useFactory: (db: DbService) => ({",` auth: createAuth(db.${r}),`," }),"," }),"," ],","})","export class AuthModule {}",""],o=j.join(t,"auth.module.ts");this.project.createSourceFile(o,n.join(`
95
+ `),{overwrite:!0})}generateTypeormModule(t,r){const s=r.includes("postgresql"),n=r.includes("mysql");let o,a;s?(o='import { Pool } from "pg";',a="new Pool({ connectionString: env.POSTGRES_URL })"):n?(o='import { createPool } from "mysql2";',a="createPool({ uri: env.MYSQL_URL })"):(o='import Database from "better-sqlite3";',a="new Database(env.SQLITE_PATH)");const i=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',o,this.environmentImport(),'import { createAuth } from "./auth.js";',"","@Module({"," exports: [BetterAuthModule],"," imports: ["," BetterAuthModule.forRootAsync({"," useFactory: () => ({",` auth: createAuth(${a}),`," }),"," }),"," ],","})","export class AuthModule {}",""],p=j.join(t,"auth.module.ts");this.project.createSourceFile(p,i.join(`
96
+ `),{overwrite:!0})}generateStatelessModule(t){const r=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";','import { auth } from "./auth.js";',"","@Module({"," imports: [BetterAuthModule.forRoot({ auth })],"," exports: [BetterAuthModule],","})","export class AuthModule {}",""],s=j.join(t,"auth.module.ts");this.project.createSourceFile(s,r.join(`
97
+ `),{overwrite:!0})}}function Zs(e,t){const r={"auth.controller.ts":`import { BadRequestException, Body, Controller, Get, HttpCode, Post, Req, UseGuards } from "@nestjs/common";
98
+ import type { Request } from "express";
99
+ import { z } from "zod";
100
+ import { AuthService } from "./auth.service.js";
101
+ import { RestAuthGuard } from "./guards/rest-auth.guard.js";
102
+
103
+ const credentials = z.object({ email: z.email().transform((value) => value.toLowerCase()), password: z.string().min(12).max(72).refine((value) => Buffer.byteLength(value, "utf8") <= 72) }).strict();
104
+ const refreshBody = z.object({ refreshToken: z.string().min(32).max(256) }).strict();
105
+ function validate<T>(schema: z.ZodType<T>, body: unknown): T {
106
+ const result = schema.safeParse(body);
107
+ if (!result.success) throw new BadRequestException("Invalid authentication input");
108
+ return result.data;
109
+ }
110
+
111
+ @Controller("auth")
112
+ export class AuthController {
113
+ constructor(private readonly auth: AuthService) {}
114
+ @Post("register")
115
+ register(@Body() body: unknown) { const input = validate(credentials, body); return this.auth.register(input.email, input.password); }
116
+ @Post("login") @HttpCode(200)
117
+ login(@Body() body: unknown) { const input = validate(credentials, body); return this.auth.login(input.email, input.password); }
118
+ @Post("refresh") @HttpCode(200)
119
+ refresh(@Body() body: unknown) { return this.auth.refresh(validate(refreshBody, body).refreshToken); }
120
+ @Post("logout") @HttpCode(200)
121
+ logout(@Body() body: unknown) { return this.auth.logout(validate(refreshBody, body).refreshToken); }
122
+ @Get("profile") @UseGuards(RestAuthGuard)
123
+ profile(@Req() request: Request) { return request.user; }
124
+ }
125
+ `,"auth.module.ts":`import { Module } from "@nestjs/common";
126
+ import { JwtModule } from "@nestjs/jwt";
127
+ import { PassportModule } from "@nestjs/passport";
128
+ import { env } from "../config/env.js";
129
+ import { AuthService } from "./auth.service.js";
130
+ import { AuthController } from "./auth.controller.js";
131
+ import { JwtStrategy } from "./strategies/jwt.strategy.js";
132
+ import { RestAuthGuard } from "./guards/rest-auth.guard.js";
133
+ @Module({
134
+ imports: [PassportModule.register({ defaultStrategy: "jwt" }), JwtModule.register({ secret: env.JWT_ACCESS_SECRET, signOptions: { algorithm: "HS256", expiresIn: "15m", issuer: env.JWT_ISSUER, audience: env.JWT_AUDIENCE, keyid: env.JWT_KEY_ID } })],
135
+ controllers: [AuthController], providers: [AuthService, JwtStrategy, RestAuthGuard], exports: [AuthService, RestAuthGuard],
136
+ })
137
+ export class AuthModule {}
138
+ `,"auth.service.ts":`import { Injectable, UnauthorizedException, ConflictException } from "@nestjs/common";
139
+ import { JwtService } from "@nestjs/jwt";
140
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
141
+ import { compare, hash } from "bcrypt";
142
+ import { DbService } from "../database/db.service.js";
143
+
144
+ const publicUser = { id: true, email: true, role: true } as const;
145
+ const digest = (token: string) => createHash("sha256").update(token).digest("hex");
146
+
147
+ @Injectable()
148
+ export class AuthService {
149
+ constructor(private readonly db: DbService, private readonly jwt: JwtService) {}
150
+
151
+ async register(email: string, password: string) {
152
+ const passwordHash = await hash(password, 12);
153
+ try {
154
+ return await this.db.prisma.user.create({ data: { email, password: passwordHash }, select: publicUser });
155
+ } catch (error) {
156
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
157
+ throw new ConflictException("Account already exists");
158
+ }
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ async login(email: string, password: string) {
164
+ const user = await this.db.prisma.user.findUnique({ where: { email }, select: { id: true, password: true } });
165
+ if (!user || !(await compare(password, user.password))) throw new UnauthorizedException("Invalid credentials");
166
+ const familyId = randomUUID();
167
+ const refreshToken = randomBytes(32).toString("base64url");
168
+ await this.db.prisma.refreshToken.create({ data: { userId: user.id, familyId, tokenHash: digest(refreshToken), expiresAt: new Date(Date.now() + 7 * 86400000) } });
169
+ return this.tokens(user.id, familyId, refreshToken);
170
+ }
171
+
172
+ private async tokens(userId: string, familyId: string, refreshToken: string) {
173
+ return { accessToken: await this.jwt.signAsync({ sub: userId, sid: familyId, jti: randomUUID() }), refreshToken };
174
+ }
175
+
176
+ async refresh(token: string) {
177
+ const replacement = randomBytes(32).toString("base64url");
178
+ const result = await this.db.prisma.$transaction(async (tx) => {
179
+ const current = await tx.refreshToken.findUnique({ where: { tokenHash: digest(token) } });
180
+ if (!current) return null;
181
+ const changed = await tx.refreshToken.updateMany({ where: { id: current.id, consumedAt: null, revokedAt: null, expiresAt: { gt: new Date() } }, data: { consumedAt: new Date() } });
182
+ if (changed.count !== 1) {
183
+ await tx.refreshToken.updateMany({ where: { familyId: current.familyId }, data: { revokedAt: new Date() } });
184
+ return null;
185
+ }
186
+ await tx.refreshToken.create({ data: { userId: current.userId, familyId: current.familyId, tokenHash: digest(replacement), expiresAt: current.expiresAt } });
187
+ return current;
188
+ });
189
+ if (!result) throw new UnauthorizedException("Invalid refresh token");
190
+ return this.tokens(result.userId, result.familyId, replacement);
191
+ }
192
+
193
+ async logout(token: string) {
194
+ const current = await this.db.prisma.refreshToken.findUnique({ where: { tokenHash: digest(token) } });
195
+ if (current) await this.db.prisma.refreshToken.updateMany({ where: { familyId: current.familyId }, data: { revokedAt: new Date() } });
196
+ return { success: true };
197
+ }
198
+
199
+ async validate(payload: Record<string, unknown>) {
200
+ if (typeof payload.sub !== "string" || typeof payload.sid !== "string" || typeof payload.exp !== "number" || typeof payload.iat !== "number" || typeof payload.jti !== "string") throw new UnauthorizedException();
201
+ const session = await this.db.prisma.refreshToken.findFirst({ where: { userId: payload.sub, familyId: payload.sid, revokedAt: null, consumedAt: null, expiresAt: { gt: new Date() } }, select: { user: { select: publicUser } } });
202
+ if (!session) throw new UnauthorizedException();
203
+ return session.user;
204
+ }
205
+ }
206
+ `,"guards/rest-auth.guard.ts":`import { Injectable } from "@nestjs/common";
207
+ import { AuthGuard } from "@nestjs/passport";
208
+ @Injectable()
209
+ export class RestAuthGuard extends AuthGuard("jwt") {}
210
+ `,"strategies/jwt.strategy.ts":`import { Injectable } from "@nestjs/common";
211
+ import { PassportStrategy } from "@nestjs/passport";
212
+ import { ExtractJwt, Strategy } from "passport-jwt";
213
+ import { env } from "../../config/env.js";
214
+ import { AuthService } from "../auth.service.js";
215
+ @Injectable()
216
+ export class JwtStrategy extends PassportStrategy(Strategy) {
217
+ constructor(private readonly auth: AuthService) {
218
+ super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: env.JWT_ACCESS_SECRET, algorithms: ["HS256"], issuer: env.JWT_ISSUER, audience: env.JWT_AUDIENCE, ignoreExpiration: false });
219
+ }
220
+ validate(payload: Record<string, unknown>) { return this.auth.validate(payload); }
221
+ }
222
+ `};for(const[s,n]of Object.entries(r))e.createSourceFile(j.join(t,s),n,{overwrite:!0})}c(Zs,"Jr"),l(Zs,"generatePassportPrisma");class Ri{static{c(this,"Br")}static{l(this,"PassportAuthGenerator")}project;config;constructor(t,r){this.project=t,this.config=r}generate(t){if(this.config.orm?.includes("prisma")&&this.config.database?.includes("postgresql")&&this.config.api?.length===1&&this.config.api[0]==="rest"){Zs(this.project,t);return}(this.config.database?.length??0)>0?this.generateDbAuth(t):this.generateStatelessAuth(t)}generateStatelessAuth(t){const r=['import { Injectable } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";','import { Request } from "express";',`import { env } from "${this.config.envImport?.startsWith("@")?this.config.envImport:"../../config/env.js"}";`,"","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: env.JWT_ACCESS_SECRET,"," });"," }",""," async validate(payload: JwtPayload) {"," // Stateless: no DB lookup \u2014 trust the token payload"," return { userId: payload.sub, ...payload };"," }","}",""].join(`
223
+ `),s=j.join(t,"strategies/jwt.strategy.ts");this.project.createSourceFile(s,r,{overwrite:!0});const n=j.join(t,"auth.service.ts"),o=this.project.createSourceFile(n,"",{overwrite:!0});o.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),o.addImportDeclaration({moduleSpecifier:"@nestjs/jwt",namedImports:["JwtService"]}),o.addClass({ctors:[{parameters:[{decorators:[{name:"Inject"}],isReadonly:!0,name:"jwtService",scope:Qr.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 a=["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";',`import { env } from "${this.config.envImport??"../config/env.js"}";`,"",'@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: 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(`
224
+ `),i=j.join(t,"auth.controller.ts");this.project.createSourceFile(i,a,{overwrite:!0}),this.generateDecorators(t),this.generateGuard(t);const p=[`import { env } from "${this.config.envImport??"../config/env.js"}";`,'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: env.JWT_ACCESS_SECRET,",' signOptions: { expiresIn: "24h" },'," }),"," ],"," controllers: [AuthController],"," providers: ["," AuthService,"," JwtStrategy,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],"," exports: ["," AuthService,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],","})","export class AuthModule {}",""].join(`
225
+ `),u=j.join(t,"auth.module.ts");this.project.createSourceFile(u,p,{overwrite:!0})}generateDbAuth(t){const r=this.config.orm??[],s=r.includes("prisma"),n=r.includes("typeorm"),o=r.includes("drizzle"),a=(this.config.api??[]).includes("graphql"),i=(this.config.extras??[]).includes("swagger");this.generatePasswordService(t),this.generateDbAuthService(t,{useDrizzle:o,usePrisma:s,useTypeorm:n}),this.generateLoginSchema(t),this.generateSignupSchema(t),this.generateRefreshTokenSchema(t),this.generateJwtDto(t),a&&(this.generateLoginInput(t),this.generateSignupInput(t),this.generateRefreshTokenInput(t)),this.generateDbJwtStrategy(t),this.generateDbRestGuard(t),a&&this.generateDbGqlGuard(t),this.generateRestOptionalAuthGuard(t),this.generateRestRolesGuard(t),a&&(this.generateGqlOptionalAuthGuard(t),this.generateGqlRolesGuard(t)),this.generateDbController(t,i),a&&(this.generateTokenModel(t),this.generateAuthModel(t),this.generateAuthResolver(t)),this.generateDecorators(t),this.generateDbModule(t,{hasGraphql:a,useTypeorm:n})}generatePasswordService(t){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(`
226
+ `);this.project.createSourceFile(j.join(t,"password.service.ts"),r,{overwrite:!0})}generateDbAuthService(t,r){const{usePrisma:s,useTypeorm:n}=r,o=["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 a,i,p,u,m;s?(a='import { DbService } from "../database/db.service.js";',i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
227
+ `),p=[" 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(`
228
+ `),u=["const user = await this.db.prisma.user.findUnique({"," where: { email },","});"].join(`
79
229
  `),m=["return this.db.prisma.user.findUnique({ where: { id: userId } });"].join(`
80
230
  `)):n?(a=['import { InjectRepository } from "@nestjs/typeorm";','import { Repository } from "typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";'].join(`
81
231
  `),i=[" @InjectRepository(UserEntity)"," private readonly userRepository: Repository<UserEntity>,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
82
- `),d=[" 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(`
83
- `),p=["const user = await this.userRepository.findOne({"," where: { email },","});"].join(`
232
+ `),p=[" 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(`
233
+ `),u=["const user = await this.userRepository.findOne({"," where: { email },","});"].join(`
84
234
  `),m=["return this.userRepository.findOne({ where: { id: userId } });"].join(`
85
235
  `)):(a=['import { DbService } from "../database/db.service.js";','import { users } from "../database/orm/drizzle/schema.js";','import { eq } from "drizzle-orm";'].join(`
86
236
  `),i=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
87
- `),d=[" 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(`
88
- `),p=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.email, email))"," .limit(1);"].join(`
237
+ `),p=[" 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(`
238
+ `),u=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.email, email))"," .limit(1);"].join(`
89
239
  `),m=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.id, userId))"," .limit(1);","return user ?? null;"].join(`
90
240
  `));const g=[o.join(`
91
- `),"",a,"",'import type { SignupInput } from "./dto/signup.input.js";',"","export interface TokenPayload {"," accessToken: string;"," refreshToken: string;","}","","@Injectable()","export class AuthService {"," constructor(",i," ) {}",""," async createUser(payload: SignupInput): Promise<TokenPayload> {",d," }",""," 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) {",` ${m}`," }",""," 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(w.join(e,"auth.service.ts"),g,{overwrite:!0})}generateLoginSchema(e){const r=['import { z } from "zod";',"","export const loginSchema = z.object({"," email: z.email(),"," password: z.string().min(8),","});",""].join(`
93
- `);this.project.createSourceFile(w.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(`
94
- `);this.project.createSourceFile(w.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(`
95
- `);this.project.createSourceFile(w.join(e,"schemas/refresh-token.schema.ts"),r,{overwrite:!0})}generateJwtDto(e){const r=["export interface JwtDto {"," userId: string;"," iat: number;"," exp: number;","}",""].join(`
96
- `);this.project.createSourceFile(w.join(e,"dto/jwt.dto.ts"),r,{overwrite:!0})}generateLoginInput(e){const r=['import { Field, InputType } from "@nestjs/graphql";',"",'import { loginSchema } from "../schemas/login.schema.js";',"","@InputType()","export class LoginInput {"," static schema = loginSchema;",""," @Field()"," email: string;",""," @Field()"," password: string;","}",""].join(`
97
- `);this.project.createSourceFile(w.join(e,"dto/login.input.ts"),r,{overwrite:!0})}generateSignupInput(e){const r=['import { Field, InputType } from "@nestjs/graphql";',"",'import { signupSchema } from "../schemas/signup.schema.js";',"","@InputType()","export class SignupInput {"," static schema = signupSchema;",""," @Field()"," email: string;",""," @Field()"," password: string;",""," @Field({ nullable: true })"," firstname?: string;",""," @Field({ nullable: true })"," lastname?: string;","}",""].join(`
98
- `);this.project.createSourceFile(w.join(e,"dto/signup.input.ts"),r,{overwrite:!0})}generateRefreshTokenInput(e){const r=['import { ArgsType, Field } from "@nestjs/graphql";','import { GraphQLJWT } from "graphql-scalars";',"",'import { refreshTokenSchema } from "../schemas/refresh-token.schema.js";',"","@ArgsType()","export class RefreshTokenInput {"," static schema = refreshTokenSchema;",""," @Field(() => GraphQLJWT)"," token: string;","}",""].join(`
99
- `);this.project.createSourceFile(w.join(e,"dto/refresh-token.input.ts"),r,{overwrite:!0})}generateDbJwtStrategy(e){const r=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { ExtractJwt, Strategy } from "passport-jwt";',"",'import { env } from "../../config/env.js";','import { AuthService } from "../auth.service.js";','import type { JwtDto } from "../dto/jwt.dto.js";',"","@Injectable()","export class JwtStrategy extends PassportStrategy(Strategy) {"," constructor(private readonly authService: AuthService) {"," super({"," jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),"," secretOrKey: env.JWT_ACCESS_SECRET,"," });"," }",""," async validate(payload: JwtDto) {"," const user = await this.authService.validateUser(payload.userId);"," if (!user) {"," throw new UnauthorizedException();"," }"," return user;"," }","}",""].join(`
100
- `);this.project.createSourceFile(w.join(e,"strategies/jwt.strategy.ts"),r,{overwrite:!0})}generateDbRestGuard(e){const r=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class RestAuthGuard extends AuthGuard("jwt") {'," handleRequest<TUser>(err: Error | null, user: TUser): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," return user;"," }","}",""].join(`
101
- `);this.project.createSourceFile(w.join(e,"guards/rest-auth.guard.ts"),r,{overwrite:!0})}generateDbGqlGuard(e){const r=["import {"," ExecutionContext,"," Injectable,"," UnauthorizedException,",'} from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class GqlAuthGuard extends AuthGuard("jwt") {'," getRequest(context: ExecutionContext) {"," const ctx = GqlExecutionContext.create(context);"," return ctx.getContext().req;"," }",""," handleRequest<TUser>(err: Error | null, user: TUser): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," return user;"," }","}",""].join(`
102
- `);this.project.createSourceFile(w.join(e,"guards/gql-auth.guard.ts"),r,{overwrite:!0})}generateRestOptionalAuthGuard(e){const r=['import { Injectable } from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class RestOptionalAuthGuard extends AuthGuard("jwt") {'," handleRequest<TUser>(err: Error | null, user: TUser): TUser | null {"," if (err || !user) {"," return null;"," }"," return user;"," }","}",""].join(`
103
- `);this.project.createSourceFile(w.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(`
104
- `);this.project.createSourceFile(w.join(e,"guards/gql-optional-auth.guard.ts"),r,{overwrite:!0})}generateRestRolesGuard(e){const r=["import {"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"",'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(`
105
- `);this.project.createSourceFile(w.join(e,"guards/rest-roles.guard.ts"),r,{overwrite:!0})}generateGqlRolesGuard(e){const r=["import {"," ExecutionContext,"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"",'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(`
106
- `);this.project.createSourceFile(w.join(e,"guards/gql-roles.guard.ts"),r,{overwrite:!0})}generateDbController(e,r){const s=r?["import {"," ApiCreatedResponse,"," ApiOperation,"," ApiTags,"," ApiUnauthorizedResponse,",'} from "@nestjs/swagger";']:[],n=[];r&&n.push('@ApiTags("Auth")');const o=[];r&&o.push(' @ApiOperation({ summary: "/api/auth/signup" })'," @ApiCreatedResponse({ description: 'User registered successfully' })");const a=[];r&&a.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 d=['import { Body, Controller, Post } from "@nestjs/common";',...s,"",'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")',...o," signup(@Body({ schema: SignupInput.schema }) data: SignupInput) {"," data.email = data.email.toLowerCase();"," return this.auth.createUser(data);"," }","",' @Post("login")',...a," 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(w.join(e,"auth.controller.ts"),d.join(`
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(`
108
- `);this.project.createSourceFile(w.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(`
109
- `);this.project.createSourceFile(w.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(`
110
- `);this.project.createSourceFile(w.join(e,"auth.resolver.ts"),r,{overwrite:!0})}generateDbModule(e,r){const{hasGraphql:s,useTypeorm:n}=r,o=['import { Global, 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 { PasswordService } from "./password.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";'];s&&(o.push('import { AuthResolver } from "./auth.resolver.js";'),o.push('import { GqlAuthGuard } from "./guards/gql-auth.guard.js";'),o.push('import { GqlOptionalAuthGuard } from "./guards/gql-optional-auth.guard.js";')),n&&o.push('import { TypeOrmModule } from "@nestjs/typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";');const a=n?" TypeOrmModule.forFeature([UserEntity]),":"",i=[" AuthService,"," JwtStrategy,"," PasswordService,"," RestAuthGuard,"," RestOptionalAuthGuard,"];s&&(i.push(" GqlAuthGuard,"),i.push(" GqlOptionalAuthGuard,"),i.push(" AuthResolver,"));const d=[" GqlAuthGuard,"," GqlOptionalAuthGuard,"," PassportModule,"," RestAuthGuard,"," RestOptionalAuthGuard,"],p=[...o,"","@Global()","@Module({"," controllers: [AuthController],"," exports: [",d.join(`
241
+ `),"",a,"",'import type { SignupInput } from "./dto/signup.input.js";',"","export interface TokenPayload {"," accessToken: string;"," refreshToken: string;","}","","@Injectable()","export class AuthService {"," constructor(",i," ) {}",""," async createUser(payload: SignupInput): Promise<TokenPayload> {",p," }",""," async login("," email: string,"," password: string"," ): Promise<TokenPayload> {",u," 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) {",` ${m}`," }",""," 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(`
242
+ `);this.project.createSourceFile(j.join(t,"auth.service.ts"),g,{overwrite:!0})}generateLoginSchema(t){const r=['import { z } from "zod";',"","export const loginSchema = z.object({"," email: z.email(),"," password: z.string().min(8),","});",""].join(`
243
+ `);this.project.createSourceFile(j.join(t,"schemas/login.schema.ts"),r,{overwrite:!0})}generateSignupSchema(t){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(`
244
+ `);this.project.createSourceFile(j.join(t,"schemas/signup.schema.ts"),r,{overwrite:!0})}generateRefreshTokenSchema(t){const r=['import { z } from "zod";',"","export const refreshTokenSchema = z.object({"," token: z.string().min(1),","});",""].join(`
245
+ `);this.project.createSourceFile(j.join(t,"schemas/refresh-token.schema.ts"),r,{overwrite:!0})}generateJwtDto(t){const r=["export interface JwtDto {"," userId: string;"," iat: number;"," exp: number;","}",""].join(`
246
+ `);this.project.createSourceFile(j.join(t,"dto/jwt.dto.ts"),r,{overwrite:!0})}generateLoginInput(t){const r=['import { Field, InputType } from "@nestjs/graphql";',"",'import { loginSchema } from "../schemas/login.schema.js";',"","@InputType()","export class LoginInput {"," static schema = loginSchema;",""," @Field()"," email: string;",""," @Field()"," password: string;","}",""].join(`
247
+ `);this.project.createSourceFile(j.join(t,"dto/login.input.ts"),r,{overwrite:!0})}generateSignupInput(t){const r=['import { Field, InputType } from "@nestjs/graphql";',"",'import { signupSchema } from "../schemas/signup.schema.js";',"","@InputType()","export class SignupInput {"," static schema = signupSchema;",""," @Field()"," email: string;",""," @Field()"," password: string;",""," @Field({ nullable: true })"," firstname?: string;",""," @Field({ nullable: true })"," lastname?: string;","}",""].join(`
248
+ `);this.project.createSourceFile(j.join(t,"dto/signup.input.ts"),r,{overwrite:!0})}generateRefreshTokenInput(t){const r=['import { ArgsType, Field } from "@nestjs/graphql";','import { GraphQLJWT } from "graphql-scalars";',"",'import { refreshTokenSchema } from "../schemas/refresh-token.schema.js";',"","@ArgsType()","export class RefreshTokenInput {"," static schema = refreshTokenSchema;",""," @Field(() => GraphQLJWT)"," token: string;","}",""].join(`
249
+ `);this.project.createSourceFile(j.join(t,"dto/refresh-token.input.ts"),r,{overwrite:!0})}generateDbJwtStrategy(t){const r=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { ExtractJwt, Strategy } from "passport-jwt";',"",'import { env } from "../../config/env.js";','import { AuthService } from "../auth.service.js";','import type { JwtDto } from "../dto/jwt.dto.js";',"","@Injectable()","export class JwtStrategy extends PassportStrategy(Strategy) {"," constructor(private readonly authService: AuthService) {"," super({"," jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),"," secretOrKey: env.JWT_ACCESS_SECRET,"," });"," }",""," async validate(payload: JwtDto) {"," const user = await this.authService.validateUser(payload.userId);"," if (!user) {"," throw new UnauthorizedException();"," }"," return user;"," }","}",""].join(`
250
+ `);this.project.createSourceFile(j.join(t,"strategies/jwt.strategy.ts"),r,{overwrite:!0})}generateDbRestGuard(t){const r=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class RestAuthGuard extends AuthGuard("jwt") {'," handleRequest<TUser>(err: Error | null, user: TUser): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," return user;"," }","}",""].join(`
251
+ `);this.project.createSourceFile(j.join(t,"guards/rest-auth.guard.ts"),r,{overwrite:!0})}generateDbGqlGuard(t){const r=["import {"," ExecutionContext,"," Injectable,"," UnauthorizedException,",'} from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class GqlAuthGuard extends AuthGuard("jwt") {'," getRequest(context: ExecutionContext) {"," const ctx = GqlExecutionContext.create(context);"," return ctx.getContext().req;"," }",""," handleRequest<TUser>(err: Error | null, user: TUser): TUser {"," if (err || !user) {",' throw err || new UnauthorizedException("Invalid or expired token");'," }"," return user;"," }","}",""].join(`
252
+ `);this.project.createSourceFile(j.join(t,"guards/gql-auth.guard.ts"),r,{overwrite:!0})}generateRestOptionalAuthGuard(t){const r=['import { Injectable } from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"","@Injectable()",'export class RestOptionalAuthGuard extends AuthGuard("jwt") {'," handleRequest<TUser>(err: Error | null, user: TUser): TUser | null {"," if (err || !user) {"," return null;"," }"," return user;"," }","}",""].join(`
253
+ `);this.project.createSourceFile(j.join(t,"guards/rest-optional-auth.guard.ts"),r,{overwrite:!0})}generateGqlOptionalAuthGuard(t){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(`
254
+ `);this.project.createSourceFile(j.join(t,"guards/gql-optional-auth.guard.ts"),r,{overwrite:!0})}generateRestRolesGuard(t){const r=["import {"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";',"",'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(`
255
+ `);this.project.createSourceFile(j.join(t,"guards/rest-roles.guard.ts"),r,{overwrite:!0})}generateGqlRolesGuard(t){const r=["import {"," ExecutionContext,"," UnauthorizedException,"," ForbiddenException,",'} from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthGuard } from "@nestjs/passport";',"",'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(`
256
+ `);this.project.createSourceFile(j.join(t,"guards/gql-roles.guard.ts"),r,{overwrite:!0})}generateDbController(t,r){const s=r?["import {"," ApiCreatedResponse,"," ApiOperation,"," ApiTags,"," ApiUnauthorizedResponse,",'} from "@nestjs/swagger";']:[],n=[];r&&n.push('@ApiTags("Auth")');const o=[];r&&o.push(' @ApiOperation({ summary: "/api/auth/signup" })'," @ApiCreatedResponse({ description: 'User registered successfully' })");const a=[];r&&a.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 p=['import { Body, Controller, Post } from "@nestjs/common";',...s,"",'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")',...o," signup(@Body({ schema: SignupInput.schema }) data: SignupInput) {"," data.email = data.email.toLowerCase();"," return this.auth.createUser(data);"," }","",' @Post("login")',...a," 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(j.join(t,"auth.controller.ts"),p.join(`
257
+ `),{overwrite:!0})}generateTokenModel(t){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(`
258
+ `);this.project.createSourceFile(j.join(t,"models/token.model.ts"),r,{overwrite:!0})}generateAuthModel(t){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(`
259
+ `);this.project.createSourceFile(j.join(t,"models/auth.model.ts"),r,{overwrite:!0})}generateAuthResolver(t){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(`
260
+ `);this.project.createSourceFile(j.join(t,"auth.resolver.ts"),r,{overwrite:!0})}generateDbModule(t,r){const{hasGraphql:s,useTypeorm:n}=r,o=['import { Global, 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 { PasswordService } from "./password.service.js";','import { JwtStrategy } from "./strategies/jwt.strategy.js";'];s&&(o.push('import { AuthResolver } from "./auth.resolver.js";'),o.push('import { GqlAuthGuard } from "./guards/gql-auth.guard.js";'),o.push('import { GqlOptionalAuthGuard } from "./guards/gql-optional-auth.guard.js";')),n&&o.push('import { TypeOrmModule } from "@nestjs/typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";');const a=n?" TypeOrmModule.forFeature([UserEntity]),":"",i=[" AuthService,"," JwtStrategy,"," PasswordService,"," RestAuthGuard,"," RestOptionalAuthGuard,"];s&&(i.push(" GqlAuthGuard,"),i.push(" GqlOptionalAuthGuard,"),i.push(" AuthResolver,"));const p=[" GqlAuthGuard,"," GqlOptionalAuthGuard,"," PassportModule,"," RestAuthGuard,"," RestOptionalAuthGuard,"],u=[...o,"","@Global()","@Module({"," controllers: [AuthController],"," exports: [",p.join(`
111
261
  `)," ],"," imports: [",' PassportModule.register({ defaultStrategy: "jwt" }),'," JwtModule.register({"," secret: env.JWT_ACCESS_SECRET,",' signOptions: { expiresIn: "15m" },'," }),",a," ],"," providers: [",i.join(`
112
- `)," ],","})","export class AuthModule {}",""];this.project.createSourceFile(w.join(e,"auth.module.ts"),p.join(`
113
- `),{overwrite:!0})}generateDecorators(e){const r=w.join(e,"decorators"),s=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const CurrentUser = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user;"," }",");",""].join(`
114
- `);this.project.createSourceFile(w.join(r,"current-user.decorator.ts"),s,{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(`
115
- `);this.project.createSourceFile(w.join(r,"user.decorator.ts"),n,{overwrite:!0});const o=['export { CurrentUser } from "./current-user.decorator.js";','export { UserEntity } from "./user.decorator.js";',""].join(`
116
- `);this.project.createSourceFile(w.join(r,"index.ts"),o,{overwrite:!0})}generateGuard(e){this.generateDbRestGuard(e),this.generateRestOptionalAuthGuard(e),this.generateRestRolesGuard(e)}}class Hs{static{l(this,"AuthModuleGenerator")}project;config;passportGen;betterAuthGen;constructor(e){this.config=e,this.project=new gr,this.passportGen=new Js(this.project,e),this.betterAuthGen=new Bs(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 Ws{static{l(this,"PresetComposer")}presets=new Map;constructor(){this.registerDefaultPresets()}registerDefaultPresets(){this.registerPreset({architectures:["nest-api"],description:"RESTful API with JWT authentication and Swagger documentation",extras:["swagger"],generators:["auth"],id:"rest-api",name:"REST API"}),this.registerPreset({architectures:["nest-api"],description:"GraphQL API with Apollo Server and authentication",extras:["graphql","apollo"],generators:["auth"],id:"graphql-api",name:"GraphQL API"}),this.registerPreset({architectures:["nest-microservice"],description:"Microservice with messaging and inter-service communication",extras:["nats","rabbitmq"],generators:["auth"],id:"microservice",name:"Microservice"}),this.registerPreset({architectures:["nest-gateway"],description:"API Gateway for routing and load balancing",extras:["rate-limiting","load-balance"],generators:[],id:"gateway",name:"API Gateway"}),this.registerPreset({architectures:["nest-api"],description:"Complete application with database, auth, and all extras",extras:["swagger","docker","health-check","rate-limiting"],generators:["auth","config","database"],id:"fullstack",name:"Full Stack"})}registerPreset(e){this.presets.set(e.id,e)}getPreset(e){return this.presets.get(e)}getAllPresets(){return[...this.presets.values()]}getPresetsForArchitecture(e){return[...this.presets.values()].filter(r=>r.architectures.includes(e))}static composeGenerators(e){const r=new Set;return e.auth!=="none"&&r.add("auth"),e.database.length>0&&r.add("database"),[...r]}static composeExtras(e){const r=new Set(e.extras);return e.api.includes("rest")&&e.extras.includes("swagger")&&r.add("swagger"),e.orm.includes("prisma")&&r.add("prisma"),e.orm.includes("typeorm")&&r.add("typeorm"),[...r]}suggestPreset(e){if(this.getPresetsForArchitecture(e.architecture).length!==0)return e.api.includes("graphql")?this.presets.get("graphql-api"):e.architecture==="nest-microservice"?this.presets.get("microservice"):e.architecture==="nest-gateway"?this.presets.get("gateway"):e.database.length>0&&e.auth!=="none"?this.presets.get("fullstack")??this.presets.get("rest-api"):this.presets.get("rest-api")}validateContext(e,r){const s=this.getPreset(r);return s?s.architectures.includes(e.architecture):!1}}async function Vs(t,e,r){const s=[];for(const n of r)try{if(n==="auth"){const o=t.api.includes("rest"),a=new Hs({api:t.api,database:t.database,extras:t.extras,orm:t.orm,outputDir:`${e}/src`,skipModule:!o&&(t.auth==="better-auth"||t.auth==="better-auth:stateless"),strategy:t.auth});await(o||t.auth==="passport"?a.generate():a.generateAuthOnly()),await a.save(),s.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${n} not yet implemented`)}catch(o){s.push({error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return s}l(Vs,"executePresetGenerators");function Qs(t){const e=["services:",` ${t.projectName}:`," build:"," context: ."," dockerfile: Dockerfile"," ports:",` - "${t.httpProvider==="fastify"?"3001:3001":"3000:3000"}"`," environment:"," - NODE_ENV=development"],r=[],s=t.projectName;if(t.database.includes("postgresql")&&r.push("postgres"),t.database.includes("mysql")&&r.push("mysql"),t.database.includes("mongodb")&&r.push("mongodb"),r.length>0){e.push(" depends_on:");for(const o of r)e.push(` - ${o}`)}return e.push(" volumes:"),e.push(" - .:/app"),e.push(" - /app/node_modules"),t.database.includes("postgresql")&&(e.push(""),e.push(" postgres:"),e.push(" image: postgres:17-alpine"),e.push(" environment:"),e.push(" POSTGRES_USER: postgres"),e.push(" POSTGRES_PASSWORD: postgres"),e.push(` POSTGRES_DB: ${s}_db`),e.push(" ports:"),e.push(' - "5432:5432"'),e.push(" volumes:"),e.push(" - postgres_data:/var/lib/postgresql/data")),t.database.includes("mysql")&&(e.push(""),e.push(" mysql:"),e.push(" image: mysql:9.7.1"),e.push(" environment:"),e.push(" MYSQL_ROOT_PASSWORD: mysql"),e.push(` MYSQL_DATABASE: ${s}_db`),e.push(" ports:"),e.push(' - "3306:3306"'),e.push(" volumes:"),e.push(" - mysql_data:/var/lib/mysql")),t.database.includes("mongodb")&&(e.push(""),e.push(" mongodb:"),e.push(" image: mongo:8.3.4-noble"),e.push(" environment:"),e.push(` MONGO_INITDB_DATABASE: ${s}_db`),e.push(" ports:"),e.push(' - "27017:27017"'),e.push(" volumes:"),e.push(" - mongo_data:/data/db")),t.database.some(o=>["postgresql","mysql","mongodb"].includes(o))&&(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(`
262
+ `)," ],","})","export class AuthModule {}",""];this.project.createSourceFile(j.join(t,"auth.module.ts"),u.join(`
263
+ `),{overwrite:!0})}generateDecorators(t){const r=j.join(t,"decorators"),s=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const CurrentUser = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user;"," }",");",""].join(`
264
+ `);this.project.createSourceFile(j.join(r,"current-user.decorator.ts"),s,{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(`
265
+ `);this.project.createSourceFile(j.join(r,"user.decorator.ts"),n,{overwrite:!0});const o=['export { CurrentUser } from "./current-user.decorator.js";','export { UserEntity } from "./user.decorator.js";',""].join(`
266
+ `);this.project.createSourceFile(j.join(r,"index.ts"),o,{overwrite:!0})}generateGuard(t){this.generateDbRestGuard(t),this.generateRestOptionalAuthGuard(t),this.generateRestRolesGuard(t)}}class Oi{static{c(this,"it")}static{l(this,"AuthModuleGenerator")}project;config;passportGen;betterAuthGen;constructor(t){this.config=t,this.project=new Yr,this.passportGen=new Ri(this.project,t),this.betterAuthGen=new zi(this.project,t)}generate(){const t=`${this.config.outputDir}/auth`,r=this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy;r==="passport"?this.passportGen.generate(t):r==="better-auth"&&this.betterAuthGen.generate(t)}generateAuthOnly(){const t=`${this.config.outputDir}/auth`;(this.config.strategy==="better-auth:stateless"?"better-auth":this.config.strategy)==="better-auth"&&this.betterAuthGen.generateAuthOnly(t)}async save(){await this.project.save()}}class Ci{static{c(this,"ct")}static{l(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(t){this.presets.set(t.id,t)}getPreset(t){return this.presets.get(t)}getAllPresets(){return[...this.presets.values()]}getPresetsForArchitecture(t){return[...this.presets.values()].filter(r=>r.architectures.includes(t))}static composeGenerators(t){const r=new Set;return t.auth!=="none"&&r.add("auth"),t.database.length>0&&r.add("database"),[...r]}static composeExtras(t){const r=new Set(t.extras);return t.api.includes("rest")&&t.extras.includes("swagger")&&r.add("swagger"),t.orm.includes("prisma")&&r.add("prisma"),t.orm.includes("typeorm")&&r.add("typeorm"),[...r]}suggestPreset(t){if(this.getPresetsForArchitecture(t.architecture).length!==0)return t.api.includes("graphql")?this.presets.get("graphql-api"):t.architecture==="nest-microservice"?this.presets.get("microservice"):t.architecture==="nest-gateway"?this.presets.get("gateway"):t.database.length>0&&t.auth!=="none"?this.presets.get("fullstack")??this.presets.get("rest-api"):this.presets.get("rest-api")}validateContext(t,r){const s=this.getPreset(r);return s?s.architectures.includes(t.architecture):!1}}async function Vs(e,t,r){const s=[];for(const n of r)try{if(n==="auth"){const o=e.api.includes("rest"),a=new Oi({api:e.api,database:e.database,envImport:e.projectType==="monorepo"?"@repo/env/api-gateway":"../config/env.js",extras:e.extras,orm:e.orm,outputDir:`${t}/src`,skipModule:!o&&(e.auth==="better-auth"||e.auth==="better-auth:stateless"),strategy:e.auth});await(o||e.auth==="passport"?a.generate():a.generateAuthOnly()),await a.save(),s.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${n} not yet implemented`)}catch(o){s.push({error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return s}c(Vs,"ut"),l(Vs,"executePresetGenerators");function Hs(e){const t=["services:",` ${e.projectName}:`," build:"," context: ."," dockerfile: Dockerfile"," ports:",` - "${e.httpProvider==="fastify"?"3001:3001":"3000:3000"}"`," environment:"," - NODE_ENV=development"];e.microservices.includes("grpc")&&t.splice(6,0,' - "5000:5000"');const r={kafka:"KAFKA_BROKER=kafka:9092",mqtt:"MQTT_URL=mqtt://mqtt:1883",nats:"NATS_URL=nats://nats:4222",rabbitmq:"RABBITMQ_URL=amqp://rabbitmq:5672",redis:"REDIS_URL=redis://redis:6379"};for(const o of e.microservices){const a=r[o];a&&t.push(` - ${a}`)}const s=[],n=e.projectName;e.database.includes("postgresql")&&s.push("postgres"),e.database.includes("mysql")&&s.push("mysql"),e.database.includes("mongodb")&&s.push("mongodb");for(const o of e.microservices)o!=="grpc"&&s.push(o);if(s.length>0){t.push(" depends_on:");for(const o of s)t.push(` - ${o}`)}return t.push(" volumes:"),t.push(" - .:/app"),t.push(" - /app/node_modules"),e.database.includes("postgresql")&&(t.push(""),t.push(" postgres:"),t.push(" image: postgres:17-alpine"),t.push(" environment:"),t.push(" POSTGRES_USER: postgres"),t.push(" POSTGRES_PASSWORD: postgres"),t.push(` POSTGRES_DB: ${n}_db`),t.push(" ports:"),t.push(' - "5432:5432"'),t.push(" volumes:"),t.push(" - postgres_data:/var/lib/postgresql/data")),e.database.includes("mysql")&&(t.push(""),t.push(" mysql:"),t.push(" image: mysql:9.7.1"),t.push(" environment:"),t.push(" MYSQL_ROOT_PASSWORD: mysql"),t.push(` MYSQL_DATABASE: ${n}_db`),t.push(" ports:"),t.push(' - "3306:3306"'),t.push(" volumes:"),t.push(" - mysql_data:/var/lib/mysql")),e.database.includes("mongodb")&&(t.push(""),t.push(" mongodb:"),t.push(" image: mongo:8.3.4-noble"),t.push(" environment:"),t.push(` MONGO_INITDB_DATABASE: ${n}_db`),t.push(" ports:"),t.push(' - "27017:27017"'),t.push(" volumes:"),t.push(" - mongo_data:/data/db")),e.microservices.includes("redis")&&(t.push(""),t.push(" redis:"),t.push(" image: redis:7-alpine"),t.push(" ports:"),t.push(' - "6379:6379"')),e.microservices.includes("mqtt")&&(t.push(""),t.push(" mqtt:"),t.push(" image: eclipse-mosquitto:2"),t.push(" ports:"),t.push(' - "1883:1883"')),e.microservices.includes("nats")&&(t.push(""),t.push(" nats:"),t.push(" image: nats:2-alpine"),t.push(" ports:"),t.push(' - "4222:4222"')),e.microservices.includes("rabbitmq")&&(t.push(""),t.push(" rabbitmq:"),t.push(" image: rabbitmq:3.13-alpine"),t.push(" ports:"),t.push(' - "5672:5672"')),e.microservices.includes("kafka")&&(t.push(""),t.push(" kafka:"),t.push(" image: apache/kafka:3.9.0"),t.push(" environment:"),t.push(" KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092"),t.push(" KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true'"),t.push(" KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER"),t.push(" KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093"),t.push(" KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: '0'"),t.push(" KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT"),t.push(" KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093"),t.push(" KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT"),t.push(" KAFKA_NODE_ID: '1'"),t.push(" KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS: '1'"),t.push(" KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: '1'"),t.push(" KAFKA_PROCESS_ROLES: broker,controller"),t.push(" KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: '1'"),t.push(" KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: '1'"),t.push(" ports:"),t.push(' - "9092:9092"')),e.database.some(o=>["postgresql","mysql","mongodb"].includes(o))&&(t.push(""),t.push("volumes:"),e.database.includes("postgresql")&&t.push(" postgres_data:"),e.database.includes("mysql")&&t.push(" mysql_data:"),e.database.includes("mongodb")&&t.push(" mongo_data:")),`${t.join(`
267
+ `)}
268
+ `}c(Hs,"Vr"),l(Hs,"generateDockerCompose");async function Ws(e,t,r,s,n){let o="postgresql";t.database.includes("mysql")?o="mysql":t.database.includes("sqlite")&&(o="sqlite");const a=t.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",i=a.replace("/schema.ts","/migrations");let p="env.POSTGRES_URL";t.database.includes("mysql")?p="env.MYSQL_URL":t.database.includes("sqlite")&&(p="env.SQLITE_PATH");const u=[t.formatter==="oxlint-oxfmt"?"// oxlint-disable typescript/no-non-null-assertion":"",t.projectType==="monorepo"?"import { env } from '@repo/env/api-gateway';":"import { env } from './src/config/env.js';","import { defineConfig } from 'drizzle-kit';","","export default defineConfig({"," dbCredentials: {",` url: ${p},`," },",` dialect: '${o}',`,` out: '${i}',`,` schema: '${a}',`,"});",""].join(`
269
+ `);try{if(t.auth==="better-auth"){const g=a.replace("schema.ts","auth-schema.ts");await e.writeFile({content:`// Run auth:generate before building.
270
+ export {};
271
+ `,filePath:g,isBinary:!1},r)}const m=await e.writeFile({content:u,filePath:"drizzle.config.ts",isBinary:!1},r);m.written&&s.push(m.filePath)}catch(m){const g=m instanceof Error?m.message:String(m);n.push(`Failed to generate drizzle.config.ts: ${g}`)}}c(Ws,"Kr"),l(Ws,"generateDrizzleConfig");function Xt(e,t){if(e instanceof Promise)throw new Error(t)}c(Xt,"pt"),l(Xt,"ensureSynchronous");function Ks(e,t){const r={},s=[];for(const n in e){const o=e[n]["~standard"].validate(t[n]);if(Xt(o,`Validation must be synchronous, but ${n} returned a Promise.`),o.issues){s.push(...o.issues.map(a=>({...a,message:a.message,path:[n,...a.path??[]]})));continue}r[n]=o.value}return s.length?{issues:s}:{value:r}}c(Ks,"Wr"),l(Ks,"parseWithDictionary");function Qs(e){const t=e.runtimeEnvStrict??e.runtimeEnv??process.env;if(e.emptyStringAsUndefined??!1)for(const[T,M]of Object.entries(t))M===""&&delete t[T];if(e.skipValidation){if(e.extends)for(const T of e.extends)T.skipValidation=!0;return t}const r=typeof e.client=="object"?e.client:{},s=typeof e.server=="object"?e.server:{},n=typeof e.shared=="object"?e.shared:{},o=e.isServer??(typeof window>"u"||"Deno"in window),a=o?{...s,...n,...r}:{...r,...n},i=e.createFinalSchema?.(a,o)?.["~standard"].validate(t)??Ks(a,t);Xt(i,"Validation must be synchronous");const p=e.onValidationError??(T=>{throw console.error("\u274C Invalid environment variables:",T),new Error("Invalid environment variables")}),u=e.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(i.issues)return p(i.issues);const m=l(T=>e.clientPrefix?!T.startsWith(e.clientPrefix)&&!(T in n):!0,"isServerAccess"),g=l(T=>o||!m(T),"isValidServerAccess"),b=l(T=>T==="__esModule"||T==="$$typeof","ignoreProp"),S=(e.extends??[]).reduce((T,M)=>Object.assign(T,M),{}),P=Object.assign(S,i.value);return new Proxy(P,{get(T,M){if(typeof M=="string"&&!b(M))return g(M)?Reflect.get(T,M):u(M)}})}c(Qs,"Hr"),l(Qs,"createEnv$1");const Di="NEXT_PUBLIC_";function Ys(e){const t=typeof e.client=="object"?e.client:{},r=typeof e.server=="object"?e.server:{},s=e.shared,n=e.runtimeEnv?e.runtimeEnv:{...process.env,...e.experimental__runtimeEnv};return Qs({...e,shared:s,client:t,server:r,clientPrefix:Di,runtimeEnv:n})}c(Ys,"Yr"),l(Ys,"createEnv");var Xs;function y(e,t,r){function s(i,p){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:p,constr:a,traits:new Set},enumerable:!1}),i._zod.traits.has(e))return;i._zod.traits.add(e),t(i,p);const u=a.prototype,m=Object.keys(u);for(let g=0;g<m.length;g++){const b=m[g];b in i||(i[b]=u[b].bind(i))}}c(s,"s"),l(s,"init");const n=r?.Parent??Object;class o extends n{static{c(this,"a")}static{l(this,"Definition")}}Object.defineProperty(o,"name",{value:e});function a(i){var p;const u=r?.Parent?new o:this;s(u,i),(p=u._zod).deferred??(p.deferred=[]);for(const m of u._zod.deferred)m();return u}return c(a,"n"),l(a,"_"),Object.defineProperty(a,"init",{value:s}),Object.defineProperty(a,Symbol.hasInstance,{value:l(i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e),"value")}),Object.defineProperty(a,"name",{value:e}),a}c(y,"m"),l(y,"$constructor");class Ne extends Error{static{c(this,"U")}static{l(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class en extends Error{static{c(this,"dt")}static{l(this,"$ZodEncodeError")}constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Xs=globalThis).__zod_globalConfig??(Xs.__zod_globalConfig={});const Ni=globalThis.__zod_globalConfig;function we(e){return Ni}c(we,"N"),l(we,"config");function er(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,s])=>t.indexOf(+r)===-1).map(([r,s])=>s)}c(er,"mt"),l(er,"getEnumValues");function yt(e,t){return typeof t=="bigint"?t.toString():t}c(yt,"he"),l(yt,"jsonStringifyReplacer");function bt(e){return e==null}c(bt,"fe"),l(bt,"nullish");function vt(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}c(vt,"ge"),l(vt,"cleanRegex");function tn(e,t){const r=e/t,s=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-s)<n?0:r-s}c(tn,"es"),l(tn,"floatSafeRemainder");const rn=Symbol("evaluating");function G(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rn)return s===void 0&&(s=rn,s=r()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}c(G,"j"),l(G,"defineLazy");function sn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}c(sn,"ts"),l(sn,"mergeDefs");function nn(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}c(nn,"rs"),l(nn,"slugify");const an="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}c(tr,"gt"),l(tr,"isObject");function wt(e){if(tr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(tr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}c(wt,"be"),l(wt,"isPlainObject");function rr(e){return wt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}c(rr,"bt"),l(rr,"shallowClone");const qi=new Set(["string","number","symbol"]);function Ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c(Ve,"Y"),l(Ve,"escapeRegex");function on(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}c(on,"os"),l(on,"clone");function k(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:l(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:l(()=>t.error,"error")}:t}c(k,"b"),l(k,"normalizeParams");const $i={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ae(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}c(Ae,"F"),l(Ae,"aborted");function cn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}c(cn,"as"),l(cn,"explicitlyAborted");function ln(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}c(ln,"is"),l(ln,"prefixIssues");function He(e){return typeof e=="string"?e:e?.message}c(He,"Q"),l(He,"unwrapMessage");function je(e,t,r){const s=e.message?e.message:He(e.inst?._zod.def?.error?.(e))??He(t?.error?.(e))??He(r.customError?.(e))??He(r.localeError?.(e))??"Invalid input",{inst:n,continue:o,input:a,...i}=e;return i.path??(i.path=[]),i.message=s,t?.reportInput&&(i.input=a),i}c(je,"M"),l(je,"finalizeIssue");function jt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}c(jt,"ye"),l(jt,"getLengthableOrigin");function qe(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}c(qe,"Z"),l(qe,"issue");const pn=l((e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,yt,2),Object.defineProperty(e,"toString",{value:l(()=>e.message,"value"),enumerable:!1})},"initializer$1"),un=y("$ZodError",pn),dn=y("$ZodError",pn,{Parent:Error});function mn(e,t=r=>r.message){const r={},s=[];for(const n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):s.push(t(n));return{formErrors:s,fieldErrors:r}}c(mn,"cs"),l(mn,"flattenError");function hn(e,t=r=>r.message){const r={_errors:[]},s=l((n,o=[])=>{for(const a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i},[...o,...a.path]));else if(a.code==="invalid_key")s({issues:a.issues},[...o,...a.path]);else if(a.code==="invalid_element")s({issues:a.issues},[...o,...a.path]);else{const i=[...o,...a.path];if(i.length===0)r._errors.push(t(a));else{let p=r,u=0;for(;u<i.length;){const m=i[u];u===i.length-1?(p[m]=p[m]||{_errors:[]},p[m]._errors.push(t(a))):p[m]=p[m]||{_errors:[]},p=p[m],u++}}}},"processError");return s(e),r}c(hn,"us"),l(hn,"formatError");const sr=l(e=>(t,r,s,n)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Ne;if(a.issues.length){const i=new(n?.Err??e)(a.issues.map(p=>je(p,o,we())));throw an(i,n?.callee),i}return a.value},"_parse"),nr=l(e=>async(t,r,s,n)=>{const o=s?{...s,async:!0}:{async:!0};let a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(n?.Err??e)(a.issues.map(p=>je(p,o,we())));throw an(i,n?.callee),i}return a.value},"_parseAsync"),St=l(e=>(t,r,s)=>{const n=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},n);if(o instanceof Promise)throw new Ne;return o.issues.length?{success:!1,error:new(e??un)(o.issues.map(a=>je(a,n,we())))}:{success:!0,data:o.value}},"_safeParse"),Mi=St(dn),kt=l(e=>async(t,r,s)=>{const n=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},n);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>je(a,n,we())))}:{success:!0,data:o.value}},"_safeParseAsync"),Fi=kt(dn),Gi=l(e=>(t,r,s)=>{const n=s?{...s,direction:"backward"}:{direction:"backward"};return sr(e)(t,r,n)},"_encode"),Ui=l(e=>(t,r,s)=>sr(e)(t,r,s),"_decode"),Li=l(e=>async(t,r,s)=>{const n=s?{...s,direction:"backward"}:{direction:"backward"};return nr(e)(t,r,n)},"_encodeAsync"),Ji=l(e=>async(t,r,s)=>nr(e)(t,r,s),"_decodeAsync"),Bi=l(e=>(t,r,s)=>{const n=s?{...s,direction:"backward"}:{direction:"backward"};return St(e)(t,r,n)},"_safeEncode"),Zi=l(e=>(t,r,s)=>St(e)(t,r,s),"_safeDecode"),Vi=l(e=>async(t,r,s)=>{const n=s?{...s,direction:"backward"}:{direction:"backward"};return kt(e)(t,r,n)},"_safeEncodeAsync"),Hi=l(e=>async(t,r,s)=>kt(e)(t,r,s),"_safeDecodeAsync"),Wi=/^[cC][0-9a-z]{6,}$/,Ki=/^[0-9a-z]+$/,Qi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yi=/^[0-9a-vA-V]{20}$/,Xi=/^[A-Za-z0-9]{27}$/,ec=/^[a-zA-Z0-9_-]{21}$/,tc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,rc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fn=l(e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,"uuid"),sc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gn(){return new RegExp(nc,"u")}c(gn,"zs"),l(gn,"emoji");const ac=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ic=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lc=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yn=/^[A-Za-z0-9_-]*$/,pc=/^https?$/,uc=/^\+[1-9]\d{6,14}$/,bn="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",dc=new RegExp(`^${bn}$`);function ar(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}c(ar,"St"),l(ar,"timeSource");function vn(e){return new RegExp(`^${ar(e)}$`)}c(vn,"Us"),l(vn,"time$1");function wn(e){const t=ar({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${bn}T(?:${s})$`)}c(wn,"Fs"),l(wn,"datetime$1");const mc=l(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),hc=/^-?\d+$/,fc=/^-?\d+(?:\.\d+)?$/,gc=/^[^A-Z]*$/,yc=/^[^a-z]*$/,oe=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),jn={number:"number",bigint:"bigint",object:"date"},Sn=y("$ZodCheckLessThan",(e,t)=>{oe.init(e,t);const r=jn[typeof t.value];e._zod.onattach.push(s=>{const n=s._zod.bag,o=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),kn=y("$ZodCheckGreaterThan",(e,t)=>{oe.init(e,t);const r=jn[typeof t.value];e._zod.onattach.push(s=>{const n=s._zod.bag,o=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bc=y("$ZodCheckMultipleOf",(e,t)=>{oe.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):tn(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),vc=y("$ZodCheckNumberFormat",(e,t)=>{oe.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[n,o]=$i[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=n,i.maximum=o,r&&(i.pattern=hc)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}i<n&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),wc=y("$ZodCheckMaxLength",(e,t)=>{var r;oe.init(e,t),(r=e._zod.def).when??(r.when=s=>{const n=s.value;return!bt(n)&&n.length!==void 0}),e._zod.onattach.push(s=>{const n=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const n=s.value;if(n.length<=t.maximum)return;const o=jt(n);s.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),jc=y("$ZodCheckMinLength",(e,t)=>{var r;oe.init(e,t),(r=e._zod.def).when??(r.when=s=>{const n=s.value;return!bt(n)&&n.length!==void 0}),e._zod.onattach.push(s=>{const n=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const n=s.value;if(n.length>=t.minimum)return;const o=jt(n);s.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Sc=y("$ZodCheckLengthEquals",(e,t)=>{var r;oe.init(e,t),(r=e._zod.def).when??(r.when=s=>{const n=s.value;return!bt(n)&&n.length!==void 0}),e._zod.onattach.push(s=>{const n=s._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=s=>{const n=s.value,o=n.length;if(o===t.length)return;const a=jt(n),i=o>t.length;s.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),_t=y("$ZodCheckStringFormat",(e,t)=>{var r,s;oe.init(e,t),e._zod.onattach.push(n=>{const o=n._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),kc=y("$ZodCheckRegex",(e,t)=>{_t.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_c=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=gc),_t.init(e,t)}),xc=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yc),_t.init(e,t)}),Tc=y("$ZodCheckIncludes",(e,t)=>{oe.init(e,t);const r=Ve(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(s)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ac=y("$ZodCheckStartsWith",(e,t)=>{oe.init(e,t);const r=new RegExp(`^${Ve(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const n=s._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Ec=y("$ZodCheckEndsWith",(e,t)=>{oe.init(e,t);const r=new RegExp(`.*${Ve(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const n=s._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Pc=y("$ZodCheckOverwrite",(e,t)=>{oe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),Ic={major:4,minor:4,patch:3},Q=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ic;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const n of s)for(const o of n._zod.onattach)o(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const n=l((a,i,p)=>{let u=Ae(a),m;for(const g of i){if(g._zod.def.when){if(cn(a)||!g._zod.def.when(a))continue}else if(u)continue;const b=a.issues.length,S=g._zod.check(a);if(S instanceof Promise&&p?.async===!1)throw new Ne;if(m||S instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await S,a.issues.length!==b&&(u||(u=Ae(a,b)))});else{if(a.issues.length===b)continue;u||(u=Ae(a,b))}}return m?m.then(()=>a):a},"runChecks"),o=l((a,i,p)=>{if(Ae(a))return a.aborted=!0,a;const u=n(i,s,p);if(u instanceof Promise){if(p.async===!1)throw new Ne;return u.then(m=>e._zod.parse(m,p))}return e._zod.parse(u,p)},"handleCanaryResult");e._zod.run=(a,i)=>{if(i.skipChecks)return e._zod.parse(a,i);if(i.direction==="backward"){const u=e._zod.parse({value:a.value,issues:[]},{...i,skipChecks:!0});return u instanceof Promise?u.then(m=>o(m,a,i)):o(u,a,i)}const p=e._zod.parse(a,i);if(p instanceof Promise){if(i.async===!1)throw new Ne;return p.then(u=>n(u,s,i))}return n(p,s,i)}}G(e,"~standard",()=>({validate:l(n=>{try{const o=Mi(e,n);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Fi(e,n).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}))}),or=y("$ZodString",(e,t)=>{Q.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??mc(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),U=y("$ZodStringFormat",(e,t)=>{_t.init(e,t),or.init(e,t)}),zc=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=rc),U.init(e,t)}),Rc=y("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=fn(r))}else t.pattern??(t.pattern=fn());U.init(e,t)}),Oc=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sc),U.init(e,t)}),Cc=y("$ZodURL",(e,t)=>{U.init(e,t),e._zod.check=r=>{try{const s=r.value.trim();if(!t.normalize&&t.protocol?.source===pc.source&&!/^https?:\/\//i.test(s)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}const n=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Dc=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=gn()),U.init(e,t)}),Nc=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ec),U.init(e,t)}),qc=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Wi),U.init(e,t)}),$c=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ki),U.init(e,t)}),Mc=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qi),U.init(e,t)}),Fc=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yi),U.init(e,t)}),Gc=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xi),U.init(e,t)}),Uc=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=wn(t)),U.init(e,t)}),Lc=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=dc),U.init(e,t)}),Jc=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=vn(t)),U.init(e,t)}),Bc=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=tc),U.init(e,t)}),Zc=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ac),U.init(e,t),e._zod.bag.format="ipv4"}),Vc=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=oc),U.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Hc=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ic),U.init(e,t)}),Wc=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cc),U.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[n,o]=s;if(!o)throw new Error;const a=Number(o);if(`${a}`!==o)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function ir(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}c(ir,"Pt"),l(ir,"isValidBase64");const Kc=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=lc),U.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{ir(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function _n(e){if(!yn.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return ir(r)}c(_n,"Eo"),l(_n,"isValidBase64URL");const Qc=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=yn),U.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{_n(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Yc=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=uc),U.init(e,t)});function xn(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const n=JSON.parse(atob(s));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}c(xn,"Ro"),l(xn,"isValidJWT");const Xc=y("$ZodJWT",(e,t)=>{U.init(e,t),e._zod.check=r=>{xn(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Tn=y("$ZodNumber",(e,t)=>{Q.init(e,t),e._zod.pattern=e._zod.bag.pattern??fc,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const o=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...o?{received:o}:{}}),r}}),el=y("$ZodNumberFormat",(e,t)=>{vc.init(e,t),Tn.init(e,t)});function cr(e,t,r){e.issues.length&&t.issues.push(...ln(r,e.issues)),t.value[r]=e.value}c(cr,"zt"),l(cr,"handleArrayResult");const tl=y("$ZodArray",(e,t)=>{Q.init(e,t),e._zod.parse=(r,s)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);const o=[];for(let a=0;a<n.length;a++){const i=n[a],p=t.element._zod.run({value:i,issues:[]},s);p instanceof Promise?o.push(p.then(u=>cr(u,r,a))):cr(p,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function lr(e,t,r,s){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const n=e.filter(o=>!Ae(o));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(a=>je(a,s,we())))}),t)}c(lr,"It"),l(lr,"handleUnionResults");const rl=y("$ZodUnion",(e,t)=>{Q.init(e,t),G(e._zod,"optin",()=>t.options.some(s=>s._zod.optin==="optional")?"optional":void 0),G(e._zod,"optout",()=>t.options.some(s=>s._zod.optout==="optional")?"optional":void 0),G(e._zod,"values",()=>{if(t.options.every(s=>s._zod.values))return new Set(t.options.flatMap(s=>Array.from(s._zod.values)))}),G(e._zod,"pattern",()=>{if(t.options.every(s=>s._zod.pattern)){const s=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${s.map(n=>vt(n.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(s,n)=>{if(r)return r(s,n);let o=!1;const a=[];for(const i of t.options){const p=i._zod.run({value:s.value,issues:[]},n);if(p instanceof Promise)a.push(p),o=!0;else{if(p.issues.length===0)return p;a.push(p)}}return o?Promise.all(a).then(i=>lr(i,s,e,n)):lr(a,s,e,n)}}),sl=y("$ZodIntersection",(e,t)=>{Q.init(e,t),e._zod.parse=(r,s)=>{const n=r.value,o=t.left._zod.run({value:n,issues:[]},s),a=t.right._zod.run({value:n,issues:[]},s);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([i,p])=>pr(r,i,p)):pr(r,o,a)}});function xt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(wt(e)&&wt(t)){const r=Object.keys(t),s=Object.keys(e).filter(o=>r.indexOf(o)!==-1),n={...e,...t};for(const o of s){const a=xt(e[o],t[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};n[o]=a.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let s=0;s<e.length;s++){const n=e[s],o=t[s],a=xt(n,o);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}c(xt,"_e"),l(xt,"mergeValues");function pr(e,t,r){const s=new Map;let n;for(const i of t.issues)if(i.code==="unrecognized_keys"){n??(n=i);for(const p of i.keys)s.has(p)||s.set(p,{}),s.get(p).l=!0}else e.issues.push(i);for(const i of r.issues)if(i.code==="unrecognized_keys")for(const p of i.keys)s.has(p)||s.set(p,{}),s.get(p).r=!0;else e.issues.push(i);const o=[...s].filter(([,i])=>i.l&&i.r).map(([i])=>i);if(o.length&&n&&e.issues.push({...n,keys:o}),Ae(e))return e;const a=xt(t.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}c(pr,"Ot"),l(pr,"handleIntersectionResults");const nl=y("$ZodEnum",(e,t)=>{Q.init(e,t);const r=er(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(n=>qi.has(typeof n)).map(n=>typeof n=="string"?Ve(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const a=n.value;return s.has(a)||n.issues.push({code:"invalid_value",values:r,input:a,inst:e}),n}}),al=y("$ZodTransform",(e,t)=>{Q.init(e,t),e._zod.optin="optional",e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new en(e.constructor.name);const n=t.transform(r.value,r);if(s.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r.fallback=!0,r));if(n instanceof Promise)throw new Ne;return r.value=n,r.fallback=!0,r}});function ur(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}c(ur,"$t"),l(ur,"handleOptionalResult");const An=y("$ZodOptional",(e,t)=>{Q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),G(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${vt(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const n=r.value,o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(a=>ur(a,n)):ur(o,n)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),ol=y("$ZodExactOptional",(e,t)=>{An.init(e,t),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),il=y("$ZodNullable",(e,t)=>{Q.init(e,t),G(e._zod,"optin",()=>t.innerType._zod.optin),G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${vt(r.source)}|null)$`):void 0}),G(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,s)=>r.value===null?r:t.innerType._zod.run(r,s)}),cl=y("$ZodDefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);if(r.value===void 0)return r.value=t.defaultValue,r;const n=t.innerType._zod.run(r,s);return n instanceof Promise?n.then(o=>dr(o,t)):dr(n,t)}});function dr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}c(dr,"qt"),l(dr,"handleDefaultResult");const ll=y("$ZodPrefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>(s.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,s))}),pl=y("$ZodNonOptional",(e,t)=>{Q.init(e,t),G(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(s=>s!==void 0)):void 0}),e._zod.parse=(r,s)=>{const n=t.innerType._zod.run(r,s);return n instanceof Promise?n.then(o=>mr(o,e)):mr(n,e)}});function mr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}c(mr,"Dt"),l(mr,"handleNonOptionalResult");const ul=y("$ZodCatch",(e,t)=>{Q.init(e,t),e._zod.optin="optional",G(e._zod,"optout",()=>t.innerType._zod.optout),G(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const n=t.innerType._zod.run(r,s);return n instanceof Promise?n.then(o=>(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(a=>je(a,s,we()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=n.value,n.issues.length&&(r.value=t.catchValue({...r,error:{issues:n.issues.map(o=>je(o,s,we()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),dl=y("$ZodPipe",(e,t)=>{Q.init(e,t),G(e._zod,"values",()=>t.in._zod.values),G(e._zod,"optin",()=>t.in._zod.optin),G(e._zod,"optout",()=>t.out._zod.optout),G(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,s)=>{if(s.direction==="backward"){const o=t.out._zod.run(r,s);return o instanceof Promise?o.then(a=>We(a,t.in,s)):We(o,t.in,s)}const n=t.in._zod.run(r,s);return n instanceof Promise?n.then(o=>We(o,t.out,s)):We(n,t.out,s)}});function We(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}c(We,"se"),l(We,"handlePipeResult");const ml=y("$ZodReadonly",(e,t)=>{Q.init(e,t),G(e._zod,"propValues",()=>t.innerType._zod.propValues),G(e._zod,"values",()=>t.innerType._zod.values),G(e._zod,"optin",()=>t.innerType?._zod?.optin),G(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const n=t.innerType._zod.run(r,s);return n instanceof Promise?n.then(hr):hr(n)}});function hr(e){return e.value=Object.freeze(e.value),e}c(hr,"Nt"),l(hr,"handleReadonlyResult");const hl=y("$ZodCustom",(e,t)=>{oe.init(e,t),Q.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,n=t.fn(s);if(n instanceof Promise)return n.then(o=>fr(o,r,s,e));fr(n,r,s,e)}});function fr(e,t,r,s){if(!e){const n={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(n.params=s._zod.def.params),t.issues.push(qe(n))}}c(fr,"Mt"),l(fr,"handleRefineResult");var En;class fl{static{c(this,"Bo")}static{l(this,"$ZodRegistry")}constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const s=r[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const s={...this.get(r)??{}};delete s.id;const n={...s,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Pn(){return new fl}c(Pn,"Vo"),l(Pn,"registry"),(En=globalThis).__zod_globalRegistry??(En.__zod_globalRegistry=Pn());const Ke=globalThis.__zod_globalRegistry;function In(e,t){return new e({type:"string",...k(t)})}c(In,"Ko"),l(In,"_string");function zn(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...k(t)})}c(zn,"Wo"),l(zn,"_email");function gr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...k(t)})}c(gr,"Ft"),l(gr,"_guid");function Rn(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...k(t)})}c(Rn,"Ho"),l(Rn,"_uuid");function On(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...k(t)})}c(On,"Xo"),l(On,"_uuidv4");function Cn(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...k(t)})}c(Cn,"Yo"),l(Cn,"_uuidv6");function Dn(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...k(t)})}c(Dn,"Qo"),l(Dn,"_uuidv7");function Nn(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...k(t)})}c(Nn,"en"),l(Nn,"_url");function qn(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...k(t)})}c(qn,"tn"),l(qn,"_emoji");function $n(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...k(t)})}c($n,"rn"),l($n,"_nanoid");function Mn(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...k(t)})}c(Mn,"sn"),l(Mn,"_cuid");function Fn(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...k(t)})}c(Fn,"on"),l(Fn,"_cuid2");function Gn(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...k(t)})}c(Gn,"nn"),l(Gn,"_ulid");function Un(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...k(t)})}c(Un,"an"),l(Un,"_xid");function Ln(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...k(t)})}c(Ln,"cn"),l(Ln,"_ksuid");function Jn(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...k(t)})}c(Jn,"un"),l(Jn,"_ipv4");function Bn(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...k(t)})}c(Bn,"pn"),l(Bn,"_ipv6");function Zn(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...k(t)})}c(Zn,"ln"),l(Zn,"_cidrv4");function Vn(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...k(t)})}c(Vn,"dn"),l(Vn,"_cidrv6");function Hn(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...k(t)})}c(Hn,"mn"),l(Hn,"_base64");function Wn(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...k(t)})}c(Wn,"hn"),l(Wn,"_base64url");function Kn(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...k(t)})}c(Kn,"fn"),l(Kn,"_e164");function Qn(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...k(t)})}c(Qn,"gn"),l(Qn,"_jwt");function Yn(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...k(t)})}c(Yn,"bn"),l(Yn,"_isoDateTime");function Xn(e,t){return new e({type:"string",format:"date",check:"string_format",...k(t)})}c(Xn,"yn"),l(Xn,"_isoDate");function ea(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...k(t)})}c(ea,"vn"),l(ea,"_isoTime");function ta(e,t){return new e({type:"string",format:"duration",check:"string_format",...k(t)})}c(ta,"wn"),l(ta,"_isoDuration");function ra(e,t){return new e({type:"number",coerce:!0,checks:[],...k(t)})}c(ra,"jn"),l(ra,"_coercedNumber");function sa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...k(t)})}c(sa,"_n"),l(sa,"_int");function yr(e,t){return new Sn({check:"less_than",...k(t),value:e,inclusive:!1})}c(yr,"Lt"),l(yr,"_lt");function Tt(e,t){return new Sn({check:"less_than",...k(t),value:e,inclusive:!0})}c(Tt,"ke"),l(Tt,"_lte");function br(e,t){return new kn({check:"greater_than",...k(t),value:e,inclusive:!1})}c(br,"Gt"),l(br,"_gt");function At(e,t){return new kn({check:"greater_than",...k(t),value:e,inclusive:!0})}c(At,"Se"),l(At,"_gte");function vr(e,t){return new bc({check:"multiple_of",...k(t),value:e})}c(vr,"xt"),l(vr,"_multipleOf");function wr(e,t){return new wc({check:"max_length",...k(t),maximum:e})}c(wr,"Zt"),l(wr,"_maxLength");function Qe(e,t){return new jc({check:"min_length",...k(t),minimum:e})}c(Qe,"oe"),l(Qe,"_minLength");function jr(e,t){return new Sc({check:"length_equals",...k(t),length:e})}c(jr,"Jt"),l(jr,"_length");function na(e,t){return new kc({check:"string_format",format:"regex",...k(t),pattern:e})}c(na,"kn"),l(na,"_regex");function aa(e){return new _c({check:"string_format",format:"lowercase",...k(e)})}c(aa,"Sn"),l(aa,"_lowercase");function oa(e){return new xc({check:"string_format",format:"uppercase",...k(e)})}c(oa,"Tn"),l(oa,"_uppercase");function ia(e,t){return new Tc({check:"string_format",format:"includes",...k(t),includes:e})}c(ia,"En"),l(ia,"_includes");function ca(e,t){return new Ac({check:"string_format",format:"starts_with",...k(t),prefix:e})}c(ca,"An"),l(ca,"_startsWith");function la(e,t){return new Ec({check:"string_format",format:"ends_with",...k(t),suffix:e})}c(la,"Pn"),l(la,"_endsWith");function Ee(e){return new Pc({check:"overwrite",tx:e})}c(Ee,"L"),l(Ee,"_overwrite");function pa(e){return Ee(t=>t.normalize(e))}c(pa,"Rn"),l(pa,"_normalize");function ua(){return Ee(e=>e.trim())}c(ua,"zn"),l(ua,"_trim");function da(){return Ee(e=>e.toLowerCase())}c(da,"In"),l(da,"_toLowerCase");function ma(){return Ee(e=>e.toUpperCase())}c(ma,"On"),l(ma,"_toUpperCase");function ha(){return Ee(e=>nn(e))}c(ha,"$n"),l(ha,"_slugify");function fa(e,t,r){return new e({type:"array",element:t,...k(r)})}c(fa,"Cn"),l(fa,"_array");function ga(e,t,r){return new e({type:"custom",check:"custom",fn:t,...k(r)})}c(ga,"qn"),l(ga,"_refine");function ya(e,t){const r=ba(s=>(s.addIssue=n=>{if(typeof n=="string")s.issues.push(qe(n,s.value,r._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=s.value),o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),s.issues.push(qe(o))}},e(s.value,s)),t);return r}c(ya,"Dn"),l(ya,"_superRefine");function ba(e,t){const r=new oe({check:"custom",...k(t)});return r._zod.check=e,r}c(ba,"Nn"),l(ba,"_check");function Sr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ke,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}c(Sr,"Bt"),l(Sr,"initializeContext");function te(e,t,r={path:[],schemaPath:[]}){var s;const n=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);const i=e._zod.toJSONSchema?.();if(i)a.schema=i;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,u);else{const g=a.schema,b=t.processors[n.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);b(e,t,g,u)}const m=e._zod.parent;m&&(a.ref||(a.ref=m),te(m,t,u),t.seen.get(m).isParent=!0)}const p=t.metadataRegistry.get(e);return p&&Object.assign(a.schema,p),t.io==="input"&&re(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((s=a.schema).default??(s.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}c(te,"P"),l(te,"process$1");function kr(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const a of e.seen.entries()){const i=e.metadataRegistry.get(a[0])?.id;if(i){const p=s.get(i);if(p&&p!==a[0])throw new Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(i,a[0])}}const n=l(a=>{const i=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const m=e.external.registry.get(a[0])?.id,g=e.external.uri??(S=>S);if(m)return{ref:g(m)};const b=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=b,{defId:b,ref:`${g("__shared")}#/${i}/${b}`}}if(a[1]===r)return{ref:"#"};const p=`#/${i}/`,u=a[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:p+u}},"makeURI"),o=l(a=>{if(a[1].schema.$ref)return;const i=a[1],{ref:p,defId:u}=n(a);i.def={...i.schema},u&&(i.defId=u);const m=i.schema;for(const g in m)delete m[g];m.$ref=p},"extractToDef");if(e.cycles==="throw")for(const a of e.seen.entries()){const i=a[1];if(i.cycle)throw new Error(`Cycle detected: #/${i.cycle?.join("/")}/<root>
272
+
273
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const a of e.seen.entries()){const i=a[1];if(t===a[0]){o(a);continue}if(e.external){const p=e.external.registry.get(a[0])?.id;if(t!==a[0]&&p){o(a);continue}}if(e.metadataRegistry.get(a[0])?.id){o(a);continue}if(i.cycle){o(a);continue}if(i.count>1&&e.reused==="ref"){o(a);continue}}}c(kr,"Vt"),l(kr,"extractDefs");function _r(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=l(i=>{const p=e.seen.get(i);if(p.ref===null)return;const u=p.def??p.schema,m={...u},g=p.ref;if(p.ref=null,g){s(g);const S=e.seen.get(g),P=S.schema;if(P.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(P)):Object.assign(u,P),Object.assign(u,m),i._zod.parent===g)for(const T in u)T==="$ref"||T==="allOf"||T in m||delete u[T];if(P.$ref&&S.def)for(const T in u)T==="$ref"||T==="allOf"||T in S.def&&JSON.stringify(u[T])===JSON.stringify(S.def[T])&&delete u[T]}const b=i._zod.parent;if(b&&b!==g){s(b);const S=e.seen.get(b);if(S?.schema.$ref&&(u.$ref=S.schema.$ref,S.def))for(const P in u)P==="$ref"||P==="allOf"||P in S.def&&JSON.stringify(u[P])===JSON.stringify(S.def[P])&&delete u[P]}e.override({zodSchema:i,jsonSchema:u,path:p.path??[]})},"flattenRef");for(const i of[...e.seen.entries()].reverse())s(i[0]);const n={};if(e.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");n.$id=e.external.uri(i)}Object.assign(n,r.def??r.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&n.id===o&&delete n.id;const a=e.external?.defs??{};for(const i of e.seen.entries()){const p=i[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,a[p.defId]=p.def)}e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?n.$defs=a:n.definitions=a);try{const i=JSON.parse(JSON.stringify(n));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Et(t,"input",e.processors),output:Et(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}c(_r,"Kt"),l(_r,"finalize");function re(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return re(s.element,r);if(s.type==="set")return re(s.valueType,r);if(s.type==="lazy")return re(s.getter(),r);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return re(s.innerType,r);if(s.type==="intersection")return re(s.left,r)||re(s.right,r);if(s.type==="record"||s.type==="map")return re(s.keyType,r)||re(s.valueType,r);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:re(s.in,r)||re(s.out,r);if(s.type==="object"){for(const n in s.shape)if(re(s.shape[n],r))return!0;return!1}if(s.type==="union"){for(const n of s.options)if(re(n,r))return!0;return!1}if(s.type==="tuple"){for(const n of s.items)if(re(n,r))return!0;return!!(s.rest&&re(s.rest,r))}return!1}c(re,"R"),l(re,"isTransforming");const gl=l((e,t={})=>r=>{const s=Sr({...r,processors:t});return te(e,s),kr(s,e),_r(s,e)},"createToJSONSchemaMethod"),Et=l((e,t,r={})=>s=>{const{libraryOptions:n,target:o}=s??{},a=Sr({...n??{},target:o,io:t,processors:r});return te(e,a),kr(a,e),_r(a,e)},"createStandardJSONSchemaMethod"),yl={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bl=l((e,t,r,s)=>{const n=r;n.type="string";const{minimum:o,maximum:a,format:i,patterns:p,contentEncoding:u}=e._zod.bag;if(typeof o=="number"&&(n.minLength=o),typeof a=="number"&&(n.maxLength=a),i&&(n.format=yl[i]??i,n.format===""&&delete n.format,i==="time"&&delete n.format),u&&(n.contentEncoding=u),p&&p.size>0){const m=[...p];m.length===1?n.pattern=m[0].source:m.length>1&&(n.allOf=[...m.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},"stringProcessor"),vl=l((e,t,r,s)=>{const n=r,{minimum:o,maximum:a,format:i,multipleOf:p,exclusiveMaximum:u,exclusiveMinimum:m}=e._zod.bag;typeof i=="string"&&i.includes("int")?n.type="integer":n.type="number";const g=typeof m=="number"&&m>=(o??Number.NEGATIVE_INFINITY),b=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";g?S?(n.minimum=m,n.exclusiveMinimum=!0):n.exclusiveMinimum=m:typeof o=="number"&&(n.minimum=o),b?S?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof a=="number"&&(n.maximum=a),typeof p=="number"&&(n.multipleOf=p)},"numberProcessor"),wl=l((e,t,r,s)=>{const n=e._zod.def,o=er(n.entries);o.every(a=>typeof a=="number")&&(r.type="number"),o.every(a=>typeof a=="string")&&(r.type="string"),r.enum=o},"enumProcessor"),jl=l((e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},"customProcessor"),Sl=l((e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},"transformProcessor"),kl=l((e,t,r,s)=>{const n=r,o=e._zod.def,{minimum:a,maximum:i}=e._zod.bag;typeof a=="number"&&(n.minItems=a),typeof i=="number"&&(n.maxItems=i),n.type="array",n.items=te(o.element,t,{...s,path:[...s.path,"items"]})},"arrayProcessor"),_l=l((e,t,r,s)=>{const n=e._zod.def,o=n.inclusive===!1,a=n.options.map((i,p)=>te(i,t,{...s,path:[...s.path,o?"oneOf":"anyOf",p]}));o?r.oneOf=a:r.anyOf=a},"unionProcessor"),xl=l((e,t,r,s)=>{const n=e._zod.def,o=te(n.left,t,{...s,path:[...s.path,"allOf",0]}),a=te(n.right,t,{...s,path:[...s.path,"allOf",1]}),i=l(u=>"allOf"in u&&Object.keys(u).length===1,"isSimpleIntersection"),p=[...i(o)?o.allOf:[o],...i(a)?a.allOf:[a]];r.allOf=p},"intersectionProcessor"),Tl=l((e,t,r,s)=>{const n=e._zod.def,o=te(n.innerType,t,s),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=n.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},"nullableProcessor"),Al=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType},"nonoptionalProcessor"),El=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},"defaultProcessor"),Pl=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},"prefaultProcessor"),Il=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType;let a;try{a=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},"catchProcessor"),zl=l((e,t,r,s)=>{const n=e._zod.def,o=n.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?o?n.out:n.in:n.out;te(a,t,s);const i=t.seen.get(e);i.ref=a},"pipeProcessor"),Rl=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType,r.readOnly=!0},"readonlyProcessor"),va=l((e,t,r,s)=>{const n=e._zod.def;te(n.innerType,t,s);const o=t.seen.get(e);o.ref=n.innerType},"optionalProcessor"),Ol=y("ZodISODateTime",(e,t)=>{Uc.init(e,t),J.init(e,t)});function wa(e){return Yn(Ol,e)}c(wa,"ra"),l(wa,"datetime");const Cl=y("ZodISODate",(e,t)=>{Lc.init(e,t),J.init(e,t)});function ja(e){return Xn(Cl,e)}c(ja,"oa"),l(ja,"date");const Dl=y("ZodISOTime",(e,t)=>{Jc.init(e,t),J.init(e,t)});function Sa(e){return ea(Dl,e)}c(Sa,"aa"),l(Sa,"time");const Nl=y("ZodISODuration",(e,t)=>{Bc.init(e,t),J.init(e,t)});function ka(e){return ta(Nl,e)}c(ka,"ca"),l(ka,"duration");const ql=l((e,t)=>{un.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:l(r=>hn(e,r),"value")},flatten:{value:l(r=>mn(e,r),"value")},addIssue:{value:l(r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,yt,2)},"value")},addIssues:{value:l(r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,yt,2)},"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),pe=y("ZodError",ql,{Parent:Error}),$l=sr(pe),Ml=nr(pe),Fl=St(pe),Gl=kt(pe),Ul=Gi(pe),Ll=Ui(pe),Jl=Li(pe),Bl=Ji(pe),Zl=Bi(pe),Vl=Zi(pe),Hl=Vi(pe),Wl=Hi(pe),_a=new WeakMap;function Ye(e,t,r){const s=Object.getPrototypeOf(e);let n=_a.get(s);if(n||(n=new Set,_a.set(s,n)),!n.has(t)){n.add(t);for(const o in r){const a=r[o];Object.defineProperty(s,o,{configurable:!0,enumerable:!1,get(){const i=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:i}),i},set(i){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:i})}})}}}c(Ye,"ae"),l(Ye,"_installLazyMethods");const Y=y("ZodType",(e,t)=>(Q.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Et(e,"input"),output:Et(e,"output")}}),e.toJSONSchema=gl(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,s)=>$l(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Fl(e,r,s),e.parseAsync=async(r,s)=>Ml(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Gl(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Ul(e,r,s),e.decode=(r,s)=>Ll(e,r,s),e.encodeAsync=async(r,s)=>Jl(e,r,s),e.decodeAsync=async(r,s)=>Bl(e,r,s),e.safeEncode=(r,s)=>Zl(e,r,s),e.safeDecode=(r,s)=>Vl(e,r,s),e.safeEncodeAsync=async(r,s)=>Hl(e,r,s),e.safeDecodeAsync=async(r,s)=>Wl(e,r,s),Ye(e,"ZodType",{check(...r){const s=this.def;return this.clone(sn(s,{checks:[...s.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,s){return on(this,r,s)},brand(){return this},register(r,s){return r.add(this,s),this},refine(r,s){return this.check($a(r,s))},superRefine(r,s){return this.check(Ma(r,s))},overwrite(r){return this.check(Ee(r))},optional(){return Er(this)},exactOptional(){return Ra(this)},nullable(){return Pr(this)},nullish(){return Er(Pr(this))},nonoptional(r){return Da(this,r)},array(){return Ea(this)},or(r){return Pa([this,r])},and(r){return Ia(this,r)},transform(r){return Ir(this,za(r))},default(r){return Oa(this,r)},prefault(r){return Ca(this,r)},catch(r){return Na(this,r)},pipe(r){return Ir(this,r)},readonly(){return qa(this)},describe(r){const s=this.clone();return Ke.add(s,{description:r}),s},meta(...r){if(r.length===0)return Ke.get(this);const s=this.clone();return Ke.add(s,r[0]),s},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Ke.get(e)?.description},configurable:!0}),e)),xa=y("_ZodString",(e,t)=>{or.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(s,n,o)=>bl(e,s,n);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Ye(e,"_ZodString",{regex(...s){return this.check(na(...s))},includes(...s){return this.check(ia(...s))},startsWith(...s){return this.check(ca(...s))},endsWith(...s){return this.check(la(...s))},min(...s){return this.check(Qe(...s))},max(...s){return this.check(wr(...s))},length(...s){return this.check(jr(...s))},nonempty(...s){return this.check(Qe(1,...s))},lowercase(s){return this.check(aa(s))},uppercase(s){return this.check(oa(s))},trim(){return this.check(ua())},normalize(...s){return this.check(pa(...s))},toLowerCase(){return this.check(da())},toUpperCase(){return this.check(ma())},slugify(){return this.check(ha())}})}),Kl=y("ZodString",(e,t)=>{or.init(e,t),xa.init(e,t),e.email=r=>e.check(zn(Ql,r)),e.url=r=>e.check(Nn(Yl,r)),e.jwt=r=>e.check(Qn(mp,r)),e.emoji=r=>e.check(qn(Xl,r)),e.guid=r=>e.check(gr(Ta,r)),e.uuid=r=>e.check(Rn(It,r)),e.uuidv4=r=>e.check(On(It,r)),e.uuidv6=r=>e.check(Cn(It,r)),e.uuidv7=r=>e.check(Dn(It,r)),e.nanoid=r=>e.check($n(ep,r)),e.guid=r=>e.check(gr(Ta,r)),e.cuid=r=>e.check(Mn(tp,r)),e.cuid2=r=>e.check(Fn(rp,r)),e.ulid=r=>e.check(Gn(sp,r)),e.base64=r=>e.check(Hn(pp,r)),e.base64url=r=>e.check(Wn(up,r)),e.xid=r=>e.check(Un(np,r)),e.ksuid=r=>e.check(Ln(ap,r)),e.ipv4=r=>e.check(Jn(op,r)),e.ipv6=r=>e.check(Bn(ip,r)),e.cidrv4=r=>e.check(Zn(cp,r)),e.cidrv6=r=>e.check(Vn(lp,r)),e.e164=r=>e.check(Kn(dp,r)),e.datetime=r=>e.check(wa(r)),e.date=r=>e.check(ja(r)),e.time=r=>e.check(Sa(r)),e.duration=r=>e.check(ka(r))});function Pt(e){return In(Kl,e)}c(Pt,"Te"),l(Pt,"string");const J=y("ZodStringFormat",(e,t)=>{U.init(e,t),xa.init(e,t)}),Ql=y("ZodEmail",(e,t)=>{Oc.init(e,t),J.init(e,t)}),Ta=y("ZodGUID",(e,t)=>{zc.init(e,t),J.init(e,t)}),It=y("ZodUUID",(e,t)=>{Rc.init(e,t),J.init(e,t)}),Yl=y("ZodURL",(e,t)=>{Cc.init(e,t),J.init(e,t)}),Xl=y("ZodEmoji",(e,t)=>{Dc.init(e,t),J.init(e,t)}),ep=y("ZodNanoID",(e,t)=>{Nc.init(e,t),J.init(e,t)}),tp=y("ZodCUID",(e,t)=>{qc.init(e,t),J.init(e,t)}),rp=y("ZodCUID2",(e,t)=>{$c.init(e,t),J.init(e,t)}),sp=y("ZodULID",(e,t)=>{Mc.init(e,t),J.init(e,t)}),np=y("ZodXID",(e,t)=>{Fc.init(e,t),J.init(e,t)}),ap=y("ZodKSUID",(e,t)=>{Gc.init(e,t),J.init(e,t)}),op=y("ZodIPv4",(e,t)=>{Zc.init(e,t),J.init(e,t)}),ip=y("ZodIPv6",(e,t)=>{Vc.init(e,t),J.init(e,t)}),cp=y("ZodCIDRv4",(e,t)=>{Hc.init(e,t),J.init(e,t)}),lp=y("ZodCIDRv6",(e,t)=>{Wc.init(e,t),J.init(e,t)}),pp=y("ZodBase64",(e,t)=>{Kc.init(e,t),J.init(e,t)}),up=y("ZodBase64URL",(e,t)=>{Qc.init(e,t),J.init(e,t)}),dp=y("ZodE164",(e,t)=>{Yc.init(e,t),J.init(e,t)}),mp=y("ZodJWT",(e,t)=>{Xc.init(e,t),J.init(e,t)}),Aa=y("ZodNumber",(e,t)=>{Tn.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(s,n,o)=>vl(e,s,n),Ye(e,"ZodNumber",{gt(s,n){return this.check(br(s,n))},gte(s,n){return this.check(At(s,n))},min(s,n){return this.check(At(s,n))},lt(s,n){return this.check(yr(s,n))},lte(s,n){return this.check(Tt(s,n))},max(s,n){return this.check(Tt(s,n))},int(s){return this.check(xr(s))},safe(s){return this.check(xr(s))},positive(s){return this.check(br(0,s))},nonnegative(s){return this.check(At(0,s))},negative(s){return this.check(yr(0,s))},nonpositive(s){return this.check(Tt(0,s))},multipleOf(s,n){return this.check(vr(s,n))},step(s,n){return this.check(vr(s,n))},finite(){return this}});const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null}),hp=y("ZodNumberFormat",(e,t)=>{el.init(e,t),Aa.init(e,t)});function xr(e){return sa(hp,e)}c(xr,"er"),l(xr,"int");const fp=y("ZodArray",(e,t)=>{tl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>kl(e,r,s,n),e.element=t.element,Ye(e,"ZodArray",{min(r,s){return this.check(Qe(r,s))},nonempty(r){return this.check(Qe(1,r))},max(r,s){return this.check(wr(r,s))},length(r,s){return this.check(jr(r,s))},unwrap(){return this.element}})});function Ea(e,t){return fa(fp,e,t)}c(Ea,"Ga"),l(Ea,"array");const gp=y("ZodUnion",(e,t)=>{rl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>_l(e,r,s,n),e.options=t.options});function Pa(e,t){return new gp({type:"union",options:e,...k(t)})}c(Pa,"Za"),l(Pa,"union");const yp=y("ZodIntersection",(e,t)=>{sl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>xl(e,r,s,n)});function Ia(e,t){return new yp({type:"intersection",left:e,right:t})}c(Ia,"Ba"),l(Ia,"intersection");const Tr=y("ZodEnum",(e,t)=>{nl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(s,n,o)=>wl(e,s,n),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(s,n)=>{const o={};for(const a of s)if(r.has(a))o[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Tr({...t,checks:[],...k(n),entries:o})},e.exclude=(s,n)=>{const o={...t.entries};for(const a of s)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new Tr({...t,checks:[],...k(n),entries:o})}});function Ar(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Tr({type:"enum",entries:r,...k(t)})}c(Ar,"tr"),l(Ar,"_enum");const bp=y("ZodTransform",(e,t)=>{al.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Sl(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new en(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(qe(o,r.value,t));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(qe(a))}};const n=t.transform(r.value,r);return n instanceof Promise?n.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=n,r.fallback=!0,r)}});function za(e){return new bp({type:"transform",transform:e})}c(za,"Ka"),l(za,"transform");const vp=y("ZodOptional",(e,t)=>{An.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>va(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function Er(e){return new vp({type:"optional",innerType:e})}c(Er,"rr"),l(Er,"optional");const wp=y("ZodExactOptional",(e,t)=>{ol.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>va(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function Ra(e){return new wp({type:"optional",innerType:e})}c(Ra,"Xa"),l(Ra,"exactOptional");const jp=y("ZodNullable",(e,t)=>{il.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Tl(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function Pr(e){return new jp({type:"nullable",innerType:e})}c(Pr,"sr"),l(Pr,"nullable");const Sp=y("ZodDefault",(e,t)=>{cl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>El(e,r,s,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Oa(e,t){return new Sp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():rr(t)}})}c(Oa,"ei"),l(Oa,"_default");const kp=y("ZodPrefault",(e,t)=>{ll.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Pl(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function Ca(e,t){return new kp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():rr(t)}})}c(Ca,"ri"),l(Ca,"prefault");const _p=y("ZodNonOptional",(e,t)=>{pl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Al(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function Da(e,t){return new _p({type:"nonoptional",innerType:e,...k(t)})}c(Da,"oi"),l(Da,"nonoptional");const xp=y("ZodCatch",(e,t)=>{ul.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Il(e,r,s,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Na(e,t){return new xp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}c(Na,"ai"),l(Na,"_catch");const Tp=y("ZodPipe",(e,t)=>{dl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>zl(e,r,s,n),e.in=t.in,e.out=t.out});function Ir(e,t){return new Tp({type:"pipe",in:e,out:t})}c(Ir,"or"),l(Ir,"pipe");const Ap=y("ZodReadonly",(e,t)=>{ml.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>Rl(e,r,s,n),e.unwrap=()=>e._zod.def.innerType});function qa(e){return new Ap({type:"readonly",innerType:e})}c(qa,"ui"),l(qa,"readonly");const Ep=y("ZodCustom",(e,t)=>{hl.init(e,t),Y.init(e,t),e._zod.processJSONSchema=(r,s,n)=>jl(e,r)});function $a(e,t={}){return ga(Ep,e,t)}c($a,"li"),l($a,"refine");function Ma(e,t){return ya(e,t)}c(Ma,"di"),l(Ma,"superRefine");function Fa(e){return ra(Aa,e)}c(Fa,"mi"),l(Fa,"number");const Pp=Ys({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:Pt().pipe(Fa()).default(95),NEST_ARCH_BETA_MODE:Ar(["true","false"]).default("false").transform(e=>e==="true"),NEST_ARCH_SCHEMA_URL:Pt().default("./schema.json"),NEST_ARCH_VERSION:Pt().default("0.0.1"),NODE_ENV:Ar(["development","production","test"]).default("development")}});function Ga(e){const t=[`pnpm create nest-arch@latest ${e.projectName}`,`--package-manager ${e.packageManager}`,`--http-provider ${e.httpProvider}`,`--project-type ${e.projectType}`,`--architecture ${e.architecture}`,`--database ${e.database.length>0?e.database.join(" "):"none"}`,`--orm ${e.orm.length>0?e.orm.join(" "):"none"}`,`--api ${e.api.length>0?e.api.join(" "):"none"}`,`--auth ${e.auth}`,`--extras ${e.extras.length>0?e.extras.join(" "):"none"}`,`--microservices ${e.microservices.length>0?e.microservices.join(" "):"none"}`,`--addons ${e.addons.length>0?e.addons.join(" "):"none"}`,`--formatter ${e.formatter}`,`--install-dependencies ${e.installDependencies?"yes":"no"}`,e.initGit?"--git":"--no-git"];return e.addons.includes("ultracite")&&(e.ultraciteEditors.length>0&&t.push(`--ultracite-editors ${e.ultraciteEditors.join(" ")}`),e.ultraciteAgents.length>0&&t.push(`--ultracite-agents ${e.ultraciteAgents.join(" ")}`),e.ultraciteHooks.length>0&&t.push(`--ultracite-hooks ${e.ultraciteHooks.join(" ")}`),t.push(`--ultracite-install-skill ${e.ultraciteInstallSkill}`)),t.join(" ")}c(Ga,"fi"),l(Ga,"buildReproducibleCommand");function Ua(e){return{$schema:Pp.NEST_ARCH_SCHEMA_URL,addons:e.addons,api:e.api,architecture:e.architecture,auth:e.auth,createdAt:new Date().toISOString(),database:e.database,description:e.description,extras:e.extras,formatter:e.formatter,httpProvider:e.httpProvider,initGit:e.initGit,installDependencies:e.installDependencies,microservices:e.microservices,orm:e.orm,packageManager:e.packageManager,projectName:e.projectName,projectType:e.projectType,reproducibleCommand:Ga(e),ultraciteAgents:e.ultraciteAgents,ultraciteEditors:e.ultraciteEditors,ultraciteHooks:e.ultraciteHooks,ultraciteInstallSkill:e.ultraciteInstallSkill,version:"0.3.0"}}c(Ua,"gi"),l(Ua,"buildMetadata");function La(e){return`${["// nest-arch","//","// Project scaffolding tool for NestJS applications","//","// This file records the options used to generate this project.","// It can be used to reproduce the exact same project setup.","// This file is safe to delete.",""].join(`
274
+ `)+JSON.stringify(e,null,2)}
275
+ `}c(La,"bi"),l(La,"serializeMetadata");function Ja(){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)}
276
+ `}c(Ja,"yi"),l(Ja,"buildSchemaContent");async function Ba(e,t,r,s,n){try{const o=Ua(t),a=La(o),i=await e.writeFile({content:a,filePath:"nest-arch.jsonc",isBinary:!1},r);i.written&&s.push(i.filePath);const p=Ja(),u=await e.writeFile({content:p,filePath:"schema.json",isBinary:!1},r);u.written&&s.push(u.filePath)}catch(o){const a=o instanceof Error?o.message:String(o);n.push(`Failed to generate nest-arch.jsonc/schema.json: ${a}`)}}c(Ba,"vi"),l(Ba,"generateMetadata");function zr(){return Be}c(zr,"nr"),l(zr,"loadReference");function f(e){const t=zr(),r=t.dependencies[e]??t.devDependencies[e];if(!r)throw new Error(`Dependency "${e}" not found in reference package.json`);return r}c(f,"d"),l(f,"getDependencyVersion");function Rr(){return{...zr().catalog}}c(Rr,"ar"),l(Rr,"getCatalogDependencies");const Ip=[{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"}],zp={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},Rp={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},Op={dest:"bunfig.toml",src:"base/bunfig.toml.hbs"},Cp=[{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"},{dest:"test/bootstrap.e2e-spec.ts",src:"base/test/bootstrap.e2e-spec.ts.hbs"}],Dp=[{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"}],Np=[{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"}],qp=[{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"}],$p=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],Mp=[{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"}],Fp=[{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"}],Gp=[{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"}],Za={"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:"proto/app.proto",src:"single-project/architecture/nest-microservice/proto/app.proto.hbs"},{dest:"test/microservice.e2e-spec.ts",src:"single-project/architecture/nest-microservice/test/microservice.e2e-spec.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"}]},Va=[{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"}],Up="package.json",Lp=[{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"}],Jp=[{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"}],Bp=[{dest:"test/app.e2e-spec.ts",src:"base/test/app.e2e-spec.ts.hbs"},{dest:"test/bootstrap.e2e-spec.ts",src:"base/test/bootstrap.e2e-spec.ts.hbs"},{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"}],Zp=[{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"}],Vp=[{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"}],Hp=[{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"}],Wp=[{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"}],Kp=[{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"}],Qp={"addons/husky":$p,"extras/database":Fp,"extras/docker":Mp,"extras/swagger":[],"feature/graphql":Bp,"feature/graphql/todo-example":Zp,"feature/rest":Cp,"feature/rest/todo-example":Dp,"feature/trpc":qp,"monorepo/apps/api-gateway":Lp,"monorepo/feature/graphql":Hp,"monorepo/feature/graphql/todo-example":Wp,"monorepo/feature/rest":Jp,"monorepo/feature/rest/todo-example":Np,"monorepo/feature/trpc":Vp,"monorepo/packages":Kp,"monorepo/packages/db":Gp,"monorepo/root":Va};function Or(e,t,r){e.auth==="passport"?(t["@nestjs/jwt"]=f("@nestjs/jwt"),t["@nestjs/passport"]=f("@nestjs/passport"),t.passport=f("passport"),t["passport-jwt"]=f("passport-jwt"),r["@types/passport-jwt"]=f("@types/passport-jwt"),e.database.length>0&&(t.bcrypt=f("bcrypt"),r["@types/bcrypt"]=f("@types/bcrypt"),e.orm.includes("typeorm")&&(t["@nestjs/typeorm"]=f("@nestjs/typeorm"),t.typeorm=f("typeorm")))):(e.auth==="better-auth"||e.auth==="better-auth:stateless")&&(t["better-auth"]=f("better-auth"),t["@thallesp/nestjs-better-auth"]=f("@thallesp/nestjs-better-auth"),e.orm.includes("drizzle")&&(t["@better-auth/drizzle-adapter"]=f("@better-auth/drizzle-adapter")));for(const s of e.api)s==="graphql"?(t["@nestjs/graphql"]=f("@nestjs/graphql"),t["@nestjs/apollo"]=f("@nestjs/apollo"),t.graphql=f("graphql"),t["@apollo/server"]=f("@apollo/server"),e.httpProvider==="fastify"?t["@as-integrations/fastify"]=f("@as-integrations/fastify"):t["@as-integrations/express5"]=f("@as-integrations/express5"),e.auth==="passport"&&(t["graphql-scalars"]=f("graphql-scalars")),e.orm.includes("typeorm")&&(t["typeorm-relations-graphql"]=f("typeorm-relations-graphql")),e.orm.includes("drizzle")&&(t["drizzle-graphql"]=f("drizzle-graphql"))):s==="trpc"&&(t["@trpc/server"]=f("@trpc/server"),t["@trpc/client"]=f("@trpc/client"),t["@trpc/openapi"]=f("@trpc/openapi"),t["nestjs-trpc"]=f("nestjs-trpc"));e.extras.includes("swagger")&&(t["@nestjs/swagger"]=f("@nestjs/swagger"),e.addons.includes("scalar-ui")&&(t["@scalar/nestjs-api-reference"]=f("@scalar/nestjs-api-reference"))),e.extras.includes("health-check")&&(t["@nestjs/terminus"]=f("@nestjs/terminus")),e.extras.includes("rate-limiting")&&(t["@nestjs/throttler"]=f("@nestjs/throttler")),e.microservices.length>0&&(t["@nestjs/microservices"]=f("@nestjs/microservices"));for(const s of e.microservices)s==="redis"?t.ioredis=f("ioredis"):s==="mqtt"?t.mqtt=f("mqtt"):s==="nats"?(t.nats=f("nats"),t["@nats-io/transport-node"]=f("@nats-io/transport-node")):s==="rabbitmq"?(t.amqplib=f("amqplib"),t["amqp-connection-manager"]=f("amqp-connection-manager"),r["@types/amqplib"]=f("@types/amqplib")):s==="kafka"?t.kafkajs=f("kafkajs"):s==="grpc"&&(t["@grpc/grpc-js"]=f("@grpc/grpc-js"),t["@grpc/proto-loader"]=f("@grpc/proto-loader"));if(e.addons.includes("nestjs-zod")){t["nestjs-zod"]=f("nestjs-zod");for(const s of["@nestjs/common","@nestjs/core","@nestjs/platform-express","@nestjs/platform-fastify","@nestjs/swagger"])t[s]&&(t[s]="^11.0.0");r["@nestjs/testing"]="^11.0.0"}}c(Or,"ur"),l(Or,"addConditionalDependencies");function Cr(e,t,r){const s=e.orm.includes("prisma"),n=e.orm.includes("drizzle"),o=e.orm.includes("typeorm"),a=e.database.length>0&&!s&&!n&&!o;for(const i of e.orm)if(i==="prisma"){const p=e.prismaVersion==="8"||e.database.includes("mongodb")&&e.prismaVersion!=="7"||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite");r.prisma=f("prisma"),p?(r.prisma="^8.0.0-rc.15",e.database.includes("mongodb")&&(t["@prisma/orm-mongo"]=f("@prisma/orm-mongo"),t.mongodb=f("mongodb")),e.database.includes("postgresql")&&(t["@prisma/orm-postgres"]=f("@prisma/orm-postgres"),t["temporal-polyfill"]=f("temporal-polyfill"))):(t["@prisma/client"]=f("@prisma/client"),e.database.includes("postgresql")&&(t["@prisma/adapter-pg"]=f("@prisma/adapter-pg")),e.database.includes("mysql")&&(t["@prisma/adapter-mariadb"]=f("@prisma/adapter-mariadb")),e.database.includes("sqlite")&&(t["@prisma/adapter-better-sqlite3"]=f("@prisma/adapter-better-sqlite3")))}else i==="typeorm"?(t.typeorm=f("typeorm"),t["@nestjs/typeorm"]=f("@nestjs/typeorm"),e.database.includes("postgresql")&&(t.pg=f("pg"),r["@types/pg"]=f("@types/pg"))):i==="drizzle"&&(t["drizzle-orm"]=f("drizzle-orm"),r["drizzle-kit"]=f("drizzle-kit"));e.database.includes("postgresql")&&(n||a)&&(t.pg=f("pg"),r["@types/pg"]=f("@types/pg")),e.database.includes("mysql")&&(n||a||o)&&(t.mysql2=f("mysql2")),e.database.includes("sqlite")&&(n||a||o)&&(t["better-sqlite3"]=f("better-sqlite3"),r["@types/better-sqlite3"]=f("@types/better-sqlite3")),e.database.includes("mongodb")&&a&&(t.mongodb=f("mongodb"))}c(Cr,"pr"),l(Cr,"addDatabaseDependencies");async function Ha(e,t,r,s,n,o){try{const a=e.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":f("@nestjs/common"),"@nestjs/core":f("@nestjs/core"),[a]:f(a),"@t3-oss/env-core":f("@t3-oss/env-core"),dotenv:f("dotenv"),"reflect-metadata":f("reflect-metadata"),rxjs:f("rxjs"),zod:f("zod")},p=e.extras.includes("typescript-7")?f("typescript-7"):f("typescript"),u={"@nestjs/cli":f("@nestjs/cli"),"@nestjs/mau":f("@nestjs/mau"),"@nestjs/schematics":f("@nestjs/schematics"),"@nestjs/testing":f("@nestjs/testing"),"@types/node":f("@types/node"),"@types/supertest":f("@types/supertest"),"@vitest/coverage-v8":f("@vitest/coverage-v8"),"source-map-support":f("source-map-support"),supertest:f("supertest"),typescript:p,vitest:f("vitest")};e.httpProvider==="express"&&(u["@types/express"]=f("@types/express"));const m={build:"nest build",deploy:"nest deploy",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"};if(Or(e,i,u),Cr(e,i,u),e.auth==="better-auth"&&e.orm.length===0&&(u.auth=f("better-auth"),m["auth:generate"]="auth generate --config src/auth/auth.ts --output auth-schema.sql --yes",m["auth:migrate"]="auth migrate --config src/auth/auth.ts --yes"),e.auth==="better-auth"&&e.orm.length>0){u.auth=f("better-auth");const P=e.orm.includes("prisma")?"auth-schema.prisma":"src/database/orm/drizzle/auth-schema.ts";m["auth:generate"]=`auth generate --config src/auth/auth.cli.ts --output ${P} --yes`,e.orm.includes("prisma")&&(m["auth:generate"]+=" && node scripts/install-auth-schema.mjs")}e.addons.includes("ultracite")&&(u.ultracite=f("ultracite"),m.check="ultracite check",m.fix="ultracite fix"),e.addons.includes("husky")&&(u.husky=f("husky"),m.prepare="husky"),e.orm.includes("prisma")&&(e.prismaVersion==="8"||e.database.includes("mongodb")&&e.prismaVersion!=="7"||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite")?(m["contract:emit"]="prisma contract emit",m["db:init"]="prisma db init",m["db:update"]="prisma db update",m["db:verify"]="prisma db verify",m.migrate="prisma db migrate",m["migration:plan"]="prisma migration plan --name initial",m["migration:show"]="prisma migration show",m["migration:status"]="prisma migration status",m["skills:sync"]="prisma skills sync || exit 0",m.postinstall="prisma skills sync || exit 0"):(m["prisma:generate"]="prisma generate",m["prisma:format"]="prisma format",m["prisma:push"]="prisma db push",m["prisma:studio"]="prisma studio",m["prisma:migrate"]="prisma migrate dev",m["prisma:migrate:deploy"]="prisma migrate deploy",m.postinstall="prisma generate")),e.orm.includes("drizzle")&&(m["db:generate"]=e.formatter==="oxlint-oxfmt"?"drizzle-kit generate && oxfmt --write .":"drizzle-kit generate",m["db:migrate"]="drizzle-kit migrate",m["db:studio"]="drizzle-kit studio",m["db:push"]="drizzle-kit push"),e.api.includes("trpc")&&(m["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o src/libs/trpc/@generated",m["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o src/libs/trpc/@generated"),e.orm.includes("typeorm")&&(m["typeorm:run"]="typeorm migration:run -d dist/database/orm/typeorm/data-source.js",m["typeorm:revert"]="typeorm migration:revert -d dist/database/orm/typeorm/data-source.js",m["typeorm:generate"]="typeorm migration:generate -d dist/database/orm/typeorm/data-source.js --outputJs --esm",m["typeorm:create"]="typeorm migration:create");const g={name:t.projectName,version:"0.0.1",description:t.description,author:"",license:"UNLICENSED",private:!0,type:"module",...e.packageManager==="yarn"?{packageManager:"yarn@4.6.0"}:{},scripts:m,dependencies:i,devDependencies:u},b=JSON.stringify(g,null,2),S=await r.writeFile({content:b,filePath:"package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});S.written&&n.push(S.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate package.json: ${i}`),console.error("Failed to generate package.json:",a)}}c(Ha,"Gi"),l(Ha,"generateSingleProjectPackageJson");async function Wa(e,t,r,s,n,o){try{const a={build:"turbo build",test:"turbo run test","test:e2e":"turbo run test:e2e","check-types":"turbo check-types",dev:"turbo dev"},i={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},p=e.extras.includes("typescript-7"),u=p?f("typescript-7"):"catalog:",m={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:f("turbo"),typescript:u};e.addons.includes("ultracite")&&(a.check="ultracite check"),e.addons.includes("husky")&&(m.husky=f("husky"),a.prepare="husky");const g={bun:"bun@1.3.14",npm:void 0,pnpm:"pnpm@11.6.0",yarn:"yarn@4.6.0"}[e.packageManager],b=p?{...Rr(),typescript:f("typescript-7")}:Rr(),S={name:t.projectName,version:"0.0.1",description:t.description,author:"",license:"UNLICENSED",private:!0,workspaces:["apps/*","packages/*"],type:"module",...g?{packageManager:g}:{},...e.packageManager==="bun"?{catalog:b}:{},scripts:a,dependencies:i,devDependencies:m},P=JSON.stringify(S,null,2),T=await r.writeFile({content:P,filePath:Up,isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});T.written&&n.push(T.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo root package.json: ${i}`),console.error("Failed to generate monorepo root package.json:",a)}}c(Wa,"xi"),l(Wa,"generateMonorepoRootPackageJson");async function Ka(e,t,r,s,n,o){try{const a=e.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":f("@nestjs/common"),"@nestjs/core":f("@nestjs/core"),[a]:f(a),"@repo/env":"workspace:*","reflect-metadata":f("reflect-metadata"),rxjs:f("rxjs"),zod:"catalog:"};e.database.length>0&&(i["@repo/db"]="workspace:*");const p=e.extras.includes("typescript-7")?f("typescript-7"):"catalog:",u={"@nestjs/cli":f("@nestjs/cli"),"@nestjs/mau":f("@nestjs/mau"),"@nestjs/schematics":f("@nestjs/schematics"),"@nestjs/testing":f("@nestjs/testing"),"@repo/config":"workspace:*","@types/node":"catalog:","@types/supertest":f("@types/supertest"),"@vitest/coverage-v8":f("@vitest/coverage-v8"),"source-map-support":f("source-map-support"),supertest:f("supertest"),typescript:p,vitest:f("vitest")};e.httpProvider==="express"&&(u["@types/express"]=f("@types/express"));const m={build:"nest build",deploy:"nest deploy",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"};Or(e,i,u),e.addons.includes("ultracite")&&(u.ultracite=f("ultracite"),m.check="ultracite check",m.fix="ultracite fix"),e.addons.includes("husky")&&(u.husky=f("husky"),m.prepare="husky"),e.api.includes("trpc")&&(m["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated",m["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated");const g={name:t.projectName,version:"0.0.1",description:t.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:m,dependencies:i,devDependencies:u},b=JSON.stringify(g,null,2),S=await r.writeFile({content:b,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});S.written&&n.push(S.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo app package.json: ${i}`),console.error("Failed to generate monorepo app package.json:",a)}}c(Ka,"Zi"),l(Ka,"generateMonorepoAppPackageJson");async function Qa(e,t,r,s,n,o){try{const a={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:","@repo/env":"workspace:*"},i={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:e.extras.includes("typescript-7")?f("typescript-7"):"catalog:"};Cr(e,a,i);const p={};e.orm.includes("prisma")&&(e.prismaVersion==="8"||e.database.includes("mongodb")&&e.prismaVersion!=="7"||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite")?(p["contract:emit"]="prisma contract emit",p["db:init"]="prisma db init",p["db:update"]="prisma db update",p["db:verify"]="prisma db verify",p.migrate="prisma db migrate",p["migration:plan"]="prisma migration plan",p["migration:show"]="prisma migration show",p["migration:status"]="prisma migration status",p["skills:sync"]="prisma skills sync || exit 0",p.postinstall="prisma skills sync || exit 0"):(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")),e.orm.includes("drizzle")&&(p["db:generate"]=e.formatter==="oxlint-oxfmt"?"drizzle-kit generate && oxfmt --write .":"drizzle-kit generate",p["db:migrate"]="drizzle-kit migrate",p["db:studio"]="drizzle-kit studio",p["db:push"]="drizzle-kit push"),e.orm.includes("typeorm")&&(p["typeorm:run"]="typeorm-ts esm migration:run -d src/database/orm/typeorm/data-source.ts",p["typeorm:revert"]="typeorm-ts esm migration:revert -d src/database/orm/typeorm/data-source.ts",p["typeorm:generate"]="typeorm-ts esm migration:generate -d src/database/orm/typeorm/data-source.ts",p["typeorm:create"]="typeorm migration:create");const u={name:"@repo/db",version:"0.0.1",private:!0,type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},...Object.keys(p).length>0?{scripts:p}:{},dependencies:a,devDependencies:i},m=JSON.stringify(u,null,2),g=await r.writeFile({content:m,filePath:"packages/db/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});g.written&&n.push(g.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo db package.json: ${i}`),console.error("Failed to generate monorepo db package.json:",a)}}c(Qa,"Ji"),l(Qa,"generateMonorepoDbPackageJson");async function Ya(e,t,r,s,n){const o=t.database.includes("mongodb"),a=t.extras.includes("todo-example"),i=["// use prisma-next",""];t.auth==="passport"&&t.database.length>0&&i.push("enum Role {"," ADMIN"," USER","}",""),o?(t.auth==="passport"&&t.database.length>0&&i.push("model User {",' id ObjectId @id @map("_id")'," email String @unique"," username String?"," name String?"," password String"," firstname String?"," lastname String?"," role Role @default(USER)",...a?[" todos Todo[]"]:[],' @@map("users")',"}",""),a&&t.database.length>0&&i.push("model Todo {",' id ObjectId @id @map("_id")'," title String"," description String?"," completed Boolean @default(false)",...t.auth!=="none"?[" author User? @relation(fields: [authorId], references: [id])"," authorId ObjectId?"]:[],' @@map("todos")',"}","")):(t.auth==="passport"&&t.database.length>0&&i.push("model User {"," id Int @id @default(autoincrement())"," email String @unique"," username String?"," name String?"," password String"," firstname String?"," lastname String?"," role Role @default(USER)",...a?[" todos Todo[]"]:[]," createdAt TimestamptzString @default(now())"," updatedAt temporal.updatedAtString()",' @@map("users")',"}",""),a&&t.database.length>0&&i.push("model Todo {"," id Int @id @default(autoincrement())"," title String"," description String?"," completed Boolean @default(false)",...t.auth!=="none"?[" author User? @relation(fields: [authorId], references: [id])"," authorId Int?"]:[]," createdAt TimestamptzString @default(now())"," updatedAt temporal.updatedAtString()",' @@map("todos")',"}",""));const p=i.join(`
277
+ `),u=t.projectType==="monorepo"?"packages/db/src/prisma/contract.prisma":"src/prisma/contract.prisma";try{const b=await e.writeFile({content:p,filePath:u,isBinary:!1},r);b.written&&s.push(b.filePath)}catch(b){const S=b instanceof Error?b.message:String(b);n.push(`Failed to generate ${u}: ${S}`)}const m=o?['import mongo from "@prisma/orm-mongo/runtime";',t.projectType==="monorepo"?'import { env } from "@repo/env/api-gateway";':'import { env } from "../config/env.js";',"",'import type { Contract } from "./contract.d.ts";','import contractJson from "./contract.json" with { type: "json" };',"","const databaseUrl = env.MONGODB_URL;","","export const db = databaseUrl"," ? mongo<Contract>({ contractJson, url: databaseUrl })"," : mongo<Contract>({ contractJson });","","let connection: Promise<void> | undefined;","","export function connectDatabase(): Promise<void> {"," connection ??= db.connect().then(() => undefined).catch((error: unknown) => {"," connection = undefined;"," throw error;"," });"," return connection;","}",""].join(`
278
+ `):['import postgres from "@prisma/orm-postgres/runtime";',t.projectType==="monorepo"?'import { env } from "@repo/env/api-gateway";':'import { env } from "../config/env.js";','import "temporal-polyfill/global";',"",'import type { Contract } from "./contract.d.ts";','import contractJson from "./contract.json" with { type: "json" };',"","const databaseUrl = env.POSTGRES_URL;","","export const db = databaseUrl"," ? postgres<Contract>({ contractJson, url: databaseUrl })"," : postgres<Contract>({ contractJson });","","let connection: Promise<void> | undefined;","","export function connectDatabase(): Promise<void> {"," connection ??= db.connect().then(() => undefined).catch((error: unknown) => {"," connection = undefined;"," throw error;"," });"," return connection;","}",""].join(`
279
+ `),g=t.projectType==="monorepo"?"packages/db/src/prisma/db.ts":"src/prisma/db.ts";try{const b=await e.writeFile({content:m,filePath:g,isBinary:!1},r);b.written&&s.push(b.filePath)}catch(b){const S=b instanceof Error?b.message:String(b);n.push(`Failed to generate ${g}: ${S}`)}}c(Ya,"Bi"),l(Ya,"generatePrisma8Contract");async function Xa(e,t,r,s,n){let o="postgresql";t.database.includes("mysql")?o="mysql":t.database.includes("sqlite")?o="sqlite":t.database.includes("mongodb")&&(o="mongodb");const a=o==="mongodb",i=["generator client {",' provider = "prisma-client"',' output = "./generated"',"}","","datasource db {",` provider = "${o}"`,"}",""],p=t.extras.includes("todo-example");t.auth==="passport"&&t.database.length>0&&i.push("enum Role {"," ADMIN"," USER","}","","model User {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," email String @unique"," password String"," refreshTokens RefreshToken[]"," firstname String?"," lastname String?"," role Role @default(USER)",...p?[" todos Todo[]",""]:[""],' @@map("user")',"}",""),t.auth==="passport"&&i.push(`model RefreshToken {
280
+ id String @id @default(cuid())
281
+ userId String
282
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
283
+ familyId String
284
+ tokenHash String @unique
285
+ expiresAt DateTime
286
+ consumedAt DateTime?
287
+ revokedAt DateTime?
288
+ @@index([familyId])
289
+ }`),p&&t.database.length>0&&(t.auth==="none"?i.push("model Todo {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)","",' @@map("todo")',"}",""):i.push("model Todo {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)",` authorId ${a?"String? @db.ObjectId":"String?"}`," author User? @relation(fields: [authorId], references: [id])","",' @@map("todo")',"}",""));const u=i.join(`
290
+ `),m=t.projectType==="monorepo"?"packages/db/src/database/orm/prisma/schema.prisma":"src/database/orm/prisma/schema.prisma";try{const g=await e.writeFile({content:u,filePath:m,isBinary:!1},r);g.written&&s.push(g.filePath)}catch(g){const b=g instanceof Error?g.message:String(g);n.push(`Failed to generate ${m}: ${b}`)}}c(Xa,"Vi"),l(Xa,"generatePrisma7Schema");async function eo(e,t,r,s,n){await(t.prismaVersion==="8"||t.database.includes("mongodb")&&t.prismaVersion!=="7"||!t.prismaVersion&&!t.database.includes("mysql")&&!t.database.includes("sqlite")?Ya(e,t,r,s,n):Xa(e,t,r,s,n))}c(eo,"Ki"),l(eo,"generatePrismaSchema");function Dr(e,t){const r=!!t.usePrisma,s=!!t.useTypeorm,n=!!t.useDrizzle,o=!!t.useRawSql,a=!!t.hasPostgres,i=!!t.hasMysql,p=!!t.hasSqlite,u=!!t.hasMongodb,m=!!t.isPrisma8;return e.filter(g=>{const{dest:b}=g;return b.includes("prisma-sql.adapter")?r&&!m&&(a||i||p):b.includes("prisma-mongo.adapter")?r&&u:b.includes("typeorm-sql.adapter")?s&&(a||i||p):b.includes("orm/typeorm/data-source")||b.includes("entities/")?s:b.includes("drizzle-sql.adapter")?n:b.includes("raw-sql.adapter")?o&&(a||i||p):b.includes("raw-mongo.adapter")?o&&u:b.includes("orm/drizzle/schema")?n:!0})}c(Dr,"lr"),l(Dr,"filterDatabaseTemplates");function Nr(e,t){const r=!!t.hasTrpcAndAuth;return e.filter(s=>s.dest.includes("libs/trpc/protected.ts")||s.dest.includes("libs/trpc/inner.context.ts")||s.dest.includes("libs/middlewares/auth.trpc.middleware.ts")?r:!0)}c(Nr,"dr"),l(Nr,"filterTrpcTemplates");function qr(e,t){const r=!!t.useTypeorm,s=!!t.usePrisma,n=!!t.useDrizzle;return e.filter(o=>{const{dest:a}=o;return a.includes("orm/typeorm")?r:a.includes("orm/prisma")?s:a.includes("orm/drizzle")?n:!0})}c(qr,"mr"),l(qr,"filterGraphqlTemplates");function $r(e,t){const r=!!t.hasTrpc,s=!!t.hasRest;return e.filter(n=>n.dest.includes("todo.router.ts")?r:n.dest.includes("todo.controller.ts")?s:!0)}c($r,"hr"),l($r,"filterTodoTemplates");function to(e){return`import { spawnSync } from "node:child_process";
291
+ import { existsSync, readFileSync } from "node:fs";
292
+ import path from "node:path";
293
+ import { parseEnv } from "node:util";
294
+
295
+ const root = import.meta.dirname;
296
+ const file = path.join(root, existsSync(path.join(root, ".env.test")) ? ".env.test" : ".env.test.example");
297
+ const [script, ...args] = process.argv.slice(2);
298
+ const scriptPattern = /^[a-zA-Z0-9:_-]+$/u;
299
+ const argumentPattern = /^[a-zA-Z0-9_./=-]+$/u;
300
+ if (!script || !scriptPattern.test(script) || args.some((arg) => !argumentPattern.test(arg))) {
301
+ throw new Error("Usage: node test-with-services.mjs <package-script> [arguments]");
302
+ }
303
+ const manager = ${JSON.stringify(e)};
304
+ const command = [manager, "run", script, ...(manager === "npm" && args.length > 0 ? ["--"] : []), ...args].join(" ");
305
+ const result = spawnSync(command, {
306
+ cwd: root,
307
+ env: { ...process.env, ...parseEnv(readFileSync(file, "utf-8")) },
308
+ shell: true,
309
+ stdio: "inherit",
310
+ windowsHide: true,
311
+ });
312
+ if (result.error) {
313
+ throw result.error;
314
+ }
315
+ process.exitCode = result.status ?? 1;
316
+ `}c(to,"Wi"),l(to,"testServicesRunnerTemplate");function ro(e){const t={},r={BETTER_AUTH_SECRET:"local-test-secret-at-least-32-characters-long",BETTER_AUTH_URL:"http://localhost:3000",JWT_ACCESS_SECRET:"local-test-access-secret-at-least-32-characters",JWT_REFRESH_SECRET:"local-test-refresh-secret-at-least-32-characters",NODE_ENV:"test"},s=l((o,a,i,p,u)=>{t[o]={environment:p,...u&&u.length>0?{healthcheck:{interval:"2s",retries:45,start_period:"10s",test:u,timeout:"5s"}}:{},image:a,labels:{"nest-arch.generated-test":"true"},ports:[`127.0.0.1:\${TEST_${o.toUpperCase()}_PORT:-${i}}:${i}`]}},"add");if(e.database.includes("postgresql")&&(s("postgres","postgres:17-alpine",5432,{POSTGRES_DB:"scenario",POSTGRES_PASSWORD:"scenario",POSTGRES_USER:"scenario"},["CMD","pg_isready","-h","127.0.0.1","-U","scenario","-d","scenario"]),r.POSTGRES_URL="postgresql://scenario:scenario@127.0.0.1:5432/scenario"),e.database.includes("mysql")&&(s("mysql","mysql:8.4",3306,{MYSQL_DATABASE:"scenario",MYSQL_ROOT_HOST:"%",MYSQL_ROOT_PASSWORD:"scenario"},["CMD","mysql","--host=127.0.0.1","--user=root","--password=scenario","--execute=SELECT 1","scenario"]),r.MYSQL_URL="mysql://root:scenario@127.0.0.1:3306/scenario"),e.database.includes("mongodb")&&(s("mongodb","mongo:8",27017,{},["CMD","mongosh","--quiet","--eval","db.adminCommand('ping')"]),r.MONGODB_URL="mongodb://127.0.0.1:27017/scenario"),e.microservices.includes("redis")&&(s("redis","redis:7-alpine",6379,{},["CMD","redis-cli","ping"]),r.REDIS_URL="redis://127.0.0.1:6379"),e.microservices.includes("mqtt")&&(s("mqtt","eclipse-mosquitto:2",1883,{},[]),r.MQTT_URL="mqtt://127.0.0.1:1883"),e.microservices.includes("nats")&&(s("nats","nats:2-alpine",4222,{},[]),r.NATS_URL="nats://127.0.0.1:4222"),e.microservices.includes("rabbitmq")&&(s("rabbitmq","rabbitmq:3.13-alpine",5672,{},["CMD","rabbitmq-diagnostics","-q","ping"]),r.RABBITMQ_URL="amqp://127.0.0.1:5672"),e.microservices.includes("kafka")&&(s("kafka","apache/kafka:3.9.0",9092,{KAFKA_ADVERTISED_LISTENERS:"PLAINTEXT://127.0.0.1:9092",KAFKA_AUTO_CREATE_TOPICS_ENABLE:"true",KAFKA_CONTROLLER_LISTENER_NAMES:"CONTROLLER",KAFKA_CONTROLLER_QUORUM_VOTERS:"1@localhost:9093",KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS:"0",KAFKA_INTER_BROKER_LISTENER_NAME:"PLAINTEXT",KAFKA_LISTENERS:"PLAINTEXT://:9092,CONTROLLER://:9093",KAFKA_LISTENER_SECURITY_PROTOCOL_MAP:"CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT",KAFKA_NODE_ID:"1",KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS:"1",KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR:"1",KAFKA_PROCESS_ROLES:"broker,controller",KAFKA_TRANSACTION_STATE_LOG_MIN_ISR:"1",KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR:"1"},[]),r.KAFKA_BROKER="127.0.0.1:9092"),Object.keys(t).length===0)return{};const n=[...e.auth==="better-auth"?["auth:generate",...e.orm.length===0?["auth:migrate"]:[]]:[],...e.orm.includes("prisma")?["prisma:generate","prisma:migrate --name initial","prisma:migrate:deploy"]:[],...e.api.includes("trpc")?["trpc:generate"]:[],...e.orm.includes("drizzle")?["db:generate","db:migrate"]:[],"build",...e.orm.includes("typeorm")?["typeorm:generate migrations/Initial","typeorm:run"]:[],"test","test:e2e"];return{".env.test.example":`${Object.entries(r).map(([o,a])=>`${o}=${a}`).join(`
117
317
  `)}
118
- `}l(Qs,"generateDockerCompose");async function Ys(t,e,r,s,n){let o="postgresql";e.database.includes("mysql")?o="mysql":e.database.includes("sqlite")&&(o="sqlite");const a=e.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",i=a.replace("/schema.ts","/migrations");let d="process.env.POSTGRES_URL!";e.database.includes("mysql")?d="process.env.MYSQL_URL!":e.database.includes("sqlite")&&(d="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: ${d},`," },",` dialect: '${o}',`,` out: '${i}',`,` schema: '${a}',`,"});",""].join(`
119
- `);try{const m=await t.writeFile({content:p,filePath:"drizzle.config.ts",isBinary:!1},r);m.written&&s.push(m.filePath)}catch(m){const g=m instanceof Error?m.message:String(m);n.push(`Failed to generate drizzle.config.ts: ${g}`)}}l(Ys,"generateDrizzleConfig");function Xs(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(" ")}l(Xs,"buildReproducibleCommand");function Ks(t){return{$schema:ke.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:Xs(t),ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill,version:"0.2.8"}}l(Ks,"buildMetadata");function Zs(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
- `}l(Zs,"serializeMetadata");function ea(){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
- `}l(ea,"buildSchemaContent");async function ta(t,e,r,s,n){try{const o=Ks(e),a=Zs(o),i=await t.writeFile({content:a,filePath:"nest-arch.jsonc",isBinary:!1},r);i.written&&s.push(i.filePath);const d=ea(),p=await t.writeFile({content:d,filePath:"schema.json",isBinary:!1},r);p.written&&s.push(p.filePath)}catch(o){const a=o instanceof Error?o.message:String(o);n.push(`Failed to generate nest-arch.jsonc/schema.json: ${a}`)}}l(ta,"generateMetadata");const ra={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":"^24.0.0",dotenv:"^17.2.2",typescript:"^6.0.2","typescript-7":"^7.0.0",zod:"^4.4.3"},dependencies:{"@apollo/server":"^5.5.1","@as-integrations/express5":"^1.1.2","@as-integrations/fastify":"^3.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","@nestjs/common":"^12.0.1","@nestjs/core":"^12.0.1","@nestjs/graphql":"^14.0.0","@nestjs/jwt":"^11.0.0","@nestjs/microservices":"^12.0.1","@nestjs/passport":"^11.0.0","@nestjs/platform-express":"^12.0.1","@nestjs/platform-fastify":"^12.0.1","@nestjs/swagger":"^12.0.1","@nestjs/terminus":"^12.0.0","@nestjs/throttler":"6.5.0","@nestjs/typeorm":"12.0.1","@prisma/adapter-better-sqlite3":"^7.10.0","@prisma/adapter-mariadb":"^7.10.0","@prisma/adapter-pg":"^7.10.0","@prisma/adapter-ppg":"^7.10.0","@prisma/client":"^7.10.0","@scalar/nestjs-api-reference":"^1.2.17","@t3-oss/env-core":"^0.13.11","@thallesp/nestjs-better-auth":"^2.7.0","@trpc/client":"^11.18.0","@trpc/openapi":"^11.18.0-alpha","@trpc/server":"^11.18.0",amqplib:"^0.10.5",bcrypt:"^6.0.0","better-auth":"^1.7.2","better-sqlite3":"^12.11.1",dotenv:"^17.2.2","drizzle-graphql":"^0.8.5","drizzle-orm":"^0.45.2",graphql:"^17.0.2","graphql-scalars":"^2.0.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.13.0","nestjs-zod":"^5.5.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.1.1","typeorm-relations-graphql":"^3.0.0",zod:"^4.5.4"},devDependencies:{"@nestjs/cli":"^12.0.0","@nestjs/mau":"^0.2.6","@nestjs/schematics":"^12.0.0","@nestjs/testing":"^12.0.1","@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.2","drizzle-kit":"^0.31.10",husky:"^9.1.7",oxfmt:"^0.66.0",oxlint:"^1.81.0",prettier:"^3.4.2",prisma:"^7.10.0","source-map-support":"^0.5.21",supertest:"^7.0.0",turbo:"^2.8.12",typescript:"^6.0.2","typescript-7":"^7.0.0",ultracite:"7.9.4","vite-tsconfig-paths":"^5.1.4",vitest:"^4.1.10"}};function $t(){return ra}l($t,"loadReference");function h(t){const e=$t(),r=e.dependencies[t]??e.devDependencies[t];if(!r)throw new Error(`Dependency "${t}" not found in reference package.json`);return r}l(h,"getDependencyVersion");function Ut(){return{...$t().catalog}}l(Ut,"getCatalogDependencies");const sa=[{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"}],aa={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},oa={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},na={dest:"bunfig.toml",src:"base/bunfig.toml.hbs"},ia=[{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"}],ca=[{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"}],la=[{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"}],pa=[{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"}],da=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],ua=[{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"}],ma=[{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"}],ha=[{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"}],Bt={"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"}]},Jt=[{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"}],ga="package.json",fa=[{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"}],ya=[{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"}],ba=[{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"}],wa=[{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"}],ja=[{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"}],va=[{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"}],Sa=[{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"}],ka=[{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"}],Aa={"addons/husky":da,"extras/database":ma,"extras/docker":ua,"extras/swagger":[],"feature/graphql":ba,"feature/graphql/todo-example":wa,"feature/rest":ia,"feature/rest/todo-example":ca,"feature/trpc":pa,"monorepo/apps/api-gateway":fa,"monorepo/feature/graphql":va,"monorepo/feature/graphql/todo-example":Sa,"monorepo/feature/rest":ya,"monorepo/feature/rest/todo-example":la,"monorepo/feature/trpc":ja,"monorepo/packages":ka,"monorepo/packages/db":ha,"monorepo/root":Jt};function Ht(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 s of t.api)s==="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"))):s==="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 s of t.microservices)s==="redis"?e.ioredis=h("ioredis"):s==="mqtt"?e.mqtt=h("mqtt"):s==="nats"?e.nats=h("nats"):s==="rabbitmq"?(e.amqplib=h("amqplib"),r["@types/amqplib"]=h("@types/amqplib")):s==="kafka"?e.kafkajs=h("kafkajs"):s==="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"))}l(Ht,"addConditionalDependencies");function Wt(t,e,r){const s=t.orm.includes("prisma"),n=t.orm.includes("drizzle"),o=t.orm.includes("typeorm"),a=t.database.length>0&&!s&&!n&&!o;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-mariadb"]=h("@prisma/adapter-mariadb")),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")&&a&&(e.mongodb=h("mongodb"))}l(Wt,"addDatabaseDependencies");async function Pa(t,e,r,s,n,o){try{const a=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":h("@nestjs/common"),"@nestjs/core":h("@nestjs/core"),[a]:h(a),"@t3-oss/env-core":h("@t3-oss/env-core"),dotenv:h("dotenv"),"reflect-metadata":h("reflect-metadata"),rxjs:h("rxjs"),zod:h("zod")},d=t.extras.includes("typescript-7")?h("typescript-7"):h("typescript"),p={"@nestjs/cli":h("@nestjs/cli"),"@nestjs/mau":h("@nestjs/mau"),"@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:d,"vite-tsconfig-paths":h("vite-tsconfig-paths"),vitest:h("vitest")};t.httpProvider==="express"&&(p["@types/express"]=h("@types/express"));const m={build:"nest build",deploy:"nest deploy",dev:"nest start --watch",start:"nest start","start:debug":"nest start --debug --watch","start:dev":"nest start --watch","start:prod":"node dist/main",test:"vitest run","test:cov":"vitest run --coverage","test:debug":"vitest --inspect-brk --no-file-parallelism","test:e2e":"vitest run --config ./vitest.config.e2e.ts","test:watch":"vitest"};Ht(t,i,p),Wt(t,i,p),t.addons.includes("ultracite")&&(p.ultracite=h("ultracite"),m.check="ultracite check",m.fix="ultracite fix"),t.addons.includes("husky")&&(p.husky=h("husky"),m.prepare="husky"),t.orm.includes("prisma")&&(m["prisma:generate"]="prisma generate",m["prisma:format"]="prisma format",m["prisma:push"]="prisma db push",m["prisma:studio"]="prisma studio",m["prisma:migrate"]="prisma migrate dev",m["prisma:migrate:deploy"]="prisma migrate deploy",m.postinstall="prisma generate"),t.orm.includes("drizzle")&&(m["db:generate"]="drizzle-kit generate",m["db:migrate"]="drizzle-kit migrate",m["db:studio"]="drizzle-kit studio",m["db:push"]="drizzle-kit push"),t.api.includes("trpc")&&(m["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o src/libs/trpc/@generated",m["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o src/libs/trpc/@generated"),t.orm.includes("typeorm")&&(m["typeorm:run"]="typeorm migration:run -d src/database/orm/typeorm/data-source.ts",m["typeorm:revert"]="typeorm migration:revert -d src/database/orm/typeorm/data-source.ts",m["typeorm:generate"]="typeorm migration:generate -d src/database/orm/typeorm/data-source.ts",m["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:m,dependencies:i,devDependencies:p},b=JSON.stringify(g,null,2),q=await r.writeFile({content:b,filePath:"package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});q.written&&n.push(q.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate package.json: ${i}`),console.error("Failed to generate package.json:",a)}}l(Pa,"generateSingleProjectPackageJson");async function Ta(t,e,r,s,n,o){try{const a={build:"turbo build","check-types":"turbo check-types",dev:"turbo dev"},i={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},d=t.extras.includes("typescript-7"),p=d?h("typescript-7"):"catalog:",m={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:h("turbo"),typescript:p};t.addons.includes("ultracite")&&(a.check="ultracite check"),t.addons.includes("husky")&&(m.husky=h("husky"),a.prepare="husky");const b={bun:"bun@1.3.14",npm:void 0,pnpm:"pnpm@11.6.0",yarn:"yarn@4.6.0"}[t.packageManager],q=d?{...Ut(),typescript:h("typescript-7")}:Ut(),M={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,workspaces:["apps/*","packages/*"],type:"module",...b?{packageManager:b}:{},...t.packageManager==="bun"?{catalog:q}:{},scripts:a,dependencies:i,devDependencies:m},U=JSON.stringify(M,null,2),F=await r.writeFile({content:U,filePath:ga,isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});F.written&&n.push(F.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo root package.json: ${i}`),console.error("Failed to generate monorepo root package.json:",a)}}l(Ta,"generateMonorepoRootPackageJson");async function Ea(t,e,r,s,n,o){try{const a=t.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",i={"@nestjs/common":h("@nestjs/common"),"@nestjs/core":h("@nestjs/core"),[a]:h(a),"@repo/env":"workspace:*","reflect-metadata":h("reflect-metadata"),rxjs:h("rxjs"),zod:"catalog:"};t.database.length>0&&(i["@repo/db"]="workspace:*");const d=t.extras.includes("typescript-7")?h("typescript-7"):"catalog:",p={"@nestjs/cli":h("@nestjs/cli"),"@nestjs/mau":h("@nestjs/mau"),"@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:d,"vite-tsconfig-paths":h("vite-tsconfig-paths"),vitest:h("vitest")};t.httpProvider==="express"&&(p["@types/express"]=h("@types/express"));const m={build:"nest build",deploy:"nest deploy",dev:"nest start --watch",start:"nest start","start:debug":"nest start --debug --watch","start:dev":"nest start --watch","start:prod":"node dist/main",test:"vitest run","test:cov":"vitest run --coverage","test:debug":"vitest --inspect-brk --no-file-parallelism","test:e2e":"vitest run --config ./vitest.config.e2e.ts","test:watch":"vitest"};Ht(t,i,p),t.addons.includes("ultracite")&&(p.ultracite=h("ultracite"),m.check="ultracite check",m.fix="ultracite fix"),t.addons.includes("husky")&&(p.husky=h("husky"),m.prepare="husky"),t.api.includes("trpc")&&(m["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated",m["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated");const g={name:e.projectName,version:"0.0.1",description:e.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:m,dependencies:i,devDependencies:p},b=JSON.stringify(g,null,2),q=await r.writeFile({content:b,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});q.written&&n.push(q.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo app package.json: ${i}`),console.error("Failed to generate monorepo app package.json:",a)}}l(Ea,"generateMonorepoAppPackageJson");async function Ra(t,e,r,s,n,o){try{const a={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:"},d={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:t.extras.includes("typescript-7")?h("typescript-7"):"catalog:"};Wt(t,a,d);const p={};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.orm.includes("typeorm")&&(p["typeorm:run"]="typeorm-ts esm migration:run -d src/database/orm/typeorm/data-source.ts",p["typeorm:revert"]="typeorm-ts esm migration:revert -d src/database/orm/typeorm/data-source.ts",p["typeorm:generate"]="typeorm-ts esm migration:generate -d src/database/orm/typeorm/data-source.ts",p["typeorm:create"]="typeorm migration:create");const m={name:"@repo/db",version:"0.0.1",private:!0,type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},...Object.keys(p).length>0?{scripts:p}:{},dependencies:a,devDependencies:d},g=JSON.stringify(m,null,2),b=await r.writeFile({content:g,filePath:"packages/db/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});b.written&&n.push(b.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate monorepo db package.json: ${i}`),console.error("Failed to generate monorepo db package.json:",a)}}l(Ra,"generateMonorepoDbPackageJson");async function qa(t,e,r,s,n){let o="postgresql";e.database.includes("mysql")?o="mysql":e.database.includes("sqlite")?o="sqlite":e.database.includes("mongodb")&&(o="mongodb");const a=o==="mongodb",i=["generator client {",' provider = "prisma-client"',' output = "./generated"',"}","","datasource db {",` provider = "${o}"`,"}",""],d=e.extras.includes("todo-example");e.auth==="passport"&&e.database.length>0&&i.push("enum Role {"," ADMIN"," USER","}","","model User {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," email String @unique"," password String"," firstname String?"," lastname String?"," role Role @default(USER)",...d?[" todos Todo[]",""]:[""],' @@map("user")',"}",""),d&&e.database.length>0&&(e.auth==="none"?i.push("model Todo {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)","",' @@map("todo")',"}",""):i.push("model Todo {",` id String ${a?'@id @default(auto()) @map("_id") @db.ObjectId':"@id @default(cuid())"}`," createdAt DateTime @default(now())"," updatedAt DateTime @updatedAt"," title String"," description String?"," completed Boolean @default(false)",` authorId ${a?"String? @db.ObjectId":"String?"}`," author User? @relation(fields: [authorId], references: [id])","",' @@map("todo")',"}",""));const p=i.join(`
123
- `);try{const m=await t.writeFile({content:p,filePath:"src/database/orm/prisma/schema.prisma",isBinary:!1},r);m.written&&s.push(m.filePath)}catch(m){const g=m instanceof Error?m.message:String(m);n.push(`Failed to generate src/database/orm/prisma/schema.prisma: ${g}`)}}l(qa,"generatePrismaSchema");function Vt(t,e){const r=!!e.usePrisma,s=!!e.useTypeorm,n=!!e.useDrizzle,o=!!e.useRawSql,a=!!e.hasPostgres,i=!!e.hasMysql,d=!!e.hasSqlite,p=!!e.hasMongodb;return t.filter(m=>{const{dest:g}=m;return g.includes("prisma-sql.adapter")?r&&(a||i||d):g.includes("prisma-mongo.adapter")?r&&p:g.includes("typeorm-sql.adapter")?s&&(a||i||d):g.includes("orm/typeorm/data-source")||g.includes("entities/")?s:g.includes("drizzle-sql.adapter")?n:g.includes("raw-sql.adapter")?o&&(a||i||d):g.includes("raw-mongo.adapter")?o&&p:g.includes("orm/drizzle/schema")?n:!0})}l(Vt,"filterDatabaseTemplates");function Qt(t,e){const r=!!e.hasTrpcAndAuth;return t.filter(s=>s.dest.includes("libs/trpc/protected.ts")||s.dest.includes("libs/trpc/inner.context.ts")||s.dest.includes("libs/middlewares/auth.trpc.middleware.ts")?r:!0)}l(Qt,"filterTrpcTemplates");function Yt(t,e){const r=!!e.useTypeorm,s=!!e.usePrisma,n=!!e.useDrizzle;return t.filter(o=>{const{dest:a}=o;return a.includes("orm/typeorm")?r:a.includes("orm/prisma")?s:a.includes("orm/drizzle")?n:!0})}l(Yt,"filterGraphqlTemplates");function Xt(t,e){const r=!!e.hasTrpc,s=!!e.hasRest;return t.filter(n=>n.dest.includes("todo.router.ts")?r:n.dest.includes("todo.controller.ts")?s:!0)}l(Xt,"filterTodoTemplates");class xa{static{l(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(e,r){this.options=r,this.fileWriter=new as(e),this.templateEngine=new dt(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new ys,this.mapper=new Be,zs(this.mapper)}getMapper(){return this.mapper}async generate(e){const r=Date.now(),s=[],n=[];try{const o=this.mapper.resolve(e);let a=$s(e);a=Us(a,o.extraVariables),a.hasUltracite=e.addons.includes("ultracite"),a.hasHusky=e.addons.includes("husky"),a.hasAgentSkills=e.addons.includes("agent-skills"),await(e.projectType==="monorepo"?this.generateMonorepo.bind(this):this.generateSingleProject.bind(this))(e,a,o.templateGroups,s,n);const d=Date.now()-r,p=n.length===0;if(p){const m={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await ta(this.fileWriter,e,m,s,n)}return console.log(`\u2705 Project generated in ${d}ms`),{error:p&&n.length===0?void 0:n.join(`
124
- `),filesCount:s.length,generatedFiles:s,success:p&&n.length===0}}catch(o){return{error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:s,success:!1}}}async generateSingleProject(e,r,s,n,o){const a={dryRun:this.options.dryRun,overwrite:this.options.overwrite},i=[...sa];r.packageManager==="pnpm"?i.push(aa):r.packageManager==="yarn"?i.push(oa):r.packageManager==="bun"&&i.push(na),await Pa(e,r,this.fileWriter,a,n,o);for(const d of i)await this.renderAndWrite(d.src,d.dest,r,n,o);await this.processTemplateGroups(e,r,s,n,o),await this.processPostTemplateSteps(e,r,n,o)}async generateMonorepo(e,r,s,n,o){const a={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await Ta(e,r,this.fileWriter,a,n,o),await Ea(e,r,this.fileWriter,a,n,o),e.database.length>0&&await Ra(e,r,this.fileWriter,a,n,o),await this.processTemplateGroups(e,r,s,n,o),await this.processPostTemplateSteps(e,r,n,o)}TEMPLATE_FILTERS={"extras/database":Vt,"feature/graphql":Yt,"feature/rest/todo-example":Xt,"feature/trpc":Qt,"monorepo/feature/graphql":Yt,"monorepo/feature/rest/todo-example":Xt,"monorepo/feature/trpc":Qt,"monorepo/packages/db":Vt};async processSingleArchTemplates(e,r,s,n){const o=Bt[e];if(!o)return;const a=new Set(["package.json","pnpm-workspace.yaml",".yarnrc.yml","bunfig.toml"]);for(const i of o)a.has(i.dest)||await this.renderAndWrite(i.src,i.dest,r,s,n)}async processMonorepoRoot(e,r,s){for(const i of Jt)await this.renderAndWrite(i.src,i.dest,e,r,s);const n={bun:{dest:"bunfig.toml",src:"monorepo/root/bunfig.toml.hbs"},pnpm:{dest:"pnpm-workspace.yaml",src:"monorepo/root/pnpm-workspace.yaml.hbs"},yarn:{dest:".yarnrc.yml",src:"monorepo/root/.yarnrc.yml.hbs"}},o=e.packageManager,a=n[o];a&&await this.renderAndWrite(a.src,a.dest,e,r,s)}shouldSkipTemplate(e,r,s){return!!(s&&e.dest==="packages/db/package.json"||e.dest==="docker-compose.yml"&&r.database.length>0)}async processTemplateGroups(e,r,s,n,o){const a=e.projectType==="monorepo";for(const i of s){if(!a&&Bt[i]){await this.processSingleArchTemplates(i,r,n,o);continue}if(a&&i==="monorepo/root"){await this.processMonorepoRoot(r,n,o);continue}if(!a&&i==="monorepo/packages/db")continue;const d=Aa[i];if(!d)continue;const p=this.TEMPLATE_FILTERS[i],m=p?p(d,r):d;for(const g of m)this.shouldSkipTemplate(g,e,a)||await this.renderAndWrite(g.src,g.dest,r,n,o)}}async processPostTemplateSteps(e,r,s,n){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite},a=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",a,r,s,n),e.extras.includes("docker")&&e.database.length>0){const i=Qs(e),d=await this.fileWriter.writeFile({content:i,filePath:"docker-compose.yml",isBinary:!1},o);d.written&&s.push(d.filePath)}if(e.orm.includes("prisma")&&(await qa(this.fileWriter,e,o,s,n),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,s,n)),e.orm.includes("drizzle")&&await Ys(this.fileWriter,e,o,s,n),e.auth!=="none"){const i=Ws.composeGenerators(e),d=await Vs(e,this.fileWriter.getBaseDir(),i);for(const p of d)!p.success&&p.error&&n.push(p.error)}}async renderAndWrite(e,r,s,n,o){try{const a=await this.templateEngine.renderToFile(e,r,{context:s}),i=await this.fileWriter.writeFile(a,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});i.written&&n.push(i.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate ${r}: ${i}`),console.error(`Failed to generate ${r}:`,a)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}const Ia=/Resolved|Resolving/iu,Oa=/Downloaded?|downloaded/iu,_a=/Link(ed|ing)/iu,Ca=/saved (to )?(lockfile|bun)/iu;function Da(t){const e=[],r=t.split(`
125
- `);for(const s of r){const n=s.trim();if(n){if(Ia.test(n)){e.push({message:"Resolving packages...",phase:"resolve"});continue}if(Oa.test(n)){e.push({message:"Downloading...",phase:"download"});continue}if(_a.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(Ca.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}l(Da,"parseBunText");class Ma{static{l(this,"BunInstaller")}async install(e,r,s){const n=Oe("bun install",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const a=l(d=>{const p=d.toString();o+=p;const m=Da(p);for(const g of m)r?.(g)},"handleData");n.stderr.on("data",a),n.stdout.on("data",a);const[i]=await Promise.race([re(n,"close"),re(n,"error").then(([d])=>{const p=d;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(o.trim()||`bun install exited with code ${i}`)}}const Ga=/^(\d+)\/(\d+)\s+resolving/iu,za=/^(\d+)\/(\d+)\s+extract:/iu,Na=/^(\d+)\/(\d+)\s+(\S+)/iu,Fa=/^(\d+)ms\s+(.*)/iu;function La(t){const e=[],r=t.split(`
127
- `);for(const s of r){const n=s.trim();if(n.includes("resolving")){const o=Ga.exec(n);o?e.push({completed:Number(o[1]),message:"Resolving packages...",percentage:Math.round(Number(o[1])/Number(o[2])*100),phase:"resolve",total:Number(o[2])}):e.push({message:"Resolving packages...",phase:"resolve"});continue}if(n.includes("extract:")||n.includes("http fetch")){const o=za.exec(n)||Na.exec(n);o?e.push({completed:Number(o[1]),message:"Downloading...",percentage:Math.round(Number(o[1])/Number(o[2])*100),phase:"download",total:Number(o[2])}):e.push({message:"Downloading...",phase:"download"});continue}if(n.includes("timing")){const o=Fa.exec(n);if(o){const a=o[2]??"";a.includes("build")?e.push({message:"Building dependencies...",phase:"build"}):a.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}l(La,"parseNpmText");class $a{static{l(this,"NpmInstaller")}async install(e,r,s){const n=Oe("npm install --loglevel silly",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const a=l(d=>{const p=d.toString();o+=p;const m=La(p);for(const g of m)r?.(g)},"handleData");n.stderr.on("data",a),n.stdout.on("data",()=>{});const[i]=await Promise.race([re(n,"close"),re(n,"error").then(([d])=>{const p=d;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(o.trim()||`npm install exited with code ${i}`)}}function Ua(t,e){const r=e?.status,s=e?.progress;switch(r){case"resolving":return{message:"Resolving packages...",percentage:s??0,phase:"resolve"};case"downloading":case"fetching":return{message:"Downloading...",percentage:s??e?.progress,phase:"download"};case"linking":return{message:"Linking packages...",percentage:s??0,phase:"link"};case"build":return{message:"Building dependencies...",percentage:s??0,phase:"build"};default:return{message:r||"Installing dependencies...",percentage:s??0,phase:"download"}}}l(Ua,"mapPnpmStage");function Ba(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}l(Ba,"mapPnpmStat");function Ja(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"}}l(Ja,"mapPnpmFetching");function Ha(t){if(!t.type)return null;switch(t.type){case"stage":{const e=t.data?.stage;return e?Ua(e,t.data):null}case"stat":return Ba(t.data);case"fetching":return Ja(t);case"warning":case"error":return{message:t.message??t.type,phase:"download"};default:return null}}l(Ha,"parsePnpmLine");class Wa{static{l(this,"PnpmInstaller")}async install(e,r,s){const n=Oe("pnpm install --reporter ndjson",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";n.stdout.on("data",i=>{const d=i.toString().split(`
129
- `).filter(Boolean);for(const p of d)try{const m=JSON.parse(p),g=Ha(m);g&&r&&r(g)}catch{}}),n.stderr.on("data",i=>{o+=i.toString()});const[a]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const d=i;throw d.code==="ENOENT"||d.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(d.message)})]);if(a===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`pnpm install exited with code ${a}`)}}function Va(t){switch(t.type){case"step":{const e=t.displayName??"";return e.includes("Resolution")?{message:"Resolving packages...",phase:"resolve"}:e.includes("Fetch")?{message:"Downloading...",phase:"download"}:e.includes("Link")?{message:"Linking packages...",phase:"link"}:e.includes("Build")?{message:"Building dependencies...",phase:"build"}:{message:e||"Installing...",phase:"postinstall"}}case"progress":{const e=typeof t.data=="object"?t.data:void 0,r=e?.current,s=e?.total;return r!==void 0&&s!==void 0?{completed:r,message:"Processing...",percentage:Math.round(r/s*100),phase:"download",total:s}:null}case"success":return{message:typeof t.data=="string"?t.data:t.data?.message??"Done",percentage:100,phase:"complete"};case"error":return{message:typeof t.data=="string"?t.data:t.data?.message??"Error",phase:"download"};default:return null}}l(Va,"parseYarnLine");class Qa{static{l(this,"YarnInstaller")}async install(e,r,s){const n=Oe("yarn install --json",[],{cwd:e,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";n.stdout.on("data",i=>{const d=i.toString().split(`
131
- `).filter(Boolean);for(const p of d)try{const m=JSON.parse(p),g=Va(m);g&&r&&r(g)}catch{}}),n.stderr.on("data",i=>{o+=i.toString()});const[a]=await Promise.race([re(n,"close"),re(n,"error").then(([i])=>{const d=i;throw d.code==="ENOENT"||d.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(d.message)})]);if(a===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`yarn install exited with code ${a}`)}}function Ya(t){switch(t){case"pnpm":return new Wa;case"npm":return new $a;case"yarn":return new Qa;case"bun":return new Ma;default:throw new Error(`Unhandled package manager: ${t}`)}}l(Ya,"createPackageInstaller");class Xa{static{l(this,"ProjectPipeline")}outputDir;generatorOptions;state;context;events;constructor(e,r){this.outputDir=e,this.generatorOptions=r}emit(e){this.events?.onStageChange?.(e)}addPhase(e){this.state.phases.push(e)}async execute(e,r){this.context=e,this.events=r,this.state={generatedFiles:[],installSucceeded:!1,phases:[]};const s=[this.phaseGenerateFiles,this.phaseInstallAgentSkills,this.phaseSetupLinter,this.phaseGitInit,this.phaseInstallDependencies,this.phaseRunFormatter,this.phaseFormatterCommit];for(const o of s)if(!await o.call(this))break;this.emit("complete");const n=this.state.phases.every(o=>o.success||o.skipped);return this.buildResult(n)}async phaseGenerateFiles(){this.emit("generate-files");const e=new xa(this.outputDir,this.generatorOptions);try{const r=await e.generate(this.context);return this.state.generatedFiles.push(...r.generatedFiles),r.success?(this.addPhase({phase:"generate-files",success:!0}),!0):(this.addPhase({error:r.error,phase:"generate-files",success:!1}),!1)}catch(r){return this.addPhase({error:r instanceof Error?r.message:String(r),phase:"generate-files",success:!1}),!1}}async phaseInstallAgentSkills(){if(!this.context.addons.includes("agent-skills"))return this.addPhase({phase:"install-agent-skills",skipped:!0,success:!0}),!0;this.emit("install-agent-skills");try{const e=await ss(this.outputDir,this.context),r=e.failed.length>0?e.failed.map(s=>`${s.name}: ${s.error}`).join(", "):void 0;this.addPhase({phase:"install-agent-skills",success:!0,...r?{error:r}:{}})}catch(e){this.addPhase({error:e instanceof Error?e.message:String(e),phase:"install-agent-skills",success:!0})}return!0}async phaseSetupLinter(){if(this.context.formatter==="none")return this.addPhase({phase:"setup-linter",skipped:!0,success:!0}),!0;this.emit("setup-linter");try{const e=await fs(this.outputDir,this.context);if(!e.success)return this.addPhase({error:e.message,phase:"setup-linter",success:!1}),!1;const r=await vs(this.outputDir,this.context.formatter);return r.success?(this.addPhase({phase:"setup-linter",success:!0}),!0):(this.addPhase({error:r.message??"Rule injection failed",phase:"setup-linter",success:!1}),!1)}catch(e){return this.addPhase({error:e instanceof Error?e.message:String(e),phase:"setup-linter",success:!1}),!1}}async phaseGitInit(){if(!this.context.initGit)return this.addPhase({phase:"initialize-git",skipped:!0,success:!0}),this.addPhase({phase:"initial-commit",skipped:!0,success:!0}),!0;this.emit("initialize-git");try{await is(this.outputDir)||await os(this.outputDir),this.addPhase({phase:"initialize-git",success:!0})}catch(s){this.addPhase({error:s instanceof Error?s.message:String(s),phase:"initialize-git",success:!1})}const{3:e}=this.state.phases;if(e?.success??!1){this.emit("initial-commit");try{await Gt(this.outputDir),await zt(this.outputDir,"Initial project scaffold"),this.addPhase({phase:"initial-commit",success:!0})}catch(s){this.addPhase({error:s instanceof Error?s.message:String(s),phase:"initial-commit",success:!1})}}else this.addPhase({phase:"initial-commit",skipped:!0,success:!0});return!0}async phaseInstallDependencies(){if(!this.context.installDependencies)return this.addPhase({phase:"install-dependencies",skipped:!0,success:!0}),!0;this.emit("install-dependencies");try{await Ya(this.context.packageManager).install(this.outputDir,r=>{this.events?.onInstallProgress?.(r)}),this.state.installSucceeded=!0,this.addPhase({phase:"install-dependencies",success:!0})}catch(e){this.addPhase({error:e instanceof Error?e.message:String(e),phase:"install-dependencies",success:!1})}return!0}async phaseRunFormatter(){if(!(this.state.installSucceeded&&this.context.formatter!=="none"))return this.addPhase({phase:"run-formatter",skipped:!0,success:!0}),!0;this.emit("run-formatter");try{const r=await ds(this.context.packageManager,this.outputDir);this.addPhase({phase:"run-formatter",success:r.success,...r.success?{}:{error:r.error}})}catch(r){this.addPhase({error:r instanceof Error?r.message:String(r),phase:"run-formatter",success:!1})}return!0}async phaseFormatterCommit(){const{5:e}=this.state.phases;if(!(this.context.initGit&&e?.success&&!e.skipped))return this.addPhase({phase:"formatter-commit",skipped:!0,success:!0}),!0;this.emit("formatter-commit");try{await Gt(this.outputDir),await ns(this.outputDir)&&await zt(this.outputDir,"Apply formatter"),this.addPhase({phase:"formatter-commit",success:!0})}catch(s){this.addPhase({error:s instanceof Error?s.message:String(s),phase:"formatter-commit",success:!1})}return!0}buildResult(e){return{generatedFiles:this.state.generatedFiles,outputDir:this.outputDir,phases:this.state.phases,success:e}}}function Ka(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}}l(Ka,"buildGeneratorContext");function $e(t){return ke.NEST_ARCH_BETA_MODE?Y(gt(),"test-projects",t):Y(process.cwd(),t)}l($e,"getOutputDir");function Za(){const t=import.meta.dirname;if(t){const r=Y(t,"templates");if(je(r))return r}return Y(t??process.cwd(),"..","..","..","..","packages","core","templates")}l(Za,"getTemplatesDir");async function Kt(t,e){const r=$e(t.projectName),s=Ka(t),n=Za(),o=new Xa(r,{cacheTemplates:!0,templatesDir:n});try{const a=await o.execute(s,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"},d=a.phases.filter(p=>!p.success&&!p.skipped&&p.error).map(p=>`${i[p.phase]||p.phase} failed:
133
- ${p.error}`);return d.length>0?{message:d.join(`
134
-
135
- `),outputDir:r,success:!1}:{message:`Project created with ${a.generatedFiles.length} files`,outputDir:r,success:!0}}catch(a){return{message:`Failed to generate project: ${a instanceof Error?a.message:String(a)}`,outputDir:r,success:!1}}}l(Kt,"generateProject");const eo=l(()=>({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 Zt(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:ne(t.projectName),projectType:t.projectType,ultraciteAgents:t.ultraciteAgents,ultraciteEditors:t.ultraciteEditors,ultraciteHooks:t.ultraciteHooks,ultraciteInstallSkill:t.ultraciteInstallSkill??"no"}}l(Zt,"buildResult");const to=l(({onBack:t,onExit:e,onStepChange:r})=>{const[s,n]=O("projectName"),o=qe(s);o.current=s;const[a,i]=O(eo),[d,p]=O(null),[m,g]=O(null),[b,q]=O(null),[M,U]=O(null),F=J(()=>ot(a),[a]),_=J(()=>Fr(s,a),[s,a]),$=J(()=>Nr(s,a),[s,a]);mt(()=>{if(!m||m.isError)return;const A=Zt(a);A&&Mt(A),n("done"),r?.("done")},[m,a,r]);const D=R(A=>{const k=Lr(o.current,A);k&&(n(k),r?.(k))},[r]),B=R(()=>{const A=$r(s,a);if(A){n(A),r?.(A);return}t()},[t,a,s,r]),z=l(A=>R(k=>{i(j=>{const x={...j,[A]:k};return D(x),x})},[A]),"useStepFieldHandler"),v=z("packageManager"),I=z("formatter"),G=z("httpProvider"),V=z("auth"),ee=z("microservices"),ge=z("addons"),fe=z("ultraciteEditors"),ye=z("ultraciteAgents"),be=z("ultraciteHooks"),ie=z("ultraciteInstallSkill"),Te=z("initGit"),T=z("installDependencies"),X=R(()=>{const A=Me(a.projectName);if(A){p(A);return}const k=ne(a.projectName),j=$e(k);if(je(j)){p(`Directory "${j}" already exists. Choose a different name or delete the existing directory.`);return}const x={...a,projectName:k};i(x),D(x)},[D,a]),ce=R(A=>{const k=A==="single"&&a.architecture==="nest-gateway"?Ct():a.architecture??Ct(),j={...a,architecture:k,extras:A==="single"?a.extras.filter(x=>x!=="packages/shared"):a.extras,microservices:k==="nest-gateway"?a.microservices:[],projectType:A};i(j),D(j)},[D,a]),C=R(A=>{const k={...a,architecture:A,microservices:A==="nest-gateway"?a.microservices:[]};i(k),D(k)},[D,a]),K=R(A=>{const k=A==="none"?[]:[A],j=Dt(a.orm,k),x=k.length===0,Ve={...a,api:x?a.api.filter(te=>te!=="graphql"):a.api,auth:x&&a.auth==="better-auth"?null:a.auth,database:k,orm:j};i(Ve),D(Ve)},[D,a]),se=R(A=>{const k=A==="none"?[]:[A],j=Wr(a.database,k),x={...a,database:j,orm:Dt(k,j)};i(x),D(x)},[D,a]),S=R(A=>{const k=ze(A),j={...a,addons:k?a.addons:a.addons.filter(x=>x!=="scalar-ui"),api:A,auth:k?a.auth:null,extras:k?a.extras:a.extras.filter(x=>x==="docker"||x==="packages/shared")};i(j),D(j)},[D,a]),Ee=R(A=>{const k=A.includes("swagger"),j={...a,addons:k?a.addons:a.addons.filter(x=>x!=="scalar-ui"),extras:A};i(j),D(j)},[D,a]),Je=J(()=>{const A=a.projectType==="monorepo"?st:st.filter(k=>k.value!=="packages/shared");return ze(a.api)?A:A.filter(k=>k.value==="docker"||k.value==="packages/shared")},[a.projectType,a.api]),Re=R(async()=>{const A=Zt(a);if(A){n("installing"),r?.("installing");try{const k=await Kt(A,{onInstallProgress:l(j=>{U(j)},"onInstallProgress"),onStageChange:l(j=>{q(j)},"onStageChange")});g({isError:!k.success,message:k.message})}catch(k){g({isError:!0,message:`Error: ${k instanceof Error?k.message:String(k)}`})}}},[a,r]),He=R(()=>{n("summary"),r?.("summary"),g(null)},[r]),We=J(()=>s==="projectName"||s==="summary"?"confirm":s==="database"||s==="orm"||s==="apiLayer"||s==="extras"||s==="microservices"||s==="addons"||s==="ultraciteEditors"||s==="ultraciteAgents"||s==="ultraciteHooks"?"select":s==="installing"&&m?.isError?"confirm":"select",[s,m?.isError]);return{architectureOpts:J(()=>Ur(a.projectType),[a.projectType]),currentStage:b,displayStep:_,extrasStepOptions:Je,generationStatus:m,goBack:B,handleAddons:ge,handleApi:S,handleArchitecture:C,handleAuth:V,handleDatabase:K,handleExtras:Ee,handleFormatter:I,handleHttpProvider:G,handleInitGit:Te,handleInstallDependencies:T,handleMicroservices:ee,handleOrm:se,handlePackageManager:v,handleProjectNameSubmit:X,handleProjectType:ce,handleRetry:He,handleSummaryConfirm:Re,handleUltraciteAgents:ye,handleUltraciteEditors:fe,handleUltraciteHooks:be,handleUltraciteInstallSkill:ie,installProgress:M,projectNameError:d,setProjectNameError:p,setState:i,state:a,statusAction:We,stepId:s,subProgress:$,totalSteps:F}},"useCreateProjectWizard"),ro=l(({onBack:t,onDone:e,onExit:r,onStepChange:s})=>{const{architectureOpts:n,currentStage:o,displayStep:a,extrasStepOptions:i,generationStatus:d,goBack:p,handleProjectNameSubmit:m,handlePackageManager:g,handleFormatter:b,handleHttpProvider:q,handleProjectType:M,handleArchitecture:U,handleDatabase:F,handleOrm:_,handleApi:$,handleAuth:D,handleExtras:B,handleMicroservices:z,handleAddons:v,handleUltraciteEditors:I,handleUltraciteAgents:G,handleUltraciteHooks:V,handleUltraciteInstallSkill:ee,handleInitGit:ge,handleInstallDependencies:fe,handleRetry:ye,handleSummaryConfirm:be,installProgress:ie,projectNameError:Te,setProjectNameError:T,setState:X,statusAction:ce,stepId:C,subProgress:K,totalSteps:se,state:S}=to({onBack:t,onExit:r,onStepChange:s}),[Ee,Je]=O([]),[Re]=O([]),He=J(()=>{const j=new Set;return S.initGit==="no"&&(j.add("initialize-git"),j.add("initial-commit")),S.installDependencies==="no"&&j.add("install-dependencies"),(S.formatter==="none"||S.installDependencies==="no")&&(j.add("setup-linter"),j.add("run-formatter")),(S.initGit==="no"||j.has("run-formatter"))&&j.add("formatter-commit"),S.addons.includes("agent-skills")||j.add("install-agent-skills"),[...j]},[S.initGit,S.installDependencies,S.formatter,S.addons]),We=J(()=>xt.filter(j=>!(j.value==="ultracite"&&S.formatter==="none"||j.value==="scalar-ui"&&!S.extras.includes("swagger"))),[S.formatter,S.extras]),ut=J(()=>{let j=S;return C==="addons"&&(j={...j,addons:Ee}),C==="database"&&(j={...j,database:Re}),ot(j)},[C,S,Ee,Re,se]);ae(()=>{C==="done"&&e()},[C,e]),le((j,x)=>{if(x.ctrl&&j==="c"){r();return}if(x.ctrl&&j==="b"&&C!=="done"){p();return}if(C==="done"&&x.return){r();return}C==="installing"&&d?.isError&&x.return&&ye()});const A=l(()=>{const x={architecture:{options:n,prompt:"Choose an application architecture"},auth:{options:Jr(S.database),prompt:"Choose an authentication strategy"},formatter:{options:Tt,prompt:"Choose a formatter-linter (with ultracite preset) setup"},httpProvider:{options:Et,prompt:"Choose an HTTP provider"},initGit:{options:It,prompt:"Initialize a git repository?"},installDependencies:{options:Ir,prompt:"Install dependencies?"},packageManager:{options:Pt,prompt:"Choose a package manager"},projectType:{options:Rt,prompt:"Choose a project layout"},ultraciteInstallSkill:{options:Dr,prompt:"Install Ultracite skill?"}}[C];if(x)return c(Ge,{onConfirm:{architecture:U,auth:D,formatter:b,httpProvider:q,initGit:ge,installDependencies:fe,packageManager:g,projectType:M,ultraciteInstallSkill:ee}[C],options:x.options,prompt:x.prompt},C);const te={addons:{initialSelected:S.addons,onChange:Je,options:We,prompt:"Select addons (optional)"},apiLayer:{initialSelected:S.architecture==="nest-api"&&S.api.length===0?["rest"]:S.api,options:Hr(S.database),prompt:"Select API layers (optional)"},extras:{initialSelected:S.extras,options:i,prompt:"Select extras (optional)"},microservices:{initialSelected:S.microservices,options:xr,prompt:"Select microservice communication protocols"},ultraciteAgents:{initialSelected:S.ultraciteAgents,minified:!0,options:_r,prompt:"Select Ultracite agents"},ultraciteEditors:{initialSelected:S.ultraciteEditors,minified:!0,options:Or,prompt:"Select Ultracite editors"},ultraciteHooks:{initialSelected:S.ultraciteHooks,options:Cr,prompt:"Select Ultracite hooks"}}[C];if(te){const Q={addons:v,apiLayer:$,extras:B,microservices:z,ultraciteAgents:G,ultraciteEditors:I,ultraciteHooks:V};return c(Rr,{initialSelected:te.initialSelected,onConfirm:Q[C],options:te.options,prompt:te.prompt,...te.minified?{minified:!0}:{},...te.onChange?{onChange:te.onChange}:{}},C)}switch(C){case"projectName":return c(At,{error:Te,onChange:l(Q=>{X(tr=>({...tr,projectName:Q})),T(Me(Q))},"onChange"),onSubmit:m,value:S.projectName});case"database":{const Q={description:"Skip database scaffolding for now",label:"No database",value:"none"};return c(Ge,{initialValue:S.database[0]??"none",onConfirm:F,options:[Q,...Br(S.orm)],prompt:"Select a database for your project (optional)"},"database")}case"orm":{const Q={description:"Use plain database access without an ORM",label:"No ORM",value:"none"};return c(Ge,{initialValue:S.orm[0]??"none",onConfirm:_,options:[Q,..._t(S.database)],prompt:"Select an ORM to include"},"orm")}case"summary":return c(Vr,{onConfirm:be,state:S});case"installing":return y(f,{flexDirection:"column",children:[c(jt,{currentStage:o,generationMessage:d?.message??"Scaffolding your project",installProgress:ie,isError:d?.isError??!1,packageManager:S.packageManager??void 0,skippedStages:He}),d?.isError?c(f,{marginTop:1,children:y(u,{color:E,children:["Press ",c(u,{color:P,children:"Enter"})," to go back to Summary and retry, or ",c(u,{color:E,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const Q=ne(S.projectName);return c(vt,{architecture:S.architecture||"nest-api",projectName:Q,packageManager:S.packageManager||"pnpm",dependenciesInstalled:S.installDependencies==="yes",isGitInitialized:S.initGit==="yes",outputDir:$e(Q)})}default:return null}},"renderStep"),k=C!=="installing"&&C!=="done";return y(f,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[k?y(N,{children:[c(Qr,{state:S,stepId:C}),c(f,{height:0}),c(Yr,{displayStep:a,stepId:C,subProgress:K??void 0,totalSteps:ut}),c(f,{height:2})]}):null,A(),c(f,{flexGrow:1}),k?y(N,{children:[c(Se,{}),c(f,{height:1}),c(Ke,{action:ce,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),lt=` _ _ ___ ___ _____ _ ___ ___ _ _
318
+ `,"TESTING.md":`# Servicios para pruebas
319
+
320
+ Desde la ra\xEDz del proyecto:
321
+
322
+ 1. Ejecuta \`docker compose -f docker-compose.test.yml up -d --wait\`.
323
+ 2. Ejecuta cada comando de abajo con \`node test-with-services.mjs <script> [argumentos]\`. El helper carga .env.test.example (o .env.test si lo creas), y la aplicaci\xF3n valida las variables con createEnv.
324
+ 3. Al terminar ejecuta \`docker compose -f docker-compose.test.yml down --volumes --remove-orphans\`. Esto elimina los datos de pruebas.
325
+
326
+ ${n.map(o=>`- \`node test-with-services.mjs ${o}\``).join(`
327
+ `)}
328
+
329
+ Las migraciones iniciales se generan una sola vez; en ejecuciones posteriores aplica las existentes. Los puertos se publican solo en localhost. Puedes cambiarlos con TEST_POSTGRES_PORT, TEST_MYSQL_PORT, TEST_MONGODB_PORT o TEST_REDIS_PORT y actualizar la URL correspondiente en .env.test. Estos servicios son exclusivamente de desarrollo/pruebas. Redis se incluye si fue seleccionado; esto no implica que las pruebas HTTP certifiquen el transporte.
330
+ `,"docker-compose.test.yml":`${JSON.stringify({services:t},null,2)}
331
+ `,"test-with-services.mjs":to(e.packageManager)}}c(ro,"Hi"),l(ro,"generateTestServices");class Yp{static{c(this,"fr")}static{l(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(t,r){this.options=r,this.fileWriter=new li(t),this.templateEngine=new Vr(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new di,this.mapper=new qt,Fs(this.mapper)}getMapper(){return this.mapper}async generate(t){const r=Date.now(),s=[],n=[];try{Ns(t,this.options.candidateProfile);const o=this.mapper.resolve(t);let a=Js(t);a=Bs(a,o.extraVariables),a.hasUltracite=t.addons.includes("ultracite"),a.hasHusky=t.addons.includes("husky"),a.hasAgentSkills=t.addons.includes("agent-skills"),await(t.projectType==="monorepo"?this.generateMonorepo.bind(this):this.generateSingleProject.bind(this))(t,a,o.templateGroups,s,n);const i=Date.now()-r,p=n.length===0;if(p){const u={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await Ba(this.fileWriter,t,u,s,n)}return console.log(`\u2705 Project generated in ${i}ms`),{error:p&&n.length===0?void 0:n.join(`
332
+ `),filesCount:s.length,generatedFiles:s,success:p&&n.length===0}}catch(o){return{error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:s,success:!1}}}async generateSingleProject(t,r,s,n,o){const a={dryRun:this.options.dryRun,overwrite:this.options.overwrite},i=[...Ip];r.packageManager==="pnpm"?i.push(zp):r.packageManager==="yarn"?(i.push(Rp),i.push({dest:"yarn.lock",src:"base/yarn.lock.hbs"})):r.packageManager==="bun"&&i.push(Op),await Ha(t,r,this.fileWriter,a,n,o);for(const p of i)await this.renderAndWrite(p.src,p.dest,r,n,o);await this.processTemplateGroups(t,r,s,n,o),await this.processPostTemplateSteps(t,r,n,o)}async generateMonorepo(t,r,s,n,o){const a={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await Wa(t,r,this.fileWriter,a,n,o),await Ka(t,r,this.fileWriter,a,n,o),t.database.length>0&&await Qa(t,r,this.fileWriter,a,n,o),await this.processTemplateGroups(t,r,s,n,o),await this.processPostTemplateSteps(t,r,n,o)}TEMPLATE_FILTERS={"extras/database":Dr,"feature/graphql":qr,"feature/rest/todo-example":$r,"feature/trpc":Nr,"monorepo/feature/graphql":qr,"monorepo/feature/rest/todo-example":$r,"monorepo/feature/trpc":Nr,"monorepo/packages/db":Dr};async processSingleArchTemplates(t,r,s,n){const o=Za[t];if(!o)return;const a=new Set(["package.json","pnpm-workspace.yaml",".yarnrc.yml","bunfig.toml"]);for(const i of o)a.has(i.dest)||await this.renderAndWrite(i.src,i.dest,r,s,n)}async processMonorepoRoot(t,r,s){for(const i of Va)await this.renderAndWrite(i.src,i.dest,t,r,s);const n={bun:{dest:"bunfig.toml",src:"monorepo/root/bunfig.toml.hbs"},pnpm:{dest:"pnpm-workspace.yaml",src:"monorepo/root/pnpm-workspace.yaml.hbs"},yarn:{dest:".yarnrc.yml",src:"monorepo/root/.yarnrc.yml.hbs"}},o=t.packageManager,a=n[o];a&&await this.renderAndWrite(a.src,a.dest,t,r,s)}shouldSkipTemplate(t,r,s){return!!(s&&t.dest==="packages/db/package.json"||t.dest==="docker-compose.yml"||r.architecture==="nest-microservice"&&(t.dest==="src/app.controller.ts"||t.dest==="test/bootstrap.e2e-spec.ts"))}async processTemplateGroups(t,r,s,n,o){const a=t.projectType==="monorepo";for(const i of s){if(!a&&Za[i]){await this.processSingleArchTemplates(i,r,n,o);continue}if(a&&i==="monorepo/root"){await this.processMonorepoRoot(r,n,o);continue}if(!a&&i==="monorepo/packages/db")continue;const p=Qp[i];if(!p)continue;const u=this.TEMPLATE_FILTERS[i],m=u?u(p,r):p;for(const g of m)this.shouldSkipTemplate(g,t,a)||await this.renderAndWrite(g.src,g.dest,r,n,o)}}async processPostTemplateSteps(t,r,s,n){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite},a=t.projectType==="monorepo"?"apps/api-gateway/src/docs/create-docs.ts":"src/docs/create-docs.ts";t.extras.includes("swagger")&&await this.renderAndWrite("extras/swagger/create-docs.ts.hbs",a,r,s,n);for(const[i,p]of Object.entries(ro(t))){const u=await this.fileWriter.writeFile({content:p,filePath:i,isBinary:!1},o);u.written&&s.push(u.filePath)}if(t.extras.includes("docker")&&(t.database.length>0||t.microservices.length>0)){const i=Hs(t),p=await this.fileWriter.writeFile({content:i,filePath:"docker-compose.yml",isBinary:!1},o);p.written&&s.push(p.filePath)}if(t.orm.includes("prisma")&&(await eo(this.fileWriter,t,o,s,n),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,s,n)),t.orm.includes("drizzle")&&await Ws(this.fileWriter,t,o,s,n),t.auth!=="none"){const i=Ci.composeGenerators(t),p=await Vs(t,this.fileWriter.getBaseDir(),i);for(const u of p)!u.success&&u.error&&n.push(u.error)}}async renderAndWrite(t,r,s,n,o){try{const a=await this.templateEngine.renderToFile(t,r,{context:s}),i=await this.fileWriter.writeFile(a,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});i.written&&n.push(i.filePath)}catch(a){const i=a instanceof Error?a.message:String(a);o.push(`Failed to generate ${r}: ${i}`),console.error(`Failed to generate ${r}:`,a)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}class Se{static{c(this,"$")}static{l(this,"ModuleGenerator")}project;config;constructor(t){this.config=t,this.project=new Yr}generate(){const t=this.config.name,r=Se.toPascalCase(t),s=this.config.routePrefix||Se.toKebabCase(t),n={controller:`${t}.controller.ts`,module:`${t}.module.ts`,service:`${t}.service.ts`};return this.generateService(r,t),this.generateController(r,t,s),this.generateModuleFile(r,t),this.config.dtos&&(this.generateDTOs(r,t),n.dto=`dto/create-${Se.toKebabCase(t)}.dto.ts`),this.config.entity&&(this.generateEntity(r,t),n.entity=`entities/${t}.entity.ts`),n}generateService(t,r){const s=j.join(this.config.outputDir,`${r}.service.ts`),n=this.project.createSourceFile(s,"",{overwrite:!0});n.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),n.addClass({decorators:[{arguments:[],name:"Injectable"}],isExported:!0,methods:[{name:"create",parameters:[{name:`create${t}Dto`,type:`Create${t}Dto`}],returnType:"void",statements:["// Create logic here"]},{name:"findAll",returnType:`${t}[]`,statements:["// Find all logic here","return []"]},{name:"findOne",parameters:[{name:"id",type:"string"}],returnType:t,statements:["// Find one logic here",`return { id } as ${t}`]},{name:"update",parameters:[{name:"id",type:"string"},{name:`update${t}Dto`,type:`Update${t}Dto`}],returnType:"void",statements:["// Update logic here"]},{name:"remove",parameters:[{name:"id",type:"string"}],returnType:"void",statements:["// Remove logic here"]}],name:`${t}Service`})}generateController(t,r,s){const n=j.join(this.config.outputDir,`${r}.controller.ts`),o=this.project.createSourceFile(n,"",{overwrite:!0});o.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Controller","Get","Post","Body","Param","Put","Delete"]}),this.config.enableSwagger&&o.addImportDeclaration({moduleSpecifier:"@nestjs/swagger",namedImports:["ApiOperation","ApiResponse","ApiTags"]}),o.addImportDeclaration({moduleSpecifier:`./${r}.service`,namedImports:[`${t}Service`]});const a=[{arguments:[`'${s}'`],name:"Controller"}];this.config.enableSwagger&&a.unshift({arguments:[`'${t}'`],name:"ApiTags"}),o.addClass({ctors:[{parameters:[{isReadonly:!0,name:`${r}Service`,scope:Qr.Private,type:`${t}Service`}]}],decorators:a,isExported:!0,methods:[{decorators:[{name:"Post"}],name:"create",parameters:[{decorators:[{name:"Body"}],name:"createDto"}],statements:[`return this.${r}Service.create(createDto)`]},{decorators:[{name:"Get"}],name:"findAll",statements:[`return this.${r}Service.findAll()`]},{decorators:[{arguments:["':id'"],name:"Get"}],name:"findOne",parameters:[{decorators:[{arguments:["'id'"],name:"Param"}],name:"id"}],statements:[`return this.${r}Service.findOne(id)`]},{decorators:[{arguments:["':id'"],name:"Put"}],name:"update",parameters:[{decorators:[{arguments:["'id'"],name:"Param"}],name:"id"},{decorators:[{name:"Body"}],name:"updateDto"}],statements:[`return this.${r}Service.update(id, updateDto)`]},{decorators:[{arguments:["':id'"],name:"Delete"}],name:"remove",parameters:[{decorators:[{arguments:["'id'"],name:"Param"}],name:"id"}],statements:[`return this.${r}Service.remove(id)`]}],name:`${t}Controller`})}generateModuleFile(t,r){const s=j.join(this.config.outputDir,`${r}.module.ts`),n=this.project.createSourceFile(s,"",{overwrite:!0});n.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Module"]}),n.addImportDeclaration({moduleSpecifier:`./${r}.service`,namedImports:[`${t}Service`]}),n.addImportDeclaration({moduleSpecifier:`./${r}.controller`,namedImports:[`${t}Controller`]}),n.addClass({decorators:[{arguments:[`{
333
+ controllers: [${t}Controller],
334
+ providers: [${t}Service],
335
+ }`],name:"Module"}],isExported:!0,name:`${t}Module`})}generateDTOs(t,r){const s=j.join(this.config.outputDir,"dto"),n=j.join(s,`create-${Se.toKebabCase(r)}.dto.ts`),o=j.join(s,`update-${Se.toKebabCase(r)}.dto.ts`);this.project.createSourceFile(n,"",{overwrite:!0}).addClass({isExported:!0,name:`Create${t}Dto`,properties:[{hasExclamationToken:!0,name:"title",type:"string"},{name:"description",type:"string | undefined"}]});const a=this.project.createSourceFile(o,"",{overwrite:!0});a.addImportDeclaration({moduleSpecifier:"@nestjs/mapped-types",namedImports:["PartialType"]}),a.addImportDeclaration({moduleSpecifier:`./create-${Se.toKebabCase(r)}.dto`,namedImports:[`Create${t}Dto`]}),a.addTypeAlias({isExported:!0,name:`Update${t}Dto`,type:`PartialType(Create${t}Dto)`})}generateEntity(t,r){const s=j.join(this.config.outputDir,`entities/${Se.toKebabCase(r)}.entity.ts`),n=this.project.createSourceFile(s,"",{overwrite:!0});this.config.ormType==="typeorm"?(n.addImportDeclaration({moduleSpecifier:"typeorm",namedImports:["Column","CreateDateColumn","Entity","PrimaryGeneratedColumn","UpdateDateColumn"]}),n.addClass({decorators:[{arguments:[],name:"Entity"}],isExported:!0,name:`${t}Entity`,properties:[{decorators:[{arguments:["'uuid'"],name:"PrimaryGeneratedColumn"}],hasExclamationToken:!0,name:"id",type:"string"},{decorators:[{arguments:[],name:"Column"}],hasExclamationToken:!0,name:"title",type:"string"},{decorators:[{arguments:[],name:"Column"}],name:"description",type:"string | undefined"},{decorators:[{arguments:[],name:"CreateDateColumn"}],hasExclamationToken:!0,name:"createdAt",type:"Date"},{decorators:[{arguments:[],name:"UpdateDateColumn"}],hasExclamationToken:!0,name:"updatedAt",type:"Date"}]})):n.addClass({isExported:!0,name:`${t}Entity`,properties:[{hasExclamationToken:!0,name:"id",type:"string"},{hasExclamationToken:!0,name:"title",type:"string"},{name:"description",type:"string | undefined"},{hasExclamationToken:!0,name:"createdAt",type:"Date"},{hasExclamationToken:!0,name:"updatedAt",type:"Date"}]})}async save(){await this.project.save()}static toPascalCase(t){return t.split(/[-_]/u).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}static toKebabCase(t){return t.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}}const Xp=/Resolved|Resolving/iu,eu=/Downloaded?|downloaded/iu,tu=/Link(ed|ing)/iu,ru=/saved (to )?(lockfile|bun)/iu;function so(e){const t=[],r=e.split(`
336
+ `);for(const s of r){const n=s.trim();if(n){if(Xp.test(n)){t.push({message:"Resolving packages...",phase:"resolve"});continue}if(eu.test(n)){t.push({message:"Downloading...",phase:"download"});continue}if(tu.test(n)){t.push({message:"Linking packages...",phase:"link"});continue}if(n.includes("packages installed")){t.push({message:n,percentage:100,phase:"link"});continue}if(ru.test(n)){t.push({message:"Saving lockfile...",phase:"postinstall"});continue}(n.includes("[script]")||n.includes("postinstall"))&&t.push({message:"Running postinstall scripts...",phase:"postinstall"})}}return t}c(so,"tc"),l(so,"parseBunText");class su{static{c(this,"rc")}static{l(this,"BunInstaller")}async install(t,r,s){const n=it("bun install",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const a=l(p=>{const u=p.toString();o+=u;const m=so(u);for(const g of m)r?.(g)},"handleData");n.stderr.on("data",a),n.stdout.on("data",a);const[i]=await Promise.race([ve(n,"close"),ve(n,"error").then(([p])=>{const u=p;throw u.code==="ENOENT"||u.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(`
337
+ `)):new Error(u.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`bun install exited with code ${i}`)}}const nu=/^(\d+)\/(\d+)\s+resolving/iu,au=/^(\d+)\/(\d+)\s+extract:/iu,ou=/^(\d+)\/(\d+)\s+(\S+)/iu,iu=/^(\d+)ms\s+(.*)/iu;function no(e){const t=[],r=e.split(`
338
+ `);for(const s of r){const n=s.trim();if(n.includes("resolving")){const o=nu.exec(n);o?t.push({completed:Number(o[1]),message:"Resolving packages...",percentage:Math.round(Number(o[1])/Number(o[2])*100),phase:"resolve",total:Number(o[2])}):t.push({message:"Resolving packages...",phase:"resolve"});continue}if(n.includes("extract:")||n.includes("http fetch")){const o=au.exec(n)||ou.exec(n);o?t.push({completed:Number(o[1]),message:"Downloading...",percentage:Math.round(Number(o[1])/Number(o[2])*100),phase:"download",total:Number(o[2])}):t.push({message:"Downloading...",phase:"download"});continue}if(n.includes("timing")){const o=iu.exec(n);if(o){const a=o[2]??"";a.includes("build")?t.push({message:"Building dependencies...",phase:"build"}):a.includes("link")&&t.push({message:"Linking packages...",phase:"link"})}continue}n.includes("postinstall")&&!n.includes("timing")&&t.push({message:"Running postinstall scripts...",phase:"postinstall"})}return t}c(no,"ic"),l(no,"parseNpmText");class cu{static{c(this,"cc")}static{l(this,"NpmInstaller")}async install(t,r,s){const n=it("npm install --loglevel silly",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const a=l(p=>{const u=p.toString();o+=u;const m=no(u);for(const g of m)r?.(g)},"handleData");n.stderr.on("data",a),n.stdout.on("data",()=>{});const[i]=await Promise.race([ve(n,"close"),ve(n,"error").then(([p])=>{const u=p;throw u.code==="ENOENT"||u.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(`
339
+ `)):new Error(u.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`npm install exited with code ${i}`)}}const lu={importing_done:{message:"Finishing installation...",phase:"link"},importing_started:{message:"Linking packages...",phase:"link"},resolution_done:{message:"Downloading packages...",phase:"download"},resolution_started:{message:"Resolving packages...",phase:"resolve"}},pu={fetched:{message:"Downloading packages...",phase:"download"},found_in_store:{message:"Reusing cached packages...",phase:"download"},imported:{message:"Linking packages...",phase:"link"},resolved:{message:"Resolving packages...",phase:"resolve"}};function ao(e){if(!e||typeof e!="object")return null;const t="name"in e?e.name:void 0,r="level"in e?e.level:void 0,s="message"in e?e.message:void 0;if(t==="pnpm:install-check"&&r==="warn"&&typeof s=="string"&&s.startsWith("Unsupported platform"))return null;if(r==="error"||r==="warn"){const n="err"in e?e.err:void 0,o=n&&typeof n=="object"&&"message"in n?n.message:void 0;let a=JSON.stringify(e);return typeof s=="string"?a=s:typeof o=="string"&&(a=o),{message:a,phase:"download"}}switch(t){case"pnpm:stage":return"stage"in e&&typeof e.stage=="string"?lu[e.stage]??null:null;case"pnpm:progress":return"status"in e&&typeof e.status=="string"?pu[e.status]??null:null;case"pnpm:lifecycle":return{message:"Running dependency scripts...",phase:"build"};default:return null}}c(ao,"lc"),l(ao,"parsePnpmLine");class uu{static{c(this,"dc")}static{l(this,"PnpmInstaller")}async install(t,r,s){const n=it("pnpm install --reporter ndjson",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="",a="",i="";n.stdout.on("data",u=>{const m=u.toString();a+=m,i+=m;const g=i.split(`
340
+ `);i=g.pop()??"";for(const b of g)try{const S=JSON.parse(b),P=ao(S);P&&r&&r(P)}catch{}}),n.stderr.on("data",u=>{o+=u.toString()});const[p]=await Promise.race([ve(n,"close"),ve(n,"error").then(([u])=>{const m=u;throw m.code==="ENOENT"||m.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(`
341
+ `)):new Error(m.message)})]);if(p===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(`pnpm install exited with code ${p}
342
+ ${o.trim()}
343
+ ${a.slice(-2e4)}`)}}function oo(e){switch(e.type){case"step":{const t=e.displayName??"";return t.includes("Resolution")?{message:"Resolving packages...",phase:"resolve"}:t.includes("Fetch")?{message:"Downloading...",phase:"download"}:t.includes("Link")?{message:"Linking packages...",phase:"link"}:t.includes("Build")?{message:"Building dependencies...",phase:"build"}:{message:t||"Installing...",phase:"postinstall"}}case"progress":{const t=typeof e.data=="object"?e.data:void 0,r=t?.current,s=t?.total;return r!==void 0&&s!==void 0?{completed:r,message:"Processing...",percentage:Math.round(r/s*100),phase:"download",total:s}:null}case"success":return{message:typeof e.data=="string"?e.data:e.data?.message??"Done",percentage:100,phase:"complete"};case"error":return{message:typeof e.data=="string"?e.data:e.data?.message??"Error",phase:"download"};default:return null}}c(oo,"mc"),l(oo,"parseYarnLine");class du{static{c(this,"hc")}static{l(this,"YarnInstaller")}async install(t,r,s){const n=it("yarn install --json",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";n.stdout.on("data",i=>{const p=i.toString().split(`
344
+ `).filter(Boolean);for(const u of p)try{const m=JSON.parse(u),g=oo(m);g&&r&&r(g)}catch{}}),n.stderr.on("data",i=>{o+=i.toString()});const[a]=await Promise.race([ve(n,"close"),ve(n,"error").then(([i])=>{const p=i;throw p.code==="ENOENT"||p.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(`
345
+ `)):new Error(p.message)})]);if(a===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`yarn install exited with code ${a}`)}}function io(e){switch(e){case"pnpm":return new uu;case"npm":return new cu;case"yarn":return new du;case"bun":return new su;default:throw new Error(`Unhandled package manager: ${e}`)}}c(io,"gr"),l(io,"createPackageInstaller");class mu{static{c(this,"fc")}static{l(this,"ProjectPipeline")}outputDir;generatorOptions;state;context;events;constructor(t,r){this.outputDir=t,this.generatorOptions=r}emit(t){this.events?.onStageChange?.(t)}addPhase(t){this.state.phases.push(t)}async execute(t,r){this.context=t,this.events=r,this.state={generatedFiles:[],installSucceeded:!1,phases:[]};const s=[this.phaseGenerateFiles,this.phaseInstallAgentSkills,this.phaseSetupLinter,this.phaseGitInit,this.phaseInstallDependencies,this.phaseRunFormatter,this.phaseFormatterCommit];for(const o of s)if(!await o.call(this))break;this.emit("complete");const n=this.state.phases.every(o=>o.success||o.skipped);return this.buildResult(n)}async phaseGenerateFiles(){this.emit("generate-files");const t=new Yp(this.outputDir,this.generatorOptions);try{const r=await t.generate(this.context);return this.state.generatedFiles.push(...r.generatedFiles),r.success?(this.addPhase({phase:"generate-files",success:!0}),!0):(this.addPhase({error:r.error,phase:"generate-files",success:!1}),!1)}catch(r){return this.addPhase({error:r instanceof Error?r.message:String(r),phase:"generate-files",success:!1}),!1}}async phaseInstallAgentSkills(){if(!this.context.addons.includes("agent-skills"))return this.addPhase({phase:"install-agent-skills",skipped:!0,success:!0}),!0;this.emit("install-agent-skills");try{const t=await js(this.outputDir,this.context),r=t.failed.length>0?t.failed.map(s=>`${s.name}: ${s.error}`).join(", "):void 0;this.addPhase({phase:"install-agent-skills",success:!0,...r?{error:r}:{}})}catch(t){this.addPhase({error:t instanceof Error?t.message:String(t),phase:"install-agent-skills",success:!0})}return!0}async phaseSetupLinter(){if(this.context.formatter==="none")return this.addPhase({phase:"setup-linter",skipped:!0,success:!0}),!0;this.emit("setup-linter");try{const t=await zs(this.outputDir,this.context);if(!t.success)return this.addPhase({error:t.message,phase:"setup-linter",success:!1}),!1;const r=this.context.addons.includes("ultracite")&&this.context.formatter!=="biome"?await Ds(this.outputDir,this.context.formatter):{success:!0};return r.success?(this.addPhase({phase:"setup-linter",success:!0}),!0):(this.addPhase({error:r.message??"Rule injection failed",phase:"setup-linter",success:!1}),!1)}catch(t){return this.addPhase({error:t instanceof Error?t.message:String(t),phase:"setup-linter",success:!1}),!1}}async phaseGitInit(){if(!this.context.initGit)return this.addPhase({phase:"initialize-git",skipped:!0,success:!0}),this.addPhase({phase:"initial-commit",skipped:!0,success:!0}),!0;this.emit("initialize-git");try{await Wt(this.outputDir)||await Ht(this.outputDir),this.addPhase({phase:"initialize-git",success:!0})}catch(r){this.addPhase({error:r instanceof Error?r.message:String(r),phase:"initialize-git",success:!1})}const{3:t}=this.state.phases;if(t?.success??!1){this.emit("initial-commit");try{await ft(this.outputDir),await gt(this.outputDir,"Initial project scaffold"),this.addPhase({phase:"initial-commit",success:!0})}catch(r){this.addPhase({error:r instanceof Error?r.message:String(r),phase:"initial-commit",success:!1})}}else this.addPhase({phase:"initial-commit",skipped:!0,success:!0});return!0}async phaseInstallDependencies(){if(!this.context.installDependencies)return this.addPhase({phase:"install-dependencies",skipped:!0,success:!0}),!0;this.emit("install-dependencies");try{await io(this.context.packageManager).install(this.outputDir,t=>{this.events?.onInstallProgress?.(t)}),this.state.installSucceeded=!0,this.addPhase({phase:"install-dependencies",success:!0})}catch(t){this.addPhase({error:t instanceof Error?t.message:String(t),phase:"install-dependencies",success:!1})}return!0}async phaseRunFormatter(){if(!(this.state.installSucceeded&&this.context.formatter!=="none"))return this.addPhase({phase:"run-formatter",skipped:!0,success:!0}),!0;this.emit("run-formatter");try{const t=await Ts(this.context.packageManager,this.outputDir);this.addPhase({phase:"run-formatter",success:t.success,...t.success?{}:{error:t.error}})}catch(t){this.addPhase({error:t instanceof Error?t.message:String(t),phase:"run-formatter",success:!1})}return!0}async phaseFormatterCommit(){const t=this.state.phases.find(r=>r.phase==="run-formatter");if(!(this.context.initGit&&t?.success&&!t.skipped))return this.addPhase({phase:"formatter-commit",skipped:!0,success:!0}),!0;this.emit("formatter-commit");try{await ft(this.outputDir),await Ss(this.outputDir)&&await gt(this.outputDir,"Apply formatter"),this.addPhase({phase:"formatter-commit",success:!0})}catch(r){this.addPhase({error:r instanceof Error?r.message:String(r),phase:"formatter-commit",success:!1})}return!0}buildResult(t){return{generatedFiles:this.state.generatedFiles,outputDir:this.outputDir,phases:this.state.phases,success:t}}}const hu=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","prismaVersion","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","installing","done"];function Mr(e){return e.includes("mongodb")}c(Mr,"databaseIncludesMongodb");function co(e){return e.length===0}c(co,"databaseIsEmpty");function zt(e){return e.includes("rest")||e.includes("trpc")||e.includes("graphql")}c(zt,"hasApiLayer");function Xe(e){return co(e)}c(Xe,"shouldSkipOrmStep");function Rt(e){return e.includes("prisma")}c(Rt,"usesPrisma");function fu(e,t){return Rt(e)?Mr(t)?"8":t.includes("mysql")||t.includes("sqlite")?"7":null:null}c(fu,"resolvePrismaVersion");function lo(e,t){return!!(!Rt(e)||co(t)||Mr(t)||t.includes("mysql")||t.includes("sqlite"))}c(lo,"shouldSkipPrismaVersionStep");function gu(e,t){return lo(e,t)?[]:hs}c(gu,"filterPrismaVersionOptions");function po(e,t,r){if(!Rt(e))return null;const s=fu(e,t);return s||(r??null)}c(po,"sanitizePrismaVersionForOrm");function et(e){return hu.filter(t=>t==="orm"&&Xe(e.database)||t==="prismaVersion"&&lo(e.orm,e.database)||t==="auth"&&!zt(e.api)?!1:t==="microservices"?e.architecture==="nest-microservice":!((t==="ultraciteEditors"||t==="ultraciteAgents"||t==="ultraciteHooks"||t==="ultraciteInstallSkill")&&(!e.addons.includes("ultracite")||e.formatter==="none")))}c(et,"getVisibleSteps");const uo=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function tt(e){return uo.includes(e)}c(tt,"isUltraciteSubStep");function yu(e,t){if(!tt(e))return null;const r=uo.filter(i=>et(t).includes(i)),s=r.indexOf(e);if(s===-1)return null;const n=r.length,o=s+1,a=Math.round(o/n*100);return{current:o,percent:a,total:n}}c(yu,"getUltraciteSubStepInfo");function Fr(e){return et(e).filter(t=>t!=="installing"&&t!=="done"&&!tt(t)).length}c(Fr,"getTotalSteps");function bu(e,t){const r=et(t).filter(o=>o!=="installing"&&o!=="done");if(e==="installing"||e==="done")return Fr(t);if(tt(e)){const o=r.indexOf("addons");return o===-1?1:o+1}const n=r.filter(o=>!tt(o)).indexOf(e);return n===-1?1:n+1}c(bu,"getDisplayStepNumber");function vu(e,t){const r=et(t),s=r.indexOf(e);return s===-1||s>=r.length-1?null:r[s+1]??null}c(vu,"getNextStepId");function wu(e,t){const r=et(t),s=r.indexOf(e);return s<=0?null:r[s-1]??null}c(wu,"getPreviousStepId");function ju(e){return e==="monorepo"?ds:ds.filter(t=>t.value!=="nest-gateway")}c(ju,"filterArchitectureOptions");function mo(e){return Mr(e)?[]:ms}c(mo,"filterOrmOptions");function Gr(e){return{addons:e.addons??[],api:e.api??["rest"],architecture:e.architecture??"nest-api",auth:e.auth??"none",database:e.database??[],extras:e.extras??[],httpProvider:e.httpProvider??"express",microservices:e.microservices??[],orm:e.orm??[],prismaVersion:e.prismaVersion??(e.orm?.includes("prisma")?"7":void 0),projectType:e.projectType??"single"}}c(Gr,"wizardSupportContext");function Ur(e){return Ze(Gr(e)).length===0}c(Ur,"isWizardSelectionSupported");function Su(e,t={}){return e.length>0?Zt.filter(r=>r.value!=="mongodb"):Zt.filter(({value:r})=>r!=="mongodb"||Ur({...t,addons:[],api:["rest"],auth:"none",database:[r],extras:[],orm:[]}))}c(Su,"filterDatabaseOptions");function ho(e,t=[],r={}){return gs.filter(({value:s})=>s==="none"||Ze({...Gr(r),auth:s,database:e,orm:t,prismaVersion:t.includes("prisma")?r.prismaVersion??"7":void 0}).length===0)}c(ho,"filterAuthOptions");function Ot(e,t,r,s={}){return ho(t,r,s).some(({value:n})=>n===e)?e:null}c(Ot,"sanitizeAuthForDatabase");function ku(e,t={}){return fs.filter(({value:r})=>Ze({...Gr(t),addons:[],api:[r],auth:"none",database:e,extras:[]}).length===0)}c(ku,"filterApiOptions");function _u(e,t){return t.includes("drizzle")?e.filter(r=>r!=="mongodb"):e}c(_u,"sanitizeDatabaseForOrm");function fo(e){return"nest-api"}c(fo,"defaultArchitecture");function go(e,t){if(Xe(t))return[];const r=new Set(mo(t).map(s=>s.value));return e.filter(s=>r.has(s))}c(go,"sanitizeOrmForDatabase");function Pe(e,t){return e.find(r=>r.value===t)?.label??t}c(Pe,"labelFor");function $e(e,t){return t.length===0?"None":t.map(r=>Pe(e,r)).join(", ")}c($e,"labelsFor");const xu=c(({onConfirm:e,state:t})=>{Re((n,o)=>{o.return&&e()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},s=[{label:"Project",value:Te(t.projectName)},{label:"Package manager",value:t.packageManager?Pe(cs,t.packageManager):"\u2014"},{label:"Formatter",value:t.formatter?Pe(ls,t.formatter):"\u2014"},{label:"HTTP provider",value:t.httpProvider?Pe(ps,t.httpProvider):"\u2014"},{label:"Project type",value:t.projectType?Pe(us,t.projectType):"\u2014"},{label:"Architecture",value:t.architecture?r[t.architecture]??t.architecture:"\u2014"},{label:"Database",value:$e(Zt,t.database)}];return Xe(t.database)||s.push({label:"ORM",value:$e(ms,t.orm)}),Rt(t.orm)&&t.prismaVersion&&s.push({label:"Prisma",value:Pe(hs,t.prismaVersion)}),s.push({label:"API layer",value:$e(fs,t.api)}),t.architecture==="nest-gateway"&&s.push({label:"Microservices",value:$e([{label:"Redis",value:"redis"},{label:"MQTT",value:"mqtt"},{label:"NATS",value:"nats"},{label:"RabbitMQ",value:"rabbitmq"},{label:"Kafka",value:"kafka"},{label:"gRPC",value:"grpc"}],t.microservices)}),zt(t.api)&&s.push({label:"Auth",value:t.auth?Pe(gs,t.auth):"\u2014"}),s.push({label:"Extras",value:$e(Vt,t.extras)},{label:"Addons",value:$e(ys,t.addons)},{label:"Git",value:t.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:t.installDependencies==="yes"?"Install":"Skip"}),w(V,{children:[d(v,{flexDirection:"column",marginBottom:1,children:w(h,{children:[d(h,{color:z,children:"\u2726 "}),d(h,{color:ie,children:"Review your selections"})]})}),d(v,{flexDirection:"column",rowGap:0,overflow:"hidden",children:s.map(n=>w(v,{flexDirection:"row",columnGap:1,children:[d(h,{color:Ao,children:`${n.label}:`}),d(h,{color:_e,children:n.value})]},n.label))})]})},"SummaryStep");function Ct(e){return e.length===0?"\u2014":e.join(", ")}c(Ct,"formatList");const Tu=c(({state:e,stepId:t})=>{const{stdout:r}=Ut(),s=r.columns||r.getWindowSize?.()[0]||80,n=Math.min(mt.APP_MAX_WIDTH,s-4),o=[];if(t!=="projectName"&&e.projectName.trim()&&o.push(Te(e.projectName)),e.packageManager&&o.push(e.packageManager),e.httpProvider&&o.push(e.httpProvider),e.projectType&&o.push(e.projectType==="monorepo"?"Monorepo":"Single"),e.architecture){const p={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};o.push(p[e.architecture]??e.architecture)}if(e.database.length>0&&o.push(Ct(e.database)),e.orm.length>0&&o.push(Ct(e.orm)),e.orm.includes("prisma")&&e.prismaVersion&&o.push(`Prisma ${e.prismaVersion}`),e.api.length>0&&o.push(Ct(e.api)),e.auth&&o.push(e.auth),e.formatter){const p={biome:"Biome",none:"No formatter","oxlint-oxfmt":"Oxlint+Oxfmt"};o.push(p[e.formatter]??e.formatter)}if(e.microservices.length>0&&o.push(Ct(e.microservices)),e.installDependencies&&o.push(e.installDependencies==="yes"?"install: yes":"install: no"),e.extras.length>0&&o.push(`+${e.extras.length} extras`),e.addons.length>0&&!tt(t)&&o.push(`+${e.addons.length} addons`),e.initGit&&o.push(e.initGit==="yes"?"git init":"no git"),o.length===0)return w(h,{children:[d(h,{color:z,children:"\u25C6 "}),d(h,{color:z,children:"Create a new NestJS project"})]});const[a,...i]=o;return w(V,{children:[w(h,{children:[d(h,{color:z,children:"\u25C6 "}),d(h,{color:z,children:"Create a new NestJS project"})]}),t!=="summary"&&d(v,{borderStyle:"single",borderColor:Oe,width:n,children:w(h,{children:[d(h,{children:"Project Name: "}),d(h,{color:z,children:a}),d(h,{color:O,children:" Selected: "}),i.length>0?d(h,{color:O,children:`${i.filter(p=>p!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),Au=c(({displayStep:e,stepId:t,subProgress:r,totalSteps:s})=>w(v,{paddingLeft:2,paddingTop:t==="summary"?2:1,marginBottom:1,children:[d(h,{color:H,children:"Create project"}),d(h,{color:O,children:` \u2014 step ${e}/${s}`}),r?d(h,{color:ie,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):d(h,{color:ie,children:` \xB7 ${ai[t]}`})]}),"WizardTitle$1"),Lr=ee(pt(),".nestarch"),Jr=ee(Lr,"last-used.json");function Eu(){try{if(!lt(Jr))return null;const e=Co(Jr,"utf-8");return JSON.parse(e)}catch{return null}}c(Eu,"getLastUsedConfig");function yo(e){try{lt(Lr)||Do(Lr,{recursive:!0}),No(Jr,JSON.stringify(e,null,2),"utf-8")}catch{}}c(yo,"saveLastUsedConfig");function Pu(e){const t=[e.packageManager];e.httpProvider&&t.push(e.httpProvider),e.api.length>0&&t.push(e.api.join(", ")),e.projectType&&t.push(e.projectType);const r=new Date,s=r.toLocaleString("en-US",{month:"short"}),n=r.getDate(),o=r.getFullYear(),a=`${s} ${n}, ${o}`;return`${t.join(", ")} (last used ${a})`}c(Pu,"buildLastUsedDescription");function Iu(e){return{addons:e.addons,api:e.api,architecture:e.architecture,auth:e.auth,database:e.database,description:`${e.projectName} NestJS application`,extras:e.extras,formatter:e.formatter,httpProvider:e.httpProvider,initGit:e.initGit==="yes",installDependencies:e.installDependencies==="yes",microservices:e.microservices,orm:e.orm,packageManager:e.packageManager,prismaVersion:e.prismaVersion,projectName:e.projectName,projectType:e.projectType,ultraciteAgents:e.ultraciteAgents,ultraciteEditors:e.ultraciteEditors,ultraciteHooks:e.ultraciteHooks,ultraciteInstallSkill:e.ultraciteInstallSkill}}c(Iu,"buildGeneratorContext");function Dt(e){return mt.NEST_ARCH_BETA_MODE?ee(pt(),"test-projects",e):ee(process.cwd(),e)}c(Dt,"getOutputDir");function zu(){const e=import.meta.dirname;if(e){const r=ee(e,"templates");if(lt(r))return r}return ee(e??process.cwd(),"..","..","..","..","packages","core","templates")}c(zu,"getTemplatesDir");async function bo(e,t){const r=Dt(e.projectName),s=Iu(e),n=zu(),o=new mu(r,{cacheTemplates:!0,templatesDir:n});try{const a=await o.execute(s,t),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"},p=a.phases.filter(u=>!u.success&&!u.skipped&&u.error).map(u=>`${i[u.phase]||u.phase} failed:
346
+ ${u.error}`);return p.length>0?{message:p.join(`
347
+
348
+ `),outputDir:r,success:!1}:{message:`Project created with ${a.generatedFiles.length} files`,outputDir:r,success:!0}}catch(a){return{message:`Failed to generate project: ${a instanceof Error?a.message:String(a)}`,outputDir:r,success:!1}}}c(bo,"generateProject");const Ru=c(()=>({addons:[],api:[],architecture:null,auth:null,database:[],extras:[],formatter:null,httpProvider:null,initGit:null,installDependencies:null,microservices:[],orm:[],packageManager:null,prismaVersion:null,projectName:"",projectType:null,ultraciteAgents:[],ultraciteEditors:[],ultraciteHooks:[],ultraciteInstallSkill:null}),"initialState");function vo(e){return!e.packageManager||!e.formatter||!e.httpProvider||!e.projectType||!e.architecture||!e.initGit||!e.installDependencies?null:{addons:e.addons,api:e.api,architecture:e.architecture,auth:e.auth??"none",database:e.database,extras:e.extras,formatter:e.formatter,httpProvider:e.httpProvider,initGit:e.initGit,installDependencies:e.installDependencies,microservices:e.architecture==="nest-microservice"?e.microservices:[],orm:Xe(e.database)?[]:e.orm,packageManager:e.packageManager,prismaVersion:Xe(e.database)?void 0:e.prismaVersion??void 0,projectName:Te(e.projectName),projectType:e.projectType,ultraciteAgents:e.ultraciteAgents,ultraciteEditors:e.ultraciteEditors,ultraciteHooks:e.ultraciteHooks,ultraciteInstallSkill:e.ultraciteInstallSkill??"no"}}c(vo,"buildResult");const Ou=c(({onBack:e,onExit:t,onStepChange:r})=>{const[s,n]=$("projectName"),o=at(s);o.current=s;const[a,i]=$(Ru),[p,u]=$(null),[m,g]=$(null),[b,S]=$(null),[P,T]=$(null),M=X(()=>Fr(a),[a]),W=X(()=>bu(s,a),[s,a]),B=X(()=>yu(s,a),[s,a]);Wr(()=>{if(!m||m.isError)return;const E=vo(a);E&&yo(E),n("done"),r?.("done")},[m,a,r]);const F=N(E=>{const A=vu(o.current,E);A&&(n(A),r?.(A))},[r]),se=N(()=>{const E=wu(s,a);if(E){n(E),r?.(E);return}e()},[e,a,s,r]),L=c(E=>N(A=>{i(_=>{const C={..._,[E]:A};return C.auth=Ot(C.auth,C.database,C.orm,C),F(C),C})},[E]),"useStepFieldHandler"),K=L("packageManager"),I=L("formatter"),q=L("httpProvider"),Z=L("auth"),ne=L("prismaVersion"),ce=L("microservices"),Me=L("addons"),Fe=L("ultraciteEditors"),Ge=L("ultraciteAgents"),Ie=L("ultraciteHooks"),rt=L("ultraciteInstallSkill"),R=L("initGit"),ue=L("installDependencies"),ze=N(()=>{const E=dt(a.projectName);if(E){u(E);return}const A=Te(a.projectName),_=Dt(A);if(lt(_)){u(`Directory "${_}" already exists. Choose a different name or delete the existing directory.`);return}const C={...a,projectName:A};i(C),F(C)},[F,a]),ge=N(E=>{const A=E==="single"&&a.architecture==="nest-gateway"?fo():a.architecture??fo(),_={...a,architecture:A,extras:E==="single"?a.extras.filter(C=>C!=="packages/shared"):a.extras,microservices:A==="nest-microservice"?a.microservices:[],projectType:E};i(_),F(_)},[F,a]),D=N(E=>{const A={...a,architecture:E,microservices:E==="nest-microservice"?a.microservices:[]};i(A),F(A)},[F,a]),ke=N(E=>{const A=E==="none"?[]:[E],_=go(a.orm,A),C=A.length===0,de={...a,api:C?a.api.filter(fe=>fe!=="graphql"):a.api,auth:Ot(a.auth,A,_,a),database:A,orm:_,prismaVersion:po(_,A,a.prismaVersion)};i(de),F(de)},[F,a]),$t=N(E=>{const A=E==="none"?[]:[E],_=_u(a.database,A),C=go(A,_),de={...a,auth:Ot(a.auth,_,C,a),database:_,orm:C,prismaVersion:po(C,_,a.prismaVersion)};i(de),F(de)},[F,a]),x=N(E=>{const A=E.includes("graphql")&&E.length>1?[E.at(-1)??"rest"]:E,_=zt(A),C={...a,addons:_?a.addons:a.addons.filter(de=>de!=="scalar-ui"),api:A,auth:_?Ot(a.auth,a.database,a.orm,{...a,api:A}):null,extras:_?a.extras:a.extras.filter(de=>de==="docker"||de==="packages/shared")};i(C),F(C)},[F,a]),st=N(E=>{const A=E.includes("swagger"),_={...a,addons:A?a.addons:a.addons.filter(C=>C!=="scalar-ui"),extras:E};i(_),F(_)},[F,a]),Mt=X(()=>{const E=a.projectType==="monorepo"?Vt:Vt.filter(A=>A.value!=="packages/shared");return zt(a.api)?E.filter(({value:A})=>Ur({...a,extras:[...a.extras,A]})):E.filter(A=>A.value==="docker"||A.value==="packages/shared")},[a]),nt=N(async()=>{const E=vo(a);if(E){n("installing"),r?.("installing");try{const A=await bo(E,{onInstallProgress:c(_=>{T(_)},"onInstallProgress"),onStageChange:c(_=>{S(_)},"onStageChange")});g({isError:!A.success,message:A.message})}catch(A){g({isError:!0,message:`Error: ${A instanceof Error?A.message:String(A)}`})}}},[a,r]),Ft=N(()=>{n("summary"),r?.("summary"),g(null)},[r]),Gt=X(()=>s==="projectName"||s==="summary"?"confirm":s==="database"||s==="orm"||s==="apiLayer"||s==="extras"||s==="microservices"||s==="addons"||s==="ultraciteEditors"||s==="ultraciteAgents"||s==="ultraciteHooks"?"select":s==="installing"&&m?.isError?"confirm":"select",[s,m?.isError]);return{architectureOpts:X(()=>ju(a.projectType),[a.projectType]),currentStage:b,displayStep:W,extrasStepOptions:Mt,generationStatus:m,goBack:se,handleAddons:Me,handleApi:x,handleArchitecture:D,handleAuth:Z,handleDatabase:ke,handleExtras:st,handleFormatter:I,handleHttpProvider:q,handleInitGit:R,handleInstallDependencies:ue,handleMicroservices:ce,handleOrm:$t,handlePackageManager:K,handlePrismaVersion:ne,handleProjectNameSubmit:ze,handleProjectType:ge,handleRetry:Ft,handleSummaryConfirm:nt,handleUltraciteAgents:Ge,handleUltraciteEditors:Fe,handleUltraciteHooks:Ie,handleUltraciteInstallSkill:rt,installProgress:P,projectNameError:p,setProjectNameError:u,setState:i,state:a,statusAction:Gt,stepId:s,subProgress:B,totalSteps:M}},"useCreateProjectWizard"),Cu=c(({onBack:e,onDone:t,onExit:r,onStepChange:s})=>{const{architectureOpts:n,currentStage:o,displayStep:a,extrasStepOptions:i,generationStatus:p,goBack:u,handleProjectNameSubmit:m,handlePackageManager:g,handleFormatter:b,handleHttpProvider:S,handleProjectType:P,handleArchitecture:T,handleDatabase:M,handleOrm:W,handlePrismaVersion:B,handleApi:F,handleAuth:se,handleExtras:L,handleMicroservices:K,handleAddons:I,handleUltraciteEditors:q,handleUltraciteAgents:Z,handleUltraciteHooks:ne,handleUltraciteInstallSkill:ce,handleInitGit:Me,handleInstallDependencies:Fe,handleRetry:Ge,handleSummaryConfirm:Ie,installProgress:rt,projectNameError:R,setProjectNameError:ue,setState:ze,statusAction:ge,stepId:D,subProgress:ke,totalSteps:$t,state:x}=Ou({onBack:e,onExit:r,onStepChange:s}),[st,Mt]=$([]),[nt]=$([]),Ft=X(()=>{const _=new Set;return x.initGit==="no"&&(_.add("initialize-git"),_.add("initial-commit")),x.installDependencies==="no"&&_.add("install-dependencies"),(x.formatter==="none"||x.installDependencies==="no")&&(_.add("setup-linter"),_.add("run-formatter")),(x.initGit==="no"||_.has("run-formatter"))&&_.add("formatter-commit"),x.addons.includes("agent-skills")||_.add("install-agent-skills"),[..._]},[x.initGit,x.installDependencies,x.formatter,x.addons]),Gt=X(()=>ys.filter(_=>_.value==="ultracite"&&x.formatter==="none"||_.value==="scalar-ui"&&!x.extras.includes("swagger")?!1:Ur({...x,addons:[...x.addons,_.value]})),[x]),Hr=X(()=>{let _=x;return D==="addons"&&(_={..._,addons:st}),D==="database"&&(_={..._,database:nt}),Fr(_)},[D,x,st,nt,$t]);ye(()=>{D==="done"&&t()},[D,t]),Re((_,C)=>{if(C.ctrl&&_==="c"){r();return}if(C.ctrl&&_==="b"&&D!=="done"){u();return}if(D==="done"&&C.return){r();return}D==="installing"&&p?.isError&&C.return&&Ge()});const E=c(()=>{const C={architecture:{options:n,prompt:"Choose an application architecture"},auth:{options:ho(x.database,x.orm,x),prompt:"Choose an authentication strategy"},formatter:{options:ls,prompt:"Choose a formatter-linter (with ultracite preset) setup"},httpProvider:{options:ps,prompt:"Choose an HTTP provider"},initGit:{options:bs,prompt:"Initialize a git repository?"},installDependencies:{options:ei,prompt:"Install dependencies?"},packageManager:{options:cs,prompt:"Choose a package manager"},projectType:{options:us,prompt:"Choose a project layout"},ultraciteInstallSkill:{options:ni,prompt:"Install Ultracite skill?"}}[D];if(C)return d(Je,{onConfirm:{architecture:T,auth:se,formatter:b,httpProvider:S,initGit:Me,installDependencies:Fe,packageManager:g,projectType:P,ultraciteInstallSkill:ce}[D],options:C.options,prompt:C.prompt},D);const fe={addons:{initialSelected:x.addons,onChange:Mt,options:Gt,prompt:"Select addons (optional)"},apiLayer:{initialSelected:x.architecture==="nest-api"&&x.api.length===0?["rest"]:x.api,options:ku(x.database,x),prompt:"Select API layers (optional)"},extras:{initialSelected:x.extras,options:i,prompt:"Select extras (optional)"},microservices:{initialSelected:x.microservices,options:Xo,prompt:"Select microservice communication protocols"},ultraciteAgents:{initialSelected:x.ultraciteAgents,minified:!0,options:ri,prompt:"Select Ultracite agents"},ultraciteEditors:{initialSelected:x.ultraciteEditors,minified:!0,options:ti,prompt:"Select Ultracite editors"},ultraciteHooks:{initialSelected:x.ultraciteHooks,options:si,prompt:"Select Ultracite hooks"}}[D];if(fe){const le={addons:I,apiLayer:F,extras:L,microservices:K,ultraciteAgents:Z,ultraciteEditors:q,ultraciteHooks:ne};return d(Qo,{exclusiveValue:D==="apiLayer"?"graphql":void 0,initialSelected:fe.initialSelected,onConfirm:le[D],options:fe.options,prompt:fe.prompt,...fe.minified?{minified:!0}:{},...fe.onChange?{onChange:fe.onChange}:{}},D)}switch(D){case"projectName":return d(is,{error:R,onChange:c(le=>{ze(ko=>({...ko,projectName:le})),ue(dt(le))},"onChange"),onSubmit:m,value:x.projectName});case"database":{const le={description:"Skip database scaffolding for now",label:"No database",value:"none"};return d(Je,{initialValue:x.database[0]??"none",onConfirm:M,options:[le,...Su(x.orm,x)],prompt:"Select a database for your project (optional)"},"database")}case"orm":{const le={description:"Use plain database access without an ORM",label:"No ORM",value:"none"};return d(Je,{initialValue:x.orm[0]??"none",onConfirm:W,options:[le,...mo(x.database)],prompt:"Select an ORM to include"},"orm")}case"prismaVersion":return d(Je,{initialValue:x.prismaVersion??"7",onConfirm:B,options:gu(x.orm,x.database),prompt:"Select a Prisma version"},"prismaVersion");case"summary":return d(xu,{onConfirm:Ie,state:x});case"installing":return w(v,{flexDirection:"column",children:[d(ss,{currentStage:o,generationMessage:p?.message??"Scaffolding your project",installProgress:rt,isError:p?.isError??!1,packageManager:x.packageManager??void 0,skippedStages:Ft}),p?.isError?d(v,{marginTop:1,children:w(h,{color:O,children:["Press ",d(h,{color:z,children:"Enter"})," to go back to Summary and retry, or ",d(h,{color:O,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const le=Te(x.projectName);return d(ns,{architecture:x.architecture||"nest-api",projectName:le,packageManager:x.packageManager||"pnpm",dependenciesInstalled:x.installDependencies==="yes",isGitInitialized:x.initGit==="yes",outputDir:Dt(le)})}default:return null}},"renderStep"),A=D!=="installing"&&D!=="done";return w(v,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[A?w(V,{children:[d(Tu,{state:x,stepId:D}),d(v,{height:0}),d(Au,{displayStep:a,stepId:D,subProgress:ke??void 0,totalSteps:Hr}),d(v,{height:2})]}):null,E(),d(v,{flexGrow:1}),A?w(V,{children:[d(Le,{}),d(v,{height:1}),d(Bt,{action:ge,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),Br=` _ _ ___ ___ _____ _ ___ ___ _ _
136
349
  | \\| | __/ __|_ _| /_\\ | _ \\/ __| || |
137
350
  | .\` | _|\\__ \\ | | / _ \\| / (__| __ |
138
- |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,so=12,ao=4,er=l(({onlyCat:t=!1})=>{const{stdout:e}=Qe(),r=e.columns||e.getWindowSize?.()[0]||80,s=e.rows||e.getWindowSize?.()[1]||24;return t?s<15||r<20?c(f,{flexDirection:"column",alignItems:"center",children:c(u,{bold:!0,color:P,children:ht})}):c(f,{flexDirection:"column",alignItems:"center",children:c(u,{color:P,children:Xe})}):s<15||r<38?y(f,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(u,{bold:!0,color:P,children:ht}),c(u,{color:E,children:xe}),c(u,{color:W,children:Ie})]}):s<15+ao||r<55?y(f,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(u,{color:P,children:lt}),c(u,{color:E,children:xe}),c(u,{color:W,children:Ie})]}):s<15+so||r<80?y(f,{flexDirection:"column",alignItems:"center",rowGap:0,children:[c(u,{color:P,children:Xe}),c(u,{color:P,children:lt}),c(u,{color:E,children:xe}),c(u,{color:W,children:Ie})]}):y(f,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[c(u,{color:P,children:Xe}),y(f,{flexDirection:"column",children:[c(u,{color:P,children:lt}),y(u,{color:E,children:[" ",xe]}),y(u,{color:W,children:[" ",Ie]})]})]})},"Header"),pt={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"},oo=l(({onSelect:t,options:e})=>{const[r,s]=O(0),n=R(()=>{const o=e[r];o&&!o.disabled&&t(o)},[t,e,r]);return De((o,a)=>{a.upArrow||o==="k"?s(i=>Math.max(0,i-1)):a.downArrow||o==="j"?s(i=>Math.min(e.length-1,i+1)):a.return&&n()}),y(f,{flexDirection:"column",children:[c(u,{color:E,children:"Choose a project preset"}),c(f,{marginTop:1,flexDirection:"column",rowGap:1,children:e.map((o,a)=>y(f,{flexDirection:"column",children:[c(u,{children:a===r?y(N,{children:[c(u,{color:o.disabled?pe:P,children:"> "}),c(u,{color:o.disabled?pe:P,children:o.name})]}):c(u,{color:o.disabled?pe:oe,children:` ${o.name}`})}),a===r&&o.description?c(u,{color:E,children:o.description}):null]},o.name))})]})},"PresetStep"),no={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},io=l(({step:t})=>y(u,{children:[c(u,{color:P,children:"\u2727 "}),c(u,{color:L,children:no[t]})]}),"WizardTitle"),co=l(({onBack:t,onDone:e,onExit:r,onStepChange:s})=>{const[n,o]=O("preset"),[a,i]=O(""),[d,p]=O(null),[m,g]=O(null),[b,q]=O(null),[M,U]=O(null),[F,_]=O(null),[$,D]=O("");ae(()=>{n==="done"&&e()},[n,e]);const B=J(()=>Xr(),[]),z=J(()=>{const T=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return B?T.push({description:Kr(B),name:"Last Used"}):T.push({description:"",disabled:!0,name:"Last Used"}),T},[B]),[v,I]=O(pt),G=J(()=>{const T=new Set;return m==="no"&&(T.add("initialize-git"),T.add("initial-commit")),v.installDependencies==="no"&&T.add("install-dependencies"),(v.formatter==="none"||v.installDependencies==="no")&&(T.add("setup-linter"),T.add("run-formatter")),(m==="no"||T.has("run-formatter"))&&T.add("formatter-commit"),v.addons.includes("agent-skills")||T.add("install-agent-skills"),[...T]},[m,v]),V=R(()=>{switch(n){case"projectName":{o("preset"),s?.("preset"),p(null);return}case"initGit":{o("projectName"),s?.("projectName");return}default:t()}},[t,n,s]),ee=R(T=>{if(T.name==="Last Used"&&B){const{projectName:X,initGit:ce,...C}=B;I(C)}else T.name==="API Gateway"?I({...pt,architecture:"nest-gateway",projectType:"monorepo"}):I(pt);o("projectName"),s?.("projectName")},[B,s]),ge=R(T=>{i(T),p(Me(T))},[]),fe=R(()=>{const T=Me(a);if(T){p(T);return}o("initGit"),s?.("initGit")},[a,s]),ye=R(async T=>{g(T);const X=ne(a),ce=$e(X);D(ce),o("installing"),s?.("installing");const C={...v,initGit:T,projectName:X};try{const K=await Kt(C,{onInstallProgress:l(se=>{_(se)},"onInstallProgress"),onStageChange:l(se=>{U(se)},"onStageChange")});q({isError:!K.success,message:K.message}),K.success&&Mt(C)}catch(K){q({isError:!0,message:`Error: ${K instanceof Error?K.message:String(K)}`})}},[a,v,s]);mt(()=>{b&&!b.isError&&(o("done"),s?.("done"))},[b,s]),le((T,X)=>{if(X.ctrl&&T==="c"){r();return}if(X.ctrl&&T==="b"&&n!=="done"){V();return}n==="done"&&X.return&&r()});const be=J(()=>n==="projectName"?"confirm":"select",[n]),ie=n!=="installing"&&n!=="done";return y(f,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[ie?y(N,{children:[c(er,{}),c(Se,{}),c(f,{height:1}),c(io,{step:n}),c(f,{height:2})]}):null,l(()=>{switch(n){case"preset":return c(oo,{onSelect:ee,options:z});case"projectName":return c(At,{error:d,onChange:ge,onSubmit:fe,value:a});case"initGit":return c(Ge,{onConfirm:ye,options:It,prompt:"Initialize a git repository?"});case"installing":return y(f,{flexDirection:"column",children:[c(jt,{currentStage:M,generationMessage:b?.message??"Scaffolding your project",installProgress:F,isError:b?.isError??!1,skippedStages:G}),b?.isError?c(f,{marginTop:1,children:y(u,{color:E,children:["Press ",c(u,{color:P,children:"Enter"})," to go back to Summary and retry, or ",c(u,{color:E,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const T=ne(a);return c(vt,{architecture:v.architecture||"nest-api",projectName:T,packageManager:v.packageManager||"pnpm",dependenciesInstalled:v.installDependencies==="yes",isGitInitialized:m==="yes",outputDir:$})}default:return null}},"renderStep")(),c(f,{flexGrow:1}),ie?y(N,{children:[c(Se,{}),c(f,{height:1}),c(Ke,{action:be,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),Ue=[{description:"Scaffold a new project with best practices",name:"Create a new NestJS project"},{description:"Choose from predefined configurations",name:"Starter templates"},{description:"Browse the Nest Arch docs",name:"Documentation"},{description:"Close Nest Arch",name:"Exit"}],lo=l(({onSelect:t})=>{const[e,r]=O(0),s=R(()=>{const a=Ue[e]??null;a?.disabled||t(e,a)},[t,e]),n=[];for(let a=0;a<Ue.length;a+=1)Ue[a].disabled||n.push(a);const o=n.indexOf(e);return De((a,i)=>{if(i.upArrow||a==="k"){const d=n[o-1];d!==void 0&&r(d)}else if(i.downArrow||a==="j"){const d=n[o+1];d!==void 0&&r(d)}else i.return&&s()}),y(f,{flexDirection:"column",children:[c(u,{color:E,children:" What would you like to do?"}),c(f,{marginTop:1,flexDirection:"column",rowGap:1,children:Ue.map((a,i)=>c(u,{children:i===e&&!a.disabled?y(N,{children:[c(u,{color:P,children:"> "}),c(u,{color:P,children:a.name})]}):c(u,{color:oe,children:` ${a.name}`})},a.name))})]})},"MainMenu"),po=l(()=>y(u,{children:[c(u,{color:P,children:"\u2727 "}),c(u,{color:L,children:" Welcome to "}),c(u,{color:P,children:"Nest Arch"}),c(u,{color:L,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),uo=l(({onCreateProject:t,onExit:e,onUsePreset:r})=>{const s=R(async()=>{const o="https://nest-arch-web-web.vercel.app/";try{await fr(o,{wait:!1})}catch{}},[]),n=R((o,a)=>{a?.name==="Exit"?e():a?.name==="Create a new NestJS project"?t():a?.name==="Starter templates"?r():a?.name==="Documentation"&&s()},[t,e,r,s]);return le((o,a)=>{a.ctrl&&o==="c"&&e()}),y(f,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[c(er,{}),c(Se,{}),c(f,{height:1}),c(po,{}),c(f,{height:2}),c(lo,{onSelect:n}),c(f,{flexGrow:1}),c(Se,{borderTop:!1}),c(f,{height:1}),c(Ke,{})]})},"WelcomeScreen"),mo=l(({onDone:t})=>{const[e,r]=O("welcome"),{stdout:s}=Qe(),{exit:n}=ar(),[o,a]=O(s?.rows??24);ae(()=>{if(!s)return;const b=l(()=>{a(s.rows)},"handleResize");return s.on("resize",b),()=>{s.off("resize",b)}},[s]);const i=R(()=>{n()},[n]),d=R(()=>{r("preset-wizard")},[]),p=R(()=>{r("create-wizard")},[]),m=R(()=>{r("welcome")},[]);return c(f,{height:o,flexDirection:"column",children:l(()=>e==="create-wizard"?c(ro,{onBack:m,onDone:t,onExit:i}):e==="preset-wizard"?c(co,{onBack:m,onDone:t,onExit:i}):c(uo,{onCreateProject:p,onExit:i,onUsePreset:d}),"renderScreen")()})},"App");async function ho(){process.stdout.write("\x1B[?1049h");let t=!1;try{await sr(c(mo,{onDone:l(()=>{process.stdout.write("\x1B[?1049l"),t=!0},"onDone")})).waitUntilExit()}finally{t||process.stdout.write("\x1B[?1049l")}}l(ho,"main");try{await ho()}catch(t){console.error("Error:",t),process.exit(1)}
351
+ |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,Du=12,Nu=4,wo=c(({onlyCat:e=!1})=>{const{stdout:t}=Ut(),r=t.columns||t.getWindowSize?.()[0]||80,s=t.rows||t.getWindowSize?.()[1]||24;return e?s<15||r<20?d(v,{flexDirection:"column",alignItems:"center",children:d(h,{bold:!0,color:z,children:Kr})}):d(v,{flexDirection:"column",alignItems:"center",children:d(h,{color:z,children:Jt})}):s<15||r<38?w(v,{flexDirection:"column",alignItems:"center",rowGap:0,children:[d(h,{bold:!0,color:z,children:Kr}),d(h,{color:O,children:ot}),d(h,{color:ie,children:Ce})]}):s<15+Nu||r<55?w(v,{flexDirection:"column",alignItems:"center",rowGap:0,children:[d(h,{color:z,children:Br}),d(h,{color:O,children:ot}),d(h,{color:ie,children:Ce})]}):s<15+Du||r<80?w(v,{flexDirection:"column",alignItems:"center",rowGap:0,children:[d(h,{color:z,children:Jt}),d(h,{color:z,children:Br}),d(h,{color:O,children:ot}),d(h,{color:ie,children:Ce})]}):w(v,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[d(h,{color:z,children:Jt}),w(v,{flexDirection:"column",children:[d(h,{color:z,children:Br}),w(h,{color:O,children:[" ",ot]}),w(h,{color:ie,children:[" ",Ce]})]})]})},"Header"),Zr={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"},qu=c(({onSelect:e,options:t})=>{const[r,s]=$(0),n=N(()=>{const o=t[r];o&&!o.disabled&&e(o)},[e,t,r]);return ut((o,a)=>{a.upArrow||o==="k"?s(i=>Math.max(0,i-1)):a.downArrow||o==="j"?s(i=>Math.min(t.length-1,i+1)):a.return&&n()}),w(v,{flexDirection:"column",children:[d(h,{color:O,children:"Choose a project preset"}),d(v,{marginTop:1,flexDirection:"column",rowGap:1,children:t.map((o,a)=>w(v,{flexDirection:"column",children:[d(h,{children:a===r?w(V,{children:[d(h,{color:o.disabled?Oe:z,children:"> "}),d(h,{color:o.disabled?Oe:z,children:o.name})]}):d(h,{color:o.disabled?Oe:xe,children:` ${o.name}`})}),a===r&&o.description?d(h,{color:O,children:o.description}):null]},o.name))})]})},"PresetStep"),$u={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},Mu=c(({step:e})=>w(h,{children:[d(h,{color:z,children:"\u2727 "}),d(h,{color:H,children:$u[e]})]}),"WizardTitle"),Fu=c(({onBack:e,onDone:t,onExit:r,onStepChange:s})=>{const[n,o]=$("preset"),[a,i]=$(""),[p,u]=$(null),[m,g]=$(null),[b,S]=$(null),[P,T]=$(null),[M,W]=$(null),[B,F]=$("");ye(()=>{n==="done"&&t()},[n,t]);const se=X(()=>Eu(),[]),L=X(()=>{const R=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return se?R.push({description:Pu(se),name:"Last Used"}):R.push({description:"",disabled:!0,name:"Last Used"}),R},[se]),[K,I]=$(Zr),q=X(()=>{const R=new Set;return m==="no"&&(R.add("initialize-git"),R.add("initial-commit")),K.installDependencies==="no"&&R.add("install-dependencies"),(K.formatter==="none"||K.installDependencies==="no")&&(R.add("setup-linter"),R.add("run-formatter")),(m==="no"||R.has("run-formatter"))&&R.add("formatter-commit"),K.addons.includes("agent-skills")||R.add("install-agent-skills"),[...R]},[m,K]),Z=N(()=>{switch(n){case"projectName":{o("preset"),s?.("preset"),u(null);return}case"initGit":{o("projectName"),s?.("projectName");return}default:e()}},[e,n,s]),ne=N(R=>{if(R.name==="Last Used"&&se){const{projectName:ue,initGit:ze,...ge}=se;I(ge)}else R.name==="API Gateway"?I({...Zr,architecture:"nest-gateway",projectType:"monorepo"}):I(Zr);o("projectName"),s?.("projectName")},[se,s]),ce=N(R=>{i(R),u(dt(R))},[]),Me=N(()=>{const R=dt(a);if(R){u(R);return}o("initGit"),s?.("initGit")},[a,s]),Fe=N(async R=>{g(R);const ue=Te(a),ze=Dt(ue);F(ze),o("installing"),s?.("installing");const ge={...K,initGit:R,projectName:ue};try{const D=await bo(ge,{onInstallProgress:c(ke=>{W(ke)},"onInstallProgress"),onStageChange:c(ke=>{T(ke)},"onStageChange")});S({isError:!D.success,message:D.message}),D.success&&yo(ge)}catch(D){S({isError:!0,message:`Error: ${D instanceof Error?D.message:String(D)}`})}},[a,K,s]);Wr(()=>{b&&!b.isError&&(o("done"),s?.("done"))},[b,s]),Re((R,ue)=>{if(ue.ctrl&&R==="c"){r();return}if(ue.ctrl&&R==="b"&&n!=="done"){Z();return}n==="done"&&ue.return&&r()});const Ge=X(()=>n==="projectName"?"confirm":"select",[n]),Ie=n!=="installing"&&n!=="done";return w(v,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[Ie?w(V,{children:[d(wo,{}),d(Le,{}),d(v,{height:1}),d(Mu,{step:n}),d(v,{height:2})]}):null,c(()=>{switch(n){case"preset":return d(qu,{onSelect:ne,options:L});case"projectName":return d(is,{error:p,onChange:ce,onSubmit:Me,value:a});case"initGit":return d(Je,{onConfirm:Fe,options:bs,prompt:"Initialize a git repository?"});case"installing":return w(v,{flexDirection:"column",children:[d(ss,{currentStage:P,generationMessage:b?.message??"Scaffolding your project",installProgress:M,isError:b?.isError??!1,skippedStages:q}),b?.isError?d(v,{marginTop:1,children:w(h,{color:O,children:["Press ",d(h,{color:z,children:"Enter"})," to go back to Summary and retry, or ",d(h,{color:O,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const R=Te(a);return d(ns,{architecture:K.architecture||"nest-api",projectName:R,packageManager:K.packageManager||"pnpm",dependenciesInstalled:K.installDependencies==="yes",isGitInitialized:m==="yes",outputDir:B})}default:return null}},"renderStep")(),d(v,{flexGrow:1}),Ie?w(V,{children:[d(Le,{}),d(v,{height:1}),d(Bt,{action:Ge,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),Nt=[{description:"Scaffold a new project with best practices",name:"Create a new NestJS project"},{description:"Choose from predefined configurations",name:"Starter templates"},{description:"Browse the Nest Arch docs",name:"Documentation"},{description:"Close Nest Arch",name:"Exit"}],Gu=c(({onSelect:e})=>{const[t,r]=$(0),s=N(()=>{const a=Nt[t]??null;a?.disabled||e(t,a)},[e,t]),n=[];for(let a=0;a<Nt.length;a+=1)Nt[a].disabled||n.push(a);const o=n.indexOf(t);return ut((a,i)=>{if(i.upArrow||a==="k"){const p=n[o-1];p!==void 0&&r(p)}else if(i.downArrow||a==="j"){const p=n[o+1];p!==void 0&&r(p)}else i.return&&s()}),w(v,{flexDirection:"column",children:[d(h,{color:O,children:" What would you like to do?"}),d(v,{marginTop:1,flexDirection:"column",rowGap:1,children:Nt.map((a,i)=>d(h,{children:i===t&&!a.disabled?w(V,{children:[d(h,{color:z,children:"> "}),d(h,{color:z,children:a.name})]}):d(h,{color:xe,children:` ${a.name}`})},a.name))})]})},"MainMenu"),Uu=1440*60*1e3,Lu=3e3,jo=he.string().max(128).refine(e=>$o(e)!==null),Ju=he.object({checkedAt:he.number().finite(),version:jo}),Bu=he.object({version:jo}),Zu=c(()=>ee(process.env.XDG_CACHE_HOME??(process.platform==="win32"?process.env.LOCALAPPDATA??ee(pt(),"AppData","Local"):ee(pt(),".cache")),"nest-arch","update.json"),"cachePath");async function Vu(e){try{const t=Zu();let r;try{const s=Ju.parse(JSON.parse(await De(t,"utf-8"))),n=Date.now()-s.checkedAt;n>=0&&n<Uu&&(r=s.version)}catch{}if(!r){const s=await fetch("https://registry.npmjs.org/@nest-arch%2Ftui/latest",{signal:AbortSignal.timeout(Lu)});if(!s.ok)return null;r=Bu.parse(await s.json()).version;try{await Ro(Oo(t),{recursive:!0}),await be(t,JSON.stringify({checkedAt:Date.now(),version:r}),"utf-8")}catch{}}return Mo(r,e)?r:null}catch{return null}}c(Vu,"checkForUpdate");let So;const Hu=c(()=>{const[e,t]=$(null);return ye(()=>{let r=!0;return c(async()=>{So??=Vu(Ce);const n=await So;r&&t(n)},"check")(),()=>{r=!1}},[]),e?w(v,{flexDirection:"column",marginTop:1,children:[w(h,{color:_e,children:["Update available: ",Ce," \u2192 v",e]}),d(h,{color:O,children:"Run: npx @nest-arch/tui@latest"}),d(h,{color:O,children:"Global install: npm install -g @nest-arch/tui@latest"})]}):null},"UpdateNotice"),Wu=c(()=>w(h,{children:[d(h,{color:z,children:"\u2727 "}),d(h,{color:H,children:" Welcome to "}),d(h,{color:z,children:"Nest Arch"}),d(h,{color:H,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),Ku=c(({onCreateProject:e,onExit:t,onUsePreset:r})=>{const s=N(async()=>{const o="https://nest-arch-web-web.vercel.app/";try{await qo(o,{wait:!1})}catch{}},[]),n=N((o,a)=>{a?.name==="Exit"?t():a?.name==="Create a new NestJS project"?e():a?.name==="Starter templates"?r():a?.name==="Documentation"&&s()},[e,t,r,s]);return Re((o,a)=>{a.ctrl&&o==="c"&&t()}),w(v,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[d(wo,{}),d(Le,{}),d(v,{height:1}),d(Wu,{}),d(Hu,{}),d(v,{height:2}),d(Gu,{onSelect:n}),d(v,{flexGrow:1}),d(Le,{borderTop:!1}),d(v,{height:1}),d(Bt,{})]})},"WelcomeScreen"),Qu=c(({onDone:e})=>{const[t,r]=$("welcome"),{stdout:s}=Ut(),{exit:n}=To(),[o,a]=$(s?.rows??24);ye(()=>{if(!s)return;const b=c(()=>{a(s.rows)},"handleResize");return s.on("resize",b),()=>{s.off("resize",b)}},[s]);const i=N(()=>{n()},[n]),p=N(()=>{r("preset-wizard")},[]),u=N(()=>{r("create-wizard")},[]),m=N(()=>{r("welcome")},[]);return d(v,{height:o,flexDirection:"column",children:c(()=>t==="create-wizard"?d(Cu,{onBack:m,onDone:e,onExit:i}):t==="preset-wizard"?d(Fu,{onBack:m,onDone:e,onExit:i}):d(Ku,{onCreateProject:u,onExit:i,onUsePreset:p}),"renderScreen")()})},"App");async function Yu(){process.stdout.write("\x1B[?1049h");let e=!1;try{await xo(d(Qu,{onDone:c(()=>{process.stdout.write("\x1B[?1049l"),e=!0},"onDone")})).waitUntilExit()}finally{e||process.stdout.write("\x1B[?1049l")}}c(Yu,"main");try{await Yu()}catch(e){console.error("Error:",e),process.exit(1)}