@nest-arch/tui 0.2.8 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +20 -42
  2. package/dist/cli.js +1 -1
  3. package/dist/constants-B5MuV-iH.js +1 -0
  4. package/dist/index.js +365 -98
  5. package/dist/templates/addons/husky/pre-commit.hbs +11 -26
  6. package/dist/templates/base/.env.example.hbs +13 -2
  7. package/dist/templates/base/.env.hbs +11 -2
  8. package/dist/templates/base/.gitignore.hbs +2 -1
  9. package/dist/templates/base/.yarnrc.yml.hbs +0 -5
  10. package/dist/templates/base/README.md.hbs +49 -5
  11. package/dist/templates/base/nest-cli.json.hbs +2 -1
  12. package/dist/templates/base/pnpm-workspace.yaml.hbs +15 -0
  13. package/dist/templates/base/prisma.config.ts.hbs +32 -6
  14. package/dist/templates/base/src/app.controller.spec.ts.hbs +3 -11
  15. package/dist/templates/base/src/app.controller.ts.hbs +2 -2
  16. package/dist/templates/base/src/app.module.ts.hbs +76 -5
  17. package/dist/templates/base/src/app.router.ts.hbs +3 -4
  18. package/dist/templates/base/src/database/adapters/interfaces/db-adapter.interface.ts.hbs +7 -0
  19. package/dist/templates/base/src/database/adapters/mongo/prisma-mongo.adapter.ts.hbs +36 -4
  20. package/dist/templates/base/src/database/adapters/mongo/raw-mongo.adapter.ts.hbs +17 -12
  21. package/dist/templates/base/src/database/adapters/sql/drizzle-sql.adapter.ts.hbs +9 -0
  22. package/dist/templates/base/src/database/adapters/sql/prisma-sql.adapter.ts.hbs +8 -5
  23. package/dist/templates/base/src/database/adapters/sql/raw-sql.adapter.ts.hbs +37 -0
  24. package/dist/templates/base/src/database/adapters/sql/typeorm-sql.adapter.ts.hbs +8 -3
  25. package/dist/templates/base/src/database/db.module.ts.hbs +55 -42
  26. package/dist/templates/base/src/database/db.service.ts.hbs +60 -6
  27. package/dist/templates/base/src/database/entities/app.entity.ts.hbs +25 -0
  28. package/dist/templates/base/src/database/entities/todo.entity.ts.hbs +12 -7
  29. package/dist/templates/base/src/database/index.ts.hbs +20 -0
  30. package/dist/templates/base/src/database/orm/drizzle/schema.ts.hbs +80 -7
  31. package/dist/templates/base/src/database/orm/typeorm/data-source.ts.hbs +23 -4
  32. package/dist/templates/base/src/libs/middlewares/auth.trpc.middleware.ts.hbs +47 -0
  33. package/dist/templates/base/src/libs/middlewares/rate-limit.trpc.middleware.ts.hbs +43 -0
  34. package/dist/templates/base/src/libs/trpc/error.handler.ts.hbs +1 -1
  35. package/dist/templates/base/src/libs/trpc/inner.context.ts.hbs +6 -3
  36. package/dist/templates/base/src/main.ts.hbs +34 -10
  37. package/dist/templates/base/src/modules/users/entities/user.entity.ts.hbs +22 -0
  38. package/dist/templates/base/test/app.e2e-spec.ts.hbs +841 -6
  39. package/dist/templates/base/test/bootstrap.e2e-spec.ts.hbs +84 -0
  40. package/dist/templates/base/tsconfig.build.json.hbs +2 -0
  41. package/dist/templates/base/vitest.config.e2e.ts.hbs +4 -3
  42. package/dist/templates/base/vitest.config.ts.hbs +4 -3
  43. package/dist/templates/base/yarn.lock.hbs +1 -0
  44. package/dist/templates/extras/docker/.dockerignore.hbs +8 -1
  45. package/dist/templates/extras/docker/Dockerfile.hbs +11 -10
  46. package/dist/templates/extras/health/src/health/health.controller.ts.hbs +54 -0
  47. package/dist/templates/extras/health/src/health/health.module.ts.hbs +9 -0
  48. package/dist/templates/extras/swagger/create-docs.ts.hbs +13 -22
  49. package/dist/templates/feature/graphql/src/graphql/graphql.module.ts.hbs +6 -10
  50. package/dist/templates/feature/graphql/src/graphql/models/todo.model.ts.hbs +4 -0
  51. package/dist/templates/feature/graphql/src/graphql/orm/drizzle/drizzle-graphql.module.ts.hbs +6 -4
  52. package/dist/templates/feature/graphql/src/graphql/resolvers/health.resolver.ts.hbs +14 -0
  53. package/dist/templates/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs +210 -47
  54. package/dist/templates/feature/rest/todo-example/src/api/todo/dto/create-todo.dto.ts.hbs +12 -0
  55. package/dist/templates/feature/rest/todo-example/src/api/todo/dto/update-todo.dto.ts.hbs +12 -0
  56. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.controller.ts.hbs +21 -9
  57. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.module.ts.hbs +1 -3
  58. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.router.ts.hbs +41 -13
  59. package/dist/templates/feature/rest/todo-example/src/api/todo/todo.service.ts.hbs +157 -33
  60. package/dist/templates/monorepo/apps/api-gateway/package.json.hbs +2 -3
  61. package/dist/templates/monorepo/apps/api-gateway/src/app.controller.spec.ts.hbs +6 -1
  62. package/dist/templates/monorepo/apps/api-gateway/src/app.controller.ts.hbs +6 -0
  63. package/dist/templates/monorepo/apps/api-gateway/src/app.module.ts.hbs +32 -1
  64. package/dist/templates/monorepo/apps/api-gateway/src/app.service.ts.hbs +1 -1
  65. package/dist/templates/monorepo/apps/api-gateway/src/main.ts.hbs +13 -4
  66. package/dist/templates/monorepo/apps/api-gateway/test/app.e2e-spec.ts.hbs +45 -1
  67. package/dist/templates/monorepo/apps/api-gateway/tsconfig.build.json.hbs +2 -1
  68. package/dist/templates/monorepo/apps/api-gateway/vitest.config.e2e.ts.hbs +3 -2
  69. package/dist/templates/monorepo/apps/api-gateway/vitest.config.ts.hbs +3 -2
  70. package/dist/templates/monorepo/feature/graphql/src/graphql/graphql.module.ts.hbs +6 -10
  71. package/dist/templates/monorepo/feature/graphql/src/graphql/resolvers/health.resolver.ts.hbs +14 -0
  72. package/dist/templates/monorepo/feature/graphql/src/graphql/resolvers/todo.resolver.ts.hbs +151 -42
  73. package/dist/templates/monorepo/packages/env/src/api-gateway.ts.hbs +16 -3
  74. package/dist/templates/monorepo/packages/shared/package.json.hbs +1 -0
  75. package/dist/templates/monorepo/packages/shared/src/auth.ts.hbs +6 -0
  76. package/dist/templates/monorepo/root/.gitignore.hbs +1 -0
  77. package/dist/templates/monorepo/root/pnpm-workspace.yaml.hbs +19 -2
  78. package/dist/templates/monorepo/root/tsconfig.json.hbs +1 -1
  79. package/dist/templates/monorepo/root/turbo.json.hbs +2 -0
  80. package/dist/templates/single-project/architecture/nest-api/.env.hbs +9 -1
  81. package/dist/templates/single-project/architecture/nest-api/package.json.hbs +1 -2
  82. package/dist/templates/single-project/architecture/nest-api/src/main.ts.hbs +33 -9
  83. package/dist/templates/single-project/architecture/nest-gateway/src/main.ts.hbs +3 -3
  84. package/dist/templates/single-project/architecture/nest-microservice/.env.hbs +18 -0
  85. package/dist/templates/single-project/architecture/nest-microservice/proto/app.proto.hbs +26 -0
  86. package/dist/templates/single-project/architecture/nest-microservice/src/app.controller.ts.hbs +23 -4
  87. package/dist/templates/single-project/architecture/nest-microservice/src/app.service.ts.hbs +6 -2
  88. package/dist/templates/single-project/architecture/nest-microservice/src/main.ts.hbs +16 -5
  89. package/dist/templates/single-project/architecture/nest-microservice/test/microservice.e2e-spec.ts.hbs +70 -0
  90. package/dist/templates/single-project/shared/config/env.ts.hbs +38 -3
  91. package/package.json +5 -2
  92. 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 Qo=Object.defineProperty;var p=(e,t)=>Qo(e,"name",{value:t,configurable:!0});import{jsx as m,jsxs as w,Fragment as V}from"react/jsx-runtime";import{Box as q,Text as h,useInput as Me,useStdout as sr,render as Vo,useApp as Zo}from"ink";import{useState as N,useEffect as Te,useMemo as ne,useRef as yt,useCallback as $,useLayoutEffect as hs}from"react";import{COLOR_DIVIDER as Ue,COLOR_RED as I,COLOR_WARM as Ie,COLOR_DIM as C,COLOR_FG as K,COLOR_SUCCESS as Qe,COLOR_DIMMER as Oe,COLOR_ACCENT as me,COLOR_WARM_SECONDARY as ar,APP_NAME as fs,APP_TAGLINE as bt,APP_VERSION as Ge}from"./constants-B5MuV-iH.js";import Wo from"ink-text-input";import{createEnv as Ko}from"@t3-oss/env-nextjs";import{z as qe}from"zod";import{exec as ir,execFile as Yo,spawn as zt}from"node:child_process";import{promisify as vt}from"node:util";import ve,{readFile as Se,access as Xo,writeFile as xe,mkdir as en}from"node:fs/promises";import S,{isAbsolute as gs,join as Y,dirname as tn}from"node:path";import pe from"handlebars";import{Project as ys,Scope as rn}from"ts-morph";import{createHash as bs}from"node:crypto";import{once as Pe}from"node:events";import{existsSync as qt,readFileSync as sn,mkdirSync as an,writeFileSync as on}from"node:fs";import{homedir as wt}from"node:os";import nn from"open";import{valid as pn,gt as ln}from"semver";const Ve=p(({borderTop:e=!0})=>m(q,{borderStyle:"single",borderBottom:!e,borderLeft:!1,borderRight:!1,borderTop:e,borderColor:Ue,height:1,width:"full"}),"Divider"),cn=` \uFF0Fl\u3001
2
2
  \uFF08\uFF9F\uFF64 \uFF61\uFF17
3
3
  l\u3001\uFF9E ~\u30FD
4
4
  \u3058\u3057(_,)\u30CE
5
- `,Xe=` ,-. _,---._ __ /\\
5
+ `,or=` ,-. _,---._ __ /\\
6
6
  / ) .-' \`./ / \\
7
7
  ( ( ,' \` / /|
8
8
  \\ \`-" \\'\\ / |
@@ -13,20 +13,41 @@ 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
+ `,dn=p(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"),zs=p(e=>{let t=0;for(const r of e){const s=r.codePointAt(0)??0;t+=dn(s)?2:1}return t},"getDisplayWidth"),un=2,vs=[0,1,2,3,2,1],qs=["",".","..","..."],mn=p(({message:e="Scaffolding your project",isError:t=!1,isComplete:r=!1,showProgressText:s=!0,paddingX:a=2})=>{const[o,i]=N(0),[n,c]=N(0),d=!t&&!r;Te(()=>{if(!d)return;const O=setInterval(()=>{i(oe=>(oe+1)%vs.length)},200),X=setInterval(()=>{c(oe=>(oe+1)%qs.length)},400);return()=>{clearInterval(O),clearInterval(X)}},[d]);const u=cn.trimEnd().split(`
17
+ `),f=Math.max(...u.map(zs)),g=vs[o];let z=Ie,k="\u25CF",x=C;return t?(z=I,k="\u2717",x=K):r&&(z=Qe,k="\u2713",x=Qe),w(q,{flexDirection:"column",paddingX:a,children:[m(q,{flexDirection:"column",children:u.map((O,X)=>{const oe=zs(O),ge=X===0||X===u.length-1,Q=f-oe+un-(ge?1:0),L=X===g;return w(h,{color:I,children:[O," ".repeat(Q),L?m(h,{color:z,children:k}):" "]},X)})}),s&&w(h,{color:x,children:[e,d?qs[n]:""]})]})},"ScaffoldingAnimation"),hn=[{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"}],ws=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function fn(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 a=r.map(o=>o.id).indexOf(e);return r.map((o,i)=>i<a?{stage:o,status:t?"failed":"completed"}:i===a?{stage:o,status:t?"failed":"active"}:t&&i>a?{stage:o,status:"pending"}:t?{stage:o,status:"failed"}:{stage:o,status:"pending"})}p(fn,"getStages");function gn(e,t){switch(e){case"completed":return"\u2713";case"active":return t;case"failed":return"\u2717";case"pending":return"\u25CB";default:return e}}p(gn,"statusIcon");function yn(e){switch(e){case"completed":return Qe;case"active":return Ie;case"failed":return I;case"pending":return Oe;default:return e}}p(yn,"statusColor");function bn(e){return e===void 0?"":` (${e}%)`}p(bn,"formatPercentage");function zn(e){return e?.message?e.message:"Installing dependencies..."}p(zn,"getInstallMessage");const Ss=p(({currentStage:e,generationMessage:t,installProgress:r,isError:s,skippedStages:a=[]})=>{const o=ne(()=>hn.filter(f=>!a.includes(f.id)),[a]),i=ne(()=>fn(e,s,o),[e,s,o]),[n,c]=N(0),d=e==="complete"&&!s;Te(()=>{if(s||d)return;const f=setInterval(()=>{c(g=>(g+1)%ws.length)},80);return()=>clearInterval(f)},[s,d]);const u=ws[n]??"\u280B";return w(q,{flexDirection:"column",paddingX:2,children:[m(q,{marginBottom:1,children:m(mn,{showProgressText:!1,paddingX:0,isError:s,isComplete:d})}),m(q,{flexDirection:"column",rowGap:0,children:i.map(f=>{const g=f.status==="active",z=g&&f.stage.id==="install-dependencies",k=r?.percentage,x=16,O=k===void 0?0:Math.round(k/100*x),X=x-O;return w(q,{flexDirection:"column",children:[w(q,{children:[w(h,{bold:g,color:yn(f.status),children:[gn(f.status,u)," ",f.stage.label]}),z?m(h,{children:k===void 0?null:w(V,{children:[m(h,{color:Ie,children:bn(k)})," ",m(h,{color:Ie,children:"\u2588".repeat(O)}),m(h,{color:Ue,children:"\u2591".repeat(X)})]})}):null]}),z?m(q,{marginLeft:4,children:m(h,{color:C,children:zn(r)})}):null]},f.stage.id)})}),!s&&e===null?m(q,{marginTop:1,children:m(h,{color:C,children:t})}):null,d?m(q,{marginTop:1,children:m(h,{color:Qe,children:t})}):null,s?m(q,{marginTop:1,flexDirection:"column",children:t.split(`
18
+ `).map((f,g)=>m(h,{color:f.startsWith(" ")?C:I,children:f},g))}):null]})},"InstallationProgress"),nr=p(({action:e="select",showBack:t=!1})=>w(h,{children:[e==="select"||e==="multi-select"?m(h,{color:C,children:"Use \u2191/\u2193 to navigate \u2022 "}):null,m(h,{color:C,children:e==="confirm"?w(V,{children:[m(h,{color:K,children:"Enter "}),"to confirm"]}):e==="multi-select"?w(V,{children:[m(h,{color:K,children:"Space "}),"to toggle \u2022",m(h,{color:K,children:" Enter "}),"to confirm"]}):w(V,{children:[m(h,{color:K,children:"Enter "}),"to select"]})}),w(h,{color:C,children:[t?w(V,{children:[" ","\u2022",m(h,{color:K,children:" Ctrl+B "}),"to go back"]}):"",w(V,{children:[" ","\u2022",m(h,{color:K,children:" Ctrl+C "}),"to exit"]})]})]}),"StatusBar"),xs=p(({architecture:e,projectName:t,packageManager:r,isGitInitialized:s,dependenciesInstalled:a,outputDir:o})=>m(q,{flexDirection:"column",children:w(q,{flexDirection:"column",marginTop:1,children:[m(h,{color:Qe,bold:!0,children:"\u2714 Project scaffold completed successfully!"}),w(q,{marginTop:1,children:[m(h,{color:K,children:"Project: "}),m(h,{color:me,bold:!0,children:t})]}),w(q,{children:[m(h,{color:K,children:"Architecture: "}),m(h,{color:me,bold:!0,children:e})]}),o?w(q,{children:[m(h,{color:K,children:"Location: "}),m(h,{color:me,bold:!0,children:o})]}):null,s?m(q,{marginTop:1,children:m(h,{color:C,children:"Git repository initialized"})}):null,w(q,{flexDirection:"column",borderStyle:"round",borderColor:I,paddingX:2,paddingY:1,marginTop:1,width:void 0,children:[m(h,{color:K,bold:!0,children:"\u{1F680} NEXT STEPS"}),m(q,{height:1}),m(h,{color:K,children:"1. Move into the project directory:"}),m(h,{color:me,bold:!0,children:` cd ${t}`}),m(q,{height:1}),a?m(q,{children:m(h,{color:C,children:"2. Dependencies already installed"})}):w(V,{children:[m(h,{color:K,children:"2. Install dependencies:"}),m(h,{color:me,bold:!0,children:` ${r} install`})]}),m(q,{height:1}),w(h,{color:K,children:["3."," Start development server:"]}),m(h,{color:me,bold:!0,children:` ${r} run dev`})]}),m(q,{marginTop:1,children:m(h,{color:C,children:"(Press enter to exit)"})})]})}),"DoneStep"),vn=100,St=p(e=>{const t=yt(0);Me((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<vn)return;t.current=o}e(r,s)})},"useArrowSelect"),qn=p(({initialSelected:e,onConfirm:t,onChange:r,options:s,prompt:a,minified:o=!1,exclusiveValue:i})=>{const n=ne(()=>new Set(s.map(R=>R.value)),[s]),c=$(R=>R.filter(M=>n.has(M)),[n]),[d,u]=N(0),[f,g]=N(()=>c(e)),[z,k]=N(null),x=yt(f);x.current=f;const O=yt(r);O.current=r,Te(()=>{const R=c(e);g(R),u(0),k(null),O.current?.(R)},[e,c]);const X=$(R=>f.includes(R),[f]),oe=$(R=>{const M=s[R];if(!M)return;const W=p(ee=>s.find(se=>se.value===ee)?.label??ee,"labelFor");g(ee=>{let se,ye;if(ee.includes(M.value))se=ee.filter(be=>be!==M.value),ye=[];else if(M.value===i)se=[M.value],ye=ee;else{const be=i!==void 0&&ee.includes(i);se=[...be?ee.filter(_=>_!==i):ee,M.value],ye=be&&i?[i]:[]}return x.current=se,r?.(se),k(ye.length>0?`Selecting "${M.label}" replaced: ${ye.map(W).join(", ")}`:null),se})},[s,r,i]),ge=$(()=>{k(null),t(x.current)},[t]),Q=s.length>16,L=Q?Math.ceil(s.length/2):s.length;St((R,M)=>{M.upArrow||R==="k"?u(W=>(W-1+s.length)%s.length):M.downArrow||R==="j"?u(W=>(W+1)%s.length):Q&&(M.leftArrow||R==="h")?u(W=>(W-L+s.length)%s.length):Q&&(M.rightArrow||R==="l")?u(W=>(W+L)%s.length):M.return?ge():(R===" "||R==="x")&&oe(d)});const re=f.length,H=p((R,M)=>{const W=X(R.value),ee=M===d,se=W?"\u25CF":"\u25CB";return w(q,{flexDirection:"column",children:[m(h,{children:ee?w(V,{children:[m(h,{color:I,children:"> "}),m(h,{color:W?I:C,children:`${se} `}),m(h,{color:W?I:K,children:R.label})]}):w(V,{children:[m(h,{color:W?I:C,children:` ${se}`}),m(h,{color:Oe,children:` ${R.label}`})]})}),ee&&!Q?w(h,{color:C,children:[" ",R.description]}):null]},R.value)},"renderOption");let ke;return Q||(ke=o?0:1),w(q,{flexDirection:"column",children:[m(h,{color:C,children:a}),m(h,{color:Ie,children:re===0?"No options selected yet \u2014 pick what you need":`${re} selected`}),z?m(q,{marginTop:1,children:w(h,{color:ar,children:["! ",z]})}):null,m(q,{marginTop:1,flexDirection:Q?"row":"column",rowGap:ke,columnGap:Q?4:void 0,overflow:"hidden",children:Q?w(V,{children:[m(q,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice(0,L).map((R,M)=>H(R,M))}),m(q,{flexDirection:"column",rowGap:o?0:1,flexGrow:1,flexBasis:0,children:s.slice(L).map((R,M)=>H(R,M+L))})]}):s.map((R,M)=>H(R,M))})]})},"MultiSelectStep"),ks="my-nest-app",js=64,wn=/^[a-z][a-z0-9-]*$/u;function Ce(e){return e.trim()||ks}p(Ce,"resolveProjectName");function xt(e){const t=e.trim();return t?t.length>js?`Project name must be at most ${js} characters`:wn.test(t)?null:"Use lowercase letters, numbers, and hyphens; must start with a letter":null}p(xt,"validateProjectName");const Ts=p(({error:e,onChange:t,onSubmit:r,value:s})=>(Me((a,o)=>{o.return&&r()}),w(q,{flexDirection:"column",children:[m(h,{color:C,children:"Enter a name for your project"}),w(q,{marginTop:1,flexDirection:"row",alignItems:"center",columnGap:1,children:[m(h,{color:K,children:"Project name:"}),m(Wo,{placeholder:ks,value:s,onChange:t})]}),e?m(h,{color:I,children:e}):null]})),"ProjectNameStep"),kt=Ko({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:qe.string().pipe(qe.coerce.number()).default(95),NEST_ARCH_BETA_MODE:qe.enum(["true","false"]).default("false").transform(e=>e==="true"),NEST_ARCH_SCHEMA_URL:qe.string().default("./schema.json"),NEST_ARCH_VERSION:qe.string().default("0.0.1"),NODE_ENV:qe.enum(["development","production","test"]).default("development")}}),Ze=p(({onConfirm:e,options:t,prompt:r,initialValue:s})=>{const[a,o]=N(()=>{const n=t.findIndex(c=>c.value===s);return Math.max(n,0)});Te(()=>{const n=t.findIndex(c=>c.value===s);o(Math.max(n,0))},[s,t]);const i=$(()=>{const n=t[a];n&&!(n.devOnly&&kt.NODE_ENV==="production")&&e(n.value)},[e,t,a]);return St((n,c)=>{c.upArrow||n==="k"?o(d=>(d-1+t.length)%t.length):c.downArrow||n==="j"?o(d=>(d+1)%t.length):c.return&&i()}),w(q,{flexDirection:"column",children:[m(h,{color:C,children:r}),m(q,{marginTop:1,flexDirection:"column",rowGap:1,children:t.map((n,c)=>{const d=c===a;return w(q,{flexDirection:"column",children:[m(h,{children:d?m(V,{children:n.devOnly&&kt.NODE_ENV==="production"?w(V,{children:[m(h,{color:Oe,children:"> "}),w(h,{color:Oe,children:[n.label,". (Comming soon)"]})]}):w(V,{children:[m(h,{color:I,children:"> "}),m(h,{color:I,children:n.label})]})}):m(h,{color:Oe,children:` ${n.label}`})}),d?m(h,{color:C,children:n.description}):null]},n.value)})})]})},"SingleSelectStep"),Ps=[{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"}],As=[{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"}],Es=[{description:"Default NestJS HTTP adapter",label:"Express",value:"express"},{description:"High-performance HTTP adapter",label:"Fastify",value:"fastify"}],_s=[{description:"Standalone NestJS application",label:"Single project",value:"single"},{description:"Multiple apps and shared packages",devOnly:!0,label:"Monorepo (Turborepo)",value:"monorepo"}],Rs=[{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"}],pr=[{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"}],Is=[{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"}],Os=[{description:"Classic Prisma ORM with driver adapters for PostgreSQL, MySQL, and SQLite",label:"Prisma 7",value:"7"}],Cs=[{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"}],$s=[{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"},{description:"Database-free OIDC sessions stored in encrypted cookies",label:"Better Auth (stateless)",value:"better-auth:stateless"}],We=[{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"}],Ke=[{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"}],Sn=[{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"}],Ds=[{description:"Run git init and create initial commit",label:"Yes",value:"yes"},{description:"Skip git initialization",label:"No",value:"no"}],xn=[{description:"Install all project dependencies using the selected package manager",label:"Yes (Recommended)",value:"yes"},{description:"Skip dependency installation",label:"No",value:"no"}],kn=[{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"}],jn=[{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"}],Tn=[{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"}],Pn=[{description:"Install the reusable Ultracite skill after setup",label:"Yes",value:"yes"},{description:"Skip installing the Ultracite skill",label:"No",value:"no"}],An={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 En=Object.defineProperty,l=p((e,t)=>En(e,"name",{value:t,configurable:!0}),"p");const _n=[{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 Ns(e){return _n.filter(t=>t.when(e))}p(Ns,"Ve"),l(Ns,"resolveSkills");const Rn=vt(ir);function Ls(e,t){if(!/^[a-z0-9-]+\/[a-z0-9-]+$/iu.test(e))throw new Error(`Invalid skill repository: ${e}`);if(!/^[a-z0-9-]+$/iu.test(t))throw new Error(`Invalid skill name: ${t}`);return`npx --yes skills add https://github.com/${e} --skill ${t} --agent codex --copy --yes --json`}p(Ls,"Hr"),l(Ls,"buildCommand");async function Ms(e,t){const r={failed:[],installed:[]};if(!t.addons.includes("agent-skills"))return r;const s=Ns(t);for(const a of s)try{await Rn(Ls(a.repo,a.name),{cwd:e,maxBuffer:4*1024*1024,timeout:6e4,windowsHide:!0}),r.installed.push(a.name)}catch(o){const i=o instanceof Error?o.message:"Unknown error";r.failed.push({error:i,name:a.name})}return r}p(Ms,"We"),l(Ms,"installAgentSkills");class us{static{p(this,"ve")}static{l(this,"TemplateEngine")}cache={};cacheEnabled;templatesDir;constructor(t,r={}){this.templatesDir=t,this.cacheEnabled=r.cache??!0,us.registerHelpers(r.helpers)}static registerHelpers(t){if(pe.registerHelper("eq",(r,s)=>r===s),pe.registerHelper("ne",(r,s)=>r!==s),pe.registerHelper("not",r=>!r),pe.registerHelper("lt",(r,s)=>r<s),pe.registerHelper("gt",(r,s)=>r>s),pe.registerHelper("and",(...r)=>(r.pop(),r.every(Boolean))),pe.registerHelper("or",(...r)=>(r.pop(),r.some(Boolean))),pe.registerHelper("includes",(r,s)=>Array.isArray(r)?r.includes(s):typeof r=="string"?r.includes(String(s)):!1),pe.registerHelper("uppercase",r=>r?.toUpperCase?.()),pe.registerHelper("lowercase",r=>r?.toLowerCase?.()),pe.registerHelper("capitalize",r=>r?r.charAt(0).toUpperCase()+r.slice(1):""),pe.registerHelper("camelCase",r=>r?.split("-").map((s,a)=>a===0?s.toLowerCase():s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),pe.registerHelper("pascalCase",r=>r?.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join("")),pe.registerHelper("snakeCase",r=>r?.replaceAll(/([A-Z])/gu,"_$1").toLowerCase()),t)for(const[r,s]of Object.entries(t))pe.registerHelper(r,s)}async loadTemplate(t){const r=t;if(this.cacheEnabled&&this.cache[r])return this.cache[r];const s=S.join(this.templatesDir,t),a=await ve.readFile(s,"utf-8"),o=pe.compile(a);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 In{static{p(this,"Ke")}static{l(this,"FileWriter")}baseDir;writtenFiles=new Set;constructor(t){this.baseDir=t}getBaseDir(){return this.baseDir}async writeFile(t,r={}){const s=S.join(this.baseDir,t.filePath),a=S.dirname(s);try{await ve.mkdir(a,{recursive:!0});let o=!1;try{await ve.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 i=!1;if(o&&r.createBackups&&!r.dryRun){const n=`${s}.bak`;await ve.copyFile(s,n),i=!0}return r.dryRun||(await ve.writeFile(s,t.content,"utf-8"),this.writtenFiles.add(s)),{backed:i,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=S.join(this.baseDir,t);try{return await ve.stat(r),!0}catch{return!1}}getWrittenFiles(){return[...this.writtenFiles]}clearWrittenFiles(){this.writtenFiles.clear()}async copyDirectory(t,r){const s=[],a=S.join(this.baseDir,t),o=S.join(this.baseDir,r);await ve.mkdir(o,{recursive:!0});const i=await ve.readdir(a,{withFileTypes:!0});for(const n of i){const c=S.join(a,n.name),d=S.join(o,n.name);if(n.isDirectory()){const u=await this.copyDirectory(S.relative(this.baseDir,c),S.relative(this.baseDir,d));s.push(...u)}else{const u=await ve.readFile(c,"utf-8");await ve.writeFile(d,u,"utf-8"),s.push(d),this.writtenFiles.add(d)}}return s}}const jt=vt(Yo);async function lr(e){await jt("git",["init"],{cwd:e})}p(lr,"ke"),l(lr,"gitInit");async function Tt(e){await jt("git",["add","."],{cwd:e})}p(Tt,"re"),l(Tt,"gitAddAll");async function Pt(e,t){await jt("git",["commit","--no-verify","-m",t],{cwd:e})}p(Pt,"se"),l(Pt,"gitCommit");async function Us(e){try{const{stdout:t}=await jt("git",["diff","--cached","--name-only"],{cwd:e});return t.trim().length>0}catch{return!1}}p(Us,"Ye"),l(Us,"gitHasStagedChanges");async function cr(e){try{return await Xo(Y(e,".git")),!0}catch{return!1}}p(cr,"Se"),l(cr,"gitDirectoryExists");class bm{static{p(this,"Qr")}static{l(this,"GitInitializer")}baseDir;constructor(t){this.baseDir=t}async initGit(){try{return await cr(this.baseDir)?{success:!0}:(await lr(this.baseDir),await Tt(this.baseDir),await Pt(this.baseDir,"init"),{success:!0})}catch(t){return{error:t instanceof Error?t.message:String(t),success:!1}}}}const Gs=vt(ir),On={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 Fs(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}`)}}}p(Fs,"Wr"),l(Fs,"getFormatterCommand");function Bs(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="EINVAL")}p(Bs,"Kr"),l(Bs,"isPackageManagerNotFoundError");async function Js(e,t){const r=Fs(e);try{return await Gs(r,{cwd:t,timeout:12e4}),await Gs(r,{cwd:t,timeout:12e4}),{success:!0}}catch(s){if(Bs(s))return{error:On[e],success:!1};const a=[s instanceof Error?s.message:String(s)];return s&&typeof s=="object"&&("stdout"in s&&typeof s.stdout=="string"&&a.push(s.stdout),"stderr"in s&&typeof s.stderr=="string"&&a.push(s.stderr)),{error:a.join(`
23
+ `),success:!1}}}p(Js,"et"),l(Js,"runFormatter");const Ye={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","jwks-rsa":"^4.1.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",tsx:"^4.22.3",turbo:"^2.8.12",typescript:"^6.0.2","typescript-7":"^7.0.0",ultracite:"7.9.4",vitest:"^4.1.10"}};function Hs(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
+ `)}p(Hs,"Yr"),l(Hs,"createEslintConfig");async function Qs(e,t){const r=t.addons.includes("ultracite"),s=Y(e,"package.json"),a=JSON.parse(await Se(s,"utf-8")),o=a.devDependencies??{},i=a.scripts??{},n={},c=["**/node_modules/**","**/dist/**","**/coverage/**","**/.turbo/**","**/generated/**","**/@generated/**","**/migrations/**",...t.auth==="better-auth"&&t.orm.includes("drizzle")?["src/database/orm/drizzle/auth-schema.ts"]:[]];if(r&&(o.ultracite=Ye.devDependencies.ultracite),t.formatter==="biome")o["@biomejs/biome"]="2.5.3",n["biome.jsonc"]=JSON.stringify({...r?{extends:["ultracite/biome/core","ultracite/biome/nestjs"]}:{},files:{includes:["**",...c.map(d=>`!${d.replace(/\/\*\*$/u,"")}`)]},javascript:{parser:{unsafeParameterDecoratorsEnabled:!0}},linter:{enabled:!0,rules:{complexity:{noStaticOnlyClass:"off",noUselessConstructor:"off"},preset:"recommended",style:{useImportType:"off"}}}},null,2),i.check="biome check .",i.fix="biome check --write .",i.format="biome check --write --unsafe .";else if(t.formatter==="oxlint-oxfmt")o.oxlint=Ye.devDependencies.oxlint,o.oxfmt=Ye.devDependencies.oxfmt,n["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(c)},
31
+ });
32
+ `,r?n["oxfmt.config.ts"]=`import { defineConfig } from "oxfmt";
33
+ import core from "ultracite/oxfmt";
34
+
35
+ export default defineConfig({ ...core, ignorePatterns: ${JSON.stringify(c)} });
36
+ `:n[".oxfmtrc.json"]=JSON.stringify({ignorePatterns:c},null,2),i.check="oxlint && oxfmt --check .",i.fix="oxlint --fix && oxfmt --write .",i.format="oxlint --fix && oxfmt --write .";else{o.eslint="^10.0.0",o.prettier=Ye.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"),n["eslint.config.mjs"]=Hs(t,c),n["prettier.config.mjs"]=r?`export { default } from "ultracite/prettier";
37
+ `:`export default {};
38
+ `,n[".prettierignore"]=`${c.join(`
39
+ `)}
40
+ `;const d='eslint "**/src/**/*.ts" "**/test/**/*.ts"';i.check=`${d} && prettier --check .`,i.fix=`${d} --fix && prettier --write .`,i.format=r?i.fix:"prettier --write .",t.formatter==="eslint-prettier-stylelint"&&(o.stylelint="^17.15.0",o["stylelint-config-standard"]="^40.0.0",n["stylelint.config.mjs"]=`export default { extends: ["stylelint-config-standard"] };
41
+ `,i.check+=' && stylelint "**/*.css" --allow-empty-input',i.fix+=' && stylelint "**/*.css" --fix --allow-empty-input')}a.devDependencies=o,a.scripts=i;for(const[d,u]of Object.entries(n))await xe(Y(e,d),`${u.trim()}
42
+ `);await xe(s,`${JSON.stringify(a,null,2)}
43
+ `)}p(Qs,"Xr"),l(Qs,"setupManualLinter");const Cn=vt(ir);function Vs(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}`}}p(Vs,"ts"),l(Vs,"buildUltraciteInitCommand");function Zs(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"}}p(Zs,"rs"),l(Zs,"mapFormatterToLinter");async function Ws(e,t){const r=Zs(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 Qs(e,t),{message:"Manual linter configuration completed",success:!0}}catch(i){return{message:String(i),success:!1}}const s=[];t.addons.includes("husky")&&s.push("husky");const a=["ultracite","init","--quiet","--skip-install","--pm",t.packageManager,"--linter",r,"--frameworks","nestjs"];s.length>0&&a.push("--integrations",...s),t.addons.includes("ultracite")&&(t.ultraciteEditors.length>0&&a.push("--editors",...t.ultraciteEditors),t.ultraciteAgents.length>0&&a.push("--agents",...t.ultraciteAgents),t.ultraciteHooks.length>0&&a.push("--hooks",...t.ultraciteHooks),t.ultraciteInstallSkill==="yes"&&a.push("--install-skill"));const o=Vs(t.packageManager,a);try{await Cn(o,{cwd:e,timeout:12e4});const i=Y(e,"package.json"),n=JSON.parse(await Se(i,"utf-8"));return n.scripts={...n.scripts,format:t.addons.includes("ultracite")?"ultracite fix":{biome:"biome format --write .",eslint:"prettier --write .",oxlint:"oxfmt --write ."}[r]},await xe(i,`${JSON.stringify(n,null,2)}
44
+ `),{message:"Ultracite setup completed",success:!0}}catch(i){let n=i instanceof Error?i.message:String(i);if(i&&typeof i=="object"&&"stderr"in i){const c=i.stderr?.trim();c&&(n=`${n}
45
+ ${c}`)}return{message:`Ultracite setup failed: ${n}`,success:!1}}}p(Ws,"tt"),l(Ws,"runUltraciteInit");class $n{static{p(this,"rt")}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 a=await ve.readdir(t,{withFileTypes:!0});for(const o of a){if(!o.isFile())continue;const{name:i}=o,n=S.extname(i);if(n===".hbs"){const c=S.basename(i,n),d={description:`Template: ${c}`,format:"handlebars",id:c,name:c.replaceAll(/[-_]/gu," "),optional:i.startsWith("_"),path:S.join(S.relative(S.dirname(t),t),i)};s.push(d),this.registerTemplate(d)}}if(r&&s.length>0){const o={description:`Templates from ${t}`,id:r,name:r,templates:s};this.registerGroup(o)}}catch(a){console.error(`Failed to load templates from ${t}:`,a)}return s}clear(){this.templates.clear(),this.groups.clear()}getStats(){return{groupCount:this.groups.size,templateCount:this.templates.size}}}function Dn(e,t,r){}p(Dn,"bc"),l(Dn,"log");const dr={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 Ks(e){const t=Y(e,"oxlint.config.ts");let r;try{r=await Se(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 a=Object.entries(dr.oxlint).map(([n,c])=>{const d=Array.isArray(c)?JSON.stringify(c):`"${c}"`;return` "${n}": ${d}`}).join(`,
47
+ `),o=JSON.stringify(["error",{pattern:".*\\.(test|spec)\\.[tj]sx?$"}]);s=s.replace(/export default defineConfig\(\{([\s\S]*?)\}\);/u,(n,c)=>{const d=c.includes("vitest"),u=c.includes("ignorePatterns"),f=c.includes("rules:"),g=c.includes("overrides:");let z=c;return d||(z=z.replace(/(extends:\s*\[)([\s\S]*?)(\s*\],)/u,(k,x,O,X)=>{const oe=O.trimEnd(),ge=!oe.endsWith(",");return`${x}${oe}${ge?",":""}
27
48
  vitest,
28
- ${F.trimStart()}`})),p||(b=b.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
29
- ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**"],`)),g||(b=`${b} overrides: [
49
+ ${X.trimStart()}`})),u&&!c.includes("migrations/**")&&!c.includes("**/migrations/**")?z=z.replace(/ignorePatterns:\s*([^,\n]+),/u,'ignorePatterns: [...($1 ?? []), "migrations/**"],'):u||(z=z.replace(/(extends:\s*\[[\s\S]*?\],?)/u,`$1
50
+ ignorePatterns: [...(core.ignorePatterns ?? []), "prisma/generated/**", "migrations/**"],`)),g||(z=`${z} overrides: [
30
51
  {
31
52
  files: ["**/*.{test,spec}.{ts,tsx,js,jsx}"],
32
53
  plugins: ["vitest"],
@@ -35,104 +56,350 @@ import vitest from "ultracite/oxlint/vitest";`));const n=Object.entries(ct.oxlin
35
56
  },
36
57
  },
37
58
  ],
38
- `),m||(b=`${b} rules: {
39
- ${n},
59
+ `),f||(z=`${z} rules: {
60
+ ${a},
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}": {
42
- "${m}": "${g}"
62
+ `),`export default defineConfig({${z}});`});try{await xe(t,s,"utf-8"),`${t}`}catch{}const i=Y(e,".gitignore");try{const n=await Se(i,"utf-8");n.split(/\r?\n/u).includes("migrations/")||await xe(i,`${n.trimEnd()}
63
+ migrations/
64
+ `)}catch{}}p(Ks,"ss"),l(Ks,"injectOxlintRules");async function Ys(e){const t=Y(e,"biome.jsonc");let r;try{r=await Se(t,"utf-8"),`${t}`}catch{return}const s=dr.biome,a=r.includes('"linter"'),o=r.includes('"rules"');if(a&&o){const i=Object.entries(s).flatMap(([c,d])=>Object.entries(d).map(([u,f])=>` "${c}": {
65
+ "${u}": "${f}"
43
66
  }`)).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}
45
- ${a}
46
- ${g}`});try{await ve(e,i,"utf-8"),`${e}`}catch{}}else{const i=` "linter": {
67
+ `),n=r.replace(/("linter"\s*:\s*\{[\s\S]*?"rules"\s*:\s*\{)([\s\S]*?)(\})/u,(c,d,u,f)=>{const g=u.trim().endsWith(",")?"":",";return`${d}${u}${g}
68
+ ${i}
69
+ ${f}`});try{await xe(t,n,"utf-8"),`${t}`}catch{}}else{const i=` "linter": {
47
70
  "rules": {
48
- ${Object.entries(s).map(([p,m])=>{const g=Object.entries(m).map(([b,q])=>` "${b}": "${q}"`).join(`,
49
- `);return` "${p}": {
50
- ${g}
71
+ ${Object.entries(s).map(([c,d])=>{const u=Object.entries(d).map(([f,g])=>` "${f}": "${g}"`).join(`,
72
+ `);return` "${c}": {
73
+ ${u}
51
74
  }`}).join(`,
52
75
  `)}
53
76
  }
54
- }`,d=r.replace(/(\}\s*)$/u,p=>`,
77
+ }`,n=r.replace(/(\}\s*)$/u,c=>`,
55
78
  ${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(`,
57
- `),n=r.replace(/\];?$/u,` {
79
+ ${c}`);try{await xe(t,n,"utf-8"),`${t}`}catch{}}}p(Ys,"as"),l(Ys,"injectBiomeRules");async function Xs(e){const t=Y(e,"eslint.config.mjs");let r;try{r=await Se(t,"utf-8"),`${t}`}catch{return}if(r.includes("rules:"))return;const s=Object.entries(dr.eslint).map(([o,i])=>{const n=Array.isArray(i)?JSON.stringify(i):`"${i}"`;return` "${o}": ${n}`}).join(`,
80
+ `),a=r.replace(/\];?$/u,` {
58
81
  rules: {
59
82
  ${s},
60
83
  },
61
84
  },
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(`
85
+ ];`);try{await xe(t,a,"utf-8"),`${t}`}catch{}}p(Xs,"os"),l(Xs,"injectEslintRules");async function ea(e,t){switch(t){case"oxlint-oxfmt":return await Ks(e),{success:!0};case"biome":return await Ys(e),{success:!0};case"eslint-prettier-stylelint":case"eslint-prettier-no-stylelint":return await Xs(e),{success:!0};default:return{message:"No injection needed",success:!0}}}p(ea,"st"),l(ea,"injectUltraciteRules");const Nn=[{profile:"passport-typeorm-mysql",scenario:"215-passport-typeorm-mysql-husky-ultracite"},{profile:"passport-typeorm-sqlite",scenario:"216-passport-typeorm-sqlite-husky-ultracite"},{profile:"passport-drizzle-mysql",scenario:"217-passport-drizzle-mysql-husky-ultracite"},{profile:"passport-drizzle-sqlite",scenario:"218-passport-drizzle-sqlite-husky-ultracite"}],Ln=[{auth:"better-auth",profile:"better-auth-typeorm-postgres-trpc",scenario:"219-better-auth-typeorm-postgres-trpc-todo"},{auth:"passport",profile:"passport-typeorm-postgres-trpc",scenario:"220-passport-typeorm-postgres-trpc-todo"},{auth:"better-auth",profile:"better-auth-drizzle-postgres-trpc",scenario:"221-better-auth-drizzle-postgres-trpc-todo"},{auth:"passport",profile:"passport-drizzle-postgres-trpc",scenario:"222-passport-drizzle-postgres-trpc-todo"},{auth:"better-auth",profile:"better-auth-typeorm-postgres-fastify-trpc",scenario:"223-better-auth-typeorm-postgres-fastify-trpc-todo"},{auth:"passport",profile:"passport-typeorm-postgres-fastify-trpc",scenario:"224-passport-typeorm-postgres-fastify-trpc-todo"},{auth:"better-auth",profile:"better-auth-drizzle-postgres-fastify-trpc",scenario:"225-better-auth-drizzle-postgres-fastify-trpc-todo"},{auth:"passport",profile:"passport-drizzle-postgres-fastify-trpc",scenario:"226-passport-drizzle-postgres-fastify-trpc-todo"}],Mn=[["better-auth","better-auth-typeorm-mysql-trpc","237-better-auth-typeorm-mysql-trpc-todo"],["passport","passport-typeorm-mysql-trpc","238-passport-typeorm-mysql-trpc-todo"],["better-auth","better-auth-drizzle-mysql-trpc","239-better-auth-drizzle-mysql-trpc-todo"],["passport","passport-drizzle-mysql-trpc","240-passport-drizzle-mysql-trpc-todo"],["better-auth","better-auth-typeorm-sqlite-trpc","241-better-auth-typeorm-sqlite-trpc-todo"],["passport","passport-typeorm-sqlite-trpc","242-passport-typeorm-sqlite-trpc-todo"],["passport","passport-drizzle-sqlite-trpc","243-passport-drizzle-sqlite-trpc-todo"]],Un=[["better-auth","better-auth-prisma-fastify-trpc","244-better-auth-prisma-postgres-fastify-trpc-todo"],["passport","passport-prisma-fastify-trpc","245-passport-prisma-postgres-fastify-trpc-todo"]],Gn=[["better-auth-drizzle-trpc","271-better-auth-drizzle-sqlite-express-trpc-todo"],["better-auth-drizzle-fastify-trpc","272-better-auth-drizzle-sqlite-fastify-trpc-todo"]],Fn=[["better-auth","better-auth-prisma-mongo-trpc","273-better-auth-prisma-mongo-express-trpc-todo"],["better-auth","better-auth-prisma-mongo-fastify-trpc","274-better-auth-prisma-mongo-fastify-trpc-todo"],["passport","passport-prisma-mongo-trpc","275-passport-prisma-mongo-express-trpc-todo"],["passport","passport-prisma-mongo-fastify-trpc","276-passport-prisma-mongo-fastify-trpc-todo"]],Bn=[["better-auth","better-auth-typeorm-mysql-fastify-trpc","246-better-auth-typeorm-mysql-fastify-trpc-todo"],["passport","passport-typeorm-mysql-fastify-trpc","247-passport-typeorm-mysql-fastify-trpc-todo"],["better-auth","better-auth-drizzle-mysql-fastify-trpc","248-better-auth-drizzle-mysql-fastify-trpc-todo"],["passport","passport-drizzle-mysql-fastify-trpc","249-passport-drizzle-mysql-fastify-trpc-todo"],["better-auth","better-auth-typeorm-sqlite-fastify-trpc","250-better-auth-typeorm-sqlite-fastify-trpc-todo"],["passport","passport-typeorm-sqlite-fastify-trpc","251-passport-typeorm-sqlite-fastify-trpc-todo"],["passport","passport-drizzle-sqlite-fastify-trpc","252-passport-drizzle-sqlite-fastify-trpc-todo"]],Jn=[["better-auth","better-auth-typeorm-mysql-fastify","253-better-auth-typeorm-mysql-fastify-rest-todo"],["passport","passport-typeorm-mysql-fastify","254-passport-typeorm-mysql-fastify-rest-todo"],["better-auth","better-auth-drizzle-mysql-fastify","255-better-auth-drizzle-mysql-fastify-rest-todo"],["passport","passport-drizzle-mysql-fastify","256-passport-drizzle-mysql-fastify-rest-todo"],["better-auth","better-auth-typeorm-sqlite-fastify","257-better-auth-typeorm-sqlite-fastify-rest-todo"],["passport","passport-typeorm-sqlite-fastify","258-passport-typeorm-sqlite-fastify-rest-todo"],["passport","passport-drizzle-sqlite-fastify","259-passport-drizzle-sqlite-fastify-rest-todo"],["better-auth","better-auth-prisma-fastify","277-better-auth-prisma-postgres-fastify-rest-todo"],["passport","passport-prisma-fastify","278-passport-prisma-postgres-fastify-rest-todo"],["passport","passport-typeorm-postgres-fastify","279-passport-typeorm-postgres-fastify-rest-todo"],["passport","passport-drizzle-postgres-fastify","280-passport-drizzle-postgres-fastify-rest-todo"]],Hn=[["passport-typeorm-postgres-fastify","260-passport-typeorm-postgresql-fastify-rate-limiting"],["passport-drizzle-postgres-fastify","261-passport-drizzle-postgresql-fastify-rate-limiting"],["passport-typeorm-mysql-fastify","262-passport-typeorm-mysql-fastify-rate-limiting"],["passport-drizzle-mysql-fastify","263-passport-drizzle-mysql-fastify-rate-limiting"],["passport-typeorm-sqlite-fastify","264-passport-typeorm-sqlite-fastify-rate-limiting"],["passport-drizzle-sqlite-fastify","265-passport-drizzle-sqlite-fastify-rate-limiting"]],Qn=[["better-auth","better-auth-drizzle-graphql-fastify","227-better-auth-drizzle-graphql-postgresql-fastify-todo"],["better-auth","better-auth-drizzle-graphql-mysql","228-better-auth-drizzle-graphql-mysql-todo"],["better-auth","better-auth-drizzle-graphql-mysql-fastify","229-better-auth-drizzle-graphql-mysql-fastify-todo"],["better-auth","better-auth-drizzle-graphql-sqlite","230-better-auth-drizzle-graphql-sqlite-todo"],["better-auth","better-auth-drizzle-graphql-sqlite-fastify","231-better-auth-drizzle-graphql-sqlite-fastify-todo"],["passport","passport-drizzle-graphql-fastify","232-passport-drizzle-graphql-postgresql-fastify-todo"],["passport","passport-drizzle-graphql-mysql","233-passport-drizzle-graphql-mysql-todo"],["passport","passport-drizzle-graphql-mysql-fastify","234-passport-drizzle-graphql-mysql-fastify-todo"],["passport","passport-drizzle-graphql-sqlite","235-passport-drizzle-graphql-sqlite-todo"],["passport","passport-drizzle-graphql-sqlite-fastify","236-passport-drizzle-graphql-sqlite-fastify-todo"]],At=[["better-auth-drizzle-graphql-fastify","281-better-auth-drizzle-graphql-postgres-fastify-rate-limiting"],["better-auth-drizzle-graphql-mysql","282-better-auth-drizzle-graphql-mysql-rate-limiting"],["better-auth-drizzle-graphql-mysql-fastify","283-better-auth-drizzle-graphql-mysql-fastify-rate-limiting"],["better-auth-drizzle-graphql-sqlite","284-better-auth-drizzle-graphql-sqlite-rate-limiting"],["better-auth-drizzle-graphql-sqlite-fastify","285-better-auth-drizzle-graphql-sqlite-fastify-rate-limiting"],["passport-drizzle-graphql-fastify","286-passport-drizzle-graphql-postgres-fastify-rate-limiting"],["passport-drizzle-graphql-mysql","287-passport-drizzle-graphql-mysql-rate-limiting"],["passport-drizzle-graphql-mysql-fastify","288-passport-drizzle-graphql-mysql-fastify-rate-limiting"],["passport-drizzle-graphql-sqlite","289-passport-drizzle-graphql-sqlite-rate-limiting"],["passport-drizzle-graphql-sqlite-fastify","290-passport-drizzle-graphql-sqlite-fastify-rate-limiting"]],Vn=[["better-auth-typeorm-postgres","better-auth","291-better-auth-typeorm-postgres-rest-todo"],["better-auth-drizzle-postgres","better-auth","292-better-auth-drizzle-postgres-rest-todo"],["passport-prisma-mongo","passport","293-passport-prisma-mongo-rest-todo"],["passport-prisma-mongo-fastify","passport","294-passport-prisma-mongo-fastify-rest-todo"]],Zn=[["better-auth-prisma-mongo","301-better-auth-prisma-mongo-rest-todo"],["better-auth-prisma-mongo-fastify","302-better-auth-prisma-mongo-fastify-rest-todo"],["better-auth-drizzle","303-better-auth-drizzle-sqlite-rest-todo"],["better-auth-drizzle-fastify","304-better-auth-drizzle-sqlite-fastify-rest-todo"]],Wn=[["better-auth-prisma-docker","better-auth",["docker","todo-example"],"305-better-auth-prisma-docker-todo"],["passport-prisma-docker","passport",["docker","todo-example"],"306-passport-prisma-docker-todo"],["better-auth-monorepo-prisma-postgres","better-auth",["packages/shared","todo-example"],"307-better-auth-monorepo-prisma-todo"]],Kn=[["passport-prisma","295-passport-prisma-typescript-7"]],Yn=[["better-auth-drizzle-graphql-fastify","296-better-auth-drizzle-graphql-postgres-fastify-health"],["better-auth-drizzle-graphql-mysql","297-better-auth-drizzle-graphql-mysql-health"],["better-auth-drizzle-graphql-mysql-fastify","298-better-auth-drizzle-graphql-mysql-fastify-health"],["better-auth-drizzle-graphql-sqlite","299-better-auth-drizzle-graphql-sqlite-health"],["better-auth-drizzle-graphql-sqlite-fastify","300-better-auth-drizzle-graphql-sqlite-fastify-health"]],Xn=[["better-auth-drizzle-graphql","better-auth","114-better-auth-drizzle-graphql-health"],["passport-prisma-graphql","passport","52-passport-prisma-graphql"],["passport-typeorm-mysql","passport","178-passport-typeorm-mysql-health"],["passport-typeorm-sqlite","passport","179-passport-typeorm-sqlite-health"],["passport-drizzle-mysql","passport","180-passport-drizzle-mysql-health"],["passport-drizzle-sqlite","passport","181-passport-drizzle-sqlite-health"]],ur=[...[["microservice-redis","22-microservice-redis"],["microservice-grpc","23-microservice-grpc"],["microservice-mqtt","24-microservice-mqtt"],["microservice-nats","25-microservice-nats"],["microservice-rabbitmq","26-microservice-rabbitmq"],["microservice-kafka","27-microservice-kafka"]].map(([e,t])=>({addons:[],auth:"none",extras:[],id:`${e}-runtime`,note:`Generated request/reply handlers passed the isolated runtime scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Xn.map(([e,t,r])=>({addons:[],auth:t,extras:["health-check"],id:`${e}-graphql-health-check`,note:`Authenticated health-check runtime behavior passed scenario ${r} for ${e}.`,profiles:[e],scenarios:[r],status:"certified"})),...Wn.map(([e,t,r,s])=>({addons:[],auth:t,extras:r,id:`${e}-todo-example`,note:`Authenticated todo ownership passed the full runtime scenario ${s} for layout profile ${e}.`,profiles:[e],scenarios:[s],status:"certified"})),...Zn.map(([e,t])=>({addons:[],auth:"better-auth",extras:["todo-example"],id:`${e}-todo-rest`,note:`Better Auth authenticated todo ownership passed runtime scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Yn.map(([e,t])=>({addons:[],auth:"better-auth",extras:["health-check"],id:`${e}-health-check`,note:`Better Auth Drizzle GraphQL healthy readiness and database outage HTTP 503 passed in scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Kn.map(([e,t])=>({addons:[],auth:"passport",extras:["typescript-7"],id:`${e}-typescript-7`,note:`Passport Prisma TypeScript 7 builds, migrates, passes unit tests, and authenticates in runtime scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Vn.map(([e,t,r])=>({addons:[],auth:t,extras:["todo-example"],id:`${e}-todo-rest`,note:`Todo create, owner isolation, update, and delete passed for ${e} in full runtime scenario ${r}.`,profiles:[e],scenarios:[r],status:"certified"})),{addons:[],auth:"better-auth",extras:["typescript-7"],id:"better-auth-prisma-typescript-7",note:"Better Auth Prisma TypeScript 7 builds, generates its adapter schema, passes unit and E2E tests, and resolves an authenticated profile in scenario 268.",profiles:["better-auth-prisma"],scenarios:["268-better-auth-prisma-typescript-7"],status:"certified"},{addons:[],auth:"better-auth",extras:["packages/shared"],id:"better-auth-monorepo-packages-shared",note:"Better Auth Prisma monorepo auth schema generation, database migrations, workspace build, and authenticated session resolution passed in scenario 267.",profiles:["better-auth-monorepo-prisma-postgres"],scenarios:["267-better-auth-monorepo-prisma-postgres"],status:"certified"},...Hn.map(([e,t])=>({addons:[],auth:"passport",extras:["rate-limiting"],id:`${e}-rate-limiting`,note:`Passport Fastify REST login remains usable and repeated invalid attempts receive HTTP 429 in scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Jn.map(([e,t,r])=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-rest`,note:`${e==="better-auth"?"Better Auth":"Passport"} PostgreSQL Fastify REST todo ownership passed authentication, owner isolation, update, delete, migrations, build, unit tests, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),...Bn.map(([e,t,r])=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-trpc`,note:`${e==="better-auth"?"Better Auth":"Passport"} ${t.includes("typeorm")?"TypeORM":"Drizzle"} ${t.includes("mysql")?"MySQL":"SQLite"} Fastify tRPC todo ownership passed anonymous rejection, authentication, owner isolation, update, delete, migrations, build, unit tests, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),...Un.map(([e,t,r])=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-trpc`,note:`${e==="better-auth"?"Better Auth":"Passport"} Prisma PostgreSQL Fastify tRPC todo ownership passed authentication, owner isolation, update, delete, Prisma migrations, build, unit tests, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),...Gn.map(([e,t])=>({addons:[],auth:"better-auth",extras:["todo-example"],id:`${e}-todo-trpc`,note:`Better Auth Drizzle SQLite ${e.includes("fastify")?"Fastify":"Express"} tRPC todo ownership passed anonymous rejection, authentication, owner isolation, update, delete, migrations, build, unit tests, and runtime checks in scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),...Fn.map(([e,t,r])=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-trpc`,note:`${e==="better-auth"?"Better Auth":"Passport"} Prisma MongoDB ${t.includes("fastify")?"Fastify":"Express"} tRPC todo ownership passed authentication, owner isolation, create, update, delete, Prisma generation and push, build, unit tests, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),...Mn.map(([e,t,r])=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-trpc`,note:`${e==="better-auth"?"Better Auth":"Passport"} ${t.includes("typeorm")?"TypeORM":"Drizzle"} ${t.includes("mysql")?"MySQL":"SQLite"} tRPC todo ownership passed anonymous rejection, authentication, owner isolation, update, delete, migrations, build, unit tests, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),...Qn.map(([e,t,r])=>{let s="PostgreSQL";t.includes("sqlite")?s="SQLite":t.includes("mysql")&&(s="MySQL");const a=t.includes("fastify")?"Fastify":"Express",o=e==="better-auth"?"Better Auth":"Passport";return{addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-graphql`,note:`${o} Drizzle GraphQL todo ownership for ${s} ${a} passed anonymous rejection, owner isolation, update, delete, build, and runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"}}),...Ln.map(({auth:e,profile:t,scenario:r})=>({addons:[],auth:e,extras:["todo-example"],id:`${t}-todo-trpc`,note:`${e==="better-auth"?"Better Auth":"Passport"} ${t.includes("typeorm")?"TypeORM":"Drizzle"} PostgreSQL tRPC todo ownership passed registration, authentication, owner isolation, update, delete, migrations, build, unit tests, and end-to-end runtime checks in scenario ${r}.`,profiles:[t],scenarios:[r],status:"certified"})),{addons:["agent-skills"],auth:"passport",extras:[],id:"passport-agent-skills",note:"Passport + Drizzle PostgreSQL skills install noninteractively into the Codex project directory without replacing generated app files (scenario 210).",profiles:["passport-drizzle-postgres"],scenarios:["210-passport-drizzle-agent-skills"],status:"certified"},{addons:["agent-skills","ultracite"],auth:"passport",extras:[],id:"passport-agent-skills-ultracite",note:"Passport + Drizzle PostgreSQL skills install noninteractively and coexist with generated Ultracite instructions (scenario 211).",profiles:["passport-drizzle-postgres"],scenarios:["211-passport-drizzle-agent-skills-ultracite"],status:"certified"},{addons:["agent-skills"],auth:"better-auth",extras:[],id:"better-auth-agent-skills",note:"Better Auth + Prisma PostgreSQL installs auth, Prisma, NestJS, and JWT skills into the Codex project directory and passes generated-project checks (scenario 212).",profiles:["better-auth-prisma"],scenarios:["212-better-auth-prisma-agent-skills"],status:"certified"},{addons:["agent-skills"],auth:"passport",extras:[],id:"passport-typeorm-agent-skills",note:"Passport + TypeORM PostgreSQL installs TypeORM, NestJS, and JWT skills into the Codex project directory (scenario 213).",profiles:["passport-typeorm-postgres"],scenarios:["213-passport-typeorm-agent-skills"],status:"certified"},{addons:["agent-skills"],auth:"better-auth",extras:[],id:"better-auth-drizzle-agent-skills",note:"Better Auth + Drizzle PostgreSQL installs auth, NestJS, and JWT skills into the Codex project directory (scenario 214).",profiles:["better-auth-drizzle-postgres"],scenarios:["214-better-auth-drizzle-agent-skills"],status:"certified"},{addons:[],auth:"any",extras:[],id:"baseline",note:"No extras and no addons is the certified baseline for every profile.",scenarios:["01-minimal-no-install-no-git","14-better-auth-prisma","15-better-auth-drizzle","17-passport-prisma","31-better-auth-native-postgres"],status:"certified"},{addons:[],auth:"none",extras:["todo-example"],id:"none-todo-example",note:"Todo example with unauthenticated scaffolds across SQL and MongoDB profiles.",scenarios:["04-postgres-prisma","11-mysql-prisma-fastify","12-sqlite-drizzle","13-postgres-typeorm","16-graphql-prisma","18-mongodb-native","20-prisma8-postgres","101-todo-fastify-drizzle-mysql"],status:"certified"},{addons:[],auth:"none",extras:["docker"],id:"none-docker",note:"PostgreSQL Prisma Docker image builds, migrates, starts under Compose, serves the health endpoint over its published port, and tears down cleanly in scenario 171.",profiles:["prisma"],scenarios:["171-docker-health-prisma"],status:"certified"},{addons:[],auth:"none",extras:["docker","health-check"],id:"none-docker-health-check",note:"PostgreSQL Prisma Docker health-check runtime passed in scenario 171.",profiles:["prisma"],scenarios:["171-docker-health-prisma"],status:"certified"},{addons:["scalar-ui"],auth:"none",extras:["swagger"],id:"none-swagger-scalar",note:"Swagger document generation with the Scalar reference UI.",scenarios:["03-rest-swagger-scalar","99-swagger-scalar-fastify-drizzle"],status:"certified"},{addons:["scalar-ui"],auth:"better-auth",extras:["swagger"],id:"better-auth-prisma-swagger-scalar",note:"Better Auth + Prisma OpenAPI generation and Scalar UI; scenario 158 checks generated auth paths and serves the reference UI.",profiles:["better-auth-prisma"],scenarios:["158-better-auth-prisma-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-prisma-swagger-scalar",note:"Passport + Prisma OpenAPI generation and Scalar UI; scenario 159 checks documented auth paths and serves the reference UI.",profiles:["passport-prisma"],scenarios:["159-passport-prisma-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-typeorm-swagger-scalar",note:"Passport TypeORM PostgreSQL REST Swagger auth documentation and Scalar UI pass build and E2E in scenario 194.",profiles:["passport-typeorm-postgres"],scenarios:["194-passport-typeorm-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-drizzle-swagger-scalar",note:"Passport Drizzle PostgreSQL REST Swagger auth documentation and Scalar UI pass migrations, build, and E2E in scenario 195.",profiles:["passport-drizzle-postgres"],scenarios:["195-passport-drizzle-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-typeorm-mysql-swagger-scalar",note:"Passport TypeORM MySQL REST Swagger auth documentation and Scalar UI pass build and E2E in scenario 202.",profiles:["passport-typeorm-mysql"],scenarios:["202-passport-typeorm-mysql-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-typeorm-sqlite-swagger-scalar",note:"Passport TypeORM SQLite REST Swagger auth documentation and Scalar UI pass build and E2E in scenario 203.",profiles:["passport-typeorm-sqlite"],scenarios:["203-passport-typeorm-sqlite-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-drizzle-mysql-swagger-scalar",note:"Passport Drizzle MySQL REST Swagger auth documentation and Scalar UI pass migrations, build, and E2E in scenario 204.",profiles:["passport-drizzle-mysql"],scenarios:["204-passport-drizzle-mysql-swagger-scalar"],status:"certified"},{addons:["scalar-ui"],auth:"passport",extras:["swagger"],id:"passport-drizzle-sqlite-swagger-scalar",note:"Passport Drizzle SQLite REST Swagger auth documentation and Scalar UI pass migrations, build, and E2E in scenario 205.",profiles:["passport-drizzle-sqlite"],scenarios:["205-passport-drizzle-sqlite-swagger-scalar"],status:"certified"},{addons:["nestjs-zod"],auth:"better-auth",extras:["swagger","todo-example"],id:"better-auth-prisma-nestjs-zod-swagger-todo",note:"Better Auth + Prisma with nestjs-zod DTO validation and Swagger generation; scenario 160 checks invalid authenticated todos and documents their request body.",profiles:["better-auth-prisma"],scenarios:["160-better-auth-prisma-nestjs-zod-swagger-todo"],status:"certified"},{addons:["husky"],auth:"better-auth",extras:[],id:"better-auth-prisma-husky",note:"Better Auth + Prisma with the Husky pre-commit hook; scenario 162 checks Git setup and both successful and failing hook execution.",profiles:["better-auth-prisma"],scenarios:["162-better-auth-prisma-husky"],status:"certified"},{addons:["husky","ultracite"],auth:"better-auth",extras:[],id:"better-auth-prisma-husky-ultracite",note:"Better Auth + Prisma with Ultracite formatting and Husky hooks passed clean install, schema/migration generation, tests, and hook success/failure checks in scenario 167.",profiles:["better-auth-prisma"],scenarios:["167-better-auth-prisma-husky-ultracite"],status:"certified"},{addons:["husky","ultracite"],auth:"passport",extras:[],id:"passport-typeorm-husky-ultracite",note:"Passport TypeORM PostgreSQL REST with Ultracite and Husky hooks passed clean install, migrations, build, tests, formatting, and passing/failing hook commits in scenario 192.",profiles:["passport-typeorm-postgres"],scenarios:["192-passport-typeorm-husky-ultracite"],status:"certified"},{addons:["husky","ultracite"],auth:"passport",extras:[],id:"passport-drizzle-husky-ultracite",note:"Passport Drizzle PostgreSQL REST with Ultracite and Husky hooks passed clean install, migrations, build, tests, formatting, and passing/failing hook commits in scenario 193.",profiles:["passport-drizzle-postgres"],scenarios:["193-passport-drizzle-husky-ultracite"],status:"certified"},{addons:["husky","ultracite"],auth:"passport",extras:[],id:"passport-prisma-husky-ultracite",note:"Passport Prisma with Ultracite passes formatting, schema generation, migrations, build, tests, and successful/failing Husky hooks in scenario 173.",profiles:["passport-prisma"],scenarios:["173-passport-prisma-husky-ultracite"],status:"certified"},...Nn.map(({profile:e,scenario:t})=>({addons:["husky","ultracite"],auth:"passport",extras:[],id:`${e}-husky-ultracite`,note:`Passport ${e.includes("typeorm")?"TypeORM":"Drizzle"} ${e.includes("mysql")?"MySQL":"SQLite"} REST with Husky and Ultracite passed migrations, build, tests, formatting, and hook success/failure checks in scenario ${t}.`,profiles:[e],scenarios:[t],status:"certified"})),{addons:["husky"],auth:"passport",extras:[],id:"passport-prisma-husky",note:"Passport + Prisma with the Husky pre-commit hook; scenario 163 checks Git setup and both successful and failing hook execution.",profiles:["passport-prisma"],scenarios:["163-passport-prisma-husky"],status:"certified"},{addons:[],auth:"better-auth",extras:["docker"],id:"better-auth-prisma-docker",note:"Better Auth + Prisma Docker image, container-side schema generation/migrations, Compose startup, and published-port auth check passed in scenario 164.",profiles:["better-auth-prisma-docker"],scenarios:["164-better-auth-prisma-docker"],status:"certified"},{addons:[],auth:"passport",extras:["docker"],id:"passport-prisma-docker",note:"Passport + Prisma Docker clean install, migrations, build/tests, Compose startup, and protected published-port endpoint passed in scenario 165.",profiles:["passport-prisma-docker"],scenarios:["165-passport-prisma-docker"],status:"certified"},{addons:[],auth:"better-auth",extras:["docker","health-check"],id:"better-auth-prisma-docker-health-restart",note:"Better Auth user creation, generated migrations, Docker health, app-container restart, and post-restart sign-in/session resolution passed in scenario 172.",profiles:["better-auth-prisma-docker"],scenarios:["172-better-auth-prisma-docker-health-restart"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-prisma-trpc-todo",note:"Better Auth + Prisma REST and tRPC todo operations pass anonymous rejection and two-user owner-isolation checks in scenario 168.",profiles:["better-auth-prisma-trpc"],scenarios:["168-better-auth-prisma-trpc-todo"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-prisma-trpc-todo",note:"Passport + Prisma REST and tRPC todo operations pass anonymous rejection and two-user owner-isolation checks in scenario 169.",profiles:["passport-prisma-trpc"],scenarios:["169-passport-prisma-trpc-todo"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-prisma-rate-limiting",note:"Normal Passport login and repeated login throttling return the expected success and 429 responses in scenario 170.",profiles:["passport-prisma"],scenarios:["170-passport-prisma-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-prisma-trpc-rate-limiting",note:"Scenario 270 verifies normal Passport login, HTTP 429 after repeated invalid login attempts, and HTTP 429 for repeated tRPC procedure requests.",profiles:["passport-prisma-trpc"],scenarios:["270-passport-prisma-trpc-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-typeorm-rate-limiting",note:"Scenario 188 verifies Passport TypeORM PostgreSQL REST login remains usable and repeated invalid logins receive HTTP 429.",profiles:["passport-typeorm-postgres"],scenarios:["188-passport-typeorm-postgres-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-drizzle-rate-limiting",note:"Scenario 189 verifies Passport Drizzle PostgreSQL REST login remains usable and repeated invalid logins receive HTTP 429.",profiles:["passport-drizzle-postgres"],scenarios:["189-passport-drizzle-postgres-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-typeorm-mysql-rate-limiting",note:"Scenario 198 verifies Passport TypeORM MySQL REST normal login and HTTP 429 after repeated invalid attempts.",profiles:["passport-typeorm-mysql"],scenarios:["198-passport-typeorm-mysql-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-typeorm-sqlite-rate-limiting",note:"Scenario 199 verifies Passport TypeORM SQLite REST normal login and HTTP 429 after repeated invalid attempts.",profiles:["passport-typeorm-sqlite"],scenarios:["199-passport-typeorm-sqlite-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-drizzle-mysql-rate-limiting",note:"Scenario 200 verifies Passport Drizzle MySQL REST normal login and HTTP 429 after repeated invalid attempts.",profiles:["passport-drizzle-mysql"],scenarios:["200-passport-drizzle-mysql-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-drizzle-sqlite-rate-limiting",note:"Scenario 201 verifies Passport Drizzle SQLite REST normal login and HTTP 429 after repeated invalid attempts.",profiles:["passport-drizzle-sqlite"],scenarios:["201-passport-drizzle-sqlite-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["health-check"],id:"passport-prisma-health-check",note:"Scenario 174 verifies healthy anonymous readiness and PostgreSQL outage transitions return HTTP 503 with Passport Prisma REST.",profiles:["passport-prisma"],scenarios:["174-passport-prisma-health-check"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-prisma-rest-todo",note:"Passport Prisma REST todo scenario 175 verifies authenticated owner access and blocks cross-user list, update, and delete operations.",profiles:["passport-prisma"],scenarios:["175-passport-prisma-rest-todo"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-typeorm-rest-todo",note:"Passport TypeORM REST todo ownership and owner isolation passed on PostgreSQL, MySQL, and SQLite in scenarios 182, 184, and 185; Fastify/tRPC variants remain gated.",profiles:["passport-typeorm-postgres","passport-typeorm-mysql","passport-typeorm-sqlite"],scenarios:["182-passport-typeorm-postgres-rest-todo","184-passport-typeorm-mysql-rest-todo","185-passport-typeorm-sqlite-rest-todo"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-drizzle-rest-todo",note:"Passport Drizzle REST todo ownership and owner isolation passed on PostgreSQL, MySQL, and SQLite in scenarios 183, 186, and 187; Fastify/tRPC variants remain gated.",profiles:["passport-drizzle-postgres","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["183-passport-drizzle-postgres-rest-todo","186-passport-drizzle-mysql-rest-todo","187-passport-drizzle-sqlite-rest-todo"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-prisma-rate-limiting",note:"A successful Better Auth sign-in followed by repeated authentication requests reaching 429 passed in scenario 48.",profiles:["better-auth-prisma"],scenarios:["48-better-auth-prisma-rate-limit"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-typeorm-nestjs-zod-swagger-todo",note:"Passport TypeORM PostgreSQL REST nestjs-zod, Swagger, and authenticated todo ownership pass build and E2E in scenario 196.",profiles:["passport-typeorm-postgres"],scenarios:["196-passport-typeorm-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-drizzle-nestjs-zod-swagger-todo",note:"Passport Drizzle PostgreSQL REST nestjs-zod, Swagger, and authenticated todo ownership pass migrations, build, and E2E in scenario 197.",profiles:["passport-drizzle-postgres"],scenarios:["197-passport-drizzle-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-typeorm-mysql-nestjs-zod-swagger-todo",note:"Passport TypeORM MySQL REST nestjs-zod, Swagger, and todo ownership pass migrations, build, and E2E in scenario 206.",profiles:["passport-typeorm-mysql"],scenarios:["206-passport-typeorm-mysql-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-typeorm-sqlite-nestjs-zod-swagger-todo",note:"Passport TypeORM SQLite REST nestjs-zod, Swagger, and todo ownership pass migrations, build, and E2E in scenario 207.",profiles:["passport-typeorm-sqlite"],scenarios:["207-passport-typeorm-sqlite-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-drizzle-mysql-nestjs-zod-swagger-todo",note:"Passport Drizzle MySQL REST nestjs-zod, Swagger, and todo ownership pass migrations, build, and E2E in scenario 208.",profiles:["passport-drizzle-mysql"],scenarios:["208-passport-drizzle-mysql-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-drizzle-sqlite-nestjs-zod-swagger-todo",note:"Passport Drizzle SQLite REST nestjs-zod, Swagger, and todo ownership pass migrations, build, and E2E in scenario 209.",profiles:["passport-drizzle-sqlite"],scenarios:["209-passport-drizzle-sqlite-nestjs-zod-swagger-todo"],status:"certified"},{addons:["nestjs-zod"],auth:"passport",extras:["swagger","todo-example"],id:"passport-prisma-nestjs-zod-swagger-todo",note:"Passport + Prisma with nestjs-zod DTO validation and Swagger generation; scenario 161 checks invalid authenticated todos and documents their request body.",profiles:["passport-prisma"],scenarios:["161-passport-prisma-nestjs-zod-swagger-todo"],status:"certified"},{addons:["ultracite"],auth:"none",extras:["health-check"],id:"none-health-ultracite",note:"Terminus health endpoints with the Ultracite toolchain preset.",scenarios:["06-fastify-health","100-health-fastify-typeorm"],status:"certified"},{addons:["ultracite"],auth:"none",extras:[],id:"none-ultracite",note:"Ultracite toolchain without feature extras.",scenarios:["05-trpc-yarn","08-rest-npm-zod","102-ultracite-fastify-native-postgres"],status:"certified"},{addons:["nestjs-zod","ultracite"],auth:"none",extras:[],id:"none-nestjs-zod-ultracite",note:"NestJS-Zod request validation with the Ultracite toolchain.",scenarios:["08-rest-npm-zod"],status:"certified"},{addons:["ultracite"],auth:"none",extras:["todo-example"],id:"none-todo-ultracite",note:"Todo example with the Ultracite toolchain.",scenarios:["11-mysql-prisma-fastify","12-sqlite-drizzle","13-postgres-typeorm"],status:"certified"},{addons:[],auth:"none",extras:["packages/shared"],id:"none-packages-shared",note:"Shared package export surface for monorepo layouts.",scenarios:["09-monorepo-gateway-redis"],status:"implemented"},{addons:["ultracite"],auth:"none",extras:["packages/shared"],id:"none-packages-shared-ultracite",note:"Shared packages combined with the Ultracite toolchain.",scenarios:["09-monorepo-gateway-redis"],status:"implemented"},{addons:["ultracite"],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-rate-limiting-ultracite",note:"Throttling applied to Better Auth endpoints with the Ultracite toolchain.",profiles:["better-auth-native-postgres-trpc"],scenarios:["07-postgres-better-auth-trpc"],status:"certified"},{addons:["ultracite"],auth:"passport",extras:[],id:"passport-prisma-ultracite",note:"Passport + Prisma generated authentication files pass Ultracite formatting, build, unit tests, and E2E in scenario 166.",profiles:["passport-prisma"],scenarios:["166-passport-prisma-ultracite"],status:"certified"},{addons:["ultracite"],auth:"passport",extras:[],id:"passport-typeorm-ultracite",note:"Passport TypeORM PostgreSQL REST with Ultracite passed clean install, migrations, lint/format, build, unit tests, and E2E in scenario 190.",profiles:["passport-typeorm-postgres"],scenarios:["190-passport-typeorm-postgres-ultracite"],status:"certified"},{addons:["ultracite"],auth:"passport",extras:[],id:"passport-drizzle-ultracite",note:"Passport Drizzle PostgreSQL REST with Ultracite passed clean install, migrations, lint/format, build, unit tests, and E2E in scenario 191.",profiles:["passport-drizzle-postgres"],scenarios:["191-passport-drizzle-postgres-ultracite"],status:"certified"},{addons:["ultracite"],auth:"passport",extras:[],id:"passport-drizzle-graphql-ultracite",note:"Ultracite with Passport and Drizzle GraphQL; scenarios 133\u2013138 passed across PostgreSQL/MySQL/SQLite and Express/Fastify.",profiles:["passport-drizzle-graphql","passport-drizzle-graphql-fastify","passport-drizzle-graphql-mysql","passport-drizzle-graphql-mysql-fastify","passport-drizzle-graphql-sqlite","passport-drizzle-graphql-sqlite-fastify"],scenarios:["133-passport-drizzle-graphql-ultracite","134-passport-drizzle-graphql-fastify-ultracite","135-passport-drizzle-graphql-mysql-ultracite","136-passport-drizzle-graphql-mysql-fastify-ultracite","137-passport-drizzle-graphql-sqlite-ultracite","138-passport-drizzle-graphql-sqlite-fastify-ultracite"],status:"certified"},{addons:["ultracite"],auth:"none",extras:[],id:"graphql-drizzle-ultracite",note:"Ultracite on the unauthenticated Drizzle GraphQL profile; runtime scenario 117 passed install, migrations, lint/format, build, and GraphQL E2E.",profiles:["graphql-drizzle"],scenarios:["117-graphql-drizzle-ultracite"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-rate-limiting",note:"Throttling applied to Better Auth endpoints alone.",profiles:["better-auth-native-postgres-trpc","better-auth-prisma"],scenarios:["07-postgres-better-auth-trpc"],status:"certified"},{addons:[],auth:"better-auth",extras:["health-check"],id:"better-auth-health-check",note:"Terminus health endpoints alongside Better Auth; scenario 47 verifies PostgreSQL outage transitions return HTTP 503.",profiles:["better-auth-prisma"],scenarios:["47-better-auth-prisma-health"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-todo-example",note:"Ownership-scoped todo example alongside Better Auth.",profiles:["better-auth-prisma"],scenarios:["49-better-auth-prisma-todo"],status:"certified"},{addons:["ultracite"],auth:"better-auth",extras:[],id:"better-auth-ultracite",note:"Bare Better Auth + Ultracite composition; scenario 157 runs auth schema generation, formatting, migrations, build, and E2E.",profiles:["better-auth-prisma"],scenarios:["157-better-auth-prisma-ultracite"],status:"certified"},{addons:[],auth:"better-auth",extras:["health-check"],id:"better-auth-graphql-health-check",note:"Terminus health endpoints alongside GraphQL and Better Auth.",profiles:["better-auth-prisma-graphql"],scenarios:["51-better-auth-prisma-graphql"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-graphql-rate-limiting",note:"GraphQL rate limiting with Better Auth and Prisma; scenario 155 exercises repeated GraphQL requests against the generated throttler guard.",profiles:["better-auth-prisma-graphql"],scenarios:["155-better-auth-prisma-graphql-rate-limiting"],status:"certified"},{addons:[],auth:"passport",extras:["health-check"],id:"passport-graphql-health-check",note:"Terminus health endpoints alongside GraphQL and Passport.",profiles:["passport-prisma-graphql"],scenarios:["52-passport-prisma-graphql"],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-graphql-rate-limiting",note:"GraphQL rate limiting with Passport and Prisma; scenario 156 exercises repeated GraphQL requests against the generated throttler guard.",profiles:["passport-prisma-graphql"],scenarios:["156-passport-prisma-graphql-rate-limiting"],status:"certified"},{addons:[],auth:"better-auth",extras:["health-check"],id:"better-auth-drizzle-graphql-health-check",note:"Terminus readiness alongside Better Auth and Drizzle GraphQL; certified by scenario 114.",profiles:["better-auth-drizzle-graphql"],scenarios:["114-better-auth-drizzle-graphql-health"],status:"certified"},{addons:[],auth:"passport",extras:["health-check"],id:"passport-drizzle-graphql-health-check",note:"Terminus readiness alongside Passport and Drizzle GraphQL; scenarios 115 and 139\u2013143 pass across PostgreSQL/MySQL/SQLite and Express/Fastify.",profiles:["passport-drizzle-graphql","passport-drizzle-graphql-fastify","passport-drizzle-graphql-mysql","passport-drizzle-graphql-mysql-fastify","passport-drizzle-graphql-sqlite","passport-drizzle-graphql-sqlite-fastify"],scenarios:["115-passport-drizzle-graphql-health","139-passport-drizzle-graphql-fastify-health","140-passport-drizzle-graphql-mysql-health","141-passport-drizzle-graphql-mysql-fastify-health","142-passport-drizzle-graphql-sqlite-health","143-passport-drizzle-graphql-sqlite-fastify-health"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-graphql-todo-example",note:"Passport GraphQL todo with Prisma; scenario 154 verifies anonymous rejection and owner isolation using Prisma Passport's register/login flow.",profiles:["passport-prisma-graphql"],scenarios:["154-passport-prisma-graphql-todo"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-prisma-graphql-todo-example",note:"Better Auth GraphQL todo with Prisma; scenario 153 verifies anonymous rejection and owner isolation across two persisted users.",profiles:["better-auth-prisma-graphql"],scenarios:["153-better-auth-prisma-graphql-todo"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-drizzle-graphql-todo-example",note:"Certified by scenario 149: anonymous access is rejected and todo ownership is isolated across two persisted users.",profiles:["better-auth-drizzle-graphql"],scenarios:["149-better-auth-drizzle-graphql-todo"],status:"certified"},{addons:[],auth:"passport",extras:["todo-example"],id:"passport-drizzle-graphql-todo-example",note:"Certified by scenario 150: anonymous access is rejected and todo ownership is isolated across two JWT-authenticated users.",profiles:["passport-drizzle-graphql"],scenarios:["150-passport-drizzle-graphql-todo"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-drizzle-graphql-rate-limiting",note:"Better Auth authentication throttling and GraphQL rate-limit errors passed on Drizzle PostgreSQL, MySQL, and SQLite with Express and Fastify in scenarios 151 and 281\u2013285.",profiles:["better-auth-drizzle-graphql",...At.filter(([e])=>e.startsWith("better-auth")).map(([e])=>e)],scenarios:["151-better-auth-drizzle-graphql-rate-limiting",...At.filter(([e])=>e.startsWith("better-auth")).map(([,e])=>e)],status:"certified"},{addons:[],auth:"passport",extras:["rate-limiting"],id:"passport-drizzle-graphql-rate-limiting",note:"Passport GraphQL throttling passed on Drizzle PostgreSQL, MySQL, and SQLite with Express and Fastify in scenarios 152 and 286\u2013290.",profiles:["passport-drizzle-graphql",...At.filter(([e])=>e.startsWith("passport")).map(([e])=>e)],scenarios:["152-passport-drizzle-graphql-rate-limiting",...At.filter(([e])=>e.startsWith("passport")).map(([,e])=>e)],status:"certified"},{addons:[],auth:"better-auth",extras:["health-check"],id:"better-auth-typeorm-health-check",note:"Terminus health endpoints alongside Better Auth and TypeORM; runtime scenario 91 is now certified.",profiles:["better-auth-typeorm-postgres","better-auth-typeorm-postgres-fastify","better-auth-typeorm-postgres-trpc","better-auth-typeorm-postgres-fastify-trpc","better-auth-typeorm-mysql","better-auth-typeorm-mysql-fastify","better-auth-typeorm-mysql-trpc","better-auth-typeorm-mysql-fastify-trpc","better-auth-typeorm-sqlite","better-auth-typeorm-sqlite-fastify","better-auth-typeorm-sqlite-trpc","better-auth-typeorm-sqlite-fastify-trpc"],scenarios:["91-better-auth-typeorm-postgres-health"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-typeorm-rate-limiting",note:"Throttling applied to Better Auth endpoints with TypeORM; runtime scenario 92 is now certified.",profiles:["better-auth-typeorm-postgres","better-auth-typeorm-postgres-fastify","better-auth-typeorm-postgres-trpc","better-auth-typeorm-postgres-fastify-trpc","better-auth-typeorm-mysql","better-auth-typeorm-mysql-fastify","better-auth-typeorm-mysql-trpc","better-auth-typeorm-mysql-fastify-trpc","better-auth-typeorm-sqlite","better-auth-typeorm-sqlite-fastify","better-auth-typeorm-sqlite-trpc","better-auth-typeorm-sqlite-fastify-trpc"],scenarios:["92-better-auth-typeorm-postgres-rate-limit"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-typeorm-todo-example",note:"Ownership-scoped todo example alongside Better Auth and TypeORM; runtime scenario 93 is now certified.",profiles:["better-auth-typeorm-postgres","better-auth-typeorm-postgres-fastify","better-auth-typeorm-postgres-trpc","better-auth-typeorm-postgres-fastify-trpc","better-auth-typeorm-mysql","better-auth-typeorm-mysql-fastify","better-auth-typeorm-mysql-trpc","better-auth-typeorm-mysql-fastify-trpc","better-auth-typeorm-sqlite","better-auth-typeorm-sqlite-fastify","better-auth-typeorm-sqlite-trpc","better-auth-typeorm-sqlite-fastify-trpc"],scenarios:["93-better-auth-typeorm-postgres-todo"],status:"certified"},{addons:[],auth:"better-auth",extras:["health-check"],id:"better-auth-drizzle-health-check",note:"Terminus health endpoints alongside Better Auth and Drizzle; runtime scenario 94 is now certified.",profiles:["better-auth-drizzle","better-auth-drizzle-fastify","better-auth-drizzle-trpc","better-auth-drizzle-postgres","better-auth-drizzle-postgres-fastify","better-auth-drizzle-postgres-trpc","better-auth-drizzle-postgres-fastify-trpc","better-auth-drizzle-mysql","better-auth-drizzle-mysql-fastify","better-auth-drizzle-mysql-trpc","better-auth-drizzle-mysql-fastify-trpc"],scenarios:["94-better-auth-drizzle-postgres-health"],status:"certified"},{addons:[],auth:"better-auth",extras:["rate-limiting"],id:"better-auth-drizzle-rate-limiting",note:"Throttling applied to Better Auth endpoints with Drizzle; runtime scenario 95 is now certified.",profiles:["better-auth-drizzle","better-auth-drizzle-fastify","better-auth-drizzle-trpc","better-auth-drizzle-postgres","better-auth-drizzle-postgres-fastify","better-auth-drizzle-postgres-trpc","better-auth-drizzle-postgres-fastify-trpc","better-auth-drizzle-mysql","better-auth-drizzle-mysql-fastify","better-auth-drizzle-mysql-trpc","better-auth-drizzle-mysql-fastify-trpc"],scenarios:["95-better-auth-drizzle-postgres-rate-limit"],status:"certified"},{addons:[],auth:"better-auth",extras:["todo-example"],id:"better-auth-drizzle-todo-example",note:"Ownership-scoped todo example alongside Better Auth and Drizzle; runtime scenario 96 is now certified.",profiles:["better-auth-drizzle","better-auth-drizzle-fastify","better-auth-drizzle-trpc","better-auth-drizzle-postgres","better-auth-drizzle-postgres-fastify","better-auth-drizzle-postgres-trpc","better-auth-drizzle-postgres-fastify-trpc","better-auth-drizzle-mysql","better-auth-drizzle-mysql-fastify","better-auth-drizzle-mysql-trpc","better-auth-drizzle-mysql-fastify-trpc"],scenarios:["96-better-auth-drizzle-postgres-todo"],status:"certified"},{addons:[],auth:"passport",extras:["health-check"],id:"passport-typeorm-health-check",note:"Terminus health checks and database-outage HTTP 503 transitions passed for Passport TypeORM PostgreSQL, MySQL, and SQLite REST; Fastify/tRPC profiles remain gated.",profiles:["passport-typeorm-postgres","passport-typeorm-mysql","passport-typeorm-sqlite"],scenarios:["97-passport-typeorm-postgres-health","176-passport-typeorm-postgres-health","178-passport-typeorm-mysql-health","179-passport-typeorm-sqlite-health"],status:"certified"},{addons:["ultracite"],auth:"better-auth",extras:["health-check"],id:"better-auth-drizzle-graphql-health-ultracite",note:"Ultracite with Better Auth, Drizzle GraphQL, and health-check; runtime scenario 116 passed install, repeated auth generation, migrations, lint/format, build, and GraphQL E2E.",profiles:["better-auth-drizzle-graphql"],scenarios:["116-better-auth-drizzle-graphql-health-ultracite"],status:"certified"},{addons:[],auth:"passport",extras:["health-check"],id:"passport-drizzle-health-check",note:"Terminus health checks and database-outage HTTP 503 transitions passed for Passport Drizzle PostgreSQL, MySQL, and SQLite REST; Fastify/tRPC profiles remain gated.",profiles:["passport-drizzle-postgres","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["98-passport-drizzle-postgres-health","177-passport-drizzle-postgres-health","180-passport-drizzle-mysql-health","181-passport-drizzle-sqlite-health"],status:"certified"}];function Xe(e,t){if(e.length!==t.length)return!1;const r=new Set(t);return e.every(s=>r.has(s))}p(Xe,"ie"),l(Xe,"sameSet");function et(e,t,r,s){if(s!==void 0){const a=ur.find(o=>(o.auth==="any"||o.auth===e)&&Xe(o.extras,t)&&Xe(o.addons,r)&&o.profiles?.includes(s));if(a)return a}return ur.find(a=>(a.auth==="any"||a.auth===e)&&Xe(a.extras,t)&&Xe(a.addons,r))}p(et,"ne"),l(et,"findEvidence");function Et(e,t){return e.profiles===void 0||e.profiles.length===0?!0:t.profile!==void 0&&e.profiles.includes(t.profile)}p(Et,"pe"),l(Et,"isEvidenceScopedToProfile");function mr(e){const t=e.auth??"none",r=e.extras??[],s=e.addons??[];if(t==="none")return!0;const a=et(t,r,s,e.profile);return a?.status==="certified"&&Et(a,e)}p(mr,"je"),l(mr,"isCompositionCertified");function ta(e){const t=e.auth??"none";if(t==="none")return!1;const r=et(t,e.extras??[],e.addons??[],e.profile);return r!==void 0&&r.status==="implemented"}p(ta,"at"),l(ta,"isCompositionImplemented");function hr(e){return et(e.auth??"none",e.extras??[],e.addons??[],e.profile)}p(hr,"Pe"),l(hr,"getCompositionEvidence");function fr(e){const t=hr(e);return t?.status==="implemented"&&Et(t,e)}p(fr,"Ee"),l(fr,"isCompositionPending");function gr(e){const t=[],r=e.extras??[],s=e.addons??[],a=e.auth??"none",o=e.projectType??"single";if(s.includes("scalar-ui")&&!r.includes("swagger")&&t.push({code:"scalar-requires-swagger",kind:"invalid",message:"Scalar UI requires the Swagger extra; enable Swagger or remove Scalar UI."}),r.includes("packages/shared")&&o!=="monorepo"&&t.push({code:"shared-requires-monorepo",kind:"invalid",message:"The packages/shared extra requires a monorepo project layout."}),s.includes("ultracite")&&e.formatter==="none"&&t.push({code:"ultracite-requires-formatter",kind:"invalid",message:"The Ultracite addon requires a formatter; choose Biome or Oxlint + Oxfmt."}),a!=="none"&&t.length===0){const i=et(a,r,s,e.profile);if(i)i.status!=="certified"?t.push({code:"auth-feature-composition",kind:"unverified",message:`The ${a} feature composition "${i.id}" is generated but not yet certified; pending scenarios: ${i.scenarios.join(", ")}.`}):Et(i,e)||t.push({code:"auth-feature-composition",kind:"unverified",message:`The ${a} feature composition "${i.id}" was certified for a different base profile and does not cover this exact selection.`});else{const n=r.length>0?r.join(", "):"none",c=s.length>0?s.join(", "):"none";t.push({code:"auth-feature-composition",kind:"unverified",message:`Extras (${n}) and addons (${c}) combined with ${a} authentication have no certified runtime evidence yet.`})}}return t}p(gr,"_e"),l(gr,"evaluateComposition");const _t={"better-auth-drizzle":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["drizzle"]},"better-auth-drizzle-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-graphql":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["drizzle"]},"better-auth-drizzle-graphql-fastify":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-graphql-mysql":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],orm:["drizzle"]},"better-auth-drizzle-graphql-mysql-fastify":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-graphql-sqlite":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["drizzle"]},"better-auth-drizzle-graphql-sqlite-fastify":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["drizzle"]},"better-auth-native-postgres":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:[]},"better-auth-native-postgres-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:[]},"better-auth-native-postgres-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:[]},"better-auth-native-postgres-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:[]},"better-auth-prisma":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"better-auth-prisma-docker":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"better-auth-monorepo-prisma-postgres":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["prisma"],prismaVersion:"7",projectType:"monorepo"},"better-auth-prisma-mongo":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mongodb"],orm:["prisma"],prismaVersion:"6"},"better-auth-prisma-mongo-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mongodb"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"6"},"better-auth-prisma-mongo-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mongodb"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"6"},"better-auth-prisma-mongo-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mongodb"],orm:["prisma"],prismaVersion:"6"},"better-auth-prisma-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"7"},"better-auth-prisma-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"7"},"better-auth-prisma-trpc":{api:["rest","trpc"],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:[]},"better-auth-stateless-fastify":{api:["rest"],auth:"better-auth:stateless",code:"better-auth-stateless",database:[],httpProvider:"fastify",orm:[]},"better-auth-stateless-trpc":{api:["rest","trpc"],auth:"better-auth:stateless",code:"better-auth-stateless",database:[],orm:[]},"better-auth-stateless-fastify-trpc":{api:["rest","trpc"],auth:"better-auth:stateless",code:"better-auth-stateless",database:[],httpProvider:"fastify",orm:[]},"better-auth-stateless-drizzle":{api:["rest"],auth:"better-auth:stateless",code:"better-auth-stateless",database:["postgresql"],orm:["drizzle"]},"better-auth-stateless-typeorm":{api:["rest"],auth:"better-auth:stateless",code:"better-auth-stateless",database:["postgresql"],orm:["typeorm"]},"better-auth-prisma-graphql":{api:["graphql"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"graphql-prisma":{api:["graphql"],auth:"none",code:"graphql",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},prisma:{api:["rest"],auth:"none",code:"prisma",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"graphql-drizzle":{api:["graphql"],auth:"none",code:"graphql",database:["postgresql"],orm:["drizzle"]},"graphql-drizzle-fastify":{api:["graphql"],auth:"none",code:"graphql",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"graphql-drizzle-mysql":{api:["graphql"],auth:"none",code:"graphql",database:["mysql"],orm:["drizzle"]},"graphql-drizzle-mysql-fastify":{api:["graphql"],auth:"none",code:"graphql",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"graphql-drizzle-sqlite":{api:["graphql"],auth:"none",code:"graphql",database:["sqlite"],orm:["drizzle"]},"graphql-drizzle-sqlite-fastify":{api:["graphql"],auth:"none",code:"graphql",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"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-external-identity":{api:["rest"],auth:"passport",code:"passport",database:[],orm:[]},"passport-prisma":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"passport-prisma-docker":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"passport-prisma-mongo":{api:["rest"],auth:"passport",code:"passport",database:["mongodb"],orm:["prisma"],prismaVersion:"6"},"passport-prisma-mongo-fastify":{api:["rest"],auth:"passport",code:"passport",database:["mongodb"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"6"},"passport-prisma-mongo-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mongodb"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"6"},"passport-prisma-mongo-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mongodb"],orm:["prisma"],prismaVersion:"6"},"passport-prisma-fastify":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"7"},"passport-prisma-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["prisma"],prismaVersion:"7"},"passport-prisma-graphql":{api:["graphql"],auth:"passport",code:"passport",database:["postgresql"],orm:["prisma"],prismaVersion:"7"},"passport-prisma-trpc":{api:["rest","trpc"],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"},"better-auth-typeorm-postgres":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["typeorm"]},"better-auth-typeorm-postgres-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-typeorm-postgres-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["typeorm"]},"better-auth-typeorm-postgres-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-typeorm-mysql":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],orm:["typeorm"]},"better-auth-typeorm-mysql-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-typeorm-mysql-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],orm:["typeorm"]},"better-auth-typeorm-mysql-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-typeorm-sqlite":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["typeorm"]},"better-auth-typeorm-sqlite-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-typeorm-sqlite-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],orm:["typeorm"]},"better-auth-typeorm-sqlite-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["sqlite"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-postgres":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],orm:["typeorm"]},"passport-typeorm-postgres-fastify":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-postgres-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["postgresql"],orm:["typeorm"]},"passport-typeorm-postgres-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-mysql":{api:["rest"],auth:"passport",code:"passport",database:["mysql"],orm:["typeorm"]},"passport-typeorm-mysql-fastify":{api:["rest"],auth:"passport",code:"passport",database:["mysql"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-mysql-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mysql"],orm:["typeorm"]},"passport-typeorm-mysql-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mysql"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-sqlite":{api:["rest"],auth:"passport",code:"passport",database:["sqlite"],orm:["typeorm"]},"passport-typeorm-sqlite-fastify":{api:["rest"],auth:"passport",code:"passport",database:["sqlite"],httpProvider:"fastify",orm:["typeorm"]},"passport-typeorm-sqlite-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["sqlite"],orm:["typeorm"]},"passport-typeorm-sqlite-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["sqlite"],httpProvider:"fastify",orm:["typeorm"]},"better-auth-drizzle-postgres":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["drizzle"]},"better-auth-drizzle-postgres-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-postgres-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],orm:["drizzle"]},"better-auth-drizzle-postgres-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-mysql":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],orm:["drizzle"]},"better-auth-drizzle-mysql-fastify":{api:["rest"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"better-auth-drizzle-mysql-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],orm:["drizzle"]},"better-auth-drizzle-mysql-fastify-trpc":{api:["rest","trpc"],auth:"better-auth",code:"better-auth-adapter",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-postgres":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],orm:["drizzle"]},"passport-drizzle-graphql":{api:["graphql"],auth:"passport",code:"passport",database:["postgresql"],orm:["drizzle"]},"passport-drizzle-graphql-fastify":{api:["graphql"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-graphql-mysql":{api:["graphql"],auth:"passport",code:"passport",database:["mysql"],orm:["drizzle"]},"passport-drizzle-graphql-mysql-fastify":{api:["graphql"],auth:"passport",code:"passport",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-graphql-sqlite":{api:["graphql"],auth:"passport",code:"passport",database:["sqlite"],orm:["drizzle"]},"passport-drizzle-graphql-sqlite-fastify":{api:["graphql"],auth:"passport",code:"passport",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-postgres-fastify":{api:["rest"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-postgres-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["postgresql"],orm:["drizzle"]},"passport-drizzle-postgres-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["postgresql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-mysql":{api:["rest"],auth:"passport",code:"passport",database:["mysql"],orm:["drizzle"]},"passport-drizzle-mysql-fastify":{api:["rest"],auth:"passport",code:"passport",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-mysql-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mysql"],orm:["drizzle"]},"passport-drizzle-mysql-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["mysql"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-sqlite":{api:["rest"],auth:"passport",code:"passport",database:["sqlite"],orm:["drizzle"]},"passport-drizzle-sqlite-fastify":{api:["rest"],auth:"passport",code:"passport",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]},"passport-drizzle-sqlite-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["sqlite"],orm:["drizzle"]},"passport-drizzle-sqlite-fastify-trpc":{api:["rest","trpc"],auth:"passport",code:"passport",database:["sqlite"],httpProvider:"fastify",orm:["drizzle"]}};function ra(e,t){const r=_t[t],s=e.projectType??"single",a=e.architecture??"nest-api",o=e.httpProvider??"express",i=e.microservices??[];return s===("projectType"in r?r.projectType:"single")&&a===("microservices"in r?"nest-microservice":"nest-api")&&o===("httpProvider"in r?r.httpProvider:"express")&&JSON.stringify(i)===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)}p(ra,"ot"),l(ra,"matchesProfileShape");function Rt(e,t,r={}){const s=_t[t],a=e.extras??[],o=e.addons??[];if(gr({addons:o,auth:e.auth,extras:a,projectType:e.projectType}).some(({kind:n})=>n==="invalid"))return!1;if(e.auth!=="none"){const n={addons:o,auth:e.auth,extras:a,profile:t};if(!(mr(n)||r.pendingComposition===!0&&fr(n)))return!1}const i=hr({addons:o,auth:e.auth,extras:a,profile:t});return e.projectType===("projectType"in s?s.projectType:"single")&&e.architecture===("microservices"in s?"nest-microservice":"nest-api")&&e.httpProvider===("httpProvider"in s?s.httpProvider:"express")&&JSON.stringify(e.microservices)===JSON.stringify("microservices"in s?s.microservices:[])&&e.auth===s.auth&&JSON.stringify(e.api)===JSON.stringify(s.api)&&JSON.stringify(e.database)===JSON.stringify(s.database)&&JSON.stringify(e.orm)===JSON.stringify(s.orm)&&e.prismaVersion===("prismaVersion"in s?s.prismaVersion:void 0)&&(e.auth==="none"?(o.length===0||i?.status==="certified"&&i.profiles?.includes(t)===!0)&&a.every(n=>n==="todo-example"||n==="docker"&&i?.status==="certified"&&i.profiles?.includes(t)===!0||"microservices"in s&&n==="docker"):!0)}p(Rt,"ce"),l(Rt,"matchesCandidate");const sa=["passport-external-identity","prisma","better-auth-monorepo-prisma-postgres","better-auth-prisma","better-auth-prisma-docker","better-auth-prisma-mongo","better-auth-prisma-fastify","better-auth-prisma-mongo-fastify","better-auth-prisma-trpc","better-auth-prisma-mongo-trpc","better-auth-prisma-fastify-trpc","better-auth-prisma-mongo-fastify-trpc","better-auth-native-postgres","better-auth-native-postgres-fastify","better-auth-native-postgres-trpc","better-auth-native-postgres-fastify-trpc","better-auth-drizzle","better-auth-drizzle-fastify","better-auth-drizzle-fastify-trpc","better-auth-drizzle-graphql","better-auth-drizzle-graphql-fastify","better-auth-drizzle-graphql-mysql","better-auth-drizzle-graphql-mysql-fastify","better-auth-drizzle-graphql-sqlite","better-auth-drizzle-graphql-sqlite-fastify","better-auth-drizzle-trpc","graphql-prisma","passport-prisma","passport-prisma-docker","passport-prisma-mongo","passport-prisma-fastify","passport-prisma-mongo-fastify","passport-prisma-trpc","passport-prisma-mongo-trpc","passport-prisma-fastify-trpc","passport-prisma-mongo-fastify-trpc","mongodb-native","prisma8-postgres","better-auth-stateless","better-auth-stateless-fastify","better-auth-stateless-trpc","better-auth-stateless-fastify-trpc","better-auth-stateless-drizzle","better-auth-stateless-typeorm","microservice-grpc","microservice-redis","microservice-kafka","microservice-mqtt","microservice-nats","microservice-rabbitmq","better-auth-drizzle-postgres","better-auth-drizzle-mysql","passport-typeorm-postgres","passport-drizzle-postgres","passport-drizzle-graphql","passport-drizzle-graphql-fastify","passport-drizzle-graphql-mysql","passport-drizzle-graphql-mysql-fastify","passport-drizzle-graphql-sqlite","passport-drizzle-graphql-sqlite-fastify","passport-drizzle-sqlite","better-auth-typeorm-postgres","better-auth-typeorm-postgres-fastify","better-auth-typeorm-postgres-trpc","better-auth-typeorm-postgres-fastify-trpc","better-auth-typeorm-mysql","better-auth-typeorm-mysql-fastify","better-auth-typeorm-mysql-trpc","better-auth-typeorm-mysql-fastify-trpc","better-auth-typeorm-sqlite","better-auth-typeorm-sqlite-fastify","better-auth-typeorm-sqlite-trpc","better-auth-typeorm-sqlite-fastify-trpc","passport-typeorm-postgres-fastify","passport-typeorm-postgres-trpc","passport-typeorm-postgres-fastify-trpc","passport-typeorm-mysql","passport-typeorm-mysql-fastify","passport-typeorm-mysql-trpc","passport-typeorm-mysql-fastify-trpc","passport-typeorm-sqlite","passport-typeorm-sqlite-fastify","passport-typeorm-sqlite-trpc","passport-typeorm-sqlite-fastify-trpc","better-auth-drizzle-postgres-fastify","better-auth-drizzle-postgres-trpc","better-auth-drizzle-postgres-fastify-trpc","better-auth-drizzle-mysql-fastify","better-auth-drizzle-mysql-trpc","better-auth-drizzle-mysql-fastify-trpc","passport-drizzle-postgres-fastify","passport-drizzle-postgres-trpc","passport-drizzle-postgres-fastify-trpc","passport-drizzle-mysql","passport-drizzle-mysql-fastify","passport-drizzle-mysql-trpc","passport-drizzle-mysql-fastify-trpc","passport-drizzle-sqlite-fastify","passport-drizzle-sqlite-trpc","passport-drizzle-sqlite-fastify-trpc","better-auth-prisma-graphql","passport-prisma-graphql","graphql-drizzle","graphql-drizzle-fastify","graphql-drizzle-mysql","graphql-drizzle-mysql-fastify","graphql-drizzle-sqlite","graphql-drizzle-sqlite-fastify"];function yr(e,t){const r=_t[e],s=r.api;return r.code===t||t==="graphql"&&s.includes("graphql")||t==="mongodb"&&r.database.some(a=>a==="mongodb")}p(yr,"it"),l(yr,"profileClearsCode");function tt(e,t={}){const r=[];(e.database.length>1||e.orm.length>1)&&r.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&&r.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&&r.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?r.push({code:"better-auth-requires-database",kind:"invalid",message:"Database-backed Better Auth requires a database."}):r.push({code:"better-auth-adapter",kind:"unverified",message:"This Better Auth combination is unverified. Select one of the certified exact profiles offered by the wizard; extras, addons, and untested API/database combinations remain gated."})),e.database.includes("mongodb")&&r.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"&&r.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")&&r.push({code:"graphql",kind:"unverified",message:"This GraphQL combination is unverified. Select an exact certified GraphQL profile from the wizard; other database, ORM, authentication, layout, extras, and addon combinations remain gated."}),e.auth==="passport"&&r.push({code:"passport",kind:"unverified",message:"This Passport combination is unverified. Select an exact certified Passport profile from the wizard; other database, ORM, API, layout, extras, and addon combinations remain gated."}),e.auth==="better-auth:stateless"&&r.push({code:"better-auth-stateless",kind:"unverified",message:"This stateless Better Auth selection has no exact runtime-certified profile for its database, ORM, API, provider, and feature set yet."});const s=Object.keys(_t).filter(i=>ra(e,i)),a=s.find(i=>{const n={addons:e.addons??[],auth:e.auth,extras:e.extras??[],profile:i};return mr(n)||t.pendingComposition===!0&&fr(n)})??s[0],o={addons:e.addons??[],auth:e.auth,extras:e.extras??[],formatter:e.formatter,profile:a,projectType:e.projectType};for(const i of gr(o))t.pendingComposition===!0&&i.kind==="unverified"&&ta(o)||r.push(i);return r.filter(({code:i})=>!sa.some(n=>yr(n,i)&&Rt(e,n)))}p(tt,"nt"),l(tt,"getUnsupportedSelections");function aa(e,t){const r=t!==void 0;if(t&&!Rt(e,t,{pendingComposition:r}))throw new Error(`Context does not match runtime certification profile: ${t}`);const s=tt(e,{pendingComposition:r}).filter(({code:a,kind:o})=>!t||!yr(t,a)||o==="invalid"?!0:!Rt(e,t,{pendingComposition:r}));if(s.length>0)throw new Error(s.map(({message:a})=>a).join(`
86
+ `))}p(aa,"pt"),l(aa,"validateProjectContext");const F=["rest"],Z=["rest","trpc"],ep=[["graphql-drizzle-fastify","none","postgresql","fastify"],["better-auth-drizzle-graphql-fastify","better-auth","postgresql","fastify"],["passport-drizzle-graphql-fastify","passport","postgresql","fastify"],["graphql-drizzle-mysql","none","mysql","express"],["graphql-drizzle-mysql-fastify","none","mysql","fastify"],["better-auth-drizzle-graphql-mysql","better-auth","mysql","express"],["better-auth-drizzle-graphql-mysql-fastify","better-auth","mysql","fastify"],["passport-drizzle-graphql-mysql","passport","mysql","express"],["passport-drizzle-graphql-mysql-fastify","passport","mysql","fastify"],["graphql-drizzle-sqlite","none","sqlite","express"],["graphql-drizzle-sqlite-fastify","none","sqlite","fastify"],["better-auth-drizzle-graphql-sqlite","better-auth","sqlite","express"],["better-auth-drizzle-graphql-sqlite-fastify","better-auth","sqlite","fastify"],["passport-drizzle-graphql-sqlite","passport","sqlite","express"],["passport-drizzle-graphql-sqlite-fastify","passport","sqlite","fastify"]],tp={"passport-external-identity":["266-passport-external-identity-express-rest"],"better-auth-monorepo-prisma-postgres":["267-better-auth-monorepo-prisma-postgres"],"better-auth-drizzle":["15-better-auth-drizzle"],"better-auth-drizzle-fastify":["29-better-auth-drizzle-fastify"],"better-auth-drizzle-fastify-trpc":["144-better-auth-drizzle-fastify-trpc"],"better-auth-drizzle-graphql":["112-better-auth-drizzle-graphql"],"better-auth-drizzle-graphql-fastify":["119-better-auth-drizzle-graphql-fastify"],"better-auth-drizzle-graphql-mysql":["123-better-auth-drizzle-graphql-mysql"],"better-auth-drizzle-graphql-mysql-fastify":["124-better-auth-drizzle-graphql-mysql-fastify"],"better-auth-drizzle-graphql-sqlite":["129-better-auth-drizzle-graphql-sqlite"],"better-auth-drizzle-graphql-sqlite-fastify":["130-better-auth-drizzle-graphql-sqlite-fastify"],"better-auth-drizzle-mysql":["46-better-auth-drizzle-mysql"],"better-auth-drizzle-mysql-fastify":["78-better-auth-drizzle-mysql-fastify"],"better-auth-drizzle-mysql-fastify-trpc":["80-better-auth-drizzle-mysql-fastify-trpc"],"better-auth-drizzle-mysql-trpc":["79-better-auth-drizzle-mysql-trpc"],"better-auth-drizzle-postgres":["42-better-auth-drizzle-postgres"],"better-auth-drizzle-postgres-fastify":["75-better-auth-drizzle-postgres-fastify"],"better-auth-drizzle-postgres-fastify-trpc":["77-better-auth-drizzle-postgres-fastify-trpc"],"better-auth-drizzle-postgres-trpc":["76-better-auth-drizzle-postgres-trpc"],"better-auth-drizzle-trpc":["35-better-auth-drizzle-trpc"],"better-auth-native-postgres":["31-better-auth-native-postgres"],"better-auth-native-postgres-fastify":["32-better-auth-native-postgres-fastify"],"better-auth-native-postgres-fastify-trpc":["40-better-auth-native-postgres-fastify-trpc"],"better-auth-native-postgres-trpc":["34-better-auth-native-postgres-trpc"],"better-auth-prisma":["14-better-auth-prisma"],"better-auth-prisma-docker":["164-better-auth-prisma-docker"],"better-auth-prisma-mongo":["103-better-auth-prisma-mongo"],"better-auth-prisma-fastify":["28-better-auth-prisma-fastify"],"better-auth-prisma-mongo-fastify":["104-better-auth-prisma-mongo-fastify"],"better-auth-prisma-fastify-trpc":["38-better-auth-prisma-fastify-trpc"],"better-auth-prisma-mongo-fastify-trpc":["106-better-auth-prisma-mongo-fastify-trpc"],"better-auth-prisma-trpc":["33-better-auth-prisma-trpc"],"better-auth-prisma-mongo-trpc":["105-better-auth-prisma-mongo-trpc"],"better-auth-stateless":["21-better-auth-stateless"],"better-auth-stateless-fastify":["145-better-auth-stateless-fastify"],"better-auth-stateless-trpc":["37-better-auth-stateless-trpc"],"better-auth-stateless-fastify-trpc":["146-better-auth-stateless-fastify-trpc"],"better-auth-stateless-drizzle":["147-better-auth-stateless-drizzle"],"better-auth-stateless-typeorm":["148-better-auth-stateless-typeorm"],"better-auth-typeorm-mysql":["56-better-auth-typeorm-mysql"],"better-auth-typeorm-mysql-fastify":["57-better-auth-typeorm-mysql-fastify"],"better-auth-typeorm-mysql-fastify-trpc":["59-better-auth-typeorm-mysql-fastify-trpc"],"better-auth-typeorm-mysql-trpc":["58-better-auth-typeorm-mysql-trpc"],"better-auth-typeorm-postgres":["41-better-auth-typeorm-postgres"],"better-auth-typeorm-postgres-fastify":["53-better-auth-typeorm-postgres-fastify"],"better-auth-typeorm-postgres-fastify-trpc":["55-better-auth-typeorm-postgres-fastify-trpc"],"better-auth-typeorm-postgres-trpc":["54-better-auth-typeorm-postgres-trpc"],"better-auth-typeorm-sqlite":["60-better-auth-typeorm-sqlite"],"better-auth-typeorm-sqlite-fastify":["61-better-auth-typeorm-sqlite-fastify"],"better-auth-typeorm-sqlite-fastify-trpc":["63-better-auth-typeorm-sqlite-fastify-trpc"],"better-auth-typeorm-sqlite-trpc":["62-better-auth-typeorm-sqlite-trpc"],"graphql-drizzle":["111-graphql-drizzle"],"graphql-drizzle-fastify":["118-graphql-drizzle-fastify"],"graphql-drizzle-mysql":["121-graphql-drizzle-mysql"],"graphql-drizzle-mysql-fastify":["122-graphql-drizzle-mysql-fastify"],"graphql-drizzle-sqlite":["127-graphql-drizzle-sqlite"],"graphql-drizzle-sqlite-fastify":["128-graphql-drizzle-sqlite-fastify"],"passport-drizzle-graphql":["113-passport-drizzle-graphql"],"passport-drizzle-graphql-fastify":["120-passport-drizzle-graphql-fastify"],"passport-drizzle-graphql-mysql":["125-passport-drizzle-graphql-mysql"],"passport-drizzle-graphql-mysql-fastify":["126-passport-drizzle-graphql-mysql-fastify"],"passport-drizzle-graphql-sqlite":["131-passport-drizzle-graphql-sqlite"],"passport-drizzle-graphql-sqlite-fastify":["132-passport-drizzle-graphql-sqlite-fastify"],"passport-drizzle-mysql":["84-passport-drizzle-mysql"],"passport-drizzle-mysql-fastify":["85-passport-drizzle-mysql-fastify"],"passport-drizzle-mysql-fastify-trpc":["87-passport-drizzle-mysql-fastify-trpc"],"passport-drizzle-mysql-trpc":["86-passport-drizzle-mysql-trpc"],"passport-drizzle-postgres":["44-passport-drizzle-postgres"],"passport-drizzle-postgres-fastify":["81-passport-drizzle-postgres-fastify"],"passport-drizzle-postgres-fastify-trpc":["83-passport-drizzle-postgres-fastify-trpc"],"passport-drizzle-postgres-trpc":["82-passport-drizzle-postgres-trpc"],"passport-drizzle-sqlite":["45-passport-drizzle-sqlite"],"passport-drizzle-sqlite-fastify":["88-passport-drizzle-sqlite-fastify"],"passport-drizzle-sqlite-fastify-trpc":["90-passport-drizzle-sqlite-fastify-trpc"],"passport-drizzle-sqlite-trpc":["89-passport-drizzle-sqlite-trpc"],"passport-prisma":["17-passport-prisma"],"passport-prisma-docker":["165-passport-prisma-docker"],"passport-prisma-mongo":["107-passport-prisma-mongo"],"passport-prisma-fastify":["30-passport-prisma-fastify"],"passport-prisma-mongo-fastify":["108-passport-prisma-mongo-fastify"],"passport-prisma-fastify-trpc":["39-passport-prisma-fastify-trpc"],"passport-prisma-mongo-fastify-trpc":["110-passport-prisma-mongo-fastify-trpc"],"passport-prisma-trpc":["36-passport-prisma-trpc"],"passport-prisma-mongo-trpc":["109-passport-prisma-mongo-trpc"],"passport-typeorm-mysql":["67-passport-typeorm-mysql"],"passport-typeorm-mysql-fastify":["68-passport-typeorm-mysql-fastify"],"passport-typeorm-mysql-fastify-trpc":["70-passport-typeorm-mysql-fastify-trpc"],"passport-typeorm-mysql-trpc":["69-passport-typeorm-mysql-trpc"],"passport-typeorm-postgres":["43-passport-typeorm-postgres"],"passport-typeorm-postgres-fastify":["64-passport-typeorm-postgres-fastify"],"passport-typeorm-postgres-fastify-trpc":["66-passport-typeorm-postgres-fastify-trpc"],"passport-typeorm-postgres-trpc":["65-passport-typeorm-postgres-trpc"],"passport-typeorm-sqlite":["71-passport-typeorm-sqlite"],"passport-typeorm-sqlite-fastify":["72-passport-typeorm-sqlite-fastify"],"passport-typeorm-sqlite-fastify-trpc":["74-passport-typeorm-sqlite-fastify-trpc"],"passport-typeorm-sqlite-trpc":["73-passport-typeorm-sqlite-trpc"],prisma:["04-postgres-prisma"],"better-auth-prisma-graphql":["51-better-auth-prisma-graphql"],"passport-prisma-graphql":["52-passport-prisma-graphql"]};function E(e){const t=e.status??"desired",r=t==="desired"&&e.profile!==void 0&&sa.includes(e.profile),s=e.scenarios??(e.profile!==void 0?tp[e.profile]??[]:[]);return{...e,reason:e.reason??"Status derived from runtime scenario evidence.",scenarios:s,status:t,...r?{status:"certified"}:{}}}p(E,"q"),l(E,"authEntry");const ia=[...ep.map(([e,t,r,s])=>E({api:["graphql"],auth:t,database:[r],httpProvider:s,id:`${e}-graphql`,orm:["drizzle"],profile:e,projectType:"single",reason:"Drizzle GraphQL profile passed clean install, migration, build, and authenticated or anonymous GraphQL runtime checks.",status:"desired",storage:"orm"})),E({api:F,auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-prisma-postgres-express-rest",orm:["prisma"],profile:"better-auth-prisma",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth",database:["mongodb"],httpProvider:"express",id:"better-auth-prisma-mongo-express-rest",orm:["prisma"],profile:"better-auth-prisma-mongo",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth",database:["postgresql"],httpProvider:"fastify",id:"better-auth-prisma-postgres-fastify-rest",orm:["prisma"],profile:"better-auth-prisma-fastify",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth",database:["mongodb"],httpProvider:"fastify",id:"better-auth-prisma-mongo-fastify-rest",orm:["prisma"],profile:"better-auth-prisma-mongo-fastify",projectType:"single",storage:"orm"}),E({api:Z,auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-prisma-postgres-express-rest-trpc",orm:["prisma"],profile:"better-auth-prisma-trpc",projectType:"single",storage:"orm"}),E({api:Z,auth:"better-auth",database:["mongodb"],httpProvider:"express",id:"better-auth-prisma-mongo-express-rest-trpc",orm:["prisma"],profile:"better-auth-prisma-mongo-trpc",projectType:"single",storage:"orm"}),E({api:Z,auth:"better-auth",database:["postgresql"],httpProvider:"fastify",id:"better-auth-prisma-postgres-fastify-rest-trpc",orm:["prisma"],profile:"better-auth-prisma-fastify-trpc",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-native-postgres-express-rest",orm:[],profile:"better-auth-native-postgres",projectType:"single",storage:"native-sql"}),E({api:F,auth:"better-auth",database:["postgresql"],httpProvider:"fastify",id:"better-auth-native-postgres-fastify-rest",orm:[],profile:"better-auth-native-postgres-fastify",projectType:"single",storage:"native-sql"}),E({api:Z,auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-native-postgres-express-rest-trpc",orm:[],profile:"better-auth-native-postgres-trpc",projectType:"single",storage:"native-sql"}),E({api:Z,auth:"better-auth",database:["postgresql"],httpProvider:"fastify",id:"better-auth-native-postgres-fastify-rest-trpc",orm:[],profile:"better-auth-native-postgres-fastify-trpc",projectType:"single",storage:"native-sql"}),E({api:F,auth:"better-auth",database:["sqlite"],httpProvider:"express",id:"better-auth-drizzle-sqlite-express-rest",orm:["drizzle"],profile:"better-auth-drizzle",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth",database:["sqlite"],httpProvider:"fastify",id:"better-auth-drizzle-sqlite-fastify-rest",orm:["drizzle"],profile:"better-auth-drizzle-fastify",projectType:"single",storage:"orm"}),E({api:Z,auth:"better-auth",database:["sqlite"],httpProvider:"fastify",id:"better-auth-drizzle-sqlite-fastify-rest-trpc",orm:["drizzle"],profile:"better-auth-drizzle-fastify-trpc",projectType:"single",storage:"orm"}),E({api:Z,auth:"better-auth",database:["sqlite"],httpProvider:"express",id:"better-auth-drizzle-sqlite-express-rest-trpc",orm:["drizzle"],profile:"better-auth-drizzle-trpc",projectType:"single",storage:"orm"}),E({api:F,auth:"better-auth:stateless",database:[],httpProvider:"express",id:"better-auth-stateless-express-rest",orm:[],profile:"better-auth-stateless",projectType:"single",storage:"stateless-cookie"}),E({api:F,auth:"better-auth:stateless",database:[],httpProvider:"fastify",id:"better-auth-stateless-fastify-rest",orm:[],profile:"better-auth-stateless-fastify",projectType:"single",storage:"stateless-cookie"}),E({api:Z,auth:"better-auth:stateless",database:[],httpProvider:"express",id:"better-auth-stateless-express-rest-trpc",orm:[],profile:"better-auth-stateless-trpc",projectType:"single",storage:"stateless-cookie"}),E({api:Z,auth:"better-auth:stateless",database:[],httpProvider:"fastify",id:"better-auth-stateless-fastify-rest-trpc",orm:[],profile:"better-auth-stateless-fastify-trpc",projectType:"single",storage:"stateless-cookie"}),E({api:F,auth:"passport",database:["postgresql"],httpProvider:"express",id:"passport-prisma-postgres-express-rest",orm:["prisma"],profile:"passport-prisma",projectType:"single",storage:"orm"}),E({api:F,auth:"passport",database:["postgresql"],httpProvider:"fastify",id:"passport-prisma-postgres-fastify-rest",orm:["prisma"],profile:"passport-prisma-fastify",projectType:"single",storage:"orm"}),E({api:Z,auth:"passport",database:["postgresql"],httpProvider:"express",id:"passport-prisma-postgres-express-rest-trpc",orm:["prisma"],profile:"passport-prisma-trpc",projectType:"single",storage:"orm"}),E({api:F,auth:"passport",database:["mongodb"],httpProvider:"express",id:"passport-prisma-mongo-express-rest",orm:["prisma"],profile:"passport-prisma-mongo",projectType:"single",storage:"orm"}),E({api:F,auth:"passport",database:["mongodb"],httpProvider:"fastify",id:"passport-prisma-mongo-fastify-rest",orm:["prisma"],profile:"passport-prisma-mongo-fastify",projectType:"single",storage:"orm"}),E({api:Z,auth:"passport",database:["postgresql"],httpProvider:"fastify",id:"passport-prisma-postgres-fastify-rest-trpc",orm:["prisma"],profile:"passport-prisma-fastify-trpc",projectType:"single",storage:"orm"}),E({api:Z,auth:"passport",database:["mongodb"],httpProvider:"express",id:"passport-prisma-mongo-express-rest-trpc",orm:["prisma"],profile:"passport-prisma-mongo-trpc",projectType:"single",storage:"orm"}),E({api:Z,auth:"passport",database:["mongodb"],httpProvider:"fastify",id:"passport-prisma-mongo-fastify-rest-trpc",orm:["prisma"],profile:"passport-prisma-mongo-fastify-trpc",projectType:"single",storage:"orm"}),...["postgresql","mysql","sqlite"].flatMap(e=>[{api:F,httpProvider:"express",profile:`better-auth-typeorm-${e==="postgresql"?"postgres":e}`},{api:F,httpProvider:"fastify",profile:`better-auth-typeorm-${e==="postgresql"?"postgres":e}-fastify`},{api:Z,httpProvider:"express",profile:`better-auth-typeorm-${e==="postgresql"?"postgres":e}-trpc`},{api:Z,httpProvider:"fastify",profile:`better-auth-typeorm-${e==="postgresql"?"postgres":e}-fastify-trpc`}].map(t=>E({api:t.api,auth:"better-auth",database:[e],httpProvider:t.httpProvider,id:`better-auth-typeorm-${e}-${t.httpProvider}-${t.api.join("-")}`,orm:["typeorm"],profile:t.profile,projectType:"single",storage:"native-sql"}))),...["postgresql","mysql","sqlite"].flatMap(e=>[{api:F,httpProvider:"express",profile:`passport-typeorm-${e==="postgresql"?"postgres":e}`},{api:F,httpProvider:"fastify",profile:`passport-typeorm-${e==="postgresql"?"postgres":e}-fastify`},{api:Z,httpProvider:"express",profile:`passport-typeorm-${e==="postgresql"?"postgres":e}-trpc`},{api:Z,httpProvider:"fastify",profile:`passport-typeorm-${e==="postgresql"?"postgres":e}-fastify-trpc`}].map(t=>E({api:t.api,auth:"passport",database:[e],httpProvider:t.httpProvider,id:`passport-typeorm-${e}-${t.httpProvider}-${t.api.join("-")}`,orm:["typeorm"],profile:t.profile,projectType:"single",storage:"orm"}))),...["postgresql","mysql"].flatMap(e=>[{api:F,httpProvider:"express",profile:`better-auth-drizzle-${e==="postgresql"?"postgres":e}`},{api:F,httpProvider:"fastify",profile:`better-auth-drizzle-${e==="postgresql"?"postgres":e}-fastify`},{api:Z,httpProvider:"express",profile:`better-auth-drizzle-${e==="postgresql"?"postgres":e}-trpc`},{api:Z,httpProvider:"fastify",profile:`better-auth-drizzle-${e==="postgresql"?"postgres":e}-fastify-trpc`}].map(t=>E({api:t.api,auth:"better-auth",database:[e],httpProvider:t.httpProvider,id:`better-auth-drizzle-${e}-${t.httpProvider}-${t.api.join("-")}`,orm:["drizzle"],profile:t.profile,projectType:"single",storage:"orm"}))),...["postgresql","mysql","sqlite"].flatMap(e=>[{api:F,httpProvider:"express",profile:`passport-drizzle-${e==="postgresql"?"postgres":e}`},{api:F,httpProvider:"fastify",profile:`passport-drizzle-${e==="postgresql"?"postgres":e}-fastify`},{api:Z,httpProvider:"express",profile:`passport-drizzle-${e==="postgresql"?"postgres":e}-trpc`},{api:Z,httpProvider:"fastify",profile:`passport-drizzle-${e==="postgresql"?"postgres":e}-fastify-trpc`}].map(t=>E({api:t.api,auth:"passport",database:[e],httpProvider:t.httpProvider,id:`passport-drizzle-${e}-${t.httpProvider}-${t.api.join("-")}`,orm:["drizzle"],profile:t.profile,projectType:"single",storage:"orm"}))),E({api:["graphql"],auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-graphql-prisma-postgres",orm:["prisma"],profile:"better-auth-prisma-graphql",projectType:"single",reason:"GraphQL resolver guards are Passport-generated, so Better Auth restricts todo-example; certified by scenario 51.",storage:"orm"}),E({api:["graphql"],auth:"passport",database:["postgresql"],httpProvider:"express",id:"passport-graphql-prisma-postgres",orm:["prisma"],profile:"passport-prisma-graphql",projectType:"single",reason:"GraphQL authentication with Passport guards/decorators; certified by scenario 52.",storage:"orm"}),E({api:["graphql"],auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-graphql-drizzle-postgres",orm:["drizzle"],profile:"better-auth-drizzle-graphql",projectType:"single",storage:"orm"}),E({api:["graphql"],auth:"passport",database:["postgresql"],httpProvider:"express",id:"passport-graphql-drizzle-postgres",orm:["drizzle"],profile:"passport-drizzle-graphql",projectType:"single",storage:"orm"}),E({api:F,auth:"passport",database:[],httpProvider:"express",id:"passport-external-identity-express-rest",orm:[],profile:"passport-external-identity",projectType:"single",reason:"External RS256 bearer access tokens are checked against a configured JWKS URI, issuer, and audience; no local credential or token-minting endpoint is generated. Scenario 266 covers successful mapping and invalid-token rejection.",scenarios:["266-passport-external-identity-express-rest"],status:"certified",storage:"none"}),E({api:F,auth:"better-auth",database:["postgresql"],httpProvider:"express",id:"better-auth-monorepo-prisma-postgres",orm:["prisma"],profile:"better-auth-monorepo-prisma-postgres",projectType:"monorepo",reason:"Better Auth Prisma monorepo auth schema generation, database migrations, workspace build, and authenticated session resolution pass in scenario 267.",scenarios:["267-better-auth-monorepo-prisma-postgres"],status:"certified",storage:"orm"}),E({api:F,auth:"better-auth:stateless",database:["postgresql"],httpProvider:"express",id:"better-auth-stateless-with-app-database",orm:["typeorm"],projectType:"single",profile:"better-auth-stateless-typeorm",reason:"TypeORM owns a small application data entity while Better Auth keeps OIDC sessions in encrypted cookies without auth tables.",scenarios:["148-better-auth-stateless-typeorm"],status:"desired",storage:"stateless-cookie"}),E({api:F,auth:"better-auth:stateless",database:["postgresql"],httpProvider:"express",id:"better-auth-stateless-with-app-drizzle",orm:["drizzle"],projectType:"single",profile:"better-auth-stateless-drizzle",reason:"Application data uses Drizzle while stateless Better Auth keeps OIDC sessions in encrypted cookies without database-backed auth tables.",scenarios:["147-better-auth-stateless-drizzle"],status:"desired",storage:"stateless-cookie"})],he=["better-auth","passport"],rp=[{appliesTo:he,feature:"docker",id:"extra-docker-auth",kind:"extra",profiles:["better-auth-prisma-docker","passport-prisma-docker"],scenarios:["164-better-auth-prisma-docker","165-passport-prisma-docker"],reason:"Full generated-project and Docker runtime checks passed for the exact Better Auth and Passport Prisma 7/PostgreSQL profiles (scenarios 164 and 165). Other database and ORM Docker combinations remain gated.",requiredEvidence:["docker compose up","auth lifecycle over published port"],status:"certified"},{appliesTo:he,feature:"health-check",id:"extra-health-check-auth",kind:"extra",profiles:["better-auth-prisma","better-auth-drizzle-graphql","better-auth-drizzle-graphql-fastify","better-auth-drizzle-graphql-mysql","better-auth-drizzle-graphql-mysql-fastify","better-auth-drizzle-graphql-sqlite","better-auth-drizzle-graphql-sqlite-fastify","passport-prisma","passport-prisma-graphql","passport-typeorm-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-postgres","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["47-better-auth-prisma-health","114-better-auth-drizzle-graphql-health","296-better-auth-drizzle-graphql-postgres-fastify-health","297-better-auth-drizzle-graphql-mysql-health","298-better-auth-drizzle-graphql-mysql-fastify-health","299-better-auth-drizzle-graphql-sqlite-health","300-better-auth-drizzle-graphql-sqlite-fastify-health","115-passport-drizzle-graphql-health","139-passport-drizzle-graphql-fastify-health","140-passport-drizzle-graphql-mysql-health","141-passport-drizzle-graphql-mysql-fastify-health","142-passport-drizzle-graphql-sqlite-health","143-passport-drizzle-graphql-sqlite-fastify-health","52-passport-prisma-graphql","174-passport-prisma-health-check","176-passport-typeorm-postgres-health","177-passport-drizzle-postgres-health","178-passport-typeorm-mysql-health","179-passport-typeorm-sqlite-health","180-passport-drizzle-mysql-health","181-passport-drizzle-sqlite-health"],reason:"Authenticated health checks and database-outage HTTP 503 transitions passed for the exact Prisma, TypeORM, Drizzle REST, Prisma GraphQL, and Drizzle GraphQL profiles listed here; scenarios 47, 52, 114\u2013115, 139\u2013143, and 174\u2013181, 296\u2013300 back those profiles. Other profiles remain gated.",requiredEvidence:["anonymous access matches policy","database outage changes readiness"],status:"certified"},{appliesTo:he,feature:"rate-limiting",id:"extra-rate-limiting-auth",kind:"extra",profiles:["better-auth-prisma","better-auth-prisma-graphql","better-auth-drizzle-graphql","better-auth-drizzle-graphql-fastify","better-auth-drizzle-graphql-mysql","better-auth-drizzle-graphql-mysql-fastify","better-auth-drizzle-graphql-sqlite","better-auth-drizzle-graphql-sqlite-fastify","passport-prisma-graphql","passport-drizzle-graphql","passport-drizzle-graphql-fastify","passport-drizzle-graphql-mysql","passport-drizzle-graphql-mysql-fastify","passport-drizzle-graphql-sqlite","passport-drizzle-graphql-sqlite-fastify","passport-prisma","passport-prisma-trpc","passport-typeorm-postgres","passport-drizzle-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite","passport-typeorm-postgres-fastify","passport-drizzle-postgres-fastify","passport-typeorm-mysql-fastify","passport-drizzle-mysql-fastify","passport-typeorm-sqlite-fastify","passport-drizzle-sqlite-fastify"],scenarios:["48-better-auth-prisma-rate-limit","155-better-auth-prisma-graphql-rate-limiting","156-passport-prisma-graphql-rate-limiting","170-passport-prisma-rate-limiting","270-passport-prisma-trpc-rate-limiting","188-passport-typeorm-postgres-rate-limiting","189-passport-drizzle-postgres-rate-limiting","198-passport-typeorm-mysql-rate-limiting","199-passport-typeorm-sqlite-rate-limiting","200-passport-drizzle-mysql-rate-limiting","201-passport-drizzle-sqlite-rate-limiting","281-better-auth-drizzle-graphql-postgres-fastify-rate-limiting","282-better-auth-drizzle-graphql-mysql-rate-limiting","283-better-auth-drizzle-graphql-mysql-fastify-rate-limiting","284-better-auth-drizzle-graphql-sqlite-rate-limiting","285-better-auth-drizzle-graphql-sqlite-fastify-rate-limiting","286-passport-drizzle-graphql-postgres-fastify-rate-limiting","287-passport-drizzle-graphql-mysql-rate-limiting","288-passport-drizzle-graphql-mysql-fastify-rate-limiting","289-passport-drizzle-graphql-sqlite-rate-limiting","290-passport-drizzle-graphql-sqlite-fastify-rate-limiting","260-passport-typeorm-postgresql-fastify-rate-limiting","261-passport-drizzle-postgresql-fastify-rate-limiting","262-passport-typeorm-mysql-fastify-rate-limiting","263-passport-drizzle-mysql-fastify-rate-limiting","264-passport-typeorm-sqlite-fastify-rate-limiting","265-passport-drizzle-sqlite-fastify-rate-limiting"],composition:"better-auth-prisma-rate-limiting",reason:"Throttling must cover actual auth endpoints, including Better Auth handlers that bypass controller guards. Runtime proof covers Prisma REST/GraphQL, Passport tRPC procedure requests (scenario 270), Passport TypeORM/Drizzle REST on PostgreSQL, MySQL, and SQLite through Express/Fastify (scenarios 188\u2013201 and 260\u2013265), and authenticated Drizzle GraphQL across PostgreSQL/MySQL/SQLite and Express/Fastify (scenarios 151\u2013152 and 281\u2013290). Other combinations remain gated.",requiredEvidence:["repeated login attempts reach 429","normal login remains usable"],status:"certified"},{appliesTo:["none"],composition:"none-docker-health-check",feature:"docker",id:"extra-docker-health-check-none",kind:"extra",profiles:["prisma"],scenarios:["171-docker-health-prisma"],reason:"PostgreSQL Prisma Docker startup and published health endpoint passed; other databases and profiles remain gated.",requiredEvidence:["container image builds","Compose startup and health probe pass","cleanup succeeds"],status:"certified"},{appliesTo:he,feature:"swagger",id:"extra-swagger-auth",kind:"extra",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["158-better-auth-prisma-swagger-scalar","159-passport-prisma-swagger-scalar","194-passport-typeorm-swagger-scalar","195-passport-drizzle-swagger-scalar","202-passport-typeorm-mysql-swagger-scalar","203-passport-typeorm-sqlite-swagger-scalar","204-passport-drizzle-mysql-swagger-scalar","205-passport-drizzle-sqlite-swagger-scalar"],reason:"OpenAPI parsing, auth paths, and Scalar UI passed for the exact Better Auth Prisma and Passport TypeORM/Drizzle REST profiles listed across PostgreSQL, MySQL, and SQLite (scenarios 158\u2013159 and 194\u2013205). Other auth/API profiles remain gated.",requiredEvidence:["document parses","paths exist","documented authentication works"],status:"certified"},{appliesTo:he,feature:"todo-example",id:"extra-todo-auth",kind:"extra",profiles:["better-auth-prisma","better-auth-typeorm-postgres","better-auth-drizzle-postgres","better-auth-prisma-fastify","better-auth-prisma-trpc","better-auth-prisma-graphql","better-auth-drizzle-trpc","better-auth-drizzle-fastify-trpc","better-auth-prisma-mongo-trpc","better-auth-prisma-mongo-fastify-trpc","better-auth-prisma-mongo","better-auth-prisma-mongo-fastify","better-auth-drizzle","better-auth-drizzle-fastify","better-auth-prisma-docker","passport-prisma-docker","better-auth-monorepo-prisma-postgres","passport-prisma","passport-prisma-fastify","passport-prisma-trpc","passport-prisma-mongo-trpc","passport-prisma-mongo-fastify-trpc","passport-prisma-mongo","passport-prisma-mongo-fastify","passport-prisma-graphql","passport-typeorm-postgres","passport-typeorm-postgres-fastify","passport-drizzle-postgres","passport-drizzle-postgres-fastify","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite","better-auth-typeorm-mysql-fastify","passport-typeorm-mysql-fastify","better-auth-drizzle-mysql-fastify","passport-drizzle-mysql-fastify","better-auth-typeorm-sqlite-fastify","passport-typeorm-sqlite-fastify","passport-drizzle-sqlite-fastify"],scenarios:["49-better-auth-prisma-todo","153-better-auth-prisma-graphql-todo","154-passport-prisma-graphql-todo","149-better-auth-drizzle-graphql-todo","150-passport-drizzle-graphql-todo","227-better-auth-drizzle-graphql-postgresql-fastify-todo","228-better-auth-drizzle-graphql-mysql-todo","229-better-auth-drizzle-graphql-mysql-fastify-todo","230-better-auth-drizzle-graphql-sqlite-todo","231-better-auth-drizzle-graphql-sqlite-fastify-todo","232-passport-drizzle-graphql-postgresql-fastify-todo","233-passport-drizzle-graphql-mysql-todo","234-passport-drizzle-graphql-mysql-fastify-todo","235-passport-drizzle-graphql-sqlite-todo","236-passport-drizzle-graphql-sqlite-fastify-todo","168-better-auth-prisma-trpc-todo","169-passport-prisma-trpc-todo","271-better-auth-drizzle-sqlite-express-trpc-todo","272-better-auth-drizzle-sqlite-fastify-trpc-todo","273-better-auth-prisma-mongo-express-trpc-todo","274-better-auth-prisma-mongo-fastify-trpc-todo","275-passport-prisma-mongo-express-trpc-todo","276-passport-prisma-mongo-fastify-trpc-todo","175-passport-prisma-rest-todo","182-passport-typeorm-postgres-rest-todo","183-passport-drizzle-postgres-rest-todo","184-passport-typeorm-mysql-rest-todo","185-passport-typeorm-sqlite-rest-todo","186-passport-drizzle-mysql-rest-todo","187-passport-drizzle-sqlite-rest-todo","196-passport-typeorm-nestjs-zod-swagger-todo","197-passport-drizzle-nestjs-zod-swagger-todo","206-passport-typeorm-mysql-nestjs-zod-swagger-todo","207-passport-typeorm-sqlite-nestjs-zod-swagger-todo","208-passport-drizzle-mysql-nestjs-zod-swagger-todo","209-passport-drizzle-sqlite-nestjs-zod-swagger-todo","253-better-auth-typeorm-mysql-fastify-rest-todo","254-passport-typeorm-mysql-fastify-rest-todo","255-better-auth-drizzle-mysql-fastify-rest-todo","256-passport-drizzle-mysql-fastify-rest-todo","257-better-auth-typeorm-sqlite-fastify-rest-todo","258-passport-typeorm-sqlite-fastify-rest-todo","259-passport-drizzle-sqlite-fastify-rest-todo","277-better-auth-prisma-postgres-fastify-rest-todo","278-passport-prisma-postgres-fastify-rest-todo","279-passport-typeorm-postgres-fastify-rest-todo","280-passport-drizzle-postgres-fastify-rest-todo","291-better-auth-typeorm-postgres-rest-todo","292-better-auth-drizzle-postgres-rest-todo","293-passport-prisma-mongo-rest-todo","294-passport-prisma-mongo-fastify-rest-todo","301-better-auth-prisma-mongo-rest-todo","302-better-auth-prisma-mongo-fastify-rest-todo","303-better-auth-drizzle-sqlite-rest-todo","304-better-auth-drizzle-sqlite-fastify-rest-todo","305-better-auth-prisma-docker-todo","306-passport-prisma-docker-todo","307-better-auth-monorepo-prisma-todo"],reason:"Todo ownership is certified for the exact authenticated Prisma REST/GraphQL, Drizzle GraphQL PostgreSQL/MySQL/SQLite Express/Fastify, tRPC, Passport TypeORM/Drizzle SQL REST, Better Auth TypeORM/Drizzle PostgreSQL and SQLite REST, Better Auth/Passport Prisma MongoDB REST, Docker, and Better Auth Prisma monorepo profiles listed here. Scenarios 291\u2013307 cover the additional ORM, MongoDB, Docker, and monorepo owner-isolation cases; other API/database combinations remain gated until their owner-isolation scenarios pass.",requiredEvidence:["two users cannot read, mutate, or delete each other's records"],status:"certified"},{appliesTo:he,feature:"typescript-7",id:"extra-typescript-7-auth",kind:"extra",profiles:["better-auth-prisma","passport-prisma"],scenarios:["268-better-auth-prisma-typescript-7","295-passport-prisma-typescript-7"],reason:"Better Auth and Passport Prisma PostgreSQL TypeScript 7 builds, migrations, unit tests, and authenticated E2E pass for the exact profiles listed here in scenarios 268 and 295; other ORM and database profiles remain gated.",requiredEvidence:["clean build","runtime auth tests"],status:"certified"},{appliesTo:he,feature:"packages/shared",id:"extra-packages-shared-auth",kind:"extra",profiles:["better-auth-monorepo-prisma-postgres"],scenarios:["267-better-auth-monorepo-prisma-postgres","307-better-auth-monorepo-prisma-todo"],reason:"Better Auth Prisma monorepo workspace packages build and authenticate in scenarios 267 and 307, including authenticated todo owner isolation; other layouts remain gated.",requiredEvidence:["consumer package compiles","packaged application authenticates"],status:"certified"}],sp=[{appliesTo:he,feature:"agent-skills",id:"addon-agent-skills-auth",profiles:["better-auth-prisma","better-auth-drizzle-postgres","passport-drizzle-postgres","passport-typeorm-postgres"],scenarios:["210-passport-drizzle-agent-skills","211-passport-drizzle-agent-skills-ultracite","212-better-auth-prisma-agent-skills","213-passport-typeorm-agent-skills","214-better-auth-drizzle-agent-skills"],kind:"addon",reason:"Non-interactive skill installation preserved each generated app, installed the selected skill files, and verified skills-lock content hashes for the exact Better Auth Prisma/Drizzle and Passport Prisma-profile candidates (scenarios 210\u2013214). Broader databases and ORMs remain gated.",requiredEvidence:["installation is non-interactive","project code is untouched"],status:"certified"},{appliesTo:he,feature:"husky",id:"addon-husky-auth",kind:"addon",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["162-better-auth-prisma-husky","163-passport-prisma-husky","167-better-auth-prisma-husky-ultracite","173-passport-prisma-husky-ultracite","192-passport-typeorm-husky-ultracite","193-passport-drizzle-husky-ultracite","215-passport-typeorm-mysql-husky-ultracite","216-passport-typeorm-sqlite-husky-ultracite","217-passport-drizzle-mysql-husky-ultracite","218-passport-drizzle-sqlite-husky-ultracite"],reason:"Git-enabled and git-disabled creation plus successful and failing hooks passed for the exact Better Auth/Passport Prisma and Passport TypeORM/Drizzle REST profiles listed (scenarios 162\u2013163, 167, 173, 192\u2013193, and 215\u2013218). Other API/auth profiles remain gated.",requiredEvidence:["git-enabled and git-disabled creation","successful and failing hook execution"],status:"certified"},{appliesTo:he,feature:"ultracite",id:"addon-ultracite-auth",kind:"addon",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres","passport-drizzle-graphql"],scenarios:["157-better-auth-prisma-ultracite","166-passport-prisma-ultracite","190-passport-typeorm-postgres-ultracite","191-passport-drizzle-postgres-ultracite","133-passport-drizzle-graphql-ultracite"],reason:"Generated Better Auth and Passport files pass Ultracite formatting, build, unit tests, and runtime tests for the five listed Prisma, TypeORM, and Drizzle PostgreSQL REST/GraphQL profiles (scenarios 133, 157, 166, and 190\u2013191). Other profiles remain gated.",requiredEvidence:["formatting preserves behavior","auth schema generation then format/build/test passes"],status:"certified"},{appliesTo:he,feature:"scalar-ui",id:"addon-scalar-auth",kind:"addon",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["158-better-auth-prisma-swagger-scalar","159-passport-prisma-swagger-scalar","194-passport-typeorm-swagger-scalar","195-passport-drizzle-swagger-scalar","202-passport-typeorm-mysql-swagger-scalar","203-passport-typeorm-sqlite-swagger-scalar","204-passport-drizzle-mysql-swagger-scalar","205-passport-drizzle-sqlite-swagger-scalar"],reason:"Authenticated Scalar pages passed for the exact Better Auth Prisma and Passport TypeORM/Drizzle REST profiles listed across PostgreSQL, MySQL, and SQLite (scenarios 158\u2013159 and 194\u2013205). Broader profiles remain gated.",requiredEvidence:["schema loads","bearer and cookie auth configured"],status:"certified"},{appliesTo:he,feature:"nestjs-zod",id:"addon-nestjs-zod-auth",kind:"addon",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-mysql","passport-drizzle-sqlite"],scenarios:["160-better-auth-prisma-nestjs-zod-swagger-todo","161-passport-prisma-nestjs-zod-swagger-todo","196-passport-typeorm-nestjs-zod-swagger-todo","197-passport-drizzle-nestjs-zod-swagger-todo","206-passport-typeorm-mysql-nestjs-zod-swagger-todo","207-passport-typeorm-sqlite-nestjs-zod-swagger-todo","208-passport-drizzle-mysql-nestjs-zod-swagger-todo","209-passport-drizzle-sqlite-nestjs-zod-swagger-todo"],reason:"Peer resolution, invalid DTO rejection, Swagger generation, authentication, and todo ownership passed for the exact Better Auth Prisma and Passport TypeORM/Drizzle REST profiles listed across PostgreSQL, MySQL, and SQLite (scenarios 160\u2013161 and 196\u2013209). Other auth/API profiles remain gated.",requiredEvidence:["peer dependencies resolve","invalid requests rejected","swagger integration works"],status:"certified"}],ap=[{features:["auth","docker","health-check"],id:"combined-auth-docker-health",profiles:["better-auth-prisma-docker"],reason:"Better Auth Prisma migrations, Docker health, authenticated user creation, container restart, and post-restart sign-in passed in scenario 172; other profiles remain gated.",scenarios:["172-better-auth-prisma-docker-health-restart"],status:"certified"},{features:["auth","rate-limiting","reverse-proxy"],id:"combined-auth-rate-limit-proxy",profiles:["passport-prisma"],reason:"Passport login throttling respects the configured trusted proxy address, returns 429 for repeated failures by one client IP, and keeps a second client IP usable in scenario 269.",scenarios:["269-passport-prisma-rate-limit-reverse-proxy"],status:"certified"},{features:["auth","swagger","scalar-ui"],id:"combined-auth-swagger-scalar",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-typeorm-mysql","passport-typeorm-sqlite","passport-drizzle-postgres","passport-drizzle-mysql","passport-drizzle-sqlite"],reason:"Documented authentication through Scalar passed for Better Auth Prisma REST and Passport TypeORM/Drizzle REST across PostgreSQL, MySQL, and SQLite; other auth/API profiles remain gated.",scenarios:["158-better-auth-prisma-swagger-scalar","159-passport-prisma-swagger-scalar","194-passport-typeorm-swagger-scalar","195-passport-drizzle-swagger-scalar","202-passport-typeorm-mysql-swagger-scalar","203-passport-typeorm-sqlite-swagger-scalar","204-passport-drizzle-mysql-swagger-scalar","205-passport-drizzle-sqlite-swagger-scalar"],status:"certified"},{features:["auth","todo-example","trpc"],id:"combined-auth-todo-trpc",profiles:["better-auth-prisma-trpc","passport-prisma-trpc","better-auth-prisma-fastify-trpc","passport-prisma-fastify-trpc","better-auth-typeorm-postgres-trpc","passport-typeorm-postgres-trpc","better-auth-drizzle-postgres-trpc","passport-drizzle-postgres-trpc","better-auth-typeorm-postgres-fastify-trpc","passport-typeorm-postgres-fastify-trpc","better-auth-drizzle-postgres-fastify-trpc","passport-drizzle-postgres-fastify-trpc","better-auth-typeorm-mysql-trpc","passport-typeorm-mysql-trpc","better-auth-drizzle-mysql-trpc","passport-drizzle-mysql-trpc","better-auth-typeorm-sqlite-trpc","passport-typeorm-sqlite-trpc","passport-drizzle-sqlite-trpc","better-auth-drizzle-trpc","better-auth-drizzle-fastify-trpc","better-auth-prisma-mongo-trpc","better-auth-prisma-mongo-fastify-trpc","passport-prisma-mongo-trpc","passport-prisma-mongo-fastify-trpc","better-auth-typeorm-mysql-fastify-trpc","passport-typeorm-mysql-fastify-trpc","better-auth-drizzle-mysql-fastify-trpc","passport-drizzle-mysql-fastify-trpc","better-auth-typeorm-sqlite-fastify-trpc","passport-typeorm-sqlite-fastify-trpc","passport-drizzle-sqlite-fastify-trpc"],reason:"Full runtime owner-isolation scenarios passed for all 32 listed authenticated tRPC todo profiles across PostgreSQL, MySQL, SQLite, and MongoDB.",scenarios:["168-better-auth-prisma-trpc-todo","169-passport-prisma-trpc-todo","219-better-auth-typeorm-postgres-trpc-todo","220-passport-typeorm-postgres-trpc-todo","221-better-auth-drizzle-postgres-trpc-todo","222-passport-drizzle-postgres-trpc-todo","223-better-auth-typeorm-postgres-fastify-trpc-todo","224-passport-typeorm-postgres-fastify-trpc-todo","225-better-auth-drizzle-postgres-fastify-trpc-todo","226-passport-drizzle-postgres-fastify-trpc-todo","237-better-auth-typeorm-mysql-trpc-todo","238-passport-typeorm-mysql-trpc-todo","239-better-auth-drizzle-mysql-trpc-todo","240-passport-drizzle-mysql-trpc-todo","241-better-auth-typeorm-sqlite-trpc-todo","242-passport-typeorm-sqlite-trpc-todo","243-passport-drizzle-sqlite-trpc-todo","244-better-auth-prisma-postgres-fastify-trpc-todo","245-passport-prisma-postgres-fastify-trpc-todo","271-better-auth-drizzle-sqlite-express-trpc-todo","272-better-auth-drizzle-sqlite-fastify-trpc-todo","273-better-auth-prisma-mongo-express-trpc-todo","274-better-auth-prisma-mongo-fastify-trpc-todo","275-passport-prisma-mongo-express-trpc-todo","276-passport-prisma-mongo-fastify-trpc-todo","246-better-auth-typeorm-mysql-fastify-trpc-todo","247-passport-typeorm-mysql-fastify-trpc-todo","248-better-auth-drizzle-mysql-fastify-trpc-todo","249-passport-drizzle-mysql-fastify-trpc-todo","250-better-auth-typeorm-sqlite-fastify-trpc-todo","251-passport-typeorm-sqlite-fastify-trpc-todo","252-passport-drizzle-sqlite-fastify-trpc-todo"],status:"certified"},{features:["auth","docker","health-check","migrations","restart-persistence"],id:"combined-auth-docker-migrations-restart",profiles:["better-auth-prisma-docker"],reason:"Better Auth Prisma 7/PostgreSQL users and sessions survive Docker-managed migrations and an application container restart in scenario 172; this certifies that exact profile, with broader auth/database profiles gated.",scenarios:["172-better-auth-prisma-docker-health-restart"],status:"certified"},{features:["auth","husky","ultracite"],id:"combined-auth-husky-ultracite",profiles:["better-auth-prisma","passport-prisma","passport-typeorm-postgres","passport-drizzle-postgres"],reason:"Hook success/failure and Ultracite formatting passed for Better Auth and Passport across Prisma, TypeORM, and Drizzle PostgreSQL REST; other database and API profiles remain gated.",scenarios:["167-better-auth-prisma-husky-ultracite","173-passport-prisma-husky-ultracite","192-passport-typeorm-husky-ultracite","193-passport-drizzle-husky-ultracite"],status:"certified"},{features:["auth","agent-skills","ultracite"],id:"combined-auth-agent-skills-ultracite",profiles:["passport-drizzle-postgres"],reason:"Passport + Drizzle PostgreSQL skills and Ultracite instructions both install successfully; generated-project formatting, build, and runtime tests pass (scenario 211).",scenarios:["211-passport-drizzle-agent-skills-ultracite"],status:"certified"},{features:["auth","typescript-7"],id:"combined-auth-typescript-7",profiles:["better-auth-prisma","passport-prisma"],reason:"Better Auth and Passport Prisma TypeScript 7 builds, migrations, and authenticated runtime pass in scenarios 268 and 295; other profiles remain gated.",scenarios:["268-better-auth-prisma-typescript-7","295-passport-prisma-typescript-7"],status:"certified"}];function oa(e){return{certified:e.filter(t=>t.status==="certified").length,desired:e.filter(t=>t.status==="desired").length,implemented:e.filter(t=>t.status==="implemented").length,unfinished:e.filter(t=>t.status!=="certified").map(({id:t,reason:r,status:s})=>({id:t,reason:r,status:s}))}}p(oa,"Ts"),l(oa,"summarize");function ip(){const e=ur.filter(r=>r.status!=="certified"&&r.auth!=="none").map(({id:r,note:s,status:a})=>({id:`composition:${r}`,reason:s,status:a})),t=[...ia,...rp,...sp,...ap,...e];return oa(t)}p(ip,"js"),l(ip,"getCoverageReport");function op(){return ia.filter(e=>e.status==="desired"&&!e.profile)}p(op,"Ps"),l(op,"getMissingProfiles");const np="single-project/architecture/nest-api",pp="single-project/architecture/nest-gateway",lp="single-project/architecture/nest-microservice",cp="monorepo/root",dp="monorepo/apps/api-gateway",up="monorepo/packages",mp="addons/husky",hp="extras/docker",fp="extras/swagger",gp="extras/health",yp="extras/database",bp="monorepo/packages/db",zp="feature/graphql/todo-example",vp="monorepo/feature/graphql/todo-example",na="feature/rest/todo-example",pa="monorepo/feature/rest/todo-example",qp=[{conditions:{extras:["docker"]},id:"extra-docker",name:"Docker Support",priority:5,templateGroups:[hp]},{conditions:{extras:["swagger"]},id:"extra-swagger",name:"Swagger Documentation",priority:5,templateGroups:[fp]},{conditions:{extras:["health-check"]},id:"extra-health-check",name:"Terminus Health Endpoints",priority:5,templateGroups:[gp]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"]},id:"extra-database",name:"Database Module",priority:5,templateGroups:[yp]},{conditions:{database:["postgresql","mysql","sqlite","mongodb"],projectType:"monorepo"},id:"monorepo-db-package",name:"Monorepo DB Package",priority:5,templateGroups:[bp]},{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:[zp]},{conditions:{api:["graphql"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-todo-example",name:"Todo Example (monorepo, graphql)",priority:5,templateGroups:[vp]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"single"},id:"extra-rest-todo-example",name:"REST Todo Example (single)",priority:5,templateGroups:[na]},{conditions:{api:["rest"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-rest-todo-example",name:"REST Todo Example (monorepo)",priority:5,templateGroups:[pa]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"single"},id:"extra-trpc-todo-example",name:"tRPC Todo Example (single)",priority:5,templateGroups:[na]},{conditions:{api:["trpc"],extras:["todo-example"],projectType:"monorepo"},id:"monorepo-extra-trpc-todo-example",name:"tRPC Todo Example (monorepo)",priority:5,templateGroups:[pa]}],wp=[{conditions:{architecture:"nest-api",projectType:"single"},id:"single-nest-api",name:"Single NestJS API",priority:10,templateGroups:[np]},{conditions:{architecture:"nest-gateway",projectType:"single"},id:"single-nest-gateway",name:"Single NestJS Gateway",priority:10,templateGroups:[pp]},{conditions:{architecture:"nest-microservice",projectType:"single"},id:"single-nest-microservice",name:"Single NestJS Microservice",priority:10,templateGroups:[lp]},{conditions:{projectType:"monorepo"},id:"monorepo-root",name:"Monorepo Root",priority:10,templateGroups:[cp,dp,up]},{conditions:{addons:["husky"]},id:"addon-husky",name:"Husky Git Hooks",priority:5,templateGroups:[mp]}],la=[...wp,...qp];function ca(e){e.registerAll(la)}p(ca,"jt"),l(ca,"initializeTemplateMappings");function Sp(){return[...la]}p(Sp,"$s"),l(Sp,"getPredefinedMappings");class Kt{static{p(this,"Y")}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 i of this.mappings)Kt.matches(i.conditions,t)&&r.push(i);const s=[],a={},o=[];for(const i of r){for(const n of i.templateGroups)s.includes(n)||s.push(n);Object.assign(a,i.extraVariables),o.push(i.id)}return{extraVariables:a,matchedMappings:o,templateGroups:s}}findFirst(t){return this.mappings.find(r=>Kt.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 da(e){return e.replaceAll(/([a-z])([A-Z])/gu,"$1-$2").replaceAll(/\s+/gu,"-").toLowerCase()}p(da,"xs"),l(da,"toKebabCase");function ua(e){return e.replaceAll(/[-_\s](.)/gu,(t,r)=>r.toUpperCase()).replace(/^(.)/u,t=>t.toLowerCase())}p(ua,"Pt"),l(ua,"toCamelCase");function ma(e){return e.replaceAll(/[-_\s](.)/gu,(t,r)=>r.toUpperCase()).replace(/^(.)/u,t=>t.toUpperCase())}p(ma,"Cs"),l(ma,"toPascalCase");function ha(e){const t=e.database.includes("postgresql"),r=e.database.includes("mysql"),s=e.database.includes("sqlite"),a=e.database.includes("mongodb"),o=e.orm.includes("prisma"),i=e.orm.includes("typeorm"),n=e.orm.includes("drizzle"),c=e.database.length>0&&!o&&!i&&!n;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",hasFormatter:e.formatter!=="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"),hasHealthCheck:e.extras.includes("health-check"),hasMongodb:a,hasMysql:r,hasOrm:e.orm.length>0,hasPostgres:t,hasRateLimiting:e.extras.includes("rate-limiting"),hasTrustedProxy:(e.trustedProxyIps?.length??0)>0,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],trustedProxyIps:[...e.trustedProxyIps??[]],ormType:e.orm[0]??null,orms:[...e.orm],packageManager:e.packageManager,projectName:e.projectName,projectNameCamelCase:ua(e.projectName),projectNameKebab:da(e.projectName),projectNamePascalCase:ma(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:n,usePrisma:o,isPrisma8:o&&(e.prismaVersion==="8"||a&&!e.prismaVersion||!e.prismaVersion&&!r&&!s),isPrisma6:o&&e.prismaVersion==="6",isPrisma7:o&&(e.prismaVersion==="7"||r||s||e.prismaVersion!=="8"&&!a),isPrismaMongo:o&&a&&(e.prismaVersion==="8"||e.prismaVersion!=="7"),isPrismaPostgres:o&&t&&(e.prismaVersion==="8"||!e.prismaVersion&&!r&&!s),useRawSql:c,useSwaggerScalar:e.extras.includes("swagger")&&e.addons.includes("scalar-ui"),useTypeorm:i,useTypescript7:e.extras.includes("typescript-7"),year:new Date().getFullYear()}}p(ha,"Et"),l(ha,"buildTemplateVariables");function fa(e,t){return{...e,...t}}p(fa,"_t"),l(fa,"mergeTemplateExtras");class we{static{p(this,"L")}static{l(this,"BetterAuthGenerator")}project;config;environmentImport(){return`import { env } from "${this.config.envImport??"../config/env.js"}";`}hasRateLimiting(){return(this.config.extras??[]).includes("rate-limiting")}rateLimitOption(){return this.hasRateLimiting()?[" rateLimit: { enabled: true, max: 60, window: 60 },"]:[]}constructor(t,r){this.project=t,this.config=r}generate(t){this.generateCliConfig(t);const r=this.config.orm??[],s=this.config.database??[],a=s.length>0,o=this.config.skipModule??!1;if(this.config.api?.includes("graphql")&&this.generateGraphqlAuthSupport(t),this.config.strategy==="better-auth:stateless"||!a){this.generateStateless(t,o);return}const i=r.includes("prisma"),n=r.includes("drizzle"),c=r.includes("typeorm");i?(this.generatePrisma(t,s),o||this.generateModule(t,"prisma")):n?(this.generateDrizzle(t,s),o||this.generateModule(t,"drizzle")):c?(this.generateNative(t,s),o||this.generateTypeormModule(t,s)):(this.generateNative(t,s),o||this.generateModule(t,"raw.sql"))}generateGraphqlAuthSupport(t){const r=['import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";','import { AuthService } from "@thallesp/nestjs-better-auth";','import { fromNodeHeaders } from "better-auth/node";','import type { IncomingHttpHeaders } from "node:http";',...this.config.strategy==="better-auth:stateless"?['import { auth } from "../auth.js";']:[],"","interface GraphqlRequest {"," headers: IncomingHttpHeaders;"," user?: { id: string };","}","","@Injectable()","export class GqlAuthGuard implements CanActivate {",...this.config.strategy==="better-auth:stateless"?[" private readonly auth = auth;"]:[" constructor(private readonly authService: AuthService) {}"," private get auth() { return this.authService.instance; }"]," async canActivate(context: ExecutionContext): Promise<boolean> {"," const { req } = GqlExecutionContext.create(context).getContext<{ req: GraphqlRequest }>();"," const session = await this.auth.api.getSession({ headers: fromNodeHeaders(req.headers) });"," if (!session) throw new UnauthorizedException();"," req.user = session.user;"," return true;"," }","}",""].join(`
87
+ `);this.project.createSourceFile(S.join(t,"guards/gql-auth.guard.ts"),r,{overwrite:!0});const s=['import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";','import { AuthService } from "@thallesp/nestjs-better-auth";','import { fromNodeHeaders } from "better-auth/node";','import type { IncomingHttpHeaders } from "node:http";',...this.config.strategy==="better-auth:stateless"?['import { auth } from "../auth.js";']:[],"","interface AuthenticatedRequest { headers: IncomingHttpHeaders; session?: { user: { id: string } }; user?: { id: string }; }","@Injectable()","export class RestAuthGuard implements CanActivate {",...this.config.strategy==="better-auth:stateless"?[" private readonly auth = auth;"]:[" constructor(private readonly authService: AuthService) {}"," private get auth() { return this.authService.instance; }"]," async canActivate(context: ExecutionContext): Promise<boolean> {"," const request = context.switchToHttp().getRequest<AuthenticatedRequest>();"," const session = await this.auth.api.getSession({ headers: fromNodeHeaders(request.headers) });"," if (!session) throw new UnauthorizedException();"," request.session = session;"," request.user = session.user;"," return true;"," }","}",""].join(`
88
+ `);this.project.createSourceFile(S.join(t,"guards/rest-auth.guard.ts"),s,{overwrite:!0});const a=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";','import { GqlExecutionContext } from "@nestjs/graphql";',"","export const UserEntity = createParamDecorator("," (_data: unknown, context: ExecutionContext) => {"," const gqlContext = GqlExecutionContext.create(context);"," return gqlContext.getContext<{ req: { user: { id: string } } }>().req.user;"," }",");",""].join(`
89
+ `);this.project.createSourceFile(S.join(t,"decorators/user.decorator.ts"),a,{overwrite:!0}),this.project.createSourceFile(S.join(t,"decorators/index.ts"),`export { UserEntity } from "./user.decorator.js";
90
+ `,{overwrite:!0})}generateAuthOnly(t){this.generateCliConfig(t);const r=this.config.database??[],s=r.length>0;if(this.config.strategy==="better-auth:stateless"||!s){this.generateStateless(t,!0);return}const a=this.config.orm??[],o=a.includes("prisma"),i=a.includes("drizzle"),n=a.includes("typeorm");o?this.generatePrisma(t,r):i?this.generateDrizzle(t,r):n?this.generateNative(t,r):this.generateNative(t,r)}generateCliConfig(t){const r=this.config.orm??[],s=this.config.database??[];if(this.config.strategy==="better-auth:stateless"||s.length===0){this.project.createSourceFile(S.join(t,"auth.cli.ts"),`export { auth } from "./auth.js";
91
+ `,{overwrite:!0});return}const a=r.includes("prisma"),o=r.includes("drizzle"),i=s.includes("postgresql"),n=s.includes("mysql"),c=s.includes("mongodb"),d=we.sqlDialect(i,n,c);if(a){this.project.createSourceFile(S.resolve(t,"../../scripts/install-auth-schema.mjs"),['import { readFile, writeFile } from "node:fs/promises";','const schema = await readFile("auth-schema.prisma", "utf8");','const datasource = schema.match(/datasource\\s+\\w+\\s*\\{[^}]*provider\\s*=\\s*"(?<provider>[^"]+)"/msu)?.groups?.provider ?? "postgresql";','const models = schema.replace(/^(?:generator|datasource)\\s+\\w+\\s*\\{[^}]*\\}/gmu, "").trim();',"const normalizeMongo = (content) => {"," let next = content;",String.raw` next = next.replace(/^(?<idPrefix>(?:\s*id\s+String\s+)).*$/gmu, '$<idPrefix>@id @default(auto()) @map("_id") @db.ObjectId');`,String.raw` next = next.replace(/@map\("_id"\)\s*@db\.ObjectId\s*@map\("_id"\)/gu, '@map("_id") @db.ObjectId');`,String.raw` next = next.replace(/@map\("_id"\)\s*@map\("_id"\)/gu, '@map("_id")');`,String.raw` next = next.replace(/^(?<relation>\s*(?:userId|sessionId|accountId)\s+String)(?!\s+@db\.ObjectId)/gmu, '$<relation> @db.ObjectId');`," return next;","};",'const normalized = datasource === "mongodb" ? normalizeMongo(models) : models;','if (!normalized.includes("model User")) throw new Error("Auth CLI produced no User model");',`await writeFile("${this.config.projectType==="monorepo"?"../../packages/db/src/database/orm/prisma/auth.prisma":"src/database/orm/prisma/auth.prisma"}", normalized + "\\n");`].join(`
92
+ `),{overwrite:!0}),this.project.createSourceFile(S.join(t,"auth.cli.ts"),['import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";',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: prismaAdapter({} as never, { provider: "${d}" }),`," emailAndPassword: { enabled: true },","});"].join(`
93
+ `),{overwrite:!0});return}if(o){const z=we.drizzleProvider(i,n);this.project.createSourceFile(S.join(t,"auth.cli.ts"),['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',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: drizzleAdapter({} as never, { provider: "${z}" }),`," emailAndPassword: { enabled: true },","});"].join(`
94
+ `),{overwrite:!0});return}const u=we.nativeClientImport(s),f=we.nativeClientConstructor(s),g=s.includes("sqlite");this.project.createSourceFile(S.join(t,"auth.cli.ts"),[`import { betterAuth${g?", type Auth, type BetterAuthOptions":""} } from "better-auth";`,this.environmentImport(),u.trim(),...g?['type AuthOptions = Omit<BetterAuthOptions, "baseURL" | "database" | "emailAndPassword" | "secret"> & { baseURL: string; database: Database.Database; emailAndPassword: { enabled: true }; secret: string };',""]:[],"// CLI-only connection used for schema discovery and migrations.",`export const auth${g?": Auth<AuthOptions>":""} = betterAuth({`," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,",` database: ${f},`," emailAndPassword: { enabled: true },","});"].join(`
95
+ `),{overwrite:!0})}generatePrisma(t,r){const s=we.prismaProvider(r),a=this.config.extras?.includes("swagger");let o='import { PrismaClient } from "../database/orm/prisma/generated/client.js";';this.config.projectType==="monorepo"&&(o='import type { PrismaClient } from "@repo/db";'),this.config.prismaVersion==="6"&&(o='import { PrismaClient } from "@prisma/client";');const i=[this.environmentImport(),'import { betterAuth } from "better-auth";','import { prismaAdapter } from "better-auth/adapters/prisma";',o,...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: "${s}" }),`,...r.includes("mongodb")?[" advanced: { database: { generateId: false } },"]:[]," emailAndPassword: { enabled: true },",...this.rateLimitOption(),...a?[" plugins: [openAPI()],"]:[]," });","}","","export type UserSession = ReturnType<typeof createAuth>['$Infer']['Session'];"],n=S.join(t,"auth.ts");this.project.createSourceFile(n,i.join(`
96
+ `),{overwrite:!0})}generateDrizzle(t,r){const s=r.includes("postgresql"),a=r.includes("mysql");let o,i,n;s?(o="NodePgDatabase",i="drizzle-orm/node-postgres",n="pg"):a?(o="MySql2Database",i="drizzle-orm/mysql2",n="mysql"):(o="BetterSQLite3Database",i="drizzle-orm/better-sqlite3",n="sqlite");const c=this.config.extras?.includes("swagger"),d=['import { betterAuth } from "better-auth";','import { drizzleAdapter } from "@better-auth/drizzle-adapter";',`import type { ${o} } from "${i}";`,this.environmentImport(),'import * as schema from "../database/orm/drizzle/schema.js";',...c?['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: "${n}", schema }),`," emailAndPassword: { enabled: true, minPasswordLength: 8 },",...this.rateLimitOption(),...c?[" plugins: [openAPI()],"]:[]," });","}","","export type UserSession = ReturnType<typeof createAuth>['$Infer']['Session'];"],u=S.join(t,"auth.ts");this.project.createSourceFile(u,d.join(`
97
+ `),{overwrite:!0})}generateNative(t,r){const s=this.config.extras?.includes("swagger"),a=r.includes("sqlite"),o=[this.environmentImport(),`import { betterAuth${a?", type Auth, type BetterAuthOptions":""} } from "better-auth";`,we.nativeClientImport(r).trim(),...s?['import { openAPI } from "better-auth/plugins";']:[],"",...a?['type AuthOptions = Omit<BetterAuthOptions, "baseURL" | "database" | "emailAndPassword" | "secret"> & { baseURL: string; database: Database.Database; emailAndPassword: { enabled: true }; secret: string };',""]:[],`export function createAuth(pool: ${we.nativeClientType(r)})${a?": Auth<AuthOptions>":""} {`," return betterAuth({"," secret: env.BETTER_AUTH_SECRET,"," baseURL: env.BETTER_AUTH_URL,"," database: pool,"," emailAndPassword: { enabled: true },",...this.rateLimitOption(),...s?[" plugins: [openAPI()],"]:[],` })${a?" as Auth<AuthOptions>":""};`,"}","","export type UserSession = ReturnType<typeof createAuth>['$Infer']['Session'];"],i=S.join(t,"auth.ts");this.project.createSourceFile(i,o.join(`
98
+ `),{overwrite:!0})}static prismaProvider(t){return t.includes("mongodb")?"mongodb":t.includes("postgresql")?"postgresql":t.includes("mysql")?"mysql":"sqlite"}static sqlDialect(t,r,s){return s?"mongodb":t?"postgresql":r?"mysql":"sqlite"}static drizzleProvider(t,r){return t?"pg":r?"mysql":"sqlite"}static nativeClientImport(t){const r=t.includes("postgresql"),s=t.includes("mysql");return r?'import { Pool } from "pg";':s?'import { createPool } from "mysql2/promise";':'import Database from "better-sqlite3";'}static nativeClientType(t){const r=t.includes("postgresql"),s=t.includes("mysql");return r?"Pool":s?"ReturnType<typeof createPool>":"Database.Database"}static nativeClientConstructor(t){const r=t.includes("postgresql"),s=t.includes("mysql");return r?"new Pool({ connectionString: env.POSTGRES_URL })":s?"createPool({ uri: env.MYSQL_URL })":"new Database(env.SQLITE_PATH)"}generateStateless(t,r=!1){const s=this.config.extras?.includes("swagger"),a=['import { betterAuth } from "better-auth";','import { genericOAuth } from "better-auth/plugins";',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",'," },",...this.rateLimitOption()," plugins: ["," genericOAuth({"," config: [{"," providerId: env.OIDC_PROVIDER_ID,"," clientId: env.OIDC_CLIENT_ID,"," clientSecret: env.OIDC_CLIENT_SECRET,"," discoveryUrl: env.OIDC_DISCOVERY_URL,",' scopes: ["openid", "email", "profile"],'," }],"," }),",...s?[" openAPI(),"]:[]," ],","});",""].join(`
99
+ `),o=S.join(t,"auth.ts");this.project.createSourceFile(o,a,{overwrite:!0}),r||this.generateStatelessModule(t)}generateModule(t,r){const s=(this.config.orm??[]).some(i=>i==="prisma"||i==="drizzle");s&&this.project.createSourceFile(S.join(t,"profile.controller.ts"),['import { Controller, Get } from "@nestjs/common";',...this.config.projectType==="monorepo"&&this.config.extras?.includes("packages/shared")?['import type { AuthUserProfile } from "@repo/shared/auth";']:[],...this.config.api?.includes("graphql")?['import { UseGuards } from "@nestjs/common";','import { RestAuthGuard } from "./guards/rest-auth.guard.js";']:[],'import { Session } from "@thallesp/nestjs-better-auth";','import type { UserSession } from "./auth.js";','@Controller("auth-profile")',...this.config.api?.includes("graphql")?["@UseGuards(RestAuthGuard)"]:[],"export class ProfileController {"," @Get()",this.config.projectType==="monorepo"&&this.config.extras?.includes("packages/shared")?" profile(@Session() session: UserSession): AuthUserProfile { return { id: session.user.id, email: session.user.email }; }":" profile(@Session() session: UserSession) { return { id: session.user.id, email: session.user.email }; }","}"].join(`
100
+ `),{overwrite:!0});const a=['import { Module } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',this.config.projectType==="monorepo"?'import { DbService } from "@repo/db";':'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({",...this.config.api?.includes("graphql")?[" disableGlobalAuthGuard: true,"]:[]," inject: [DbService],"," useFactory: (db: DbService) => ({",` auth: createAuth(db.${r}),`,...this.config.api?.includes("graphql")&&this.config.strategy!=="better-auth:stateless"?[]:[]," }),"," }),"," ],","})","export class AuthModule {}",""],o=S.join(t,"auth.module.ts");this.project.createSourceFile(o,a.join(`
101
+ `),{overwrite:!0})}generateTypeormModule(t,r){const{clientImport:s,poolType:a,poolCtor:o,destroyCalls:i}=we.nativeModuleParts(r),n=a==="DatabaseType"?`this.pool.${i};`:`return this.pool.${i};`,c=['import { Injectable, Module, type OnModuleDestroy } from "@nestjs/common";','import { AuthModule as BetterAuthModule } from "@thallesp/nestjs-better-auth";',s,this.environmentImport(),'import { createAuth } from "./auth.js";',"","@Injectable()","export class AuthPool implements OnModuleDestroy {",` readonly pool: ${a};`," constructor() {",` this.pool = ${o};`," }"," onModuleDestroy(): Promise<void> | void {",` ${n}`," }","}","","@Module({ providers: [AuthPool], exports: [AuthPool] })","export class AuthPoolModule {}","","@Module({"," controllers: [],"," exports: [BetterAuthModule],"," imports: ["," AuthPoolModule,"," BetterAuthModule.forRootAsync({"," imports: [AuthPoolModule],"," inject: [AuthPool],"," useFactory: (pool: AuthPool) => ({"," auth: createAuth(pool.pool),"," }),"," }),"," ],","})","export class AuthModule {}",""],d=S.join(t,"auth.module.ts");this.project.createSourceFile(d,c.join(`
102
+ `),{overwrite:!0})}static nativeModuleParts(t){const r=t.includes("postgresql"),s=t.includes("mysql");return r?{clientImport:'import { Pool } from "pg";',destroyCalls:"end()",poolCtor:"new Pool({ connectionString: env.POSTGRES_URL })",poolType:"Pool"}:s?{clientImport:'import { createPool, type Pool as MysqlPool } from "mysql2/promise";',destroyCalls:"end()",poolCtor:"createPool({ uri: env.MYSQL_URL })",poolType:"MysqlPool"}:{clientImport:'import Database, { type Database as DatabaseType } from "better-sqlite3";',destroyCalls:"close()",poolCtor:"new Database(env.SQLITE_PATH)",poolType:"DatabaseType"}}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=S.join(t,"auth.module.ts");this.project.createSourceFile(s,r.join(`
103
+ `),{overwrite:!0})}}function ga(e,t,r){const s={"auth.controller.ts":`import { BadRequestException, Body, Controller, Get, HttpCode, Post, Req, UseGuards } from "@nestjs/common";
104
+ ${r?`import {
105
+ ApiBadRequestResponse,
106
+ ApiBearerAuth,
107
+ ApiBody,
108
+ ApiConflictResponse,
109
+ ApiCreatedResponse,
110
+ ApiOkResponse,
111
+ ApiOperation,
112
+ ApiTags,
113
+ ApiUnauthorizedResponse,
114
+ } from "@nestjs/swagger";`:""}
115
+ import { z } from "zod";
116
+ import { AuthService } from "./auth.service.js";
117
+ import { RestAuthGuard } from "./guards/rest-auth.guard.js";
118
+
119
+ 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();
120
+ const refreshBody = z.object({ refreshToken: z.string().min(32).max(256) }).strict();
121
+ function validate<T>(schema: z.ZodType<T>, body: unknown): T {
122
+ const result = schema.safeParse(body);
123
+ if (!result.success) throw new BadRequestException("Invalid authentication input");
124
+ return result.data;
125
+ }
126
+
127
+ ${r?`@ApiTags("Authentication")
128
+ `:""}@Controller("auth")
129
+ export class AuthController {
130
+ constructor(private readonly auth: AuthService) {}
131
+ @Post("register")
132
+ ${r?` @ApiOperation({ summary: "Register an account" })
133
+ @ApiBody({ schema: { type: "object", properties: { email: { type: "string", format: "email" }, password: { type: "string", format: "password" } }, required: ["email", "password"] } })
134
+ @ApiCreatedResponse({ description: "Account created" })
135
+ @ApiConflictResponse({ description: "Account already exists" })
136
+ @ApiBadRequestResponse({ description: "Invalid registration input" })
137
+ `:""}
138
+ register(@Body() body: unknown) { const input = validate(credentials, body); return this.auth.register(input.email, input.password); }
139
+ @Post("login") @HttpCode(200)
140
+ ${r?` @ApiOperation({ summary: "Create an authenticated session" })
141
+ @ApiBody({ schema: { type: "object", properties: { email: { type: "string", format: "email" }, password: { type: "string", format: "password" } }, required: ["email", "password"] } })
142
+ @ApiOkResponse({ description: "Access and refresh tokens" })
143
+ @ApiUnauthorizedResponse({ description: "Invalid credentials" })
144
+ `:""}
145
+ login(@Body() body: unknown) { const input = validate(credentials, body); return this.auth.login(input.email, input.password); }
146
+ @Post("refresh") @HttpCode(200)
147
+ ${r?` @ApiOperation({ summary: "Rotate a refresh token" })
148
+ @ApiBody({ schema: { type: "object", properties: { refreshToken: { type: "string" } }, required: ["refreshToken"] } })
149
+ @ApiOkResponse({ description: "Rotated access and refresh tokens" })
150
+ `:""}
151
+ refresh(@Body() body: unknown) { return this.auth.refresh(validate(refreshBody, body).refreshToken); }
152
+ @Post("logout") @HttpCode(200)
153
+ ${r?` @ApiOperation({ summary: "Revoke a refresh-token family" })
154
+ @ApiBody({ schema: { type: "object", properties: { refreshToken: { type: "string" } }, required: ["refreshToken"] } })
155
+ @ApiOkResponse({ description: "Session revoked" })
156
+ `:""}
157
+ logout(@Body() body: unknown) { return this.auth.logout(validate(refreshBody, body).refreshToken); }
158
+ @Get("profile") @UseGuards(RestAuthGuard)
159
+ ${r?` @ApiBearerAuth()
160
+ @ApiOperation({ summary: "Get the authenticated profile" })
161
+ @ApiOkResponse({ description: "Authenticated profile" })
162
+ @ApiUnauthorizedResponse({ description: "Authentication required" })
163
+ `:""}
164
+ profile(@Req() request: { user: unknown }) { return request.user; }
165
+ }
166
+ `,"auth.module.ts":`import { Module } from "@nestjs/common";
167
+ import { JwtModule } from "@nestjs/jwt";
168
+ import { PassportModule } from "@nestjs/passport";
169
+ import { env } from "../config/env.js";
170
+ import { AuthService } from "./auth.service.js";
171
+ import { AuthController } from "./auth.controller.js";
172
+ import { JwtStrategy } from "./strategies/jwt.strategy.js";
173
+ import { RestAuthGuard } from "./guards/rest-auth.guard.js";
174
+ @Module({
175
+ imports: [PassportModule.register({ defaultStrategy: "jwt" }), JwtModule.register({ secret: env.JWT_ACCESS_SECRET, signOptions: { algorithm: "HS256", audience: env.JWT_AUDIENCE, expiresIn: "15m", issuer: env.JWT_ISSUER, keyid: env.JWT_KEY_ID } })],
176
+ controllers: [AuthController], providers: [AuthService, JwtStrategy, RestAuthGuard], exports: [AuthService, JwtModule, RestAuthGuard],
177
+ })
178
+ export class AuthModule {}
179
+ `,"auth.service.ts":`import { Injectable, UnauthorizedException, ConflictException } from "@nestjs/common";
180
+ import { JwtService } from "@nestjs/jwt";
181
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
182
+ import { compare, hash } from "bcrypt";
183
+ import { DbService } from "../database/db.service.js";
184
+
185
+ const publicUser = { id: true, email: true, role: true } as const;
186
+ const digest = (token: string) => createHash("sha256").update(token).digest("hex");
187
+
188
+ @Injectable()
189
+ export class AuthService {
190
+ constructor(private readonly db: DbService, private readonly jwt: JwtService) {}
191
+
192
+ async register(email: string, password: string) {
193
+ const passwordHash = await hash(password, 12);
194
+ try {
195
+ return await this.db.prisma.user.create({ data: { email, password: passwordHash }, select: publicUser });
196
+ } catch (error) {
197
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
198
+ throw new ConflictException("Account already exists");
199
+ }
200
+ throw error;
201
+ }
202
+ }
203
+
204
+ async login(email: string, password: string) {
205
+ const user = await this.db.prisma.user.findUnique({ where: { email }, select: { id: true, password: true } });
206
+ if (!user || !(await compare(password, user.password))) throw new UnauthorizedException("Invalid credentials");
207
+ const familyId = randomUUID();
208
+ const refreshToken = randomBytes(32).toString("base64url");
209
+ await this.db.prisma.refreshToken.create({ data: { userId: user.id, familyId, tokenHash: digest(refreshToken), expiresAt: new Date(Date.now() + 7 * 86_400_000) } });
210
+ return this.tokens(user.id, familyId, refreshToken);
211
+ }
212
+
213
+ private async tokens(userId: string, familyId: string, refreshToken: string) {
214
+ return { accessToken: await this.jwt.signAsync({ sub: userId, sid: familyId, jti: randomUUID() }), refreshToken };
215
+ }
216
+
217
+ async refresh(token: string) {
218
+ const replacement = randomBytes(32).toString("base64url");
219
+ const result = await this.db.prisma.$transaction(async (tx) => {
220
+ const current = await tx.refreshToken.findUnique({ where: { tokenHash: digest(token) } });
221
+ if (!current) return null;
222
+ const changed = await tx.refreshToken.updateMany({ data: { consumedAt: new Date() }, where: { consumedAt: null, expiresAt: { gt: new Date() }, id: current.id, revokedAt: null } });
223
+ if (changed.count !== 1) {
224
+ await tx.refreshToken.updateMany({ data: { revokedAt: new Date() }, where: { familyId: current.familyId } });
225
+ return null;
226
+ }
227
+ await tx.refreshToken.create({ data: { userId: current.userId, familyId: current.familyId, tokenHash: digest(replacement), expiresAt: current.expiresAt } });
228
+ return current;
229
+ });
230
+ if (!result) throw new UnauthorizedException("Invalid refresh token");
231
+ return this.tokens(result.userId, result.familyId, replacement);
232
+ }
233
+
234
+ async logout(token: string) {
235
+ const current = await this.db.prisma.refreshToken.findUnique({ where: { tokenHash: digest(token) } });
236
+ if (current) await this.db.prisma.refreshToken.updateMany({ data: { revokedAt: new Date() }, where: { familyId: current.familyId } });
237
+ return { success: true };
238
+ }
239
+
240
+ async validate(payload: Record<string, unknown>) {
241
+ if (typeof payload.sub !== "string" || typeof payload.sid !== "string" || typeof payload.exp !== "number" || typeof payload.iat !== "number" || typeof payload.jti !== "string") throw new UnauthorizedException();
242
+ const session = await this.db.prisma.refreshToken.findFirst({ where: { consumedAt: null, expiresAt: { gt: new Date() }, familyId: payload.sid, revokedAt: null, userId: payload.sub }, select: { user: { select: publicUser } } });
243
+ if (!session) throw new UnauthorizedException();
244
+ return session.user;
245
+ }
246
+ }
247
+ `,"decorators/current-user.decorator.ts":`import { createParamDecorator, type ExecutionContext } from "@nestjs/common";
248
+
249
+ export const CurrentUser = createParamDecorator(
250
+ (_data: unknown, context: ExecutionContext) => {
251
+ const request = context.switchToHttp().getRequest<{ user: unknown }>();
252
+ return request.user;
253
+ }
254
+ );
255
+ `,"guards/rest-auth.guard.ts":`import { Injectable } from "@nestjs/common";
256
+ import { AuthGuard } from "@nestjs/passport";
257
+ @Injectable()
258
+ export class RestAuthGuard extends AuthGuard("jwt") {}
259
+ `,"strategies/jwt.strategy.ts":`import { Injectable } from "@nestjs/common";
260
+ import { PassportStrategy } from "@nestjs/passport";
261
+ import { ExtractJwt, Strategy } from "passport-jwt";
262
+ import { env } from "../../config/env.js";
263
+ import { AuthService } from "../auth.service.js";
264
+ @Injectable()
265
+ export class JwtStrategy extends PassportStrategy(Strategy) {
266
+ constructor(private readonly auth: AuthService) {
267
+ super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: env.JWT_ACCESS_SECRET, algorithms: ["HS256"], issuer: env.JWT_ISSUER, audience: env.JWT_AUDIENCE, ignoreExpiration: false });
268
+ }
269
+ validate(payload: Record<string, unknown>) { return this.auth.validate(payload); }
270
+ }
271
+ `};for(const[a,o]of Object.entries(s))e.createSourceFile(S.join(t,a),o,{overwrite:!0})}p(ga,"Ds"),l(ga,"generatePassportPrisma");class xp{static{p(this,"Ls")}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?.includes("rest")&&!this.config.api.includes("graphql")){ga(this.project,t,this.config.extras?.includes("swagger")??!1);return}(this.config.database?.length??0)>0?this.generateDbAuth(t):this.generateStatelessAuth(t)}generateStatelessAuth(t){const r=['import { Injectable, UnauthorizedException } from "@nestjs/common";','import { PassportStrategy } from "@nestjs/passport";','import { Strategy, ExtractJwt } from "passport-jwt";','import { passportJwtSecret } from "jwks-rsa";',`import { env } from "${this.config.envImport?.startsWith("@")?this.config.envImport:"../../config/env.js"}";`,"","interface JwtPayload {"," iss?: string;"," sub?: string;"," email?: string;"," [key: string]: unknown;","}","","@Injectable()","export class JwtStrategy extends PassportStrategy(Strategy) {"," constructor() {"," super({"," jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),"," secretOrKeyProvider: passportJwtSecret({"," cache: true,"," jwksRequestsPerMinute: 5,"," jwksUri: env.OIDC_JWKS_URI,"," rateLimit: true,"," }),"," issuer: env.OIDC_ISSUER,"," audience: env.OIDC_AUDIENCE,",' algorithms: ["RS256"],'," ignoreExpiration: false,"," });"," }",""," validate(payload: JwtPayload) {",' if (typeof payload.sub !== "string" || payload.sub.length === 0) {',' throw new UnauthorizedException("External identity token has no subject");'," }"," return {",' email: typeof payload.email === "string" ? payload.email : undefined,'," id: payload.sub,"," issuer: payload.iss,"," userId: payload.sub,"," };"," }","}",""].join(`
272
+ `),s=S.join(t,"strategies/jwt.strategy.ts");this.project.createSourceFile(s,r,{overwrite:!0});const a=["import {"," Controller,"," Get, UseGuards, Req",'} from "@nestjs/common";','import { AuthGuard } from "@nestjs/passport";','import type { Request } from "express";',"",'@Controller("auth")',"export class AuthController {","",' @Get("profile")',' @UseGuards(AuthGuard("jwt"))'," getProfile(@Req() request: Request) {"," return request.user;"," }","","}",""].join(`
273
+ `),o=S.join(t,"auth.controller.ts");this.project.createSourceFile(o,a,{overwrite:!0}),this.generateDecorators(t),this.generateGuard(t);const i=['import { Module } from "@nestjs/common";','import { PassportModule } from "@nestjs/passport";','import { AuthController } from "./auth.controller.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" })],'," controllers: [AuthController],"," providers: ["," JwtStrategy,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],"," exports: ["," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"," ],","})","export class AuthModule {}",""].join(`
274
+ `),n=S.join(t,"auth.module.ts");this.project.createSourceFile(n,i,{overwrite:!0})}generateDbAuth(t){const r=this.config.orm??[],s=r.includes("prisma"),a=r.includes("typeorm"),o=r.includes("drizzle"),i=(this.config.api??[]).includes("graphql"),n=(this.config.extras??[]).includes("swagger");this.generatePasswordService(t),this.generateDbAuthService(t,{useDrizzle:o,usePrisma:s,useTypeorm:a}),this.generateLoginSchema(t),this.generateSignupSchema(t),this.generateRefreshTokenSchema(t),this.generateJwtDto(t),i?(this.generateLoginInput(t),this.generateSignupInput(t),this.generateRefreshTokenInput(t)):(this.generateRestLoginInput(t),this.generateRestSignupInput(t),this.generateRestRefreshTokenInput(t)),this.generateDbJwtStrategy(t),this.generateDbRestGuard(t),i&&this.generateDbGqlGuard(t),this.generateRestOptionalAuthGuard(t),this.generateRestRolesGuard(t),i&&(this.generateGqlOptionalAuthGuard(t),this.generateGqlRolesGuard(t)),this.generateDbController(t,n),i&&(this.generateTokenModel(t),this.generateAuthModel(t),this.generateAuthResolver(t)),this.generateDecorators(t),this.generateDbModule(t,{hasGraphql:i})}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(`
275
+ `);this.project.createSourceFile(S.join(t,"password.service.ts"),r,{overwrite:!0})}generateDbAuthService(t,r){const{useDrizzle:s,usePrisma:a,useTypeorm:o}=r,i=["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 n,c,d,u,f;a?(n='import { DbService } from "../database/db.service.js";',c=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
77
276
  `),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(`
79
- `),m=["return this.db.prisma.user.findUnique({ where: { id: userId } });"].join(`
80
- `)):n?(a=['import { InjectRepository } from "@nestjs/typeorm";','import { Repository } from "typeorm";','import { UserEntity } from "../modules/users/entities/user.entity.js";'].join(`
81
- `),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(`
84
- `),m=["return this.userRepository.findOne({ where: { id: userId } });"].join(`
85
- `)):(a=['import { DbService } from "../database/db.service.js";','import { users } from "../database/orm/drizzle/schema.js";','import { eq } from "drizzle-orm";'].join(`
86
- `),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(`
89
- `),m=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.id, userId))"," .limit(1);","return user ?? null;"].join(`
90
- `));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(`
111
- `)," ],"," 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(`
277
+ `),u=["const user = await this.db.prisma.user.findUnique({"," where: { email },","});"].join(`
278
+ `),f=["return this.db.prisma.user.findUnique({ where: { id: userId } });"].join(`
279
+ `)):o?(n=['import { DbService } from "../database/db.service.js";','import { UserEntity } from "../modules/users/entities/user.entity.js";'].join(`
280
+ `),c=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
281
+ `),d=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," try {"," const repository = this.db.typeorm.getRepository(UserEntity);"," const user = repository.create({"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," });"," await repository.save(user);"," return this.generateTokens({ userId: user.id });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
282
+ `),u=["const user = await this.db.typeorm"," .getRepository(UserEntity)"," .findOne({"," where: { email },"," });"].join(`
283
+ `),f=["return this.db.typeorm"," .getRepository(UserEntity)"," .findOne({"," where: { id: userId },"," });"].join(`
284
+ `)):(n=['import { DbService } from "../database/db.service.js";','import { users } from "../database/orm/drizzle/schema.js";','import { eq } from "drizzle-orm";','import { randomUUID } from "node:crypto";'].join(`
285
+ `),c=[" private readonly db: DbService,"," private readonly jwtService: JwtService,"," private readonly passwordService: PasswordService,"].join(`
286
+ `),d=[" const hashedPassword = await this.passwordService.hashPassword("," payload.password"," );"," const userId = randomUUID();"," try {"," await this.db.sql.getClient()"," .insert(users)"," .values({"," id: userId,"," email: payload.email,"," firstname: payload.firstname ?? null,"," lastname: payload.lastname ?? null,"," password: hashedPassword,",' role: "USER",'," });"," return this.generateTokens({ userId });"," } catch {"," throw new ConflictException(`Email ${payload.email} already used.`);"," }"].join(`
287
+ `),u=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.email, email))"," .limit(1);"].join(`
288
+ `),f=["const [user] = await this.db.sql.getClient()"," .select()"," .from(users)"," .where(eq(users.id, userId))"," .limit(1);","return user ?? null;"].join(`
289
+ `));const g=[i.join(`
290
+ `),"",n,"",'import type { SignupInput } from "./dto/signup.input.js";',"","export interface TokenPayload {"," accessToken: string;"," refreshToken: string;","}","","@Injectable()","export class AuthService {"," constructor(",c," ) {}",""," async createUser(payload: SignupInput): Promise<TokenPayload> {",d," }",""," 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 });"," }","",` ${a||s?"async ":""}validateUser(userId: string) {`,` ${f}`," }",""," 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(`
291
+ `);this.project.createSourceFile(S.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(`
292
+ `);this.project.createSourceFile(S.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(`
293
+ `);this.project.createSourceFile(S.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(`
294
+ `);this.project.createSourceFile(S.join(t,"schemas/refresh-token.schema.ts"),r,{overwrite:!0})}generateJwtDto(t){const r=["export interface JwtDto {"," userId: string;"," iat: number;"," exp: number;","}",""].join(`
295
+ `);this.project.createSourceFile(S.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(`
296
+ `);this.project.createSourceFile(S.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(`
297
+ `);this.project.createSourceFile(S.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(`
298
+ `);this.project.createSourceFile(S.join(t,"dto/refresh-token.input.ts"),r,{overwrite:!0})}generateRestLoginInput(t){const r=['import { loginSchema } from "../schemas/login.schema.js";',"","export class LoginInput {"," static schema = loginSchema;",""," email: string;",""," password: string;","}",""].join(`
299
+ `);this.project.createSourceFile(S.join(t,"dto/login.input.ts"),r,{overwrite:!0})}generateRestSignupInput(t){const r=['import { signupSchema } from "../schemas/signup.schema.js";',"","export class SignupInput {"," static schema = signupSchema;",""," email: string;",""," password: string;",""," firstname?: string;",""," lastname?: string;","}",""].join(`
300
+ `);this.project.createSourceFile(S.join(t,"dto/signup.input.ts"),r,{overwrite:!0})}generateRestRefreshTokenInput(t){const r=['import { refreshTokenSchema } from "../schemas/refresh-token.schema.js";',"","export class RefreshTokenInput {"," static schema = refreshTokenSchema;",""," token: string;","}",""].join(`
301
+ `);this.project.createSourceFile(S.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,",' algorithms: ["HS256"],'," audience: env.JWT_AUDIENCE,"," issuer: env.JWT_ISSUER,"," });"," }",""," async validate(payload: JwtDto) {"," const user = await this.authService.validateUser(payload.userId);"," if (!user) {"," throw new UnauthorizedException();"," }"," return user;"," }","}",""].join(`
302
+ `);this.project.createSourceFile(S.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(`
303
+ `);this.project.createSourceFile(S.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(`
304
+ `);this.project.createSourceFile(S.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(`
305
+ `);this.project.createSourceFile(S.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(`
306
+ `);this.project.createSourceFile(S.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(`
307
+ `);this.project.createSourceFile(S.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(`
308
+ `);this.project.createSourceFile(S.join(t,"guards/gql-roles.guard.ts"),r,{overwrite:!0})}generateDbController(t,r){const s=r?["import {"," ApiCreatedResponse,"," ApiOperation,"," ApiTags,"," ApiUnauthorizedResponse,",'} from "@nestjs/swagger";']:[],a=[];r&&a.push('@ApiTags("Auth")');const o=[];r&&o.push(' @ApiOperation({ summary: "/api/auth/signup" })'," @ApiCreatedResponse({ description: 'User registered successfully' })");const i=[];r&&i.push(' @ApiOperation({ summary: "/api/auth/login" })'," @ApiCreatedResponse({ description: 'User logged in successfully' })"," @ApiUnauthorizedResponse({ description: 'Invalid credentials' })");const n=[];r&&n.push(' @ApiOperation({ summary: "/api/auth/refresh" })');const c=this.config.addons?.includes("nestjs-zod")?['import { ZodValidationPipe } from "nestjs-zod";',""]:[],d=this.config.addons?.includes("nestjs-zod")?"@Body(new ZodValidationPipe(SignupInput.schema))":"@Body()",u=this.config.addons?.includes("nestjs-zod")?"@Body(new ZodValidationPipe(LoginInput.schema))":"@Body()",f=this.config.addons?.includes("nestjs-zod")?"@Body(new ZodValidationPipe(RefreshTokenInput.schema))":"@Body()",g=['import { Body, Controller, HttpCode, Post } from "@nestjs/common";',...c,...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";',"",...a,'@Controller("auth")',"export class AuthController {"," constructor(private readonly auth: AuthService) {}","",' @Post("signup")',...o,` signup(${d} data: SignupInput) {`," data.email = data.email.toLowerCase();"," return this.auth.createUser(data);"," }","",' @Post("login") @HttpCode(200)',...i,` login(${u} { email, password }: LoginInput) {`," return this.auth.login(email.toLowerCase(), password);"," }","",' @Post("refresh") @HttpCode(200)',...n," refreshToken(",` ${f} { token }: RefreshTokenInput`," ) {"," return this.auth.refreshToken(token);"," }","}",""];this.project.createSourceFile(S.join(t,"auth.controller.ts"),g.join(`
309
+ `),{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(`
310
+ `);this.project.createSourceFile(S.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(`
311
+ `);this.project.createSourceFile(S.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(`
312
+ `);this.project.createSourceFile(S.join(t,"auth.resolver.ts"),r,{overwrite:!0})}generateDbModule(t,r){const{hasGraphql:s}=r,a=['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?(a.push('import { AuthResolver } from "./auth.resolver.js";'),a.push('import { GqlAuthGuard } from "./guards/gql-auth.guard.js";'),a.push('import { GqlOptionalAuthGuard } from "./guards/gql-optional-auth.guard.js";')):a.push('import { RestRolesGuard } from "./guards/rest-roles.guard.js";');const o=[" AuthService,"," JwtStrategy,"," PasswordService,"," RestAuthGuard,"," RestOptionalAuthGuard,"];s?(o.push(" GqlAuthGuard,"),o.push(" GqlOptionalAuthGuard,"),o.push(" AuthResolver,")):o.push(" RestRolesGuard,");const i=s?[" GqlAuthGuard,"," GqlOptionalAuthGuard,"," PassportModule,"," RestAuthGuard,"," RestOptionalAuthGuard,"]:[" PassportModule,"," RestAuthGuard,"," RestOptionalAuthGuard,"," RestRolesGuard,"],n=[...a,"","@Global()","@Module({"," controllers: [AuthController],"," exports: [",i.join(`
313
+ `)," AuthService,"," JwtModule,"," ],"," imports: [",' PassportModule.register({ defaultStrategy: "jwt" }),'," JwtModule.register({"," secret: env.JWT_ACCESS_SECRET,",' signOptions: { algorithm: "HS256", audience: env.JWT_AUDIENCE, expiresIn: "15m", issuer: env.JWT_ISSUER, keyid: env.JWT_KEY_ID },'," }),"," ],"," providers: [",o.join(`
314
+ `)," ],","})","export class AuthModule {}",""];this.project.createSourceFile(S.join(t,"auth.module.ts"),n.join(`
315
+ `),{overwrite:!0})}generateDecorators(t){const r=S.join(t,"decorators"),s=(this.config.api??[]).includes("graphql"),a=['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const CurrentUser = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user;"," }",");",""].join(`
316
+ `);this.project.createSourceFile(S.join(r,"current-user.decorator.ts"),a,{overwrite:!0});const o=s?['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(`
317
+ `):['import { createParamDecorator, ExecutionContext } from "@nestjs/common";',"","export const UserEntity = createParamDecorator("," (_data: unknown, ctx: ExecutionContext) => {"," const request = ctx.switchToHttp().getRequest();"," return request.user;"," }",");",""].join(`
318
+ `);this.project.createSourceFile(S.join(r,"user.decorator.ts"),o,{overwrite:!0});const i=['export { CurrentUser } from "./current-user.decorator.js";','export { UserEntity } from "./user.decorator.js";',""].join(`
319
+ `);this.project.createSourceFile(S.join(r,"index.ts"),i,{overwrite:!0})}generateGuard(t){this.generateDbRestGuard(t),this.generateRestOptionalAuthGuard(t),this.generateRestRolesGuard(t)}}class kp{static{p(this,"At")}static{l(this,"AuthModuleGenerator")}project;config;passportGen;betterAuthGen;constructor(t){this.config=t,this.project=new ys,this.passportGen=new xp(this.project,t),this.betterAuthGen=new we(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 jp{static{p(this,"Rt")}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 ya(e,t,r){const s=[];for(const a of r)try{if(a==="auth"){const o=e.api.includes("rest"),i=e.api.includes("graphql"),n=new kp({addons:e.addons,api:e.api,database:e.database,envImport:e.projectType==="monorepo"?"@repo/env/api-gateway":"../config/env.js",extras:e.extras,orm:e.orm,outputDir:e.projectType==="monorepo"?`${t}/apps/api-gateway/src`:`${t}/src`,prismaVersion:e.prismaVersion,projectType:e.projectType,skipModule:!o&&!i&&(e.auth==="better-auth"||e.auth==="better-auth:stateless"),strategy:e.auth});await(o||i||e.auth==="passport"?n.generate():n.generateAuthOnly()),await n.save(),s.push({filesCount:3,generatedFiles:[],success:!0})}else console.log(`Generator ${a} not yet implemented`)}catch(o){s.push({error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:[],success:!1})}return s}p(ya,"It"),l(ya,"executePresetGenerators");function ba(e){const t=e.httpProvider==="fastify"?3001:3e3,r=e.projectName;let s=`${e.packageManager} run`;e.packageManager==="npm"?s="npm run":e.packageManager==="yarn"&&(s="yarn");const a=["services:",` ${e.projectName}:`,` image: ${e.projectName}:local`," build:"," context: ."," dockerfile: Dockerfile"," init: true"," restart: unless-stopped"," ports:",` - "127.0.0.1:${t}:${t}"`," environment:"," NODE_ENV: production",` PORT: "${t}"`],o=[],i=[];e.auth==="better-auth"&&e.orm.includes("prisma")&&o.push(`${s} auth:generate`),e.orm.includes("prisma")?o.push(`${s} prisma:migrate:deploy`):e.orm.includes("drizzle")?o.push(`${s} db:migrate`):e.orm.includes("typeorm")&&o.push(`${s} typeorm:run`);const n=e.extras.includes("health-check")?[" healthcheck:",` test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:${t}/api/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]`," interval: 10s"," timeout: 5s"," retries: 10"," start_period: 30s"]:[],c=[];e.database.includes("postgresql")&&(c.push("postgres"),i.push(` POSTGRES_URL: postgresql://postgres:postgres@postgres:5432/${r}_db?schema=public`)),e.database.includes("mysql")&&(c.push("mysql"),i.push(` MYSQL_URL: mysql://root:mysql@mysql:3306/${r}_db`)),e.database.includes("mongodb")&&(c.push("mongodb"),i.push(` MONGODB_URL: mongodb://mongodb:27017/${r}_db`)),(e.auth==="better-auth"||e.auth==="better-auth:stateless")&&i.push(" BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:?Set BETTER_AUTH_SECRET in .env}",` BETTER_AUTH_URL: http://localhost:${t}`),e.auth==="passport"&&(i.push(" JWT_ACCESS_SECRET: ${JWT_ACCESS_SECRET:?Set JWT_ACCESS_SECRET in .env}"," JWT_ISSUER: ${JWT_ISSUER:-generated-app}"," JWT_AUDIENCE: ${JWT_AUDIENCE:-generated-app-api}"," JWT_KEY_ID: ${JWT_KEY_ID:-primary}"),e.database.length>0&&i.push(" JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET:?Set JWT_REFRESH_SECRET in .env}"));const d=[],u={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 k of e.microservices){if(k==="grpc")continue;d.push(k);const[x,O]=u[k].split("=");i.push(` ${x}: ${O}`)}e.microservices.includes("grpc")&&a.splice(8,0,' - "127.0.0.1:5000:5000"'),a.push(...i),a.push(...n),o.length>0&&a.push(` command: ["sh", "-c", "${o.join(" && ")} && ${s} start:prod"]`);const f=[...c,...d];if(f.length>0){a.push(" depends_on:");for(const k of f)a.push(` ${k}:`),a.push(" condition: service_healthy")}e.database.includes("postgresql")&&a.push(""," postgres:"," image: postgres:17-alpine"," environment:"," POSTGRES_USER: postgres"," POSTGRES_PASSWORD: postgres",` POSTGRES_DB: ${r}_db`," healthcheck:",` test: ["CMD-SHELL", "pg_isready -U postgres -d ${r}_db"]`," interval: 5s"," timeout: 3s"," retries: 20"," volumes:"," - postgres_data:/var/lib/postgresql/data"),e.database.includes("mysql")&&a.push(""," mysql:"," image: mysql:9.7.1"," environment:"," MYSQL_ROOT_PASSWORD: mysql",` MYSQL_DATABASE: ${r}_db`," healthcheck:",' test: ["CMD", "mysqladmin", "ping", "-hmysql", "-uroot", "-pmysql"]'," interval: 5s"," timeout: 3s"," retries: 30"," volumes:"," - mysql_data:/var/lib/mysql"),e.database.includes("mongodb")&&a.push(""," mongodb:"," image: mongo:8.3.4-noble",' command: ["mongod", "--dbpath", "/data/db", "--setParameter", "diagnosticDataCollectionEnabled=false"]'," environment:",` MONGO_INITDB_DATABASE: ${r}_db`," healthcheck:",' test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand({ ping: 1 }).ok"]'," interval: 5s"," timeout: 3s"," retries: 20"," volumes:"," - mongo_data:/data/db");const g={kafka:["image: apache/kafka:3.9.0","environment: { KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka: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' }",'ports: ["9092:9092"]','healthcheck: { test: ["CMD-SHELL", "bash -c \\"</dev/tcp/localhost/9092\\""], interval: 10s, timeout: 5s, retries: 30 }'],mqtt:["image: eclipse-mosquitto:2",'ports: ["1883:1883"]','healthcheck: { test: ["CMD-SHELL", "nc -z localhost 1883"], interval: 5s, timeout: 3s, retries: 20 }'],nats:["image: nats:2-alpine",'ports: ["4222:4222"]','healthcheck: { test: ["CMD-SHELL", "wget -qO- http://localhost:8222/healthz"], interval: 5s, timeout: 3s, retries: 20 }'],rabbitmq:["image: rabbitmq:3.13-alpine",'ports: ["5672:5672"]','healthcheck: { test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"], interval: 5s, timeout: 3s, retries: 20 }'],redis:["image: redis:7-alpine",'ports: ["6379:6379"]','healthcheck: { test: ["CMD", "redis-cli", "ping"], interval: 5s, timeout: 3s, retries: 20 }']};for(const k of d){a.push("",` ${k}:`);for(const x of g[k]??[])a.push(` ${x}`)}const z=[...e.database.includes("postgresql")?["postgres_data"]:[],...e.database.includes("mysql")?["mysql_data"]:[],...e.database.includes("mongodb")?["mongo_data"]:[]];return z.length>0&&a.push("","volumes:",...z.map(k=>` ${k}:`)),`${a.join(`
320
+ `)}
321
+ `}p(ba,"Ms"),l(ba,"generateDockerCompose");async function za(e,t,r,s,a){let o="postgresql";t.database.includes("mysql")?o="mysql":t.database.includes("sqlite")&&(o="sqlite");const i=t.projectType==="monorepo"?"./packages/db/src/orm/drizzle/schema.ts":"./src/database/orm/drizzle/schema.ts",n=i.replace("/schema.ts","/migrations");let c="env.POSTGRES_URL";t.database.includes("mysql")?c="env.MYSQL_URL":t.database.includes("sqlite")&&(c="env.SQLITE_PATH");const d=[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: ${c},`," },",` dialect: '${o}',`,` out: '${n}',`,` schema: '${i}',`,"});",""].join(`
322
+ `);try{if(t.auth==="better-auth"){const f=i.replace("schema.ts","auth-schema.ts");await e.writeFile({content:`// Run auth:generate before building.
323
+ // oxlint-disable eslint/no-inline-comments
324
+ export const authSchemaPlaceholder = true;
325
+ `,filePath:f,isBinary:!1},r)}const u=await e.writeFile({content:d,filePath:"drizzle.config.ts",isBinary:!1},r);u.written&&s.push(u.filePath)}catch(u){const f=u instanceof Error?u.message:String(u);a.push(`Failed to generate drizzle.config.ts: ${f}`)}}p(za,"Us"),l(za,"generateDrizzleConfig");function br(e,t){if(e instanceof Promise)throw new Error(t)}p(br,"Ot"),l(br,"ensureSynchronous");function va(e,t){const r={},s=[];for(const a in e){const o=e[a]["~standard"].validate(t[a]);if(br(o,`Validation must be synchronous, but ${a} returned a Promise.`),o.issues){s.push(...o.issues.map(i=>({...i,message:i.message,path:[a,...i.path??[]]})));continue}r[a]=o.value}return s.length?{issues:s}:{value:r}}p(va,"Ns"),l(va,"parseWithDictionary");function qa(e){const t=e.runtimeEnvStrict??e.runtimeEnv??process.env;if(e.emptyStringAsUndefined??!1)for(const[x,O]of Object.entries(t))O===""&&delete t[x];if(e.skipValidation){if(e.extends)for(const x of e.extends)x.skipValidation=!0;return t}const r=typeof e.client=="object"?e.client:{},s=typeof e.server=="object"?e.server:{},a=typeof e.shared=="object"?e.shared:{},o=e.isServer??(typeof window>"u"||"Deno"in window),i=o?{...s,...a,...r}:{...r,...a},n=e.createFinalSchema?.(i,o)?.["~standard"].validate(t)??va(i,t);br(n,"Validation must be synchronous");const c=e.onValidationError??(x=>{throw console.error("\u274C Invalid environment variables:",x),new Error("Invalid environment variables")}),d=e.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(n.issues)return c(n.issues);const u=l(x=>e.clientPrefix?!x.startsWith(e.clientPrefix)&&!(x in a):!0,"isServerAccess"),f=l(x=>o||!u(x),"isValidServerAccess"),g=l(x=>x==="__esModule"||x==="$$typeof","ignoreProp"),z=(e.extends??[]).reduce((x,O)=>Object.assign(x,O),{}),k=Object.assign(z,n.value);return new Proxy(k,{get(x,O){if(typeof O=="string"&&!g(O))return f(O)?Reflect.get(x,O):d(O)}})}p(qa,"Fs"),l(qa,"createEnv$1");const Tp="NEXT_PUBLIC_";function wa(e){const t=typeof e.client=="object"?e.client:{},r=typeof e.server=="object"?e.server:{},s=e.shared,a=e.runtimeEnv?e.runtimeEnv:{...process.env,...e.experimental__runtimeEnv};return qa({...e,shared:s,client:t,server:r,clientPrefix:Tp,runtimeEnv:a})}p(wa,"Bs"),l(wa,"createEnv");var Sa;function b(e,t,r){function s(n,c){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,c);const d=i.prototype,u=Object.keys(d);for(let f=0;f<u.length;f++){const g=u[f];g in n||(n[g]=d[g].bind(n))}}p(s,"s"),l(s,"init");const a=r?.Parent??Object;class o extends a{static{p(this,"i")}static{l(this,"Definition")}}Object.defineProperty(o,"name",{value:e});function i(n){var c;const d=r?.Parent?new o:this;s(d,n),(c=d._zod).deferred??(c.deferred=[]);for(const u of d._zod.deferred)u();return d}return p(i,"o"),l(i,"_"),Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:l(n=>r?.Parent&&n instanceof r.Parent?!0:n?._zod?.traits?.has(e),"value")}),Object.defineProperty(i,"name",{value:e}),i}p(b,"m"),l(b,"$constructor");class Fe extends Error{static{p(this,"Z")}static{l(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xa extends Error{static{p(this,"xt")}static{l(this,"$ZodEncodeError")}constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Sa=globalThis).__zod_globalConfig??(Sa.__zod_globalConfig={});const Pp=globalThis.__zod_globalConfig;function Ae(e){return Pp}p(Ae,"G"),l(Ae,"config");function zr(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)}p(zr,"Ct"),l(zr,"getEnumValues");function It(e,t){return typeof t=="bigint"?t.toString():t}p(It,"Re"),l(It,"jsonStringifyReplacer");function Ot(e){return e==null}p(Ot,"Ie"),l(Ot,"nullish");function Ct(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}p(Ct,"Oe"),l(Ct,"cleanRegex");function ka(e,t){const r=e/t,s=Math.round(r),a=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-s)<a?0:r-s}p(ka,"Js"),l(ka,"floatSafeRemainder");const ja=Symbol("evaluating");function U(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==ja)return s===void 0&&(s=ja,s=r()),s},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}p(U,"S"),l(U,"defineLazy");function Ta(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}p(Ta,"Hs"),l(Ta,"mergeDefs");function Pa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}p(Pa,"Qs"),l(Pa,"slugify");const Aa="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}p(vr,"Mt"),l(vr,"isObject");function $t(e){if(vr(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(vr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}p($t,"$e"),l($t,"isPlainObject");function qr(e){return $t(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}p(qr,"Ut"),l(qr,"shallowClone");const Ap=new Set(["string","number","symbol"]);function rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}p(rt,"de"),l(rt,"escapeRegex");function Ea(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}p(Ea,"Ws"),l(Ea,"clone");function j(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}p(j,"b"),l(j,"normalizeParams");const Ep={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 $e(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}p($e,"J"),l($e,"aborted");function _a(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}p(_a,"Ys"),l(_a,"explicitlyAborted");function Ra(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}p(Ra,"Xs"),l(Ra,"prefixIssues");function st(e){return typeof e=="string"?e:e?.message}p(st,"ue"),l(st,"unwrapMessage");function Ee(e,t,r){const s=e.message?e.message:st(e.inst?._zod.def?.error?.(e))??st(t?.error?.(e))??st(r.customError?.(e))??st(r.localeError?.(e))??"Invalid input",{inst:a,continue:o,input:i,...n}=e;return n.path??(n.path=[]),n.message=s,t?.reportInput&&(n.input=i),n}p(Ee,"B"),l(Ee,"finalizeIssue");function Dt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}p(Dt,"xe"),l(Dt,"getLengthableOrigin");function Be(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}p(Be,"W"),l(Be,"issue");const Ia=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,It,2),Object.defineProperty(e,"toString",{value:l(()=>e.message,"value"),enumerable:!1})},"initializer$1"),Oa=b("$ZodError",Ia),Ca=b("$ZodError",Ia,{Parent:Error});function $a(e,t=r=>r.message){const r={},s=[];for(const a of e.issues)a.path.length>0?(r[a.path[0]]=r[a.path[0]]||[],r[a.path[0]].push(t(a))):s.push(t(a));return{formErrors:s,fieldErrors:r}}p($a,"ea"),l($a,"flattenError");function Da(e,t=r=>r.message){const r={_errors:[]},s=l((a,o=[])=>{for(const i of a.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(n=>s({issues:n},[...o,...i.path]));else if(i.code==="invalid_key")s({issues:i.issues},[...o,...i.path]);else if(i.code==="invalid_element")s({issues:i.issues},[...o,...i.path]);else{const n=[...o,...i.path];if(n.length===0)r._errors.push(t(i));else{let c=r,d=0;for(;d<n.length;){const u=n[d];d===n.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(i))):c[u]=c[u]||{_errors:[]},c=c[u],d++}}}},"processError");return s(e),r}p(Da,"ta"),l(Da,"formatError");const wr=l(e=>(t,r,s,a)=>{const o=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Fe;if(i.issues.length){const n=new(a?.Err??e)(i.issues.map(c=>Ee(c,o,Ae())));throw Aa(n,a?.callee),n}return i.value},"_parse"),Sr=l(e=>async(t,r,s,a)=>{const o=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const n=new(a?.Err??e)(i.issues.map(c=>Ee(c,o,Ae())));throw Aa(n,a?.callee),n}return i.value},"_parseAsync"),Nt=l(e=>(t,r,s)=>{const a=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},a);if(o instanceof Promise)throw new Fe;return o.issues.length?{success:!1,error:new(e??Oa)(o.issues.map(i=>Ee(i,a,Ae())))}:{success:!0,data:o.value}},"_safeParse"),_p=Nt(Ca),Lt=l(e=>async(t,r,s)=>{const a=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(i=>Ee(i,a,Ae())))}:{success:!0,data:o.value}},"_safeParseAsync"),Rp=Lt(Ca),Ip=l(e=>(t,r,s)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return wr(e)(t,r,a)},"_encode"),Op=l(e=>(t,r,s)=>wr(e)(t,r,s),"_decode"),Cp=l(e=>async(t,r,s)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return Sr(e)(t,r,a)},"_encodeAsync"),$p=l(e=>async(t,r,s)=>Sr(e)(t,r,s),"_decodeAsync"),Dp=l(e=>(t,r,s)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return Nt(e)(t,r,a)},"_safeEncode"),Np=l(e=>(t,r,s)=>Nt(e)(t,r,s),"_safeDecode"),Lp=l(e=>async(t,r,s)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return Lt(e)(t,r,a)},"_safeEncodeAsync"),Mp=l(e=>async(t,r,s)=>Lt(e)(t,r,s),"_safeDecodeAsync"),Up=/^[cC][0-9a-z]{6,}$/,Gp=/^[0-9a-z]+$/,Fp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Bp=/^[0-9a-vA-V]{20}$/,Jp=/^[A-Za-z0-9]{27}$/,Hp=/^[a-zA-Z0-9_-]{21}$/,Qp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vp=/^([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})$/,Na=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"),Zp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function La(){return new RegExp(Wp,"u")}p(La,"wa"),l(La,"emoji");const Kp=/^(?:(?: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])$/,Yp=/^(([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}|:))$/,Xp=/^((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])$/,el=/^(([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])$/,tl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ma=/^[A-Za-z0-9_-]*$/,rl=/^https?$/,sl=/^\+[1-9]\d{6,14}$/,Ua="(?:(?:\\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])))",al=new RegExp(`^${Ua}$`);function xr(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+)?)?`}p(xr,"Ht"),l(xr,"timeSource");function Ga(e){return new RegExp(`^${xr(e)}$`)}p(Ga,"Ra"),l(Ga,"time$1");function Fa(e){const t=xr({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(`^${Ua}T(?:${s})$`)}p(Fa,"Ia"),l(Fa,"datetime$1");const il=l(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),ol=/^-?\d+$/,nl=/^-?\d+(?:\.\d+)?$/,pl=/^[^A-Z]*$/,ll=/^[^a-z]*$/,ue=b("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ba={number:"number",bigint:"bigint",object:"date"},Ja=b("$ZodCheckLessThan",(e,t)=>{ue.init(e,t);const r=Ba[typeof t.value];e._zod.onattach.push(s=>{const a=s._zod.bag,o=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?a.maximum=t.value:a.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})}}),Ha=b("$ZodCheckGreaterThan",(e,t)=>{ue.init(e,t);const r=Ba[typeof t.value];e._zod.onattach.push(s=>{const a=s._zod.bag,o=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?a.minimum=t.value:a.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})}}),cl=b("$ZodCheckMultipleOf",(e,t)=>{ue.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):ka(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})}}),dl=b("$ZodCheckNumberFormat",(e,t)=>{ue.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[a,o]=Ep[t.format];e._zod.onattach.push(i=>{const n=i._zod.bag;n.format=t.format,n.minimum=a,n.maximum=o,r&&(n.pattern=ol)}),e._zod.check=i=>{const n=i.value;if(r){if(!Number.isInteger(n)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:n,inst:e});return}if(!Number.isSafeInteger(n)){n>0?i.issues.push({input:n,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}):i.issues.push({input:n,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}}n<a&&i.issues.push({origin:"number",input:n,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),n>o&&i.issues.push({origin:"number",input:n,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),ul=b("$ZodCheckMaxLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=s=>{const a=s.value;return!Ot(a)&&a.length!==void 0}),e._zod.onattach.push(s=>{const a=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const a=s.value;if(a.length<=t.maximum)return;const o=Dt(a);s.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),ml=b("$ZodCheckMinLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=s=>{const a=s.value;return!Ot(a)&&a.length!==void 0}),e._zod.onattach.push(s=>{const a=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const a=s.value;if(a.length>=t.minimum)return;const o=Dt(a);s.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),hl=b("$ZodCheckLengthEquals",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=s=>{const a=s.value;return!Ot(a)&&a.length!==void 0}),e._zod.onattach.push(s=>{const a=s._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=s=>{const a=s.value,o=a.length;if(o===t.length)return;const i=Dt(a),n=o>t.length;s.issues.push({origin:i,...n?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Mt=b("$ZodCheckStringFormat",(e,t)=>{var r,s;ue.init(e,t),e._zod.onattach.push(a=>{const o=a._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=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),fl=b("$ZodCheckRegex",(e,t)=>{Mt.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})}}),gl=b("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=pl),Mt.init(e,t)}),yl=b("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ll),Mt.init(e,t)}),bl=b("$ZodCheckIncludes",(e,t)=>{ue.init(e,t);const r=rt(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(s)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),zl=b("$ZodCheckStartsWith",(e,t)=>{ue.init(e,t);const r=new RegExp(`^${rt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),vl=b("$ZodCheckEndsWith",(e,t)=>{ue.init(e,t);const r=new RegExp(`.*${rt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const a=s._zod.bag;a.patterns??(a.patterns=new Set),a.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})}}),ql=b("$ZodCheckOverwrite",(e,t)=>{ue.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),wl={major:4,minor:4,patch:3},ae=b("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=wl;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const a of s)for(const o of a._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 a=l((i,n,c)=>{let d=$e(i),u;for(const f of n){if(f._zod.def.when){if(_a(i)||!f._zod.def.when(i))continue}else if(d)continue;const g=i.issues.length,z=f._zod.check(i);if(z instanceof Promise&&c?.async===!1)throw new Fe;if(u||z instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await z,i.issues.length!==g&&(d||(d=$e(i,g)))});else{if(i.issues.length===g)continue;d||(d=$e(i,g))}}return u?u.then(()=>i):i},"runChecks"),o=l((i,n,c)=>{if($e(i))return i.aborted=!0,i;const d=a(n,s,c);if(d instanceof Promise){if(c.async===!1)throw new Fe;return d.then(u=>e._zod.parse(u,c))}return e._zod.parse(d,c)},"handleCanaryResult");e._zod.run=(i,n)=>{if(n.skipChecks)return e._zod.parse(i,n);if(n.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...n,skipChecks:!0});return d instanceof Promise?d.then(u=>o(u,i,n)):o(d,i,n)}const c=e._zod.parse(i,n);if(c instanceof Promise){if(n.async===!1)throw new Fe;return c.then(d=>a(d,s,n))}return a(c,s,n)}}U(e,"~standard",()=>({validate:l(a=>{try{const o=_p(e,a);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Rp(e,a).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},"validate"),vendor:"zod",version:1}))}),kr=b("$ZodString",(e,t)=>{ae.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??il(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}}),B=b("$ZodStringFormat",(e,t)=>{Mt.init(e,t),kr.init(e,t)}),Sl=b("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Vp),B.init(e,t)}),xl=b("$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=Na(r))}else t.pattern??(t.pattern=Na());B.init(e,t)}),kl=b("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Zp),B.init(e,t)}),jl=b("$ZodURL",(e,t)=>{B.init(e,t),e._zod.check=r=>{try{const s=r.value.trim();if(!t.normalize&&t.protocol?.source===rl.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 a=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.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(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.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=a.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Tl=b("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=La()),B.init(e,t)}),Pl=b("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Hp),B.init(e,t)}),Al=b("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Up),B.init(e,t)}),El=b("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gp),B.init(e,t)}),_l=b("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Fp),B.init(e,t)}),Rl=b("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Bp),B.init(e,t)}),Il=b("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jp),B.init(e,t)}),Ol=b("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Fa(t)),B.init(e,t)}),Cl=b("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=al),B.init(e,t)}),$l=b("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ga(t)),B.init(e,t)}),Dl=b("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qp),B.init(e,t)}),Nl=b("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Kp),B.init(e,t),e._zod.bag.format="ipv4"}),Ll=b("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Yp),B.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})}}}),Ml=b("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Xp),B.init(e,t)}),Ul=b("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=el),B.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[a,o]=s;if(!o)throw new Error;const i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function jr(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}p(jr,"Kt"),l(jr,"isValidBase64");const Gl=b("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=tl),B.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{jr(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Qa(e){if(!Ma.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return jr(r)}p(Qa,"bo"),l(Qa,"isValidBase64URL");const Fl=b("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ma),B.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Qa(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Bl=b("$ZodE164",(e,t)=>{t.pattern??(t.pattern=sl),B.init(e,t)});function Va(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const a=JSON.parse(atob(s));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}p(Va,"vo"),l(Va,"isValidJWT");const Jl=b("$ZodJWT",(e,t)=>{B.init(e,t),e._zod.check=r=>{Va(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Za=b("$ZodNumber",(e,t)=>{ae.init(e,t),e._zod.pattern=e._zod.bag.pattern??nl,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const a=r.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return r;const o=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...o?{received:o}:{}}),r}}),Hl=b("$ZodNumberFormat",(e,t)=>{dl.init(e,t),Za.init(e,t)});function Tr(e,t,r){e.issues.length&&t.issues.push(...Ra(r,e.issues)),t.value[r]=e.value}p(Tr,"Xt"),l(Tr,"handleArrayResult");const Ql=b("$ZodArray",(e,t)=>{ae.init(e,t),e._zod.parse=(r,s)=>{const a=r.value;if(!Array.isArray(a))return r.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),r;r.value=Array(a.length);const o=[];for(let i=0;i<a.length;i++){const n=a[i],c=t.element._zod.run({value:n,issues:[]},s);c instanceof Promise?o.push(c.then(d=>Tr(d,r,i))):Tr(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});function Pr(e,t,r,s){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const a=e.filter(o=>!$e(o));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(i=>Ee(i,s,Ae())))}),t)}p(Pr,"er"),l(Pr,"handleUnionResults");const Vl=b("$ZodUnion",(e,t)=>{ae.init(e,t),U(e._zod,"optin",()=>t.options.some(s=>s._zod.optin==="optional")?"optional":void 0),U(e._zod,"optout",()=>t.options.some(s=>s._zod.optout==="optional")?"optional":void 0),U(e._zod,"values",()=>{if(t.options.every(s=>s._zod.values))return new Set(t.options.flatMap(s=>Array.from(s._zod.values)))}),U(e._zod,"pattern",()=>{if(t.options.every(s=>s._zod.pattern)){const s=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${s.map(a=>Ct(a.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(s,a)=>{if(r)return r(s,a);let o=!1;const i=[];for(const n of t.options){const c=n._zod.run({value:s.value,issues:[]},a);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}return o?Promise.all(i).then(n=>Pr(n,s,e,a)):Pr(i,s,e,a)}}),Zl=b("$ZodIntersection",(e,t)=>{ae.init(e,t),e._zod.parse=(r,s)=>{const a=r.value,o=t.left._zod.run({value:a,issues:[]},s),i=t.right._zod.run({value:a,issues:[]},s);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([n,c])=>Ar(r,n,c)):Ar(r,o,i)}});function Ut(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($t(e)&&$t(t)){const r=Object.keys(t),s=Object.keys(e).filter(o=>r.indexOf(o)!==-1),a={...e,...t};for(const o of s){const i=Ut(e[o],t[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};a[o]=i.data}return{valid:!0,data:a}}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 a=e[s],o=t[s],i=Ut(a,o);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}p(Ut,"Me"),l(Ut,"mergeValues");function Ar(e,t,r){const s=new Map;let a;for(const n of t.issues)if(n.code==="unrecognized_keys"){a??(a=n);for(const c of n.keys)s.has(c)||s.set(c,{}),s.get(c).l=!0}else e.issues.push(n);for(const n of r.issues)if(n.code==="unrecognized_keys")for(const c of n.keys)s.has(c)||s.set(c,{}),s.get(c).r=!0;else e.issues.push(n);const o=[...s].filter(([,n])=>n.l&&n.r).map(([n])=>n);if(o.length&&a&&e.issues.push({...a,keys:o}),$e(e))return e;const i=Ut(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}p(Ar,"tr"),l(Ar,"handleIntersectionResults");const Wl=b("$ZodEnum",(e,t)=>{ae.init(e,t);const r=zr(t.entries),s=new Set(r);e._zod.values=s,e._zod.pattern=new RegExp(`^(${r.filter(a=>Ap.has(typeof a)).map(a=>typeof a=="string"?rt(a):a.toString()).join("|")})$`),e._zod.parse=(a,o)=>{const i=a.value;return s.has(i)||a.issues.push({code:"invalid_value",values:r,input:i,inst:e}),a}}),Kl=b("$ZodTransform",(e,t)=>{ae.init(e,t),e._zod.optin="optional",e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new xa(e.constructor.name);const a=t.transform(r.value,r);if(s.async)return(a instanceof Promise?a:Promise.resolve(a)).then(o=>(r.value=o,r.fallback=!0,r));if(a instanceof Promise)throw new Fe;return r.value=a,r.fallback=!0,r}});function Er(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}p(Er,"rr"),l(Er,"handleOptionalResult");const Wa=b("$ZodOptional",(e,t)=>{ae.init(e,t),e._zod.optin="optional",e._zod.optout="optional",U(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),U(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ct(r.source)})?$`):void 0}),e._zod.parse=(r,s)=>{if(t.innerType._zod.optin==="optional"){const a=r.value,o=t.innerType._zod.run(r,s);return o instanceof Promise?o.then(i=>Er(i,a)):Er(o,a)}return r.value===void 0?r:t.innerType._zod.run(r,s)}}),Yl=b("$ZodExactOptional",(e,t)=>{Wa.init(e,t),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,s)=>t.innerType._zod.run(r,s)}),Xl=b("$ZodNullable",(e,t)=>{ae.init(e,t),U(e._zod,"optin",()=>t.innerType._zod.optin),U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ct(r.source)}|null)$`):void 0}),U(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)}),ec=b("$ZodDefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",U(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 a=t.innerType._zod.run(r,s);return a instanceof Promise?a.then(o=>_r(o,t)):_r(a,t)}});function _r(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}p(_r,"ar"),l(_r,"handleDefaultResult");const tc=b("$ZodPrefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",U(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))}),rc=b("$ZodNonOptional",(e,t)=>{ae.init(e,t),U(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 a=t.innerType._zod.run(r,s);return a instanceof Promise?a.then(o=>Rr(o,e)):Rr(a,e)}});function Rr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}p(Rr,"or"),l(Rr,"handleNonOptionalResult");const sc=b("$ZodCatch",(e,t)=>{ae.init(e,t),e._zod.optin="optional",U(e._zod,"optout",()=>t.innerType._zod.optout),U(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const a=t.innerType._zod.run(r,s);return a instanceof Promise?a.then(o=>(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Ee(i,s,Ae()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(o=>Ee(o,s,Ae()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),ac=b("$ZodPipe",(e,t)=>{ae.init(e,t),U(e._zod,"values",()=>t.in._zod.values),U(e._zod,"optin",()=>t.in._zod.optin),U(e._zod,"optout",()=>t.out._zod.optout),U(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(i=>at(i,t.in,s)):at(o,t.in,s)}const a=t.in._zod.run(r,s);return a instanceof Promise?a.then(o=>at(o,t.out,s)):at(a,t.out,s)}});function at(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}p(at,"ge"),l(at,"handlePipeResult");const ic=b("$ZodReadonly",(e,t)=>{ae.init(e,t),U(e._zod,"propValues",()=>t.innerType._zod.propValues),U(e._zod,"values",()=>t.innerType._zod.values),U(e._zod,"optin",()=>t.innerType?._zod?.optin),U(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,s)=>{if(s.direction==="backward")return t.innerType._zod.run(r,s);const a=t.innerType._zod.run(r,s);return a instanceof Promise?a.then(Ir):Ir(a)}});function Ir(e){return e.value=Object.freeze(e.value),e}p(Ir,"ir"),l(Ir,"handleReadonlyResult");const oc=b("$ZodCustom",(e,t)=>{ue.init(e,t),ae.init(e,t),e._zod.parse=(r,s)=>r,e._zod.check=r=>{const s=r.value,a=t.fn(s);if(a instanceof Promise)return a.then(o=>Or(o,r,s,e));Or(a,r,s,e)}});function Or(e,t,r,s){if(!e){const a={code:"custom",input:r,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(a.params=s._zod.def.params),t.issues.push(Be(a))}}p(Or,"nr"),l(Or,"handleRefineResult");var Ka;class nc{static{p(this,"Lo")}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 a={...s,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Ya(){return new nc}p(Ya,"Mo"),l(Ya,"registry"),(Ka=globalThis).__zod_globalRegistry??(Ka.__zod_globalRegistry=Ya());const it=globalThis.__zod_globalRegistry;function Xa(e,t){return new e({type:"string",...j(t)})}p(Xa,"Uo"),l(Xa,"_string");function ei(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...j(t)})}p(ei,"No"),l(ei,"_email");function Cr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...j(t)})}p(Cr,"cr"),l(Cr,"_guid");function ti(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...j(t)})}p(ti,"Fo"),l(ti,"_uuid");function ri(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(t)})}p(ri,"Go"),l(ri,"_uuidv4");function si(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(t)})}p(si,"Bo"),l(si,"_uuidv6");function ai(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(t)})}p(ai,"Zo"),l(ai,"_uuidv7");function ii(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...j(t)})}p(ii,"Jo"),l(ii,"_url");function oi(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...j(t)})}p(oi,"Ho"),l(oi,"_emoji");function ni(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(t)})}p(ni,"Qo"),l(ni,"_nanoid");function pi(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...j(t)})}p(pi,"Vo"),l(pi,"_cuid");function li(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(t)})}p(li,"Wo"),l(li,"_cuid2");function ci(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...j(t)})}p(ci,"Ko"),l(ci,"_ulid");function di(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...j(t)})}p(di,"Yo"),l(di,"_xid");function ui(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(t)})}p(ui,"Xo"),l(ui,"_ksuid");function mi(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(t)})}p(mi,"ei"),l(mi,"_ipv4");function hi(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(t)})}p(hi,"ti"),l(hi,"_ipv6");function fi(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(t)})}p(fi,"ri"),l(fi,"_cidrv4");function gi(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(t)})}p(gi,"si"),l(gi,"_cidrv6");function yi(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...j(t)})}p(yi,"ai"),l(yi,"_base64");function bi(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...j(t)})}p(bi,"oi"),l(bi,"_base64url");function zi(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...j(t)})}p(zi,"ii"),l(zi,"_e164");function vi(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...j(t)})}p(vi,"ni"),l(vi,"_jwt");function qi(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(t)})}p(qi,"pi"),l(qi,"_isoDateTime");function wi(e,t){return new e({type:"string",format:"date",check:"string_format",...j(t)})}p(wi,"ci"),l(wi,"_isoDate");function Si(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...j(t)})}p(Si,"li"),l(Si,"_isoTime");function xi(e,t){return new e({type:"string",format:"duration",check:"string_format",...j(t)})}p(xi,"di"),l(xi,"_isoDuration");function ki(e,t){return new e({type:"number",coerce:!0,checks:[],...j(t)})}p(ki,"ui"),l(ki,"_coercedNumber");function ji(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...j(t)})}p(ji,"mi"),l(ji,"_int");function $r(e,t){return new Ja({check:"less_than",...j(t),value:e,inclusive:!1})}p($r,"lr"),l($r,"_lt");function Gt(e,t){return new Ja({check:"less_than",...j(t),value:e,inclusive:!0})}p(Gt,"Ue"),l(Gt,"_lte");function Dr(e,t){return new Ha({check:"greater_than",...j(t),value:e,inclusive:!1})}p(Dr,"dr"),l(Dr,"_gt");function Ft(e,t){return new Ha({check:"greater_than",...j(t),value:e,inclusive:!0})}p(Ft,"Ne"),l(Ft,"_gte");function Nr(e,t){return new cl({check:"multiple_of",...j(t),value:e})}p(Nr,"ur"),l(Nr,"_multipleOf");function Lr(e,t){return new ul({check:"max_length",...j(t),maximum:e})}p(Lr,"mr"),l(Lr,"_maxLength");function ot(e,t){return new ml({check:"min_length",...j(t),minimum:e})}p(ot,"ye"),l(ot,"_minLength");function Mr(e,t){return new hl({check:"length_equals",...j(t),length:e})}p(Mr,"hr"),l(Mr,"_length");function Ti(e,t){return new fl({check:"string_format",format:"regex",...j(t),pattern:e})}p(Ti,"hi"),l(Ti,"_regex");function Pi(e){return new gl({check:"string_format",format:"lowercase",...j(e)})}p(Pi,"fi"),l(Pi,"_lowercase");function Ai(e){return new yl({check:"string_format",format:"uppercase",...j(e)})}p(Ai,"gi"),l(Ai,"_uppercase");function Ei(e,t){return new bl({check:"string_format",format:"includes",...j(t),includes:e})}p(Ei,"yi"),l(Ei,"_includes");function _i(e,t){return new zl({check:"string_format",format:"starts_with",...j(t),prefix:e})}p(_i,"bi"),l(_i,"_startsWith");function Ri(e,t){return new vl({check:"string_format",format:"ends_with",...j(t),suffix:e})}p(Ri,"zi"),l(Ri,"_endsWith");function De(e){return new ql({check:"overwrite",tx:e})}p(De,"H"),l(De,"_overwrite");function Ii(e){return De(t=>t.normalize(e))}p(Ii,"qi"),l(Ii,"_normalize");function Oi(){return De(e=>e.trim())}p(Oi,"vi"),l(Oi,"_trim");function Ci(){return De(e=>e.toLowerCase())}p(Ci,"wi"),l(Ci,"_toLowerCase");function $i(){return De(e=>e.toUpperCase())}p($i,"ki"),l($i,"_toUpperCase");function Di(){return De(e=>Pa(e))}p(Di,"Si"),l(Di,"_slugify");function Ni(e,t,r){return new e({type:"array",element:t,...j(r)})}p(Ni,"Ti"),l(Ni,"_array");function Li(e,t,r){return new e({type:"custom",check:"custom",fn:t,...j(r)})}p(Li,"ji"),l(Li,"_refine");function Mi(e,t){const r=Ui(s=>(s.addIssue=a=>{if(typeof a=="string")s.issues.push(Be(a,s.value,r._zod.def));else{const o=a;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(Be(o))}},e(s.value,s)),t);return r}p(Mi,"Pi"),l(Mi,"_superRefine");function Ui(e,t){const r=new ue({check:"custom",...j(t)});return r._zod.check=e,r}p(Ui,"Ei"),l(Ui,"_check");function Ur(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??it,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}}p(Ur,"fr"),l(Ur,"initializeContext");function le(e,t,r={path:[],schemaPath:[]}){var s;const a=e._zod.def,o=t.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);const n=e._zod.toJSONSchema?.();if(n)i.schema=n;else{const d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{const f=i.schema,g=t.processors[a.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);g(e,t,f,d)}const u=e._zod.parent;u&&(i.ref||(i.ref=u),le(u,t,d),t.seen.get(u).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),t.io==="input"&&ce(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((s=i.schema).default??(s.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}p(le,"R"),l(le,"process$1");function Gr(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 i of e.seen.entries()){const n=e.metadataRegistry.get(i[0])?.id;if(n){const c=s.get(n);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(n,i[0])}}const a=l(i=>{const n=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(i[0])?.id,f=e.external.uri??(z=>z);if(u)return{ref:f(u)};const g=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=g,{defId:g,ref:`${f("__shared")}#/${n}/${g}`}}if(i[1]===r)return{ref:"#"};const c=`#/${n}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:c+d}},"makeURI"),o=l(i=>{if(i[1].schema.$ref)return;const n=i[1],{ref:c,defId:d}=a(i);n.def={...n.schema},d&&(n.defId=d);const u=n.schema;for(const f in u)delete u[f];u.$ref=c},"extractToDef");if(e.cycles==="throw")for(const i of e.seen.entries()){const n=i[1];if(n.cycle)throw new Error(`Cycle detected: #/${n.cycle?.join("/")}/<root>
326
+
327
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t===i[0]){o(i);continue}if(e.external){const c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(n.cycle){o(i);continue}if(n.count>1&&e.reused==="ref"){o(i);continue}}}p(Gr,"gr"),l(Gr,"extractDefs");function Fr(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=l(n=>{const c=e.seen.get(n);if(c.ref===null)return;const d=c.def??c.schema,u={...d},f=c.ref;if(c.ref=null,f){s(f);const z=e.seen.get(f),k=z.schema;if(k.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(k)):Object.assign(d,k),Object.assign(d,u),n._zod.parent===f)for(const x in d)x==="$ref"||x==="allOf"||x in u||delete d[x];if(k.$ref&&z.def)for(const x in d)x==="$ref"||x==="allOf"||x in z.def&&JSON.stringify(d[x])===JSON.stringify(z.def[x])&&delete d[x]}const g=n._zod.parent;if(g&&g!==f){s(g);const z=e.seen.get(g);if(z?.schema.$ref&&(d.$ref=z.schema.$ref,z.def))for(const k in d)k==="$ref"||k==="allOf"||k in z.def&&JSON.stringify(d[k])===JSON.stringify(z.def[k])&&delete d[k]}e.override({zodSchema:n,jsonSchema:d,path:c.path??[]})},"flattenRef");for(const n of[...e.seen.entries()].reverse())s(n[0]);const a={};if(e.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(n)}Object.assign(a,r.def??r.schema);const o=e.metadataRegistry.get(t)?.id;o!==void 0&&a.id===o&&delete a.id;const i=e.external?.defs??{};for(const n of e.seen.entries()){const c=n[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?a.$defs=i:a.definitions=i);try{const n=JSON.parse(JSON.stringify(a));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Bt(t,"input",e.processors),output:Bt(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch{throw new Error("Error converting schema to JSON.")}}p(Fr,"yr"),l(Fr,"finalize");function ce(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 ce(s.element,r);if(s.type==="set")return ce(s.valueType,r);if(s.type==="lazy")return ce(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 ce(s.innerType,r);if(s.type==="intersection")return ce(s.left,r)||ce(s.right,r);if(s.type==="record"||s.type==="map")return ce(s.keyType,r)||ce(s.valueType,r);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ce(s.in,r)||ce(s.out,r);if(s.type==="object"){for(const a in s.shape)if(ce(s.shape[a],r))return!0;return!1}if(s.type==="union"){for(const a of s.options)if(ce(a,r))return!0;return!1}if(s.type==="tuple"){for(const a of s.items)if(ce(a,r))return!0;return!!(s.rest&&ce(s.rest,r))}return!1}p(ce,"I"),l(ce,"isTransforming");const pc=l((e,t={})=>r=>{const s=Ur({...r,processors:t});return le(e,s),Gr(s,e),Fr(s,e)},"createToJSONSchemaMethod"),Bt=l((e,t,r={})=>s=>{const{libraryOptions:a,target:o}=s??{},i=Ur({...a??{},target:o,io:t,processors:r});return le(e,i),Gr(i,e),Fr(i,e)},"createStandardJSONSchemaMethod"),lc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cc=l((e,t,r,s)=>{const a=r;a.type="string";const{minimum:o,maximum:i,format:n,patterns:c,contentEncoding:d}=e._zod.bag;if(typeof o=="number"&&(a.minLength=o),typeof i=="number"&&(a.maxLength=i),n&&(a.format=lc[n]??n,a.format===""&&delete a.format,n==="time"&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const u=[...c];u.length===1?a.pattern=u[0].source:u.length>1&&(a.allOf=[...u.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},"stringProcessor"),dc=l((e,t,r,s)=>{const a=r,{minimum:o,maximum:i,format:n,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=e._zod.bag;typeof n=="string"&&n.includes("int")?a.type="integer":a.type="number";const f=typeof u=="number"&&u>=(o??Number.NEGATIVE_INFINITY),g=typeof d=="number"&&d<=(i??Number.POSITIVE_INFINITY),z=t.target==="draft-04"||t.target==="openapi-3.0";f?z?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof o=="number"&&(a.minimum=o),g?z?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof i=="number"&&(a.maximum=i),typeof c=="number"&&(a.multipleOf=c)},"numberProcessor"),uc=l((e,t,r,s)=>{const a=e._zod.def,o=zr(a.entries);o.every(i=>typeof i=="number")&&(r.type="number"),o.every(i=>typeof i=="string")&&(r.type="string"),r.enum=o},"enumProcessor"),mc=l((e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},"customProcessor"),hc=l((e,t,r,s)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},"transformProcessor"),fc=l((e,t,r,s)=>{const a=r,o=e._zod.def,{minimum:i,maximum:n}=e._zod.bag;typeof i=="number"&&(a.minItems=i),typeof n=="number"&&(a.maxItems=n),a.type="array",a.items=le(o.element,t,{...s,path:[...s.path,"items"]})},"arrayProcessor"),gc=l((e,t,r,s)=>{const a=e._zod.def,o=a.inclusive===!1,i=a.options.map((n,c)=>le(n,t,{...s,path:[...s.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=i:r.anyOf=i},"unionProcessor"),yc=l((e,t,r,s)=>{const a=e._zod.def,o=le(a.left,t,{...s,path:[...s.path,"allOf",0]}),i=le(a.right,t,{...s,path:[...s.path,"allOf",1]}),n=l(d=>"allOf"in d&&Object.keys(d).length===1,"isSimpleIntersection"),c=[...n(o)?o.allOf:[o],...n(i)?i.allOf:[i]];r.allOf=c},"intersectionProcessor"),bc=l((e,t,r,s)=>{const a=e._zod.def,o=le(a.innerType,t,s),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=a.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]},"nullableProcessor"),zc=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType},"nonoptionalProcessor"),vc=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType,r.default=JSON.parse(JSON.stringify(a.defaultValue))},"defaultProcessor"),qc=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},"prefaultProcessor"),wc=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType;let i;try{i=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},"catchProcessor"),Sc=l((e,t,r,s)=>{const a=e._zod.def,o=a.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?a.out:a.in:a.out;le(i,t,s);const n=t.seen.get(e);n.ref=i},"pipeProcessor"),xc=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType,r.readOnly=!0},"readonlyProcessor"),Gi=l((e,t,r,s)=>{const a=e._zod.def;le(a.innerType,t,s);const o=t.seen.get(e);o.ref=a.innerType},"optionalProcessor"),kc=b("ZodISODateTime",(e,t)=>{Ol.init(e,t),J.init(e,t)});function Fi(e){return qi(kc,e)}p(Fi,"Hi"),l(Fi,"datetime");const jc=b("ZodISODate",(e,t)=>{Cl.init(e,t),J.init(e,t)});function Bi(e){return wi(jc,e)}p(Bi,"Vi"),l(Bi,"date");const Tc=b("ZodISOTime",(e,t)=>{$l.init(e,t),J.init(e,t)});function Ji(e){return Si(Tc,e)}p(Ji,"Ki"),l(Ji,"time");const Pc=b("ZodISODuration",(e,t)=>{Dl.init(e,t),J.init(e,t)});function Hi(e){return xi(Pc,e)}p(Hi,"Xi"),l(Hi,"duration");const Ac=l((e,t)=>{Oa.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:l(r=>Da(e,r),"value")},flatten:{value:l(r=>$a(e,r),"value")},addIssue:{value:l(r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,It,2)},"value")},addIssues:{value:l(r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,It,2)},"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),fe=b("ZodError",Ac,{Parent:Error}),Ec=wr(fe),_c=Sr(fe),Rc=Nt(fe),Ic=Lt(fe),Oc=Ip(fe),Cc=Op(fe),$c=Cp(fe),Dc=$p(fe),Nc=Dp(fe),Lc=Np(fe),Mc=Lp(fe),Uc=Mp(fe),Qi=new WeakMap;function nt(e,t,r){const s=Object.getPrototypeOf(e);let a=Qi.get(s);if(a||(a=new Set,Qi.set(s,a)),!a.has(t)){a.add(t);for(const o in r){const i=r[o];Object.defineProperty(s,o,{configurable:!0,enumerable:!1,get(){const n=i.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(n){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:n})}})}}}p(nt,"ze"),l(nt,"_installLazyMethods");const ie=b("ZodType",(e,t)=>(ae.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Bt(e,"input"),output:Bt(e,"output")}}),e.toJSONSchema=pc(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,s)=>Ec(e,r,s,{callee:e.parse}),e.safeParse=(r,s)=>Rc(e,r,s),e.parseAsync=async(r,s)=>_c(e,r,s,{callee:e.parseAsync}),e.safeParseAsync=async(r,s)=>Ic(e,r,s),e.spa=e.safeParseAsync,e.encode=(r,s)=>Oc(e,r,s),e.decode=(r,s)=>Cc(e,r,s),e.encodeAsync=async(r,s)=>$c(e,r,s),e.decodeAsync=async(r,s)=>Dc(e,r,s),e.safeEncode=(r,s)=>Nc(e,r,s),e.safeDecode=(r,s)=>Lc(e,r,s),e.safeEncodeAsync=async(r,s)=>Mc(e,r,s),e.safeDecodeAsync=async(r,s)=>Uc(e,r,s),nt(e,"ZodType",{check(...r){const s=this.def;return this.clone(Ta(s,{checks:[...s.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,s){return Ea(this,r,s)},brand(){return this},register(r,s){return r.add(this,s),this},refine(r,s){return this.check(no(r,s))},superRefine(r,s){return this.check(po(r,s))},overwrite(r){return this.check(De(r))},optional(){return Qr(this)},exactOptional(){return to(this)},nullable(){return Vr(this)},nullish(){return Qr(Vr(this))},nonoptional(r){return ao(this,r)},array(){return Ki(this)},or(r){return Yi([this,r])},and(r){return Xi(this,r)},transform(r){return Zr(this,eo(r))},default(r){return ro(this,r)},prefault(r){return so(this,r)},catch(r){return io(this,r)},pipe(r){return Zr(this,r)},readonly(){return oo(this)},describe(r){const s=this.clone();return it.add(s,{description:r}),s},meta(...r){if(r.length===0)return it.get(this);const s=this.clone();return it.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 it.get(e)?.description},configurable:!0}),e)),Vi=b("_ZodString",(e,t)=>{kr.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(s,a,o)=>cc(e,s,a);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,nt(e,"_ZodString",{regex(...s){return this.check(Ti(...s))},includes(...s){return this.check(Ei(...s))},startsWith(...s){return this.check(_i(...s))},endsWith(...s){return this.check(Ri(...s))},min(...s){return this.check(ot(...s))},max(...s){return this.check(Lr(...s))},length(...s){return this.check(Mr(...s))},nonempty(...s){return this.check(ot(1,...s))},lowercase(s){return this.check(Pi(s))},uppercase(s){return this.check(Ai(s))},trim(){return this.check(Oi())},normalize(...s){return this.check(Ii(...s))},toLowerCase(){return this.check(Ci())},toUpperCase(){return this.check($i())},slugify(){return this.check(Di())}})}),Gc=b("ZodString",(e,t)=>{kr.init(e,t),Vi.init(e,t),e.email=r=>e.check(ei(Fc,r)),e.url=r=>e.check(ii(Bc,r)),e.jwt=r=>e.check(vi(id,r)),e.emoji=r=>e.check(oi(Jc,r)),e.guid=r=>e.check(Cr(Zi,r)),e.uuid=r=>e.check(ti(Ht,r)),e.uuidv4=r=>e.check(ri(Ht,r)),e.uuidv6=r=>e.check(si(Ht,r)),e.uuidv7=r=>e.check(ai(Ht,r)),e.nanoid=r=>e.check(ni(Hc,r)),e.guid=r=>e.check(Cr(Zi,r)),e.cuid=r=>e.check(pi(Qc,r)),e.cuid2=r=>e.check(li(Vc,r)),e.ulid=r=>e.check(ci(Zc,r)),e.base64=r=>e.check(yi(rd,r)),e.base64url=r=>e.check(bi(sd,r)),e.xid=r=>e.check(di(Wc,r)),e.ksuid=r=>e.check(ui(Kc,r)),e.ipv4=r=>e.check(mi(Yc,r)),e.ipv6=r=>e.check(hi(Xc,r)),e.cidrv4=r=>e.check(fi(ed,r)),e.cidrv6=r=>e.check(gi(td,r)),e.e164=r=>e.check(zi(ad,r)),e.datetime=r=>e.check(Fi(r)),e.date=r=>e.check(Bi(r)),e.time=r=>e.check(Ji(r)),e.duration=r=>e.check(Hi(r))});function Jt(e){return Xa(Gc,e)}p(Jt,"Fe"),l(Jt,"string");const J=b("ZodStringFormat",(e,t)=>{B.init(e,t),Vi.init(e,t)}),Fc=b("ZodEmail",(e,t)=>{kl.init(e,t),J.init(e,t)}),Zi=b("ZodGUID",(e,t)=>{Sl.init(e,t),J.init(e,t)}),Ht=b("ZodUUID",(e,t)=>{xl.init(e,t),J.init(e,t)}),Bc=b("ZodURL",(e,t)=>{jl.init(e,t),J.init(e,t)}),Jc=b("ZodEmoji",(e,t)=>{Tl.init(e,t),J.init(e,t)}),Hc=b("ZodNanoID",(e,t)=>{Pl.init(e,t),J.init(e,t)}),Qc=b("ZodCUID",(e,t)=>{Al.init(e,t),J.init(e,t)}),Vc=b("ZodCUID2",(e,t)=>{El.init(e,t),J.init(e,t)}),Zc=b("ZodULID",(e,t)=>{_l.init(e,t),J.init(e,t)}),Wc=b("ZodXID",(e,t)=>{Rl.init(e,t),J.init(e,t)}),Kc=b("ZodKSUID",(e,t)=>{Il.init(e,t),J.init(e,t)}),Yc=b("ZodIPv4",(e,t)=>{Nl.init(e,t),J.init(e,t)}),Xc=b("ZodIPv6",(e,t)=>{Ll.init(e,t),J.init(e,t)}),ed=b("ZodCIDRv4",(e,t)=>{Ml.init(e,t),J.init(e,t)}),td=b("ZodCIDRv6",(e,t)=>{Ul.init(e,t),J.init(e,t)}),rd=b("ZodBase64",(e,t)=>{Gl.init(e,t),J.init(e,t)}),sd=b("ZodBase64URL",(e,t)=>{Fl.init(e,t),J.init(e,t)}),ad=b("ZodE164",(e,t)=>{Bl.init(e,t),J.init(e,t)}),id=b("ZodJWT",(e,t)=>{Jl.init(e,t),J.init(e,t)}),Wi=b("ZodNumber",(e,t)=>{Za.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(s,a,o)=>dc(e,s,a),nt(e,"ZodNumber",{gt(s,a){return this.check(Dr(s,a))},gte(s,a){return this.check(Ft(s,a))},min(s,a){return this.check(Ft(s,a))},lt(s,a){return this.check($r(s,a))},lte(s,a){return this.check(Gt(s,a))},max(s,a){return this.check(Gt(s,a))},int(s){return this.check(Br(s))},safe(s){return this.check(Br(s))},positive(s){return this.check(Dr(0,s))},nonnegative(s){return this.check(Ft(0,s))},negative(s){return this.check($r(0,s))},nonpositive(s){return this.check(Gt(0,s))},multipleOf(s,a){return this.check(Nr(s,a))},step(s,a){return this.check(Nr(s,a))},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}),od=b("ZodNumberFormat",(e,t)=>{Hl.init(e,t),Wi.init(e,t)});function Br(e){return ji(od,e)}p(Br,"kr"),l(Br,"int");const nd=b("ZodArray",(e,t)=>{Ql.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>fc(e,r,s,a),e.element=t.element,nt(e,"ZodArray",{min(r,s){return this.check(ot(r,s))},nonempty(r){return this.check(ot(1,r))},max(r,s){return this.check(Lr(r,s))},length(r,s){return this.check(Mr(r,s))},unwrap(){return this.element}})});function Ki(e,t){return Ni(nd,e,t)}p(Ki,"$n"),l(Ki,"array");const pd=b("ZodUnion",(e,t)=>{Vl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>gc(e,r,s,a),e.options=t.options});function Yi(e,t){return new pd({type:"union",options:e,...j(t)})}p(Yi,"Cn"),l(Yi,"union");const ld=b("ZodIntersection",(e,t)=>{Zl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>yc(e,r,s,a)});function Xi(e,t){return new ld({type:"intersection",left:e,right:t})}p(Xi,"Ln"),l(Xi,"intersection");const Jr=b("ZodEnum",(e,t)=>{Wl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(s,a,o)=>uc(e,s,a),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(s,a)=>{const o={};for(const i of s)if(r.has(i))o[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Jr({...t,checks:[],...j(a),entries:o})},e.exclude=(s,a)=>{const o={...t.entries};for(const i of s)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Jr({...t,checks:[],...j(a),entries:o})}});function Hr(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Jr({type:"enum",entries:r,...j(t)})}p(Hr,"Sr"),l(Hr,"_enum");const cd=b("ZodTransform",(e,t)=>{Kl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>hc(e,r),e._zod.parse=(r,s)=>{if(s.direction==="backward")throw new xa(e.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(Be(o,r.value,t));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(Be(i))}};const a=t.transform(r.value,r);return a instanceof Promise?a.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=a,r.fallback=!0,r)}});function eo(e){return new cd({type:"transform",transform:e})}p(eo,"Un"),l(eo,"transform");const dd=b("ZodOptional",(e,t)=>{Wa.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>Gi(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function Qr(e){return new dd({type:"optional",innerType:e})}p(Qr,"Tr"),l(Qr,"optional");const ud=b("ZodExactOptional",(e,t)=>{Yl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>Gi(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function to(e){return new ud({type:"optional",innerType:e})}p(to,"Gn"),l(to,"exactOptional");const md=b("ZodNullable",(e,t)=>{Xl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>bc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function Vr(e){return new md({type:"nullable",innerType:e})}p(Vr,"jr"),l(Vr,"nullable");const hd=b("ZodDefault",(e,t)=>{ec.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>vc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ro(e,t){return new hd({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():qr(t)}})}p(ro,"Jn"),l(ro,"_default");const fd=b("ZodPrefault",(e,t)=>{tc.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>qc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function so(e,t){return new fd({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():qr(t)}})}p(so,"Qn"),l(so,"prefault");const gd=b("ZodNonOptional",(e,t)=>{rc.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>zc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function ao(e,t){return new gd({type:"nonoptional",innerType:e,...j(t)})}p(ao,"Wn"),l(ao,"nonoptional");const yd=b("ZodCatch",(e,t)=>{sc.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>wc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function io(e,t){return new yd({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}p(io,"Yn"),l(io,"_catch");const bd=b("ZodPipe",(e,t)=>{ac.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>Sc(e,r,s,a),e.in=t.in,e.out=t.out});function Zr(e,t){return new bd({type:"pipe",in:e,out:t})}p(Zr,"Pr"),l(Zr,"pipe");const zd=b("ZodReadonly",(e,t)=>{ic.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>xc(e,r,s,a),e.unwrap=()=>e._zod.def.innerType});function oo(e){return new zd({type:"readonly",innerType:e})}p(oo,"tp"),l(oo,"readonly");const vd=b("ZodCustom",(e,t)=>{oc.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,s,a)=>mc(e,r)});function no(e,t={}){return Li(vd,e,t)}p(no,"sp"),l(no,"refine");function po(e,t){return Mi(e,t)}p(po,"ap"),l(po,"superRefine");function lo(e){return ki(Wi,e)}p(lo,"op"),l(lo,"number");const qd=wa({emptyStringAsUndefined:!0,runtimeEnv:process.env,server:{APP_MAX_WIDTH:Jt().pipe(lo()).default(95),NEST_ARCH_BETA_MODE:Hr(["true","false"]).default("false").transform(e=>e==="true"),NEST_ARCH_SCHEMA_URL:Jt().default("./schema.json"),NEST_ARCH_VERSION:Jt().default("0.0.1"),NODE_ENV:Hr(["development","production","test"]).default("development")}});function co(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(" ")}p(co,"np"),l(co,"buildReproducibleCommand");function uo(e){return{$schema:qd.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:co(e),ultraciteAgents:e.ultraciteAgents,ultraciteEditors:e.ultraciteEditors,ultraciteHooks:e.ultraciteHooks,ultraciteInstallSkill:e.ultraciteInstallSkill,version:"0.3.0"}}p(uo,"pp"),l(uo,"buildMetadata");function mo(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(`
328
+ `)+JSON.stringify(e,null,2)}
329
+ `}p(mo,"cp"),l(mo,"serializeMetadata");function ho(){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)}
330
+ `}p(ho,"lp"),l(ho,"buildSchemaContent");async function fo(e,t,r,s,a){try{const o=uo(t),i=mo(o),n=await e.writeFile({content:i,filePath:"nest-arch.jsonc",isBinary:!1},r);n.written&&s.push(n.filePath);const c=ho(),d=await e.writeFile({content:c,filePath:"schema.json",isBinary:!1},r);d.written&&s.push(d.filePath)}catch(o){const i=o instanceof Error?o.message:String(o);a.push(`Failed to generate nest-arch.jsonc/schema.json: ${i}`)}}p(fo,"dp"),l(fo,"generateMetadata");function Wr(){return Ye}p(Wr,"Er"),l(Wr,"loadReference");function y(e){const t=Wr(),r=t.dependencies[e]??t.devDependencies[e];if(!r)throw new Error(`Dependency "${e}" not found in reference package.json`);return r}p(y,"u"),l(y,"getDependencyVersion");function Kr(){return{...Wr().catalog}}p(Kr,"_r"),l(Kr,"getCatalogDependencies");const wd=[{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"}],Sd={dest:"pnpm-workspace.yaml",src:"base/pnpm-workspace.yaml.hbs"},xd={dest:".yarnrc.yml",src:"base/.yarnrc.yml.hbs"},kd={dest:"bunfig.toml",src:"base/bunfig.toml.hbs"},jd=[{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"}],Td=[{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"}],Pd=[{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"}],Ad=[{dest:"src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"},{dest:"src/libs/middlewares/rate-limit.trpc.middleware.ts",src:"base/src/libs/middlewares/rate-limit.trpc.middleware.ts.hbs"}],Ed=[{dest:".husky/pre-commit",src:"addons/husky/pre-commit.hbs"}],_d=[{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"}],Rd=[{dest:"src/health/health.module.ts",src:"extras/health/src/health/health.module.ts.hbs"},{dest:"src/health/health.controller.ts",src:"extras/health/src/health/health.controller.ts.hbs"}],Id=[{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"},{dest:"src/database/entities/app.entity.ts",src:"base/src/database/entities/app.entity.ts.hbs"},{dest:"src/modules/users/entities/user.entity.ts",src:"base/src/modules/users/entities/user.entity.ts.hbs"}],Od=[{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"}],go={"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"}]},yo=[{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"}],Cd="package.json",$d=[{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"}],Dd=[{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"}],Nd=[{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/resolvers/health.resolver.ts",src:"feature/graphql/src/graphql/resolvers/health.resolver.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"}],Ld=[{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"}],Md=[{dest:"apps/api-gateway/src/app.router.ts",src:"base/src/app.router.ts.hbs"},{dest:"apps/api-gateway/src/app.router.spec.ts",src:"base/src/app.router.spec.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/context.ts",src:"base/src/libs/trpc/context.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/error.handler.ts",src:"base/src/libs/trpc/error.handler.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/protected.ts",src:"base/src/libs/trpc/protected.ts.hbs"},{dest:"apps/api-gateway/src/libs/trpc/inner.context.ts",src:"base/src/libs/trpc/inner.context.ts.hbs"},{dest:"apps/api-gateway/src/libs/middlewares/auth.trpc.middleware.ts",src:"base/src/libs/middlewares/auth.trpc.middleware.ts.hbs"},{dest:"apps/api-gateway/src/libs/middlewares/rate-limit.trpc.middleware.ts",src:"base/src/libs/middlewares/rate-limit.trpc.middleware.ts.hbs"}],Ud=[{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/resolvers/health.resolver.ts",src:"monorepo/feature/graphql/src/graphql/resolvers/health.resolver.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"}],Gd=[{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"}],Fd=[{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"},{dest:"packages/shared/src/auth.ts",src:"monorepo/packages/shared/src/auth.ts.hbs"}],Bd={"addons/husky":Ed,"extras/database":Id,"extras/docker":_d,"extras/health":Rd,"extras/swagger":[],"feature/graphql":Nd,"feature/graphql/todo-example":Ld,"feature/rest":jd,"feature/rest/todo-example":Td,"feature/trpc":Ad,"monorepo/apps/api-gateway":$d,"monorepo/feature/graphql":Ud,"monorepo/feature/graphql/todo-example":Gd,"monorepo/feature/rest":Dd,"monorepo/feature/rest/todo-example":Pd,"monorepo/feature/trpc":Md,"monorepo/packages":Fd,"monorepo/packages/db":Od,"monorepo/root":yo};function Yr(e,t,r){e.auth==="passport"?(t["@nestjs/passport"]=y("@nestjs/passport"),t.passport=y("passport"),t["passport-jwt"]=y("passport-jwt"),r["@types/passport-jwt"]=y("@types/passport-jwt"),e.database.length>0?(t["@nestjs/jwt"]=y("@nestjs/jwt"),t.bcrypt=y("bcrypt"),r["@types/bcrypt"]=y("@types/bcrypt"),e.orm.includes("typeorm")&&(t.typeorm=y("typeorm"))):t["jwks-rsa"]=y("jwks-rsa")):(e.auth==="better-auth"||e.auth==="better-auth:stateless")&&(t["better-auth"]=y("better-auth"),t["@thallesp/nestjs-better-auth"]=y("@thallesp/nestjs-better-auth"),e.orm.includes("drizzle")&&(t["@better-auth/drizzle-adapter"]=y("@better-auth/drizzle-adapter")));for(const s of e.api)s==="graphql"?(t["@nestjs/graphql"]=y("@nestjs/graphql"),t["@nestjs/apollo"]=y("@nestjs/apollo"),t.graphql=y("graphql"),t["@apollo/server"]=y("@apollo/server"),e.httpProvider==="fastify"?t["@as-integrations/fastify"]=y("@as-integrations/fastify"):t["@as-integrations/express5"]=y("@as-integrations/express5"),e.auth==="passport"&&(t["graphql-scalars"]=y("graphql-scalars")),e.orm.includes("typeorm")&&(t["typeorm-relations-graphql"]=y("typeorm-relations-graphql")),e.orm.includes("drizzle")&&(t["drizzle-graphql"]=y("drizzle-graphql"))):s==="trpc"&&(t["@trpc/server"]=y("@trpc/server"),t["@trpc/client"]=y("@trpc/client"),t["@trpc/openapi"]=y("@trpc/openapi"),t["nestjs-trpc"]=y("nestjs-trpc"));e.extras.includes("swagger")&&(t["@nestjs/swagger"]=y("@nestjs/swagger"),e.addons.includes("scalar-ui")&&(t["@scalar/nestjs-api-reference"]=y("@scalar/nestjs-api-reference"))),e.extras.includes("health-check")&&(t["@nestjs/terminus"]=y("@nestjs/terminus")),e.extras.includes("rate-limiting")&&(t["@nestjs/throttler"]=y("@nestjs/throttler")),e.microservices.length>0&&(t["@nestjs/microservices"]=y("@nestjs/microservices"));for(const s of e.microservices)s==="redis"?t.ioredis=y("ioredis"):s==="mqtt"?t.mqtt=y("mqtt"):s==="nats"?(t.nats=y("nats"),t["@nats-io/transport-node"]=y("@nats-io/transport-node")):s==="rabbitmq"?(t.amqplib=y("amqplib"),t["amqp-connection-manager"]=y("amqp-connection-manager"),r["@types/amqplib"]=y("@types/amqplib")):s==="kafka"?t.kafkajs=y("kafkajs"):s==="grpc"&&(t["@grpc/grpc-js"]=y("@grpc/grpc-js"),t["@grpc/proto-loader"]=y("@grpc/proto-loader"));if(e.addons.includes("nestjs-zod")){t["nestjs-zod"]=y("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"}}p(Yr,"Ir"),l(Yr,"addConditionalDependencies");function Xr(e,t,r){const s=e.orm.includes("prisma"),a=e.orm.includes("drizzle"),o=e.orm.includes("typeorm"),i=e.database.length>0&&!s&&!a&&!o;for(const n of e.orm)if(n==="prisma"){const c=e.prismaVersion==="8"||e.database.includes("mongodb")&&!e.prismaVersion||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite");r.prisma=y("prisma"),e.prismaVersion==="6"&&e.database.includes("mongodb")&&(r.prisma="^6.19.0"),c?(r.prisma="^8.0.0-rc.15",e.database.includes("mongodb")&&(t["@prisma/orm-mongo"]=y("@prisma/orm-mongo"),t.mongodb=y("mongodb")),e.database.includes("postgresql")&&(t["@prisma/orm-postgres"]=y("@prisma/orm-postgres"),t["temporal-polyfill"]=y("temporal-polyfill"))):(t["@prisma/client"]=y("@prisma/client"),e.prismaVersion==="6"&&e.database.includes("mongodb")&&(t["@prisma/client"]="^6.19.0"),e.database.includes("postgresql")&&(t["@prisma/adapter-pg"]=y("@prisma/adapter-pg")),e.database.includes("mysql")&&(t["@prisma/adapter-mariadb"]=y("@prisma/adapter-mariadb")),e.database.includes("sqlite")&&(t["@prisma/adapter-better-sqlite3"]=y("@prisma/adapter-better-sqlite3")))}else n==="typeorm"?(t.typeorm=y("typeorm"),e.database.includes("postgresql")&&(t.pg=y("pg"),r["@types/pg"]=y("@types/pg"))):n==="drizzle"&&(t["drizzle-orm"]=y("drizzle-orm"),r["drizzle-kit"]=y("drizzle-kit"));e.database.includes("postgresql")&&(a||i)&&(t.pg=y("pg"),r["@types/pg"]=y("@types/pg")),e.database.includes("mysql")&&(a||i||o)&&(t.mysql2=y("mysql2")),e.database.includes("sqlite")&&(a||i||o)&&(t["better-sqlite3"]=y("better-sqlite3"),r["@types/better-sqlite3"]=y("@types/better-sqlite3")),e.database.includes("mongodb")&&i&&(t.mongodb=y("mongodb"))}p(Xr,"Or"),l(Xr,"addDatabaseDependencies");async function bo(e,t,r,s,a,o){try{const i=e.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",n={"@nestjs/common":y("@nestjs/common"),"@nestjs/core":y("@nestjs/core"),[i]:y(i),"@t3-oss/env-core":y("@t3-oss/env-core"),dotenv:y("dotenv"),"reflect-metadata":y("reflect-metadata"),rxjs:y("rxjs"),zod:y("zod")},c=e.extras.includes("typescript-7")?y("typescript-7"):y("typescript"),d={"@nestjs/cli":y("@nestjs/cli"),"@nestjs/mau":y("@nestjs/mau"),"@nestjs/schematics":y("@nestjs/schematics"),"@nestjs/testing":y("@nestjs/testing"),"@types/node":y("@types/node"),"@types/supertest":y("@types/supertest"),"@vitest/coverage-v8":y("@vitest/coverage-v8"),"source-map-support":y("source-map-support"),supertest:y("supertest"),typescript:c,vitest:y("vitest")};e.httpProvider==="express"&&(d["@types/express"]=y("@types/express"));const u={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(e.extras.includes("typescript-7")&&(d.tsx=y("tsx"),u.build="tsc --project tsconfig.build.json",u.dev="tsx watch src/main.ts",u.start="tsx src/main.ts",u["start:debug"]="tsx --inspect-brk src/main.ts",u["start:dev"]="tsx watch src/main.ts"),Yr(e,n,d),Xr(e,n,d),e.auth==="better-auth"&&e.database.length>0){d.auth=y("better-auth");const k=e.orm.includes("prisma"),x=e.orm.includes("drizzle");let O="auth-schema.sql";k?O="auth-schema.prisma":x&&(O="src/database/orm/drizzle/auth-schema.ts"),u["auth:generate"]=`auth generate --config src/auth/auth.cli.ts --output ${O} --yes`,k&&(u["auth:generate"]+=" && node scripts/install-auth-schema.mjs"),!k&&!x&&(u["auth:migrate"]="auth migrate --config src/auth/auth.cli.ts --yes")}e.addons.includes("ultracite")&&(d.ultracite=y("ultracite"),u.check="ultracite check",u.fix="ultracite fix"),e.addons.includes("husky")&&(d.husky=y("husky"),u.prepare="husky"),e.orm.includes("prisma")&&(e.prismaVersion==="8"||e.database.includes("mongodb")&&!e.prismaVersion||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite")?(u["contract:emit"]="prisma contract emit",u["db:init"]="prisma db init",u["db:update"]="prisma db update",u["db:verify"]="prisma db verify",u.migrate="prisma db migrate",u["migration:plan"]="prisma migration plan --name initial",u["migration:show"]="prisma migration show",u["migration:status"]="prisma migration status",u["skills:sync"]="prisma skills sync || exit 0"):(u["prisma:generate"]="prisma generate",u["prisma:format"]="prisma format",u["prisma:push"]="prisma db push",u["prisma:studio"]="prisma studio",u["prisma:migrate"]="prisma migrate dev",u["prisma:migrate:deploy"]="prisma migrate deploy",u.postinstall="prisma generate")),e.orm.includes("drizzle")&&(u["db:generate"]=e.formatter==="oxlint-oxfmt"?"drizzle-kit generate && oxfmt --write .":"drizzle-kit generate",u["db:migrate"]="drizzle-kit migrate",u["db:studio"]="drizzle-kit studio",u["db:push"]="drizzle-kit push"),e.api.includes("trpc")&&(u["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o src/libs/trpc/@generated",u["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o src/libs/trpc/@generated"),e.orm.includes("typeorm")&&(u["typeorm:run"]="typeorm migration:run -d dist/database/orm/typeorm/data-source.js",u["typeorm:revert"]="typeorm migration:revert -d dist/database/orm/typeorm/data-source.js",u["typeorm:generate"]="typeorm migration:generate -d dist/database/orm/typeorm/data-source.js --outputJs --esm",u["typeorm:create"]="typeorm migration:create");const f={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:u,dependencies:n,devDependencies:d},g=JSON.stringify(f,null,2),z=await r.writeFile({content:g,filePath:"package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});z.written&&a.push(z.filePath)}catch(i){const n=i instanceof Error?i.message:String(i);o.push(`Failed to generate package.json: ${n}`),console.error("Failed to generate package.json:",i)}}p(bo,"xp"),l(bo,"generateSingleProjectPackageJson");async function zo(e,t,r,s,a,o){try{const i={build:"turbo build",test:"turbo run test","test:e2e":"turbo run test:e2e","check-types":"turbo check-types",dev:"turbo dev"},n={"@repo/env":"workspace:*",dotenv:"catalog:",zod:"catalog:"},c=e.extras.includes("typescript-7"),d=c?y("typescript-7"):"catalog:",u={"@repo/config":"workspace:*","@types/node":"catalog:",turbo:y("turbo"),typescript:d};e.addons.includes("ultracite")&&(i.check="ultracite check"),e.addons.includes("husky")&&(u.husky=y("husky"),i.prepare="husky");const f={bun:"bun@1.3.14",npm:void 0,pnpm:"pnpm@11.6.0",yarn:"yarn@4.6.0"}[e.packageManager],g=c?{...Kr(),typescript:y("typescript-7")}:Kr(),z={name:t.projectName,version:"0.0.1",description:t.description,author:"",license:"UNLICENSED",private:!0,workspaces:["apps/*","packages/*"],type:"module",...f?{packageManager:f}:{},...e.packageManager==="bun"?{catalog:g}:{},scripts:i,dependencies:n,devDependencies:u},k=JSON.stringify(z,null,2),x=await r.writeFile({content:k,filePath:Cd,isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});x.written&&a.push(x.filePath)}catch(i){const n=i instanceof Error?i.message:String(i);o.push(`Failed to generate monorepo root package.json: ${n}`),console.error("Failed to generate monorepo root package.json:",i)}}p(zo,"Cp"),l(zo,"generateMonorepoRootPackageJson");async function vo(e,t,r,s,a,o){try{const i=e.httpProvider==="fastify"?"@nestjs/platform-fastify":"@nestjs/platform-express",n={"@nestjs/common":y("@nestjs/common"),"@nestjs/core":y("@nestjs/core"),[i]:y(i),"@repo/env":"workspace:*","reflect-metadata":y("reflect-metadata"),rxjs:y("rxjs"),zod:"catalog:"};e.database.length>0&&(n["@repo/db"]="workspace:*"),e.extras.includes("packages/shared")&&(n["@repo/shared"]="workspace:*");const c=e.extras.includes("typescript-7")?y("typescript-7"):"catalog:",d={"@nestjs/cli":y("@nestjs/cli"),"@nestjs/mau":y("@nestjs/mau"),"@nestjs/schematics":y("@nestjs/schematics"),"@nestjs/testing":y("@nestjs/testing"),"@repo/config":"workspace:*","@types/node":"catalog:","@types/supertest":y("@types/supertest"),"@vitest/coverage-v8":y("@vitest/coverage-v8"),"source-map-support":y("source-map-support"),supertest:y("supertest"),typescript:c,vitest:y("vitest")};e.httpProvider==="express"&&(d["@types/express"]=y("@types/express"));const u={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"};e.extras.includes("typescript-7")&&(d.tsx=y("tsx"),u.build="tsc --project tsconfig.build.json",u.dev="tsx watch src/main.ts",u.start="tsx src/main.ts",u["start:debug"]="tsx --inspect-brk src/main.ts",u["start:dev"]="tsx watch src/main.ts"),Yr(e,n,d),e.auth==="better-auth"&&e.orm.includes("prisma")&&(d.auth=y("better-auth"),u["auth:generate"]="auth generate --config src/auth/auth.cli.ts --output auth-schema.prisma --yes && node scripts/install-auth-schema.mjs"),e.addons.includes("ultracite")&&(d.ultracite=y("ultracite"),u.check="ultracite check",u.fix="ultracite fix"),e.addons.includes("husky")&&(d.husky=y("husky"),u.prepare="husky"),e.api.includes("trpc")&&(u["trpc:generate"]="nestjs-trpc generate -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated",u["trpc:watch"]="nestjs-trpc watch -e src/app.module.ts -o ../../packages/shared/src/trpc/@generated");const f={name:"@repo/api-gateway",version:"0.0.1",description:t.description,author:"",license:"UNLICENSED",private:!0,type:"module",scripts:u,dependencies:n,devDependencies:d},g=JSON.stringify(f,null,2),z=await r.writeFile({content:g,filePath:"apps/api-gateway/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});z.written&&a.push(z.filePath)}catch(i){const n=i instanceof Error?i.message:String(i);o.push(`Failed to generate monorepo app package.json: ${n}`),console.error("Failed to generate monorepo app package.json:",i)}}p(vo,"Dp"),l(vo,"generateMonorepoAppPackageJson");async function qo(e,t,r,s,a,o){try{const i={"@nestjs/common":"catalog:","@nestjs/core":"catalog:","reflect-metadata":"catalog:",rxjs:"catalog:","@repo/env":"workspace:*"},n={"@repo/config":"workspace:*","@types/node":"catalog:",typescript:e.extras.includes("typescript-7")?y("typescript-7"):"catalog:"};Xr(e,i,n);const c={};if(e.orm.includes("prisma"))if(e.prismaVersion==="8"||e.database.includes("mongodb")&&!e.prismaVersion||!e.prismaVersion&&!e.database.includes("mysql")&&!e.database.includes("sqlite"))c["contract:emit"]="prisma contract emit",c["db:init"]="prisma db init",c["db:update"]="prisma db update",c["db:verify"]="prisma db verify",c.migrate="prisma db migrate",c["migration:plan"]="prisma migration plan",c["migration:show"]="prisma migration show",c["migration:status"]="prisma migration status",c["skills:sync"]="prisma skills sync || exit 0";else{const g="--schema ./src/database/orm/prisma",z="--config ../../prisma.config.ts";c["prisma:generate"]=`prisma generate ${g}`,c["prisma:format"]=`prisma format ${g}`,c["prisma:push"]=`prisma db push ${g} ${z}`,c["prisma:studio"]=`prisma studio ${g} ${z}`,c["prisma:migrate"]=`prisma migrate dev ${g} ${z}`,c["prisma:migrate:deploy"]=`prisma migrate deploy ${g} ${z}`,c.postinstall="prisma generate --schema ./src/database/orm/prisma"}e.orm.includes("drizzle")&&(c["db:generate"]=e.formatter==="oxlint-oxfmt"?"drizzle-kit generate && oxfmt --write .":"drizzle-kit generate",c["db:migrate"]="drizzle-kit migrate",c["db:studio"]="drizzle-kit studio",c["db:push"]="drizzle-kit push"),e.orm.includes("typeorm")&&(c["typeorm:run"]="typeorm-ts esm migration:run -d src/database/orm/typeorm/data-source.ts",c["typeorm:revert"]="typeorm-ts esm migration:revert -d src/database/orm/typeorm/data-source.ts",c["typeorm:generate"]="typeorm-ts esm migration:generate -d src/database/orm/typeorm/data-source.ts",c["typeorm:create"]="typeorm migration:create");const d={name:"@repo/db",version:"0.0.1",private:!0,type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},...Object.keys(c).length>0?{scripts:c}:{},dependencies:i,devDependencies:n},u=JSON.stringify(d,null,2),f=await r.writeFile({content:u,filePath:"packages/db/package.json",isBinary:!1},{dryRun:s.dryRun,overwrite:s.overwrite});f.written&&a.push(f.filePath)}catch(i){const n=i instanceof Error?i.message:String(i);o.push(`Failed to generate monorepo db package.json: ${n}`),console.error("Failed to generate monorepo db package.json:",i)}}p(qo,"Lp"),l(qo,"generateMonorepoDbPackageJson");async function wo(e,t,r,s,a){const o=t.database.includes("mongodb"),i=t.extras.includes("todo-example"),n=["// use prisma-next",""];t.auth==="passport"&&t.database.length>0&&n.push("enum Role {"," ADMIN"," USER","}",""),o?(t.auth==="passport"&&t.database.length>0&&n.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)",...i?[" todos Todo[]"]:[],' @@map("users")',"}",""),i&&t.database.length>0&&n.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&&n.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)",...i?[" todos Todo[]"]:[]," createdAt TimestamptzString @default(now())"," updatedAt temporal.updatedAtString()",' @@map("users")',"}",""),i&&t.database.length>0&&n.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 c=n.join(`
331
+ `),d=t.projectType==="monorepo"?"packages/db/src/prisma/contract.prisma":"src/prisma/contract.prisma";try{const g=await e.writeFile({content:c,filePath:d,isBinary:!1},r);g.written&&s.push(g.filePath)}catch(g){const z=g instanceof Error?g.message:String(g);a.push(`Failed to generate ${d}: ${z}`)}const u=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(`
332
+ `):['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(`
333
+ `),f=t.projectType==="monorepo"?"packages/db/src/prisma/db.ts":"src/prisma/db.ts";try{const g=await e.writeFile({content:u,filePath:f,isBinary:!1},r);g.written&&s.push(g.filePath)}catch(g){const z=g instanceof Error?g.message:String(g);a.push(`Failed to generate ${f}: ${z}`)}}p(wo,"Mp"),l(wo,"generatePrisma8Contract");async function So(e,t,r,s,a){let o="postgresql";t.database.includes("mysql")?o="mysql":t.database.includes("sqlite")?o="sqlite":t.database.includes("mongodb")&&(o="mongodb");const i=o==="mongodb",n=["generator client {",` provider = "${t.prismaVersion==="6"?"prisma-client-js":"prisma-client"}"`,...t.prismaVersion==="6"?[]:[' output = "./generated"'],...t.prismaVersion==="6"?[' previewFeatures = ["prismaSchemaFolder"]']:[],"}","","datasource db {",` provider = "${o}"`,...t.prismaVersion==="6"&&i?[' url = env("MONGODB_URL")']:[],"}",""],c=t.extras.includes("todo-example");t.auth==="passport"&&t.database.length>0&&n.push("enum Role {"," ADMIN"," USER","}","","model User {",` id String ${i?'@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)",...c?[" todos Todo[]",""]:[""],' @@map("user")',"}",""),t.auth==="passport"&&n.push(`model RefreshToken {
334
+ id String @id @default(cuid())${i?' @map("_id")':""}
335
+ userId String${i?" @db.ObjectId":""}
336
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
337
+ familyId String
338
+ tokenHash String @unique
339
+ expiresAt DateTime
340
+ consumedAt DateTime?
341
+ revokedAt DateTime?
342
+ @@index([familyId])
343
+ }`),c&&t.database.length>0&&(t.auth==="none"?n.push("model Todo {",` id String ${i?'@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")',"}",""):t.auth==="passport"?n.push("model Todo {",` id String ${i?'@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 ${i?"String? @db.ObjectId":"String?"}`," author User? @relation(fields: [authorId], references: [id])","",' @@map("todo")',"}",""):n.push("model Todo {",` id String ${i?'@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 ${i?"String? @db.ObjectId":"String?"}`,"",' @@map("todo")',"}",""));const d=n.join(`
344
+ `),u=t.projectType==="monorepo"?"packages/db/src/database/orm/prisma/schema.prisma":"src/database/orm/prisma/schema.prisma";try{const f=await e.writeFile({content:d,filePath:u,isBinary:!1},r);f.written&&s.push(f.filePath)}catch(f){const g=f instanceof Error?f.message:String(f);a.push(`Failed to generate ${u}: ${g}`)}}p(So,"Up"),l(So,"generatePrisma7Schema");async function xo(e,t,r,s,a){await(t.prismaVersion==="8"||t.database.includes("mongodb")&&!t.prismaVersion||!t.prismaVersion&&!t.database.includes("mysql")&&!t.database.includes("sqlite")?wo(e,t,r,s,a):So(e,t,r,s,a))}p(xo,"Np"),l(xo,"generatePrismaSchema");function es(e,t){const r=!!t.usePrisma,s=!!t.useTypeorm,a=!!t.useDrizzle,o=!!t.useRawSql,i=!!t.hasPostgres,n=!!t.hasMysql,c=!!t.hasSqlite,d=!!t.hasMongodb,u=!!t.isPrisma8;return e.filter(f=>{const{dest:g}=f;return g.includes("prisma-sql.adapter")?r&&!u&&(i||n||c):g.includes("prisma-mongo.adapter")?r&&d:g.includes("typeorm-sql.adapter")?s&&(i||n||c):g.includes("orm/typeorm/data-source")?s:g.includes("modules/users/entities/")?s&&!!t.isPassportAuth:g.endsWith("entities/app.entity.ts")?s&&t.auth==="better-auth:stateless":g.includes("entities/")?s:g.includes("drizzle-sql.adapter")?a:g.includes("raw-sql.adapter")?o&&(i||n||c):g.includes("raw-mongo.adapter")?o&&d:g.includes("orm/drizzle/schema")?a:!0})}p(es,"$r"),l(es,"filterDatabaseTemplates");function ts(e,t){const r=!!t.hasTrpcAndAuth,s=!!t.hasRateLimiting;return e.filter(a=>a.dest.includes("libs/trpc/protected.ts")||a.dest.includes("libs/trpc/inner.context.ts")||a.dest.includes("libs/middlewares/auth.trpc.middleware.ts")?r:a.dest.includes("libs/middlewares/rate-limit.trpc.middleware.ts")?s:!0)}p(ts,"xr"),l(ts,"filterTrpcTemplates");function rs(e,t){const r=!!t.useTypeorm,s=!!t.usePrisma,a=!!t.useDrizzle;return e.filter(o=>{const{dest:i}=o;return i.includes("orm/typeorm")?r:i.includes("orm/prisma")?s:i.includes("orm/drizzle")?a:!0})}p(rs,"Cr"),l(rs,"filterGraphqlTemplates");function ss(e,t){const r=!!t.hasTrpc,s=!!t.hasRest;return e.filter(a=>a.dest.includes("todo.router.ts")?r:a.dest.includes("todo.controller.ts")?s:!0)}p(ss,"Dr"),l(ss,"filterTodoTemplates");function ko(e){return`import { spawnSync } from "node:child_process";
345
+ import { existsSync, readFileSync } from "node:fs";
346
+ import path from "node:path";
347
+ import { parseEnv } from "node:util";
348
+
349
+ const root = import.meta.dirname;
350
+ const file = path.join(root, existsSync(path.join(root, ".env.test")) ? ".env.test" : ".env.test.example");
351
+ const [script, ...args] = process.argv.slice(2);
352
+ const scriptPattern = /^[a-zA-Z0-9:_-]+$/u;
353
+ const argumentPattern = /^[a-zA-Z0-9_./=-]+$/u;
354
+ if (!script || !scriptPattern.test(script) || args.some((arg) => !argumentPattern.test(arg))) {
355
+ throw new Error("Usage: node test-with-services.mjs <package-script> [arguments]");
356
+ }
357
+ const manager = ${JSON.stringify(e)};
358
+ const command = [manager, "run", script, ...(manager === "npm" && args.length > 0 ? ["--"] : []), ...args].join(" ");
359
+ const result = spawnSync(command, {
360
+ cwd: root,
361
+ env: { ...process.env, ...parseEnv(readFileSync(file, "utf-8")) },
362
+ shell: true,
363
+ stdio: "inherit",
364
+ windowsHide: true,
365
+ });
366
+ if (result.error) {
367
+ throw result.error;
368
+ }
369
+ process.exitCode = result.status ?? 1;
370
+ `}p(ko,"Fp"),l(ko,"testServicesRunnerTemplate");function jo(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",OIDC_CLIENT_ID:"generated-scenario-client",OIDC_CLIENT_SECRET:"generated-scenario-secret",OIDC_DISCOVERY_URL:"http://127.0.0.1:1/.well-known/openid-configuration",OIDC_PROVIDER_ID:"scenario-oidc"},s=l((o,i,n,c,d,u)=>{t[o]={environment:c,...d&&d.length>0?{healthcheck:{interval:"2s",retries:45,start_period:"10s",test:d,timeout:"5s"}}:{},image:i,labels:{"nest-arch.generated-test":"true"},ports:[`127.0.0.1:\${TEST_${o.toUpperCase()}_PORT:-${n}}:${n}`],...u?{command:u}:{}}},"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')"],["mongod","--replSet","rs0","--bind_ip_all"]),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("grpc")&&(r.GRPC_URL="127.0.0.1:5000"),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:"INTERNAL://kafka:9093,EXTERNAL://127.0.0.1:9092",KAFKA_AUTO_CREATE_TOPICS_ENABLE:"true",KAFKA_CONTROLLER_LISTENER_NAMES:"CONTROLLER",KAFKA_CONTROLLER_QUORUM_VOTERS:"1@localhost:9094",KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS:"0",KAFKA_INTER_BROKER_LISTENER_NAME:"INTERNAL",KAFKA_LISTENERS:"INTERNAL://:9093,EXTERNAL://:9092,CONTROLLER://:9094",KAFKA_LISTENER_SECURITY_PROTOCOL_MAP:"CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT,INTERNAL: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 a=[...e.auth==="better-auth"?["auth:generate",...e.orm.length===0||e.orm.includes("typeorm")?["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,i])=>`${o}=${i}`).join(`
117
371
  `)}
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=` _ _ ___ ___ _____ _ ___ ___ _ _
372
+ `,"TESTING.md":`# Servicios para pruebas
373
+
374
+ Desde la ra\xEDz del proyecto:
375
+
376
+ 1. Ejecuta \`docker compose -f docker-compose.test.yml up -d --wait\`.
377
+ 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.
378
+ 3. Al terminar ejecuta \`docker compose -f docker-compose.test.yml down --volumes --remove-orphans\`. Esto elimina los datos de pruebas.
379
+
380
+ ${a.map(o=>`- \`node test-with-services.mjs ${o}\``).join(`
381
+ `)}
382
+
383
+ 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.
384
+ `,"docker-compose.test.yml":`${JSON.stringify({services:t},null,2)}
385
+ `,"test-with-services.mjs":ko(e.packageManager)}}p(jo,"Gp"),l(jo,"generateTestServices");class Jd{static{p(this,"Lr")}static{l(this,"ProjectGenerator")}templateEngine;fileWriter;registry;options;mapper;constructor(t,r){this.options=r,this.fileWriter=new In(t),this.templateEngine=new us(r.templatesDir,{cache:r.cacheTemplates??!0}),this.registry=new $n,this.mapper=new Kt,ca(this.mapper)}getMapper(){return this.mapper}async generate(t){const r=Date.now(),s=[],a=[];try{aa(t,this.options.candidateProfile);const o=this.mapper.resolve(t);let i=ha(t);i=fa(i,o.extraVariables),i.hasUltracite=t.addons.includes("ultracite"),i.hasHusky=t.addons.includes("husky"),i.hasAgentSkills=t.addons.includes("agent-skills"),await(t.projectType==="monorepo"?this.generateMonorepo.bind(this):this.generateSingleProject.bind(this))(t,i,o.templateGroups,s,a);const n=Date.now()-r,c=a.length===0;if(c){const d={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await fo(this.fileWriter,t,d,s,a)}return console.log(`\u2705 Project generated in ${n}ms`),{error:c&&a.length===0?void 0:a.join(`
386
+ `),filesCount:s.length,generatedFiles:s,success:c&&a.length===0}}catch(o){return{error:o instanceof Error?o.message:"Unknown error",filesCount:0,generatedFiles:s,success:!1}}}async generateSingleProject(t,r,s,a,o){const i={dryRun:this.options.dryRun,overwrite:this.options.overwrite},n=[...wd];r.packageManager==="pnpm"?n.push(Sd):r.packageManager==="yarn"?(n.push(xd),n.push({dest:"yarn.lock",src:"base/yarn.lock.hbs"})):r.packageManager==="bun"&&n.push(kd),await bo(t,r,this.fileWriter,i,a,o);for(const c of n)await this.renderAndWrite(c.src,c.dest,r,a,o);await this.processTemplateGroups(t,r,s,a,o),await this.processPostTemplateSteps(t,r,a,o)}async generateMonorepo(t,r,s,a,o){const i={dryRun:this.options.dryRun,overwrite:this.options.overwrite};await zo(t,r,this.fileWriter,i,a,o),await vo(t,r,this.fileWriter,i,a,o),t.database.length>0&&await qo(t,r,this.fileWriter,i,a,o),await this.processTemplateGroups(t,r,s,a,o),await this.processPostTemplateSteps(t,r,a,o)}TEMPLATE_FILTERS={"extras/database":es,"feature/graphql":rs,"feature/rest/todo-example":ss,"feature/trpc":ts,"monorepo/feature/graphql":rs,"monorepo/feature/rest/todo-example":ss,"monorepo/feature/trpc":ts,"monorepo/packages/db":es};async processSingleArchTemplates(t,r,s,a){const o=go[t];if(!o)return;const i=new Set(["package.json","pnpm-workspace.yaml",".yarnrc.yml","bunfig.toml"]);for(const n of o)i.has(n.dest)||await this.renderAndWrite(n.src,n.dest,r,s,a)}async processMonorepoRoot(t,r,s){for(const n of yo)await this.renderAndWrite(n.src,n.dest,t,r,s);const a={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,i=a[o];i&&await this.renderAndWrite(i.src,i.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,a,o){const i=t.projectType==="monorepo";for(const n of s){if(!i&&go[n]){await this.processSingleArchTemplates(n,r,a,o);continue}if(i&&n==="monorepo/root"){await this.processMonorepoRoot(r,a,o);continue}if(!i&&n==="monorepo/packages/db")continue;const c=Bd[n];if(!c)continue;const d=this.TEMPLATE_FILTERS[n],u=d?d(c,r):c;for(const f of u)this.shouldSkipTemplate(f,t,i)||await this.renderAndWrite(f.src,f.dest,r,a,o)}}async processPostTemplateSteps(t,r,s,a){const o={dryRun:this.options.dryRun,overwrite:this.options.overwrite},i=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",i,r,s,a);for(const[n,c]of Object.entries(jo(t))){const d=await this.fileWriter.writeFile({content:c,filePath:n,isBinary:!1},o);d.written&&s.push(d.filePath)}if(t.extras.includes("docker")&&(t.database.length>0||t.microservices.length>0)){const n=ba(t),c=await this.fileWriter.writeFile({content:n,filePath:"docker-compose.yml",isBinary:!1},o);c.written&&s.push(c.filePath)}if(t.orm.includes("prisma")&&(await xo(this.fileWriter,t,o,s,a),await this.renderAndWrite("base/prisma.config.ts.hbs","prisma.config.ts",r,s,a)),t.orm.includes("drizzle")&&await za(this.fileWriter,t,o,s,a),t.auth!=="none"){const n=jp.composeGenerators(t),c=await ya(t,this.fileWriter.getBaseDir(),n);for(const d of c)!d.success&&d.error&&a.push(d.error)}}async renderAndWrite(t,r,s,a,o){try{const i=await this.templateEngine.renderToFile(t,r,{context:s}),n=await this.fileWriter.writeFile(i,{dryRun:this.options.dryRun,overwrite:this.options.overwrite});n.written&&a.push(n.filePath)}catch(i){const n=i instanceof Error?i.message:String(i);o.push(`Failed to generate ${r}: ${n}`),console.error(`Failed to generate ${r}:`,i)}}getBaseDir(){return this.fileWriter.getBaseDir()}clearCaches(){this.templateEngine.clearCache(),this.registry.clear()}}class _e{static{p(this,"M")}static{l(this,"ModuleGenerator")}project;config;constructor(t){this.config=t,this.project=new ys}generate(){const t=this.config.name,r=_e.toPascalCase(t),s=this.config.routePrefix||_e.toKebabCase(t),a={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),a.dto=`dto/create-${_e.toKebabCase(t)}.dto.ts`),this.config.entity&&(this.generateEntity(r,t),a.entity=`entities/${t}.entity.ts`),a}generateService(t,r){const s=S.join(this.config.outputDir,`${r}.service.ts`),a=this.project.createSourceFile(s,"",{overwrite:!0});a.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Injectable"]}),a.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 a=S.join(this.config.outputDir,`${r}.controller.ts`),o=this.project.createSourceFile(a,"",{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 i=[{arguments:[`'${s}'`],name:"Controller"}];this.config.enableSwagger&&i.unshift({arguments:[`'${t}'`],name:"ApiTags"}),o.addClass({ctors:[{parameters:[{isReadonly:!0,name:`${r}Service`,scope:rn.Private,type:`${t}Service`}]}],decorators:i,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=S.join(this.config.outputDir,`${r}.module.ts`),a=this.project.createSourceFile(s,"",{overwrite:!0});a.addImportDeclaration({moduleSpecifier:"@nestjs/common",namedImports:["Module"]}),a.addImportDeclaration({moduleSpecifier:`./${r}.service`,namedImports:[`${t}Service`]}),a.addImportDeclaration({moduleSpecifier:`./${r}.controller`,namedImports:[`${t}Controller`]}),a.addClass({decorators:[{arguments:[`{
387
+ controllers: [${t}Controller],
388
+ providers: [${t}Service],
389
+ }`],name:"Module"}],isExported:!0,name:`${t}Module`})}generateDTOs(t,r){const s=S.join(this.config.outputDir,"dto"),a=S.join(s,`create-${_e.toKebabCase(r)}.dto.ts`),o=S.join(s,`update-${_e.toKebabCase(r)}.dto.ts`);this.project.createSourceFile(a,"",{overwrite:!0}).addClass({isExported:!0,name:`Create${t}Dto`,properties:[{hasExclamationToken:!0,name:"title",type:"string"},{name:"description",type:"string | undefined"}]});const i=this.project.createSourceFile(o,"",{overwrite:!0});i.addImportDeclaration({moduleSpecifier:"@nestjs/mapped-types",namedImports:["PartialType"]}),i.addImportDeclaration({moduleSpecifier:`./create-${_e.toKebabCase(r)}.dto`,namedImports:[`Create${t}Dto`]}),i.addTypeAlias({isExported:!0,name:`Update${t}Dto`,type:`PartialType(Create${t}Dto)`})}generateEntity(t,r){const s=S.join(this.config.outputDir,`entities/${_e.toKebabCase(r)}.entity.ts`),a=this.project.createSourceFile(s,"",{overwrite:!0});this.config.ormType==="typeorm"?(a.addImportDeclaration({moduleSpecifier:"typeorm",namedImports:["Column","CreateDateColumn","Entity","PrimaryGeneratedColumn","UpdateDateColumn"]}),a.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"}]})):a.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 Hd=/Resolved|Resolving/iu,Qd=/Downloaded?|downloaded/iu,Vd=/Link(ed|ing)/iu,Zd=/saved (to )?(lockfile|bun)/iu;function To(e){const t=[],r=e.split(`
390
+ `);for(const s of r){const a=s.trim();if(a){if(Hd.test(a)){t.push({message:"Resolving packages...",phase:"resolve"});continue}if(Qd.test(a)){t.push({message:"Downloading...",phase:"download"});continue}if(Vd.test(a)){t.push({message:"Linking packages...",phase:"link"});continue}if(a.includes("packages installed")){t.push({message:a,percentage:100,phase:"link"});continue}if(Zd.test(a)){t.push({message:"Saving lockfile...",phase:"postinstall"});continue}(a.includes("[script]")||a.includes("postinstall"))&&t.push({message:"Running postinstall scripts...",phase:"postinstall"})}}return t}p(To,"Qp"),l(To,"parseBunText");class Wd{static{p(this,"Vp")}static{l(this,"BunInstaller")}async install(t,r,s){const a=zt("bun install",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const i=l(c=>{const d=c.toString();o+=d;const u=To(d);for(const f of u)r?.(f)},"handleData");a.stderr.on("data",i),a.stdout.on("data",i);const[n]=await Promise.race([Pe(a,"close"),Pe(a,"error").then(([c])=>{const d=c;throw d.code==="ENOENT"||d.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(`
391
+ `)):new Error(d.message)})]);if(n===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`bun install exited with code ${n}`)}}const Kd=/^(\d+)\/(\d+)\s+resolving/iu,Yd=/^(\d+)\/(\d+)\s+extract:/iu,Xd=/^(\d+)\/(\d+)\s+(\S+)/iu,eu=/^(\d+)ms\s+(.*)/iu;function Po(e){const t=[],r=e.split(`
392
+ `);for(const s of r){const a=s.trim();if(a.includes("resolving")){const o=Kd.exec(a);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(a.includes("extract:")||a.includes("http fetch")){const o=Yd.exec(a)||Xd.exec(a);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(a.includes("timing")){const o=eu.exec(a);if(o){const i=o[2]??"";i.includes("build")?t.push({message:"Building dependencies...",phase:"build"}):i.includes("link")&&t.push({message:"Linking packages...",phase:"link"})}continue}a.includes("postinstall")&&!a.includes("timing")&&t.push({message:"Running postinstall scripts...",phase:"postinstall"})}return t}p(Po,"ec"),l(Po,"parseNpmText");class tu{static{p(this,"tc")}static{l(this,"NpmInstaller")}async install(t,r,s){const a=zt("npm install --loglevel silly",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";const i=l(c=>{const d=c.toString();o+=d;const u=Po(d);for(const f of u)r?.(f)},"handleData");a.stderr.on("data",i),a.stdout.on("data",()=>{});const[n]=await Promise.race([Pe(a,"close"),Pe(a,"error").then(([c])=>{const d=c;throw d.code==="ENOENT"||d.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(`
393
+ `)):new Error(d.message)})]);if(n===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`npm install exited with code ${n}`)}}const ru={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"}},su={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 a="err"in e?e.err:void 0,o=a&&typeof a=="object"&&"message"in a?a.message:void 0;let i=JSON.stringify(e);return typeof s=="string"?i=s:typeof o=="string"&&(i=o),{message:i,phase:"download"}}switch(t){case"pnpm:stage":return"stage"in e&&typeof e.stage=="string"?ru[e.stage]??null:null;case"pnpm:progress":return"status"in e&&typeof e.status=="string"?su[e.status]??null:null;case"pnpm:lifecycle":return{message:"Running dependency scripts...",phase:"build"};default:return null}}p(Ao,"ac"),l(Ao,"parsePnpmLine");class au{static{p(this,"oc")}static{l(this,"PnpmInstaller")}async install(t,r,s){const a=zt("pnpm install --reporter ndjson",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="",i="",n="";a.stdout.on("data",d=>{const u=d.toString();i+=u,n+=u;const f=n.split(`
394
+ `);n=f.pop()??"";for(const g of f)try{const z=JSON.parse(g),k=Ao(z);k&&r&&r(k)}catch{}}),a.stderr.on("data",d=>{o+=d.toString()});const[c]=await Promise.race([Pe(a,"close"),Pe(a,"error").then(([d])=>{const u=d;throw u.code==="ENOENT"||u.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(`
395
+ `)):new Error(u.message)})]);if(c===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(`pnpm install exited with code ${c}
396
+ ${o.trim()}
397
+ ${i.slice(-2e4)}`)}}function Eo(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}}p(Eo,"ic"),l(Eo,"parseYarnLine");class iu{static{p(this,"nc")}static{l(this,"YarnInstaller")}async install(t,r,s){const a=zt("yarn install --json",[],{cwd:t,shell:!0,signal:s,stdio:["ignore","pipe","pipe"]});let o="";a.stdout.on("data",n=>{const c=n.toString().split(`
398
+ `).filter(Boolean);for(const d of c)try{const u=JSON.parse(d),f=Eo(u);f&&r&&r(f)}catch{}}),a.stderr.on("data",n=>{o+=n.toString()});const[i]=await Promise.race([Pe(a,"close"),Pe(a,"error").then(([n])=>{const c=n;throw c.code==="ENOENT"||c.code==="EINVAL"?new Error(["Yarn is not installed or not found in your PATH.",""," Install Yarn: npm install -g yarn",""," Then restart your terminal and try again."].join(`
399
+ `)):new Error(c.message)})]);if(i===0){r?.({message:"Done",percentage:100,phase:"complete"});return}throw new Error(o.trim()||`yarn install exited with code ${i}`)}}function _o(e){switch(e){case"pnpm":return new au;case"npm":return new tu;case"yarn":return new iu;case"bun":return new Wd;default:throw new Error(`Unhandled package manager: ${e}`)}}p(_o,"Mr"),l(_o,"createPackageInstaller");class ou{static{p(this,"pc")}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 a=this.state.phases.every(o=>o.success||o.skipped);return this.buildResult(a)}async phaseGenerateFiles(){this.emit("generate-files");const t=new Jd(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 Promise.all(this.state.generatedFiles.map(async o=>[o,bs("sha256").update(await Se(gs(o)?o:Y(this.outputDir,o))).digest("hex")])),r=await Ms(this.outputDir,this.context),s=[];for(const[o,i]of t)try{bs("sha256").update(await Se(gs(o)?o:Y(this.outputDir,o))).digest("hex")!==i&&s.push(o)}catch{s.push(o)}const a=[...r.failed.length>0?[r.failed.map(o=>`${o.name}: ${o.error}`).join(", ")]:[],...s.length>0?[`Agent skills changed generated files: ${s.join(", ")}`]:[]].join("; ")||void 0;this.addPhase({phase:"install-agent-skills",success:r.failed.length===0&&s.length===0,...a?{error:a}:{}})}catch(t){this.addPhase({error:t instanceof Error?t.message:String(t),phase:"install-agent-skills",success:!1})}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 Ws(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 ea(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 cr(this.outputDir)||await lr(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 Tt(this.outputDir),await Pt(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 _o(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 Js(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 Tt(this.outputDir),await Us(this.outputDir)&&await Pt(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 nu=["projectName","packageManager","formatter","httpProvider","projectType","architecture","database","orm","prismaVersion","apiLayer","auth","extras","microservices","addons","ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill","initGit","installDependencies","summary","installing","done"];function as(e){return e.includes("mongodb")}p(as,"databaseIncludesMongodb");function Ro(e){return e.length===0}p(Ro,"databaseIsEmpty");function pt(e){return e.includes("rest")||e.includes("trpc")||e.includes("graphql")}p(pt,"hasApiLayer");function lt(e){return Ro(e)}p(lt,"shouldSkipOrmStep");function Qt(e){return e.includes("prisma")}p(Qt,"usesPrisma");function pu(e,t){return Qt(e)?as(t)?"8":t.includes("mysql")||t.includes("sqlite")?"7":null:null}p(pu,"resolvePrismaVersion");function Io(e,t){return!!(!Qt(e)||Ro(t)||as(t)||t.includes("mysql")||t.includes("sqlite"))}p(Io,"shouldSkipPrismaVersionStep");function lu(e,t){return Io(e,t)?[]:Os}p(lu,"filterPrismaVersionOptions");function Oo(e,t,r){if(!Qt(e))return null;const s=pu(e,t);return s||(r??null)}p(Oo,"sanitizePrismaVersionForOrm");function ct(e){return nu.filter(t=>t==="orm"&&lt(e.database)||t==="prismaVersion"&&Io(e.orm,e.database)||t==="auth"&&!pt(e.api)?!1:t==="microservices"?e.architecture==="nest-microservice":!((t==="ultraciteEditors"||t==="ultraciteAgents"||t==="ultraciteHooks"||t==="ultraciteInstallSkill")&&(!e.addons.includes("ultracite")||e.formatter==="none")))}p(ct,"getVisibleSteps");const Co=["ultraciteEditors","ultraciteAgents","ultraciteHooks","ultraciteInstallSkill"];function dt(e){return Co.includes(e)}p(dt,"isUltraciteSubStep");function cu(e,t){if(!dt(e))return null;const r=Co.filter(n=>ct(t).includes(n)),s=r.indexOf(e);if(s===-1)return null;const a=r.length,o=s+1,i=Math.round(o/a*100);return{current:o,percent:i,total:a}}p(cu,"getUltraciteSubStepInfo");function is(e){return ct(e).filter(t=>t!=="installing"&&t!=="done"&&!dt(t)).length}p(is,"getTotalSteps");function du(e,t){const r=ct(t).filter(o=>o!=="installing"&&o!=="done");if(e==="installing"||e==="done")return is(t);if(dt(e)){const o=r.indexOf("addons");return o===-1?1:o+1}const a=r.filter(o=>!dt(o)).indexOf(e);return a===-1?1:a+1}p(du,"getDisplayStepNumber");function uu(e,t){const r=ct(t),s=r.indexOf(e);return s===-1||s>=r.length-1?null:r[s+1]??null}p(uu,"getNextStepId");function mu(e,t){const r=ct(t),s=r.indexOf(e);return s<=0?null:r[s-1]??null}p(mu,"getPreviousStepId");function hu(e){return e==="monorepo"?Rs:Rs.filter(t=>t.value!=="nest-gateway")}p(hu,"filterArchitectureOptions");function $o(e){return as(e)?[]:Is}p($o,"filterOrmOptions");function os(e){return{addons:e.addons??[],api:e.api??["rest"],architecture:e.architecture??"nest-api",auth:e.auth??"none",database:e.database??[],extras:e.extras??[],formatter:e.formatter??"none",httpProvider:e.httpProvider??"express",microservices:e.microservices??[],orm:e.orm??[],prismaVersion:e.prismaVersion??(e.orm?.includes("prisma")?"7":void 0),projectType:e.projectType??"single"}}p(os,"wizardSupportContext");function ns(e){return tt(os(e)).length===0}p(ns,"isWizardSelectionSupported");function fu(e,t={}){return e.length>0?pr.filter(r=>r.value!=="mongodb"):pr.filter(({value:r})=>r!=="mongodb"||ns({...t,addons:[],api:["rest"],auth:"none",database:[r],extras:[],orm:[]}))}p(fu,"filterDatabaseOptions");function Do(e,t=[],r={}){return $s.filter(({value:s})=>s==="none"||tt({...os(r),auth:s,database:e,orm:t,prismaVersion:t.includes("prisma")?r.prismaVersion??"7":void 0}).length===0)}p(Do,"filterAuthOptions");function ut(e,t,r,s={}){return Do(t,r,s).some(({value:a})=>a===e)?e:null}p(ut,"sanitizeAuthForDatabase");function gu(e,t={}){return Cs.filter(({value:r})=>tt({...os(t),addons:[],api:[r],auth:"none",database:e,extras:[]}).length===0)}p(gu,"filterApiOptions");function yu(e,t){return t.includes("drizzle")?e.filter(r=>r!=="mongodb"):e}p(yu,"sanitizeDatabaseForOrm");function No(e){return"nest-api"}p(No,"defaultArchitecture");function Lo(e,t){if(lt(t))return[];const r=new Set($o(t).map(s=>s.value));return e.filter(s=>r.has(s))}p(Lo,"sanitizeOrmForDatabase");function mt(e,t){return e.find(r=>r.value===t)?.label??t}p(mt,"labelFor$1");function bu(e,t){return t!=="none"||!e.includes("ultracite")?null:`Removed the ${mt(Ke,"ultracite")} addon \u2014 it requires a formatter to be installed.`}p(bu,"formatterConflictNotice");function zu(e,t,r){if(pt(r))return null;const s=[];return e.includes("scalar-ui")&&s.push(`the ${mt(Ke,"scalar-ui")} addon`),s.push(...t.filter(a=>a!=="docker"&&a!=="packages/shared").map(a=>`the ${mt(We,a)} extra`)),s.length===0?null:`Removed ${s.join(", ")} \u2014 a project without REST, tRPC, or GraphQL has no API layer.`}p(zu,"apiLayerConflictNotice");function vu(e,t){return t.includes("swagger")||!e.includes("scalar-ui")?null:`Removed the ${mt(Ke,"scalar-ui")} addon \u2014 it requires the Swagger extra.`}p(vu,"extrasConflictNotice");function qu(e,t){return t.length>0||!e.includes("graphql")?null:"Removed the GraphQL API layer \u2014 GraphQL requires a database."}p(qu,"databaseConflictNotice");function wu(e,t){return!t.includes("drizzle")||!e.includes("mongodb")?null:"Removed the MongoDB database \u2014 Drizzle ORM does not support MongoDB."}p(wu,"ormConflictNotice");function Su(e,t){return t!=="single"||!e.includes("packages/shared")?null:`Removed the ${mt(We,"packages/shared")} extra \u2014 it is only available in a monorepo.`}p(Su,"projectTypeConflictNotice");function Ne(e,t){return e.find(r=>r.value===t)?.label??t}p(Ne,"labelFor");function Je(e,t){return t.length===0?"None":t.map(r=>Ne(e,r)).join(", ")}p(Je,"labelsFor");const xu=p(({onConfirm:e,state:t})=>{Me((a,o)=>{o.return&&e()});const r={"nest-api":"NestJS API","nest-gateway":"NestJS API Gateway","nest-microservice":"NestJS Microservice"},s=[{label:"Project",value:Ce(t.projectName)},{label:"Package manager",value:t.packageManager?Ne(Ps,t.packageManager):"\u2014"},{label:"Formatter",value:t.formatter?Ne(As,t.formatter):"\u2014"},{label:"HTTP provider",value:t.httpProvider?Ne(Es,t.httpProvider):"\u2014"},{label:"Project type",value:t.projectType?Ne(_s,t.projectType):"\u2014"},{label:"Architecture",value:t.architecture?r[t.architecture]??t.architecture:"\u2014"},{label:"Database",value:Je(pr,t.database)}];return lt(t.database)||s.push({label:"ORM",value:Je(Is,t.orm)}),Qt(t.orm)&&t.prismaVersion&&s.push({label:"Prisma",value:Ne(Os,t.prismaVersion)}),s.push({label:"API layer",value:Je(Cs,t.api)}),t.architecture==="nest-gateway"&&s.push({label:"Microservices",value:Je([{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)}),pt(t.api)&&s.push({label:"Auth",value:t.auth?Ne($s,t.auth):"\u2014"}),s.push({label:"Extras",value:Je(We,t.extras)},{label:"Addons",value:Je(Ke,t.addons)},{label:"Git",value:t.initGit==="yes"?"Initialize repository":"Skip"},{label:"Install deps",value:t.installDependencies==="yes"?"Install":"Skip"}),w(V,{children:[m(q,{flexDirection:"column",marginBottom:1,children:w(h,{children:[m(h,{color:I,children:"\u2726 "}),m(h,{color:me,children:"Review your selections"})]})}),m(q,{flexDirection:"column",rowGap:0,overflow:"hidden",children:s.map(a=>w(q,{flexDirection:"row",columnGap:1,children:[m(h,{color:ar,children:`${a.label}:`}),m(h,{color:Ie,children:a.value})]},a.label))})]})},"SummaryStep");function Vt(e){return e.length===0?"\u2014":e.join(", ")}p(Vt,"formatList");const ku=p(({state:e,stepId:t})=>{const{stdout:r}=sr(),s=r.columns||r.getWindowSize?.()[0]||80,a=Math.min(kt.APP_MAX_WIDTH,s-4),o=[];if(t!=="projectName"&&e.projectName.trim()&&o.push(Ce(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 c={"nest-api":"Nest API","nest-gateway":"API Gateway","nest-microservice":"Microservice"};o.push(c[e.architecture]??e.architecture)}if(e.database.length>0&&o.push(Vt(e.database)),e.orm.length>0&&o.push(Vt(e.orm)),e.orm.includes("prisma")&&e.prismaVersion&&o.push(`Prisma ${e.prismaVersion}`),e.api.length>0&&o.push(Vt(e.api)),e.auth&&o.push(e.auth),e.formatter){const c={biome:"Biome",none:"No formatter","oxlint-oxfmt":"Oxlint+Oxfmt"};o.push(c[e.formatter]??e.formatter)}if(e.microservices.length>0&&o.push(Vt(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&&!dt(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:[m(h,{color:I,children:"\u25C6 "}),m(h,{color:I,children:"Create a new NestJS project"})]});const[i,...n]=o;return w(V,{children:[w(h,{children:[m(h,{color:I,children:"\u25C6 "}),m(h,{color:I,children:"Create a new NestJS project"})]}),t!=="summary"&&m(q,{borderStyle:"single",borderColor:Ue,width:a,children:w(h,{children:[m(h,{children:"Project Name: "}),m(h,{color:I,children:i}),m(h,{color:C,children:" Selected: "}),n.length>0?m(h,{color:C,children:`${n.filter(c=>c!=="none").join(" \xB7 ")}`}):null]})})]})},"WizardContextBar"),ju=p(({displayStep:e,stepId:t,subProgress:r,totalSteps:s})=>w(q,{paddingLeft:2,paddingTop:t==="summary"?2:1,marginBottom:1,children:[m(h,{color:K,children:"Create project"}),m(h,{color:C,children:` \u2014 step ${e}/${s}`}),r?m(h,{color:me,children:` \xB7 Ultracite configuration (${r.current}/${r.total} \xB7 ${r.percent}%)`}):m(h,{color:me,children:` \xB7 ${An[t]}`})]}),"WizardTitle$1"),ps=Y(wt(),".nestarch"),ls=Y(ps,"last-used.json");function Tu(){try{if(!qt(ls))return null;const e=sn(ls,"utf-8");return JSON.parse(e)}catch{return null}}p(Tu,"getLastUsedConfig");function Mo(e){try{qt(ps)||an(ps,{recursive:!0}),on(ls,JSON.stringify(e,null,2),"utf-8")}catch{}}p(Mo,"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"}),a=r.getDate(),o=r.getFullYear(),i=`${s} ${a}, ${o}`;return`${t.join(", ")} (last used ${i})`}p(Pu,"buildLastUsedDescription");function Au(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}}p(Au,"buildGeneratorContext");function Zt(e){return kt.NEST_ARCH_BETA_MODE?Y(wt(),"test-projects",e):Y(process.cwd(),e)}p(Zt,"getOutputDir");function Eu(){const e=import.meta.dirname;if(e){const r=Y(e,"templates");if(qt(r))return r}return Y(e??process.cwd(),"..","..","..","..","packages","core","templates")}p(Eu,"getTemplatesDir");async function Uo(e,t){const r=Zt(e.projectName),s=Au(e),a=Eu(),o=new ou(r,{cacheTemplates:!0,templatesDir:a});try{const i=await o.execute(s,t),n={"formatter-commit":"Commit formatting","generate-files":"Generate project","initial-commit":"Initial commit","initialize-git":"Initialize Git","install-dependencies":"Install dependencies","run-formatter":"Run formatter","setup-linter":"Setup linter"},c=i.phases.filter(d=>!d.success&&!d.skipped&&d.error).map(d=>`${n[d.phase]||d.phase} failed:
400
+ ${d.error}`);return c.length>0?{message:c.join(`
401
+
402
+ `),outputDir:r,success:!1}:{message:`Project created with ${i.generatedFiles.length} files`,outputDir:r,success:!0}}catch(i){return{message:`Failed to generate project: ${i instanceof Error?i.message:String(i)}`,outputDir:r,success:!1}}}p(Uo,"generateProject");const _u=p(()=>({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 Go(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:lt(e.database)?[]:e.orm,packageManager:e.packageManager,prismaVersion:lt(e.database)?void 0:e.prismaVersion??void 0,projectName:Ce(e.projectName),projectType:e.projectType,ultraciteAgents:e.ultraciteAgents,ultraciteEditors:e.ultraciteEditors,ultraciteHooks:e.ultraciteHooks,ultraciteInstallSkill:e.ultraciteInstallSkill??"no"}}p(Go,"buildResult");const Ru=p(({onBack:e,onExit:t,onStepChange:r})=>{const[s,a]=N("projectName"),o=yt(s);o.current=s;const[i,n]=N(_u),[c,d]=N(null),[u,f]=N(null),[g,z]=N(null),[k,x]=N(null),[O,X]=N(null),oe=ne(()=>is(i),[i]),ge=ne(()=>du(s,i),[s,i]),Q=ne(()=>cu(s,i),[s,i]);hs(()=>{if(!g||g.isError)return;const P=Go(i);P&&Mo(P),a("done"),r?.("done")},[g,i,r]);const L=$(P=>{const v=uu(o.current,P);v&&(a(v),r?.(v))},[r]),re=$(()=>{f(null);const P=mu(s,i);if(P){a(P),r?.(P);return}e()},[e,i,s,r]),H=p(P=>$(v=>{n(A=>{const G={...A,[P]:v};return G.auth=ut(G.auth,G.database,G.orm,G),f(null),L(G),G})},[P]),"useStepFieldHandler"),ke=H("packageManager"),R=$(P=>{n(v=>{const A={...v,addons:P==="none"?v.addons.filter(G=>G!=="ultracite"):v.addons,formatter:P};return A.auth=ut(A.auth,A.database,A.orm,A),f(bu(v.addons,P)),L(A),A})},[L]),M=H("httpProvider"),W=H("auth"),ee=H("prismaVersion"),se=H("microservices"),ye=H("addons"),be=H("ultraciteEditors"),He=H("ultraciteAgents"),_=H("ultraciteHooks"),ze=H("ultraciteInstallSkill"),Le=H("initGit"),je=H("installDependencies"),D=$(()=>{const P=xt(i.projectName);if(P){d(P);return}const v=Ce(i.projectName),A=Zt(v);if(qt(A)){d(`Directory "${A}" already exists. Choose a different name or delete the existing directory.`);return}const G={...i,projectName:v};n(G),L(G)},[L,i]),Re=$(P=>{const v=P==="single"&&i.architecture==="nest-gateway"?No():i.architecture??No(),A={...i,architecture:v,extras:P==="single"?i.extras.filter(G=>G!=="packages/shared"):i.extras,microservices:v==="nest-microservice"?i.microservices:[],projectType:P};f(Su(i.extras,P)),n(A),L(A)},[L,i]),Yt=$(P=>{const v={...i,architecture:P,microservices:P==="nest-microservice"?i.microservices:[]};n(v),L(v)},[L,i]),T=$(P=>{const v=P==="none"?[]:[P],A=Lo(i.orm,v),G=v.length===0,te={...i,api:G?i.api.filter(de=>de!=="graphql"):i.api,auth:ut(i.auth,v,A,i),database:v,orm:A,prismaVersion:Oo(A,v,i.prismaVersion)};f(qu(i.api,v)),n(te),L(te)},[L,i]),ht=$(P=>{const v=P==="none"?[]:[P],A=yu(i.database,v),G=Lo(v,A),te={...i,auth:ut(i.auth,A,G,i),database:A,orm:G,prismaVersion:Oo(G,A,i.prismaVersion)};f(wu(i.database,v)),n(te),L(te)},[L,i]),ft=$(P=>{const v=P.includes("graphql")&&P.length>1?[P.at(-1)??"rest"]:P,A=pt(v),G={...i,addons:A?i.addons:i.addons.filter(te=>te!=="scalar-ui"),api:v,auth:A?ut(i.auth,i.database,i.orm,{...i,api:v}):null,extras:A?i.extras:i.extras.filter(te=>te==="docker"||te==="packages/shared")};f(zu(i.addons,i.extras,v)),n(G),L(G)},[L,i]),Xt=$(P=>{const v=P.includes("swagger"),A={...i,addons:v?i.addons:i.addons.filter(G=>G!=="scalar-ui"),extras:P};f(vu(i.addons,P)),n(A),L(A)},[L,i]),gt=ne(()=>{const P=i.projectType==="monorepo"?We:We.filter(v=>v.value!=="packages/shared");return pt(i.api)?P.filter(({value:v})=>ns({...i,extras:[...i.extras,v]})):P.filter(v=>v.value==="docker"||v.value==="packages/shared")},[i]),er=$(async()=>{const P=Go(i);if(P){f(null),a("installing"),r?.("installing");try{const v=await Uo(P,{onInstallProgress:p(A=>{X(A)},"onInstallProgress"),onStageChange:p(A=>{x(A)},"onStageChange")});z({isError:!v.success,message:v.message})}catch(v){z({isError:!0,message:`Error: ${v instanceof Error?v.message:String(v)}`})}}},[i,r]),tr=$(()=>{f(null),a("summary"),r?.("summary"),z(null)},[r]),rr=ne(()=>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"&&g?.isError?"confirm":"select",[s,g?.isError]);return{architectureOpts:ne(()=>hu(i.projectType),[i.projectType]),currentStage:k,displayStep:ge,extrasStepOptions:gt,generationStatus:g,goBack:re,handleAddons:ye,handleApi:ft,handleArchitecture:Yt,handleAuth:W,handleDatabase:T,handleExtras:Xt,handleFormatter:R,handleHttpProvider:M,handleInitGit:Le,handleInstallDependencies:je,handleMicroservices:se,handleOrm:ht,handlePackageManager:ke,handlePrismaVersion:ee,handleProjectNameSubmit:D,handleProjectType:Re,handleRetry:tr,handleSummaryConfirm:er,handleUltraciteAgents:He,handleUltraciteEditors:be,handleUltraciteHooks:_,handleUltraciteInstallSkill:ze,installProgress:O,projectNameError:c,setProjectNameError:d,setState:n,state:i,statusAction:rr,stepId:s,subProgress:Q,totalSteps:oe,wizardNotice:u}},"useCreateProjectWizard"),Iu=p(({onBack:e,onDone:t,onExit:r,onStepChange:s})=>{const{architectureOpts:a,currentStage:o,displayStep:i,extrasStepOptions:n,generationStatus:c,goBack:d,handleProjectNameSubmit:u,handlePackageManager:f,handleFormatter:g,handleHttpProvider:z,handleProjectType:k,handleArchitecture:x,handleDatabase:O,handleOrm:X,handlePrismaVersion:oe,handleApi:ge,handleAuth:Q,handleExtras:L,handleMicroservices:re,handleAddons:H,handleUltraciteEditors:ke,handleUltraciteAgents:R,handleUltraciteHooks:M,handleUltraciteInstallSkill:W,handleInitGit:ee,handleInstallDependencies:se,handleRetry:ye,handleSummaryConfirm:be,installProgress:He,projectNameError:_,setProjectNameError:ze,setState:Le,statusAction:je,stepId:D,subProgress:Re,totalSteps:Yt,state:T,wizardNotice:ht}=Ru({onBack:e,onExit:r,onStepChange:s}),[ft,Xt]=N([]),[gt]=N([]),er=ne(()=>{const v=new Set;return T.initGit==="no"&&(v.add("initialize-git"),v.add("initial-commit")),T.installDependencies==="no"&&v.add("install-dependencies"),(T.formatter==="none"||T.installDependencies==="no")&&(v.add("setup-linter"),v.add("run-formatter")),(T.initGit==="no"||v.has("run-formatter"))&&v.add("formatter-commit"),T.addons.includes("agent-skills")||v.add("install-agent-skills"),[...v]},[T.initGit,T.installDependencies,T.formatter,T.addons]),tr=ne(()=>Ke.filter(v=>v.value==="ultracite"&&T.formatter==="none"||v.value==="scalar-ui"&&!T.extras.includes("swagger")?!1:ns({...T,addons:[...T.addons,v.value]})),[T]),rr=ne(()=>{let v=T;return D==="addons"&&(v={...v,addons:ft}),D==="database"&&(v={...v,database:gt}),is(v)},[D,T,ft,gt,Yt]);Te(()=>{D==="done"&&t()},[D,t]),Me((v,A)=>{if(A.ctrl&&v==="c"){r();return}if(A.ctrl&&v==="b"&&D!=="done"){d();return}if(D==="done"&&A.return){r();return}D==="installing"&&c?.isError&&A.return&&ye()});const ms=p(()=>{const A={architecture:{options:a,prompt:"Choose an application architecture"},auth:{options:Do(T.database,T.orm,T),prompt:"Choose an authentication strategy"},formatter:{options:As,prompt:"Choose a formatter-linter (with ultracite preset) setup"},httpProvider:{options:Es,prompt:"Choose an HTTP provider"},initGit:{options:Ds,prompt:"Initialize a git repository?"},installDependencies:{options:xn,prompt:"Install dependencies?"},packageManager:{options:Ps,prompt:"Choose a package manager"},projectType:{options:_s,prompt:"Choose a project layout"},ultraciteInstallSkill:{options:Pn,prompt:"Install Ultracite skill?"}}[D];if(A)return m(Ze,{onConfirm:{architecture:x,auth:Q,formatter:g,httpProvider:z,initGit:ee,installDependencies:se,packageManager:f,projectType:k,ultraciteInstallSkill:W}[D],options:A.options,prompt:A.prompt},D);const te={addons:{initialSelected:T.addons,onChange:Xt,options:tr,prompt:"Select addons (optional)"},apiLayer:{initialSelected:T.architecture==="nest-api"&&T.api.length===0?["rest"]:T.api,options:gu(T.database,T),prompt:"Select API layers (optional)"},extras:{initialSelected:T.extras,options:n,prompt:"Select extras (optional)"},microservices:{initialSelected:T.microservices,options:Sn,prompt:"Select microservice communication protocols"},ultraciteAgents:{initialSelected:T.ultraciteAgents,minified:!0,options:jn,prompt:"Select Ultracite agents"},ultraciteEditors:{initialSelected:T.ultraciteEditors,minified:!0,options:kn,prompt:"Select Ultracite editors"},ultraciteHooks:{initialSelected:T.ultraciteHooks,options:Tn,prompt:"Select Ultracite hooks"}}[D];if(te){const de={addons:H,apiLayer:ge,extras:L,microservices:re,ultraciteAgents:R,ultraciteEditors:ke,ultraciteHooks:M};return m(qn,{exclusiveValue:D==="apiLayer"?"graphql":void 0,initialSelected:te.initialSelected,onConfirm:de[D],options:te.options,prompt:te.prompt,...te.minified?{minified:!0}:{},...te.onChange?{onChange:te.onChange}:{}},D)}switch(D){case"projectName":return m(Ts,{error:_,onChange:p(de=>{Le(Ho=>({...Ho,projectName:de})),ze(xt(de))},"onChange"),onSubmit:u,value:T.projectName});case"database":{const de={description:"Skip database scaffolding for now",label:"No database",value:"none"};return m(Ze,{initialValue:T.database[0]??"none",onConfirm:O,options:[de,...fu(T.orm,T)],prompt:"Select a database for your project (optional)"},"database")}case"orm":{const de={description:"Use plain database access without an ORM",label:"No ORM",value:"none"};return m(Ze,{initialValue:T.orm[0]??"none",onConfirm:X,options:[de,...$o(T.database)],prompt:"Select an ORM to include"},"orm")}case"prismaVersion":return m(Ze,{initialValue:T.prismaVersion??"7",onConfirm:oe,options:lu(T.orm,T.database),prompt:"Select a Prisma version"},"prismaVersion");case"summary":return m(xu,{onConfirm:be,state:T});case"installing":return w(q,{flexDirection:"column",children:[m(Ss,{currentStage:o,generationMessage:c?.message??"Scaffolding your project",installProgress:He,isError:c?.isError??!1,packageManager:T.packageManager??void 0,skippedStages:er}),c?.isError?m(q,{marginTop:1,children:w(h,{color:C,children:["Press ",m(h,{color:I,children:"Enter"})," to go back to Summary and retry, or ",m(h,{color:C,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const de=Ce(T.projectName);return m(xs,{architecture:T.architecture||"nest-api",projectName:de,packageManager:T.packageManager||"pnpm",dependenciesInstalled:T.installDependencies==="yes",isGitInitialized:T.initGit==="yes",outputDir:Zt(de)})}default:return null}},"renderStep"),P=D!=="installing"&&D!=="done";return w(q,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[P?w(V,{children:[m(ku,{state:T,stepId:D}),m(q,{height:0}),m(ju,{displayStep:i,stepId:D,subProgress:Re??void 0,totalSteps:rr}),m(q,{height:2}),ht?m(q,{marginBottom:1,children:w(h,{color:ar,children:["! ",ht]})}):null]}):null,ms(),m(q,{flexGrow:1}),P?w(V,{children:[m(Ve,{}),m(q,{height:1}),m(nr,{action:je,showBack:!0})]}):null]})},"CreateProjectWizardScreen"),cs=` _ _ ___ ___ _____ _ ___ ___ _ _
136
403
  | \\| | __/ __|_ _| /_\\ | _ \\/ __| || |
137
404
  | .\` | _|\\__ \\ | | / _ \\| / (__| __ |
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)}
405
+ |_|\\_|___|___/ |_| /_/ \\_\\_|_\\\\___|_||_|`,Ou=12,Cu=4,Fo=p(({onlyCat:e=!1})=>{const{stdout:t}=sr(),r=t.columns||t.getWindowSize?.()[0]||80,s=t.rows||t.getWindowSize?.()[1]||24;return e?s<15||r<20?m(q,{flexDirection:"column",alignItems:"center",children:m(h,{bold:!0,color:I,children:fs})}):m(q,{flexDirection:"column",alignItems:"center",children:m(h,{color:I,children:or})}):s<15||r<38?w(q,{flexDirection:"column",alignItems:"center",rowGap:0,children:[m(h,{bold:!0,color:I,children:fs}),m(h,{color:C,children:bt}),m(h,{color:me,children:Ge})]}):s<15+Cu||r<55?w(q,{flexDirection:"column",alignItems:"center",rowGap:0,children:[m(h,{color:I,children:cs}),m(h,{color:C,children:bt}),m(h,{color:me,children:Ge})]}):s<15+Ou||r<80?w(q,{flexDirection:"column",alignItems:"center",rowGap:0,children:[m(h,{color:I,children:or}),m(h,{color:I,children:cs}),m(h,{color:C,children:bt}),m(h,{color:me,children:Ge})]}):w(q,{flexDirection:"row",columnGap:2,alignItems:"flex-start",children:[m(h,{color:I,children:or}),w(q,{flexDirection:"column",children:[m(h,{color:I,children:cs}),w(h,{color:C,children:[" ",bt]}),w(h,{color:me,children:[" ",Ge]})]})]})},"Header"),ds={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"},$u=p(({onSelect:e,options:t})=>{const[r,s]=N(0),a=$(()=>{const o=t[r];o&&!o.disabled&&e(o)},[e,t,r]);return St((o,i)=>{i.upArrow||o==="k"?s(n=>Math.max(0,n-1)):i.downArrow||o==="j"?s(n=>Math.min(t.length-1,n+1)):i.return&&a()}),w(q,{flexDirection:"column",children:[m(h,{color:C,children:"Choose a project preset"}),m(q,{marginTop:1,flexDirection:"column",rowGap:1,children:t.map((o,i)=>w(q,{flexDirection:"column",children:[m(h,{children:i===r?w(V,{children:[m(h,{color:o.disabled?Ue:I,children:"> "}),m(h,{color:o.disabled?Ue:I,children:o.name})]}):m(h,{color:o.disabled?Ue:Oe,children:` ${o.name}`})}),i===r&&o.description?m(h,{color:C,children:o.description}):null]},o.name))})]})},"PresetStep"),Du={done:"Done",initGit:"Git repository",installing:"Installing",preset:"Project preset",projectName:"Project name"},Nu=p(({step:e})=>w(h,{children:[m(h,{color:I,children:"\u2727 "}),m(h,{color:K,children:Du[e]})]}),"WizardTitle"),Lu=p(({onBack:e,onDone:t,onExit:r,onStepChange:s})=>{const[a,o]=N("preset"),[i,n]=N(""),[c,d]=N(null),[u,f]=N(null),[g,z]=N(null),[k,x]=N(null),[O,X]=N(null),[oe,ge]=N("");Te(()=>{a==="done"&&t()},[a,t]);const Q=ne(()=>Tu(),[]),L=ne(()=>{const _=[{description:"REST API with standard NestJS modules and structure",name:"Basic NestJS API"},{description:"Microservice support with gateway routing",name:"API Gateway"}];return Q?_.push({description:Pu(Q),name:"Last Used"}):_.push({description:"",disabled:!0,name:"Last Used"}),_},[Q]),[re,H]=N(ds),ke=ne(()=>{const _=new Set;return u==="no"&&(_.add("initialize-git"),_.add("initial-commit")),re.installDependencies==="no"&&_.add("install-dependencies"),(re.formatter==="none"||re.installDependencies==="no")&&(_.add("setup-linter"),_.add("run-formatter")),(u==="no"||_.has("run-formatter"))&&_.add("formatter-commit"),re.addons.includes("agent-skills")||_.add("install-agent-skills"),[..._]},[u,re]),R=$(()=>{switch(a){case"projectName":{o("preset"),s?.("preset"),d(null);return}case"initGit":{o("projectName"),s?.("projectName");return}default:e()}},[e,a,s]),M=$(_=>{if(_.name==="Last Used"&&Q){const{projectName:ze,initGit:Le,...je}=Q;H(je)}else _.name==="API Gateway"?H({...ds,architecture:"nest-gateway",projectType:"monorepo"}):H(ds);o("projectName"),s?.("projectName")},[Q,s]),W=$(_=>{n(_),d(xt(_))},[]),ee=$(()=>{const _=xt(i);if(_){d(_);return}o("initGit"),s?.("initGit")},[i,s]),se=$(async _=>{f(_);const ze=Ce(i),Le=Zt(ze);ge(Le),o("installing"),s?.("installing");const je={...re,initGit:_,projectName:ze};try{const D=await Uo(je,{onInstallProgress:p(Re=>{X(Re)},"onInstallProgress"),onStageChange:p(Re=>{x(Re)},"onStageChange")});z({isError:!D.success,message:D.message}),D.success&&Mo(je)}catch(D){z({isError:!0,message:`Error: ${D instanceof Error?D.message:String(D)}`})}},[i,re,s]);hs(()=>{g&&!g.isError&&(o("done"),s?.("done"))},[g,s]),Me((_,ze)=>{if(ze.ctrl&&_==="c"){r();return}if(ze.ctrl&&_==="b"&&a!=="done"){R();return}a==="done"&&ze.return&&r()});const ye=ne(()=>a==="projectName"?"confirm":"select",[a]),be=a!=="installing"&&a!=="done";return w(q,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[be?w(V,{children:[m(Fo,{}),m(Ve,{}),m(q,{height:1}),m(Nu,{step:a}),m(q,{height:2})]}):null,p(()=>{switch(a){case"preset":return m($u,{onSelect:M,options:L});case"projectName":return m(Ts,{error:c,onChange:W,onSubmit:ee,value:i});case"initGit":return m(Ze,{onConfirm:se,options:Ds,prompt:"Initialize a git repository?"});case"installing":return w(q,{flexDirection:"column",children:[m(Ss,{currentStage:k,generationMessage:g?.message??"Scaffolding your project",installProgress:O,isError:g?.isError??!1,skippedStages:ke}),g?.isError?m(q,{marginTop:1,children:w(h,{color:C,children:["Press ",m(h,{color:I,children:"Enter"})," to go back to Summary and retry, or ",m(h,{color:C,children:"Ctrl+B"})," to go back"]})}):null]});case"done":{const _=Ce(i);return m(xs,{architecture:re.architecture||"nest-api",projectName:_,packageManager:re.packageManager||"pnpm",dependenciesInstalled:re.installDependencies==="yes",isGitInitialized:u==="yes",outputDir:oe})}default:return null}},"renderStep")(),m(q,{flexGrow:1}),be?w(V,{children:[m(Ve,{}),m(q,{height:1}),m(nr,{action:ye,showBack:!0})]}):null]})},"ProjectPresetWizardScreen"),Wt=[{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"}],Mu=p(({onSelect:e})=>{const[t,r]=N(0),s=$(()=>{const i=Wt[t]??null;i?.disabled||e(t,i)},[e,t]),a=[];for(let i=0;i<Wt.length;i+=1)Wt[i].disabled||a.push(i);const o=a.indexOf(t);return St((i,n)=>{if(n.upArrow||i==="k"){const c=a[o-1];c!==void 0&&r(c)}else if(n.downArrow||i==="j"){const c=a[o+1];c!==void 0&&r(c)}else n.return&&s()}),w(q,{flexDirection:"column",children:[m(h,{color:C,children:" What would you like to do?"}),m(q,{marginTop:1,flexDirection:"column",rowGap:1,children:Wt.map((i,n)=>m(h,{children:n===t&&!i.disabled?w(V,{children:[m(h,{color:I,children:"> "}),m(h,{color:I,children:i.name})]}):m(h,{color:Oe,children:` ${i.name}`})},i.name))})]})},"MainMenu"),Uu=1440*60*1e3,Gu=3e3,Bo=qe.string().max(128).refine(e=>pn(e)!==null),Fu=qe.object({checkedAt:qe.number().finite(),version:Bo}),Bu=qe.object({version:Bo}),Ju=p(()=>Y(process.env.XDG_CACHE_HOME??(process.platform==="win32"?process.env.LOCALAPPDATA??Y(wt(),"AppData","Local"):Y(wt(),".cache")),"nest-arch","update.json"),"cachePath");async function Hu(e){try{const t=Ju();let r;try{const s=Fu.parse(JSON.parse(await Se(t,"utf-8"))),a=Date.now()-s.checkedAt;a>=0&&a<Uu&&(r=s.version)}catch{}if(!r){const s=await fetch("https://registry.npmjs.org/@nest-arch%2Ftui/latest",{signal:AbortSignal.timeout(Gu)});if(!s.ok)return null;r=Bu.parse(await s.json()).version;try{await en(tn(t),{recursive:!0}),await xe(t,JSON.stringify({checkedAt:Date.now(),version:r}),"utf-8")}catch{}}return ln(r,e)?r:null}catch{return null}}p(Hu,"checkForUpdate");let Jo;const Qu=p(()=>{const[e,t]=N(null);return Te(()=>{let r=!0;return p(async()=>{Jo??=Hu(Ge);const a=await Jo;r&&t(a)},"check")(),()=>{r=!1}},[]),e?w(q,{flexDirection:"column",marginTop:1,children:[w(h,{color:Ie,children:["Update available: ",Ge," \u2192 v",e]}),m(h,{color:C,children:"Run: npx @nest-arch/tui@latest"}),m(h,{color:C,children:"Global install: npm install -g @nest-arch/tui@latest"})]}):null},"UpdateNotice"),Vu=p(()=>w(h,{children:[m(h,{color:I,children:"\u2727 "}),m(h,{color:K,children:" Welcome to "}),m(h,{color:I,children:"Nest Arch"}),m(h,{color:K,children:" \u2013 Let's build something amazing."})]}),"WelcomeMessage"),Zu=p(({onCreateProject:e,onExit:t,onUsePreset:r})=>{const s=$(async()=>{const o="https://nest-arch-web-web.vercel.app/";try{await nn(o,{wait:!1})}catch{}},[]),a=$((o,i)=>{i?.name==="Exit"?t():i?.name==="Create a new NestJS project"?e():i?.name==="Starter templates"?r():i?.name==="Documentation"&&s()},[e,t,r,s]);return Me((o,i)=>{i.ctrl&&o==="c"&&t()}),w(q,{flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:[m(Fo,{}),m(Ve,{}),m(q,{height:1}),m(Vu,{}),m(Qu,{}),m(q,{height:2}),m(Mu,{onSelect:a}),m(q,{flexGrow:1}),m(Ve,{borderTop:!1}),m(q,{height:1}),m(nr,{})]})},"WelcomeScreen"),Wu=p(({onDone:e})=>{const[t,r]=N("welcome"),{stdout:s}=sr(),{exit:a}=Zo(),[o,i]=N(s?.rows??24);Te(()=>{if(!s)return;const g=p(()=>{i(s.rows)},"handleResize");return s.on("resize",g),()=>{s.off("resize",g)}},[s]);const n=$(()=>{a()},[a]),c=$(()=>{r("preset-wizard")},[]),d=$(()=>{r("create-wizard")},[]),u=$(()=>{r("welcome")},[]);return m(q,{height:o,flexDirection:"column",children:p(()=>t==="create-wizard"?m(Iu,{onBack:u,onDone:e,onExit:n}):t==="preset-wizard"?m(Lu,{onBack:u,onDone:e,onExit:n}):m(Zu,{onCreateProject:d,onExit:n,onUsePreset:c}),"renderScreen")()})},"App");async function Ku(){process.stdout.write("\x1B[?1049h");let e=!1;try{await Vo(m(Wu,{onDone:p(()=>{process.stdout.write("\x1B[?1049l"),e=!0},"onDone")})).waitUntilExit()}finally{e||process.stdout.write("\x1B[?1049l")}}p(Ku,"main");try{await Ku()}catch(e){console.error("Error:",e),process.exit(1)}