nestjs-ddd-cli 2.2.0 → 3.2.1

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 (254) hide show
  1. package/README.md +247 -408
  2. package/ddd.schema.json +111 -0
  3. package/dist/commands/aggregate-validator.d.ts +9 -0
  4. package/dist/commands/aggregate-validator.js +953 -0
  5. package/dist/commands/aggregate-validator.js.map +1 -0
  6. package/dist/commands/ai-assist.d.ts +8 -0
  7. package/dist/commands/ai-assist.js +337 -0
  8. package/dist/commands/ai-assist.js.map +1 -0
  9. package/dist/commands/api-contracts.d.ts +9 -0
  10. package/dist/commands/api-contracts.js +1368 -0
  11. package/dist/commands/api-contracts.js.map +1 -0
  12. package/dist/commands/api-docs.d.ts +8 -0
  13. package/dist/commands/api-docs.js +408 -0
  14. package/dist/commands/api-docs.js.map +1 -0
  15. package/dist/commands/api-versioning.d.ts +11 -0
  16. package/dist/commands/api-versioning.js +643 -0
  17. package/dist/commands/api-versioning.js.map +1 -0
  18. package/dist/commands/audit-logging.d.ts +9 -0
  19. package/dist/commands/audit-logging.js +1129 -0
  20. package/dist/commands/audit-logging.js.map +1 -0
  21. package/dist/commands/batch-generate.d.ts +10 -0
  22. package/dist/commands/batch-generate.js +405 -0
  23. package/dist/commands/batch-generate.js.map +1 -0
  24. package/dist/commands/caching-strategies.d.ts +9 -0
  25. package/dist/commands/caching-strategies.js +874 -0
  26. package/dist/commands/caching-strategies.js.map +1 -0
  27. package/dist/commands/code-analyzer.d.ts +42 -0
  28. package/dist/commands/code-analyzer.js +474 -0
  29. package/dist/commands/code-analyzer.js.map +1 -0
  30. package/dist/commands/database-seeding.d.ts +6 -0
  31. package/dist/commands/database-seeding.js +621 -0
  32. package/dist/commands/database-seeding.js.map +1 -0
  33. package/dist/commands/db-optimization.d.ts +7 -0
  34. package/dist/commands/db-optimization.js +687 -0
  35. package/dist/commands/db-optimization.js.map +1 -0
  36. package/dist/commands/dependency-graph.d.ts +6 -0
  37. package/dist/commands/dependency-graph.js +329 -0
  38. package/dist/commands/dependency-graph.js.map +1 -0
  39. package/dist/commands/doctor-enhanced.d.ts +22 -0
  40. package/dist/commands/doctor-enhanced.js +543 -0
  41. package/dist/commands/doctor-enhanced.js.map +1 -0
  42. package/dist/commands/doctor.d.ts +4 -0
  43. package/dist/commands/doctor.js +151 -0
  44. package/dist/commands/doctor.js.map +1 -0
  45. package/dist/commands/env-manager.d.ts +6 -0
  46. package/dist/commands/env-manager.js +419 -0
  47. package/dist/commands/env-manager.js.map +1 -0
  48. package/dist/commands/event-sourcing-full.d.ts +10 -0
  49. package/dist/commands/event-sourcing-full.js +1107 -0
  50. package/dist/commands/event-sourcing-full.js.map +1 -0
  51. package/dist/commands/feature-flags.d.ts +9 -0
  52. package/dist/commands/feature-flags.js +824 -0
  53. package/dist/commands/feature-flags.js.map +1 -0
  54. package/dist/commands/filter-dsl.d.ts +10 -0
  55. package/dist/commands/filter-dsl.js +1407 -0
  56. package/dist/commands/filter-dsl.js.map +1 -0
  57. package/dist/commands/generate-all.js +485 -32
  58. package/dist/commands/generate-all.js.map +1 -1
  59. package/dist/commands/generate-deployment.d.ts +8 -0
  60. package/dist/commands/generate-deployment.js +746 -0
  61. package/dist/commands/generate-deployment.js.map +1 -0
  62. package/dist/commands/generate-domain-service.d.ts +14 -0
  63. package/dist/commands/generate-domain-service.js +796 -0
  64. package/dist/commands/generate-domain-service.js.map +1 -0
  65. package/dist/commands/generate-entity.js +82 -24
  66. package/dist/commands/generate-entity.js.map +1 -1
  67. package/dist/commands/generate-from-schema.d.ts +56 -0
  68. package/dist/commands/generate-from-schema.js +222 -0
  69. package/dist/commands/generate-from-schema.js.map +1 -0
  70. package/dist/commands/generate-orchestrator.d.ts +14 -0
  71. package/dist/commands/generate-orchestrator.js +887 -0
  72. package/dist/commands/generate-orchestrator.js.map +1 -0
  73. package/dist/commands/generate-repository.d.ts +14 -0
  74. package/dist/commands/generate-repository.js +1019 -0
  75. package/dist/commands/generate-repository.js.map +1 -0
  76. package/dist/commands/generate-shared.d.ts +4 -0
  77. package/dist/commands/generate-shared.js +388 -0
  78. package/dist/commands/generate-shared.js.map +1 -0
  79. package/dist/commands/generate-value-object.d.ts +32 -0
  80. package/dist/commands/generate-value-object.js +700 -0
  81. package/dist/commands/generate-value-object.js.map +1 -0
  82. package/dist/commands/graphql-subscriptions.d.ts +6 -0
  83. package/dist/commands/graphql-subscriptions.js +607 -0
  84. package/dist/commands/graphql-subscriptions.js.map +1 -0
  85. package/dist/commands/graphql-types.d.ts +5 -0
  86. package/dist/commands/graphql-types.js +423 -0
  87. package/dist/commands/graphql-types.js.map +1 -0
  88. package/dist/commands/health-probes-advanced.d.ts +6 -0
  89. package/dist/commands/health-probes-advanced.js +655 -0
  90. package/dist/commands/health-probes-advanced.js.map +1 -0
  91. package/dist/commands/i18n-setup.d.ts +10 -0
  92. package/dist/commands/i18n-setup.js +677 -0
  93. package/dist/commands/i18n-setup.js.map +1 -0
  94. package/dist/commands/init-config.d.ts +6 -0
  95. package/dist/commands/init-config.js +370 -0
  96. package/dist/commands/init-config.js.map +1 -0
  97. package/dist/commands/init-project.js +56 -6
  98. package/dist/commands/init-project.js.map +1 -1
  99. package/dist/commands/interactive-scaffold.d.ts +5 -0
  100. package/dist/commands/interactive-scaffold.js +271 -0
  101. package/dist/commands/interactive-scaffold.js.map +1 -0
  102. package/dist/commands/metrics-prometheus.d.ts +6 -0
  103. package/dist/commands/metrics-prometheus.js +681 -0
  104. package/dist/commands/metrics-prometheus.js.map +1 -0
  105. package/dist/commands/migration-engine.d.ts +6 -0
  106. package/dist/commands/migration-engine.js +446 -0
  107. package/dist/commands/migration-engine.js.map +1 -0
  108. package/dist/commands/migration.d.ts +12 -0
  109. package/dist/commands/migration.js +484 -0
  110. package/dist/commands/migration.js.map +1 -0
  111. package/dist/commands/monorepo.d.ts +8 -0
  112. package/dist/commands/monorepo.js +483 -0
  113. package/dist/commands/monorepo.js.map +1 -0
  114. package/dist/commands/multi-database.d.ts +5 -0
  115. package/dist/commands/multi-database.js +439 -0
  116. package/dist/commands/multi-database.js.map +1 -0
  117. package/dist/commands/observability-tracing.d.ts +10 -0
  118. package/dist/commands/observability-tracing.js +740 -0
  119. package/dist/commands/observability-tracing.js.map +1 -0
  120. package/dist/commands/openapi-export.d.ts +8 -0
  121. package/dist/commands/openapi-export.js +359 -0
  122. package/dist/commands/openapi-export.js.map +1 -0
  123. package/dist/commands/perf-analyzer.d.ts +8 -0
  124. package/dist/commands/perf-analyzer.js +423 -0
  125. package/dist/commands/perf-analyzer.js.map +1 -0
  126. package/dist/commands/rate-limiting.d.ts +10 -0
  127. package/dist/commands/rate-limiting.js +953 -0
  128. package/dist/commands/rate-limiting.js.map +1 -0
  129. package/dist/commands/recipe-plugin.d.ts +56 -0
  130. package/dist/commands/recipe-plugin.js +315 -0
  131. package/dist/commands/recipe-plugin.js.map +1 -0
  132. package/dist/commands/recipe.d.ts +6 -0
  133. package/dist/commands/recipe.js +3941 -0
  134. package/dist/commands/recipe.js.map +1 -0
  135. package/dist/commands/recipes/elasticsearch.recipe.d.ts +1 -0
  136. package/dist/commands/recipes/elasticsearch.recipe.js +761 -0
  137. package/dist/commands/recipes/elasticsearch.recipe.js.map +1 -0
  138. package/dist/commands/recipes/event-sourcing.recipe.d.ts +1 -0
  139. package/dist/commands/recipes/event-sourcing.recipe.js +889 -0
  140. package/dist/commands/recipes/event-sourcing.recipe.js.map +1 -0
  141. package/dist/commands/recipes/index.d.ts +7 -0
  142. package/dist/commands/recipes/index.js +24 -0
  143. package/dist/commands/recipes/index.js.map +1 -0
  144. package/dist/commands/recipes/message-queue.recipe.d.ts +1 -0
  145. package/dist/commands/recipes/message-queue.recipe.js +706 -0
  146. package/dist/commands/recipes/message-queue.recipe.js.map +1 -0
  147. package/dist/commands/recipes/middleware.recipe.d.ts +1 -0
  148. package/dist/commands/recipes/middleware.recipe.js +383 -0
  149. package/dist/commands/recipes/middleware.recipe.js.map +1 -0
  150. package/dist/commands/recipes/multi-tenancy.recipe.d.ts +1 -0
  151. package/dist/commands/recipes/multi-tenancy.recipe.js +520 -0
  152. package/dist/commands/recipes/multi-tenancy.recipe.js.map +1 -0
  153. package/dist/commands/recipes/oauth2.recipe.d.ts +1 -0
  154. package/dist/commands/recipes/oauth2.recipe.js +472 -0
  155. package/dist/commands/recipes/oauth2.recipe.js.map +1 -0
  156. package/dist/commands/recipes/websocket.recipe.d.ts +1 -0
  157. package/dist/commands/recipes/websocket.recipe.js +453 -0
  158. package/dist/commands/recipes/websocket.recipe.js.map +1 -0
  159. package/dist/commands/resilience-patterns.d.ts +13 -0
  160. package/dist/commands/resilience-patterns.js +1029 -0
  161. package/dist/commands/resilience-patterns.js.map +1 -0
  162. package/dist/commands/security-patterns.d.ts +11 -0
  163. package/dist/commands/security-patterns.js +2233 -0
  164. package/dist/commands/security-patterns.js.map +1 -0
  165. package/dist/commands/template-debug.d.ts +27 -0
  166. package/dist/commands/template-debug.js +388 -0
  167. package/dist/commands/template-debug.js.map +1 -0
  168. package/dist/commands/test-factory-full.d.ts +9 -0
  169. package/dist/commands/test-factory-full.js +1570 -0
  170. package/dist/commands/test-factory-full.js.map +1 -0
  171. package/dist/commands/test-scaffold.d.ts +7 -0
  172. package/dist/commands/test-scaffold.js +621 -0
  173. package/dist/commands/test-scaffold.js.map +1 -0
  174. package/dist/index.js +1088 -0
  175. package/dist/index.js.map +1 -1
  176. package/dist/templates/ai-context/CLAUDE.md.hbs +158 -0
  177. package/dist/templates/ai-context/conventions.md.hbs +154 -0
  178. package/dist/templates/command/create-command.hbs +6 -14
  179. package/dist/templates/command/delete-command.hbs +19 -0
  180. package/dist/templates/command/update-command.hbs +24 -0
  181. package/dist/templates/controller/controller.hbs +64 -17
  182. package/dist/templates/dto/create-dto.hbs +29 -5
  183. package/dist/templates/dto/filter-dto.hbs +52 -0
  184. package/dist/templates/dto/filter-query.dto.hbs +148 -0
  185. package/dist/templates/dto/paginated-response.dto.hbs +29 -0
  186. package/dist/templates/dto/pagination-query.dto.hbs +30 -0
  187. package/dist/templates/dto/response-dto.hbs +38 -0
  188. package/dist/templates/dto/update-dto.hbs +11 -0
  189. package/dist/templates/entity/entity.hbs +32 -1
  190. package/dist/templates/event/domain-event.hbs +33 -7
  191. package/dist/templates/event/event-handler.hbs +40 -0
  192. package/dist/templates/exception/base-exceptions.hbs +69 -0
  193. package/dist/templates/exception/entity-not-found.exception.hbs +7 -0
  194. package/dist/templates/mapper/mapper.hbs +49 -24
  195. package/dist/templates/module/module.hbs +34 -10
  196. package/dist/templates/orm-entity/orm-entity.hbs +63 -12
  197. package/dist/templates/prisma/prisma-mapper.hbs +71 -0
  198. package/dist/templates/prisma/prisma-repository.hbs +114 -0
  199. package/dist/templates/prisma/prisma-schema.hbs +20 -0
  200. package/dist/templates/prisma/prisma-service.hbs +51 -0
  201. package/dist/templates/query/get-all.query.hbs +50 -0
  202. package/dist/templates/query/get-by-id.query.hbs +31 -0
  203. package/dist/templates/repository/repository.hbs +55 -13
  204. package/dist/templates/resolver/graphql-input.hbs +54 -0
  205. package/dist/templates/resolver/graphql-type.hbs +58 -0
  206. package/dist/templates/resolver/pagination-args.hbs +33 -0
  207. package/dist/templates/resolver/resolver.hbs +62 -0
  208. package/dist/templates/shared/prisma-query-builder.util.hbs +189 -0
  209. package/dist/templates/shared/query-builder.util.hbs +218 -0
  210. package/dist/templates/test/controller.spec.hbs +124 -0
  211. package/dist/templates/test/repository.spec.hbs +158 -0
  212. package/dist/templates/test/usecase.spec.hbs +116 -0
  213. package/dist/templates/usecase/create-usecase.hbs +19 -7
  214. package/dist/templates/usecase/delete-usecase.hbs +17 -0
  215. package/dist/templates/usecase/update-usecase.hbs +31 -0
  216. package/dist/utils/config.utils.d.ts +45 -0
  217. package/dist/utils/config.utils.js +211 -0
  218. package/dist/utils/config.utils.js.map +1 -0
  219. package/dist/utils/error.utils.d.ts +145 -0
  220. package/dist/utils/error.utils.js +422 -0
  221. package/dist/utils/error.utils.js.map +1 -0
  222. package/dist/utils/field.utils.d.ts +54 -0
  223. package/dist/utils/field.utils.js +389 -0
  224. package/dist/utils/field.utils.js.map +1 -0
  225. package/dist/utils/file.utils.d.ts +19 -8
  226. package/dist/utils/file.utils.js +135 -4
  227. package/dist/utils/file.utils.js.map +1 -1
  228. package/dist/utils/idempotency.utils.d.ts +123 -0
  229. package/dist/utils/idempotency.utils.js +444 -0
  230. package/dist/utils/idempotency.utils.js.map +1 -0
  231. package/dist/utils/naming.utils.js +26 -3
  232. package/dist/utils/naming.utils.js.map +1 -1
  233. package/dist/utils/performance.utils.d.ts +37 -0
  234. package/dist/utils/performance.utils.js +158 -0
  235. package/dist/utils/performance.utils.js.map +1 -0
  236. package/dist/utils/relation.utils.d.ts +92 -0
  237. package/dist/utils/relation.utils.js +388 -0
  238. package/dist/utils/relation.utils.js.map +1 -0
  239. package/dist/utils/rollback.utils.d.ts +49 -0
  240. package/dist/utils/rollback.utils.js +306 -0
  241. package/dist/utils/rollback.utils.js.map +1 -0
  242. package/dist/utils/schema.utils.d.ts +123 -0
  243. package/dist/utils/schema.utils.js +419 -0
  244. package/dist/utils/schema.utils.js.map +1 -0
  245. package/dist/utils/security.utils.d.ts +57 -0
  246. package/dist/utils/security.utils.js +315 -0
  247. package/dist/utils/security.utils.js.map +1 -0
  248. package/dist/utils/template-engine.utils.d.ts +80 -0
  249. package/dist/utils/template-engine.utils.js +463 -0
  250. package/dist/utils/template-engine.utils.js.map +1 -0
  251. package/dist/utils/validation-registry.utils.d.ts +160 -0
  252. package/dist/utils/validation-registry.utils.js +526 -0
  253. package/dist/utils/validation-registry.utils.js.map +1 -0
  254. package/package.json +3 -1
@@ -0,0 +1,453 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.applyWebSocketRecipe = applyWebSocketRecipe;
40
+ const path = __importStar(require("path"));
41
+ const chalk_1 = __importDefault(require("chalk"));
42
+ const file_utils_1 = require("../../utils/file.utils");
43
+ async function applyWebSocketRecipe(basePath) {
44
+ const sharedPath = path.join(basePath, 'src/shared');
45
+ const wsPath = path.join(sharedPath, 'websocket');
46
+ await (0, file_utils_1.ensureDir)(wsPath);
47
+ await (0, file_utils_1.ensureDir)(path.join(wsPath, 'gateways'));
48
+ await (0, file_utils_1.ensureDir)(path.join(wsPath, 'decorators'));
49
+ await (0, file_utils_1.ensureDir)(path.join(wsPath, 'guards'));
50
+ // Base Gateway
51
+ const baseGatewayContent = `import {
52
+ WebSocketGateway,
53
+ WebSocketServer,
54
+ OnGatewayInit,
55
+ OnGatewayConnection,
56
+ OnGatewayDisconnect,
57
+ SubscribeMessage,
58
+ MessageBody,
59
+ ConnectedSocket,
60
+ } from "@nestjs/websockets";
61
+ import { Logger } from "@nestjs/common";
62
+ import { Server, Socket } from "socket.io";
63
+
64
+ export interface WsClient extends Socket {
65
+ userId?: string;
66
+ tenantId?: string;
67
+ rooms: Set<string>;
68
+ }
69
+
70
+ @WebSocketGateway({
71
+ cors: {
72
+ origin: process.env.CORS_ORIGIN || "*",
73
+ credentials: true,
74
+ },
75
+ namespace: "/",
76
+ transports: ["websocket", "polling"],
77
+ })
78
+ export class BaseGateway
79
+ implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
80
+ {
81
+ @WebSocketServer()
82
+ server: Server;
83
+
84
+ protected readonly logger = new Logger(BaseGateway.name);
85
+ protected clients: Map<string, WsClient> = new Map();
86
+ protected userSockets: Map<string, Set<string>> = new Map();
87
+
88
+ afterInit(server: Server) {
89
+ this.logger.log("WebSocket Gateway initialized");
90
+ }
91
+
92
+ handleConnection(client: WsClient) {
93
+ this.logger.log(\`Client connected: \${client.id}\`);
94
+ this.clients.set(client.id, client);
95
+ }
96
+
97
+ handleDisconnect(client: WsClient) {
98
+ this.logger.log(\`Client disconnected: \${client.id}\`);
99
+ this.clients.delete(client.id);
100
+
101
+ // Remove from user sockets mapping
102
+ if (client.userId) {
103
+ const userSockets = this.userSockets.get(client.userId);
104
+ if (userSockets) {
105
+ userSockets.delete(client.id);
106
+ if (userSockets.size === 0) {
107
+ this.userSockets.delete(client.userId);
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Associate a socket with a user ID
115
+ */
116
+ protected associateUser(client: WsClient, userId: string) {
117
+ client.userId = userId;
118
+
119
+ if (!this.userSockets.has(userId)) {
120
+ this.userSockets.set(userId, new Set());
121
+ }
122
+ this.userSockets.get(userId)!.add(client.id);
123
+ }
124
+
125
+ /**
126
+ * Send event to specific user (all their connected sockets)
127
+ */
128
+ protected sendToUser(userId: string, event: string, data: any) {
129
+ const sockets = this.userSockets.get(userId);
130
+ if (sockets) {
131
+ for (const socketId of sockets) {
132
+ this.server.to(socketId).emit(event, data);
133
+ }
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Send event to all users in a room
139
+ */
140
+ protected sendToRoom(room: string, event: string, data: any) {
141
+ this.server.to(room).emit(event, data);
142
+ }
143
+
144
+ /**
145
+ * Broadcast to all connected clients
146
+ */
147
+ protected broadcast(event: string, data: any, excludeClient?: string) {
148
+ if (excludeClient) {
149
+ this.server.except(excludeClient).emit(event, data);
150
+ } else {
151
+ this.server.emit(event, data);
152
+ }
153
+ }
154
+ }
155
+ `;
156
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'gateways/base.gateway.ts'), baseGatewayContent);
157
+ // Events Gateway
158
+ const eventsGatewayContent = `import {
159
+ SubscribeMessage,
160
+ MessageBody,
161
+ ConnectedSocket,
162
+ } from "@nestjs/websockets";
163
+ import { UseGuards } from "@nestjs/common";
164
+ import { BaseGateway, WsClient } from "./base.gateway";
165
+ import { WsJwtGuard } from "../guards/ws-jwt.guard";
166
+
167
+ export class EventsGateway extends BaseGateway {
168
+ @UseGuards(WsJwtGuard)
169
+ @SubscribeMessage("authenticate")
170
+ handleAuthenticate(
171
+ @ConnectedSocket() client: WsClient,
172
+ @MessageBody() data: { userId: string }
173
+ ) {
174
+ this.associateUser(client, data.userId);
175
+ return { event: "authenticated", data: { success: true } };
176
+ }
177
+
178
+ @SubscribeMessage("join_room")
179
+ handleJoinRoom(
180
+ @ConnectedSocket() client: WsClient,
181
+ @MessageBody() data: { room: string }
182
+ ) {
183
+ client.join(data.room);
184
+ client.rooms.add(data.room);
185
+ this.logger.log(\`Client \${client.id} joined room \${data.room}\`);
186
+
187
+ // Notify others in room
188
+ client.to(data.room).emit("user_joined", {
189
+ userId: client.userId,
190
+ room: data.room,
191
+ });
192
+
193
+ return { event: "joined_room", data: { room: data.room } };
194
+ }
195
+
196
+ @SubscribeMessage("leave_room")
197
+ handleLeaveRoom(
198
+ @ConnectedSocket() client: WsClient,
199
+ @MessageBody() data: { room: string }
200
+ ) {
201
+ client.leave(data.room);
202
+ client.rooms.delete(data.room);
203
+
204
+ // Notify others in room
205
+ client.to(data.room).emit("user_left", {
206
+ userId: client.userId,
207
+ room: data.room,
208
+ });
209
+
210
+ return { event: "left_room", data: { room: data.room } };
211
+ }
212
+
213
+ @SubscribeMessage("message")
214
+ handleMessage(
215
+ @ConnectedSocket() client: WsClient,
216
+ @MessageBody() data: { room?: string; content: string; type?: string }
217
+ ) {
218
+ const message = {
219
+ id: Date.now().toString(),
220
+ userId: client.userId,
221
+ content: data.content,
222
+ type: data.type || "text",
223
+ timestamp: new Date().toISOString(),
224
+ };
225
+
226
+ if (data.room) {
227
+ this.sendToRoom(data.room, "new_message", message);
228
+ } else {
229
+ this.broadcast("new_message", message, client.id);
230
+ }
231
+
232
+ return { event: "message_sent", data: message };
233
+ }
234
+
235
+ @SubscribeMessage("typing")
236
+ handleTyping(
237
+ @ConnectedSocket() client: WsClient,
238
+ @MessageBody() data: { room: string; isTyping: boolean }
239
+ ) {
240
+ client.to(data.room).emit("user_typing", {
241
+ userId: client.userId,
242
+ isTyping: data.isTyping,
243
+ });
244
+ }
245
+
246
+ @SubscribeMessage("ping")
247
+ handlePing(@ConnectedSocket() client: WsClient) {
248
+ return { event: "pong", data: { timestamp: Date.now() } };
249
+ }
250
+ }
251
+ `;
252
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'gateways/events.gateway.ts'), eventsGatewayContent);
253
+ // Presence service
254
+ const presenceServiceContent = `import { Injectable, Logger } from "@nestjs/common";
255
+ import { Server } from "socket.io";
256
+
257
+ export interface UserPresence {
258
+ userId: string;
259
+ status: "online" | "away" | "busy" | "offline";
260
+ lastSeen: Date;
261
+ metadata?: Record<string, any>;
262
+ }
263
+
264
+ @Injectable()
265
+ export class PresenceService {
266
+ private readonly logger = new Logger(PresenceService.name);
267
+ private presence: Map<string, UserPresence> = new Map();
268
+ private server: Server;
269
+
270
+ setServer(server: Server) {
271
+ this.server = server;
272
+ }
273
+
274
+ /**
275
+ * Set user as online
276
+ */
277
+ setOnline(userId: string, metadata?: Record<string, any>) {
278
+ const presence: UserPresence = {
279
+ userId,
280
+ status: "online",
281
+ lastSeen: new Date(),
282
+ metadata,
283
+ };
284
+ this.presence.set(userId, presence);
285
+ this.broadcastPresence(userId, presence);
286
+ }
287
+
288
+ /**
289
+ * Set user as offline
290
+ */
291
+ setOffline(userId: string) {
292
+ const presence = this.presence.get(userId);
293
+ if (presence) {
294
+ presence.status = "offline";
295
+ presence.lastSeen = new Date();
296
+ this.broadcastPresence(userId, presence);
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Update user status
302
+ */
303
+ updateStatus(userId: string, status: UserPresence["status"]) {
304
+ const presence = this.presence.get(userId);
305
+ if (presence) {
306
+ presence.status = status;
307
+ presence.lastSeen = new Date();
308
+ this.broadcastPresence(userId, presence);
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Get user presence
314
+ */
315
+ getPresence(userId: string): UserPresence | undefined {
316
+ return this.presence.get(userId);
317
+ }
318
+
319
+ /**
320
+ * Get all online users
321
+ */
322
+ getOnlineUsers(): UserPresence[] {
323
+ return Array.from(this.presence.values()).filter(
324
+ (p) => p.status !== "offline"
325
+ );
326
+ }
327
+
328
+ /**
329
+ * Check if user is online
330
+ */
331
+ isOnline(userId: string): boolean {
332
+ const presence = this.presence.get(userId);
333
+ return presence?.status === "online";
334
+ }
335
+
336
+ /**
337
+ * Get presence for multiple users
338
+ */
339
+ getMultiplePresence(userIds: string[]): Map<string, UserPresence> {
340
+ const result = new Map<string, UserPresence>();
341
+ for (const id of userIds) {
342
+ const presence = this.presence.get(id);
343
+ if (presence) {
344
+ result.set(id, presence);
345
+ }
346
+ }
347
+ return result;
348
+ }
349
+
350
+ private broadcastPresence(userId: string, presence: UserPresence) {
351
+ if (this.server) {
352
+ this.server.emit("presence_update", { userId, presence });
353
+ }
354
+ }
355
+ }
356
+ `;
357
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'presence.service.ts'), presenceServiceContent);
358
+ // WS JWT Guard
359
+ const wsJwtGuardContent = `import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
360
+ import { JwtService } from "@nestjs/jwt";
361
+ import { WsException } from "@nestjs/websockets";
362
+ import { Socket } from "socket.io";
363
+
364
+ @Injectable()
365
+ export class WsJwtGuard implements CanActivate {
366
+ constructor(private jwtService: JwtService) {}
367
+
368
+ async canActivate(context: ExecutionContext): Promise<boolean> {
369
+ try {
370
+ const client: Socket = context.switchToWs().getClient();
371
+ const token = this.extractToken(client);
372
+
373
+ if (!token) {
374
+ throw new WsException("Unauthorized: No token provided");
375
+ }
376
+
377
+ const payload = await this.jwtService.verifyAsync(token, {
378
+ secret: process.env.JWT_SECRET,
379
+ });
380
+
381
+ (client as any).userId = payload.sub;
382
+ (client as any).user = payload;
383
+
384
+ return true;
385
+ } catch (error) {
386
+ throw new WsException("Unauthorized: Invalid token");
387
+ }
388
+ }
389
+
390
+ private extractToken(client: Socket): string | undefined {
391
+ // Try auth header
392
+ const authHeader = client.handshake.headers.authorization;
393
+ if (authHeader?.startsWith("Bearer ")) {
394
+ return authHeader.slice(7);
395
+ }
396
+
397
+ // Try query param
398
+ const queryToken = client.handshake.query.token;
399
+ if (queryToken) {
400
+ return Array.isArray(queryToken) ? queryToken[0] : queryToken;
401
+ }
402
+
403
+ // Try auth object
404
+ const authToken = (client.handshake.auth as any)?.token;
405
+ if (authToken) {
406
+ return authToken;
407
+ }
408
+
409
+ return undefined;
410
+ }
411
+ }
412
+ `;
413
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'guards/ws-jwt.guard.ts'), wsJwtGuardContent);
414
+ // WebSocket module
415
+ const wsModuleContent = `import { Module, Global } from "@nestjs/common";
416
+ import { JwtModule } from "@nestjs/jwt";
417
+ import { EventsGateway } from "./gateways/events.gateway";
418
+ import { PresenceService } from "./presence.service";
419
+ import { WsJwtGuard } from "./guards/ws-jwt.guard";
420
+
421
+ @Global()
422
+ @Module({
423
+ imports: [
424
+ JwtModule.register({
425
+ secret: process.env.JWT_SECRET,
426
+ signOptions: { expiresIn: "7d" },
427
+ }),
428
+ ],
429
+ providers: [EventsGateway, PresenceService, WsJwtGuard],
430
+ exports: [EventsGateway, PresenceService],
431
+ })
432
+ export class WebSocketModule {}
433
+ `;
434
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'websocket.module.ts'), wsModuleContent);
435
+ // Index exports
436
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'index.ts'), `export * from "./gateways/base.gateway";
437
+ export * from "./gateways/events.gateway";
438
+ export * from "./presence.service";
439
+ export * from "./guards/ws-jwt.guard";
440
+ export * from "./websocket.module";
441
+ `);
442
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'gateways/index.ts'), `export * from "./base.gateway";
443
+ export * from "./events.gateway";
444
+ `);
445
+ await (0, file_utils_1.writeFile)(path.join(wsPath, 'guards/index.ts'), `export * from "./ws-jwt.guard";
446
+ `);
447
+ console.log(chalk_1.default.green(' ✓ Base WebSocket Gateway with room management'));
448
+ console.log(chalk_1.default.green(' ✓ Events Gateway (join/leave rooms, messaging, typing)'));
449
+ console.log(chalk_1.default.green(' ✓ Presence Service (online/offline tracking)'));
450
+ console.log(chalk_1.default.green(' ✓ WebSocket JWT Guard'));
451
+ console.log(chalk_1.default.green(' ✓ WebSocket Module'));
452
+ }
453
+ //# sourceMappingURL=websocket.recipe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.recipe.js","sourceRoot":"","sources":["../../../src/commands/recipes/websocket.recipe.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oDAmaC;AAvaD,2CAA6B;AAC7B,kDAA0B;AAC1B,uDAA8D;AAEvD,KAAK,UAAU,oBAAoB,CAAC,QAAgB;IACzD,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,QAA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* Circuit Breaker & Resilience Patterns Generator
3
+ * Implements retry logic, timeout handling, and fallback strategies
4
+ */
5
+ export interface ResilienceOptions {
6
+ path?: string;
7
+ includeCircuitBreaker?: boolean;
8
+ includeRetry?: boolean;
9
+ includeTimeout?: boolean;
10
+ includeFallback?: boolean;
11
+ includeBulkhead?: boolean;
12
+ }
13
+ export declare function setupResiliencePatterns(basePath: string, options?: ResilienceOptions): Promise<void>;