@engjts/nexus 0.1.8 → 0.1.9

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 (205) hide show
  1. package/package.json +1 -1
  2. package/BENCHMARK_REPORT.md +0 -343
  3. package/documentation/01-getting-started.md +0 -240
  4. package/documentation/02-context.md +0 -335
  5. package/documentation/03-routing.md +0 -397
  6. package/documentation/04-middleware.md +0 -483
  7. package/documentation/05-validation.md +0 -514
  8. package/documentation/06-error-handling.md +0 -465
  9. package/documentation/07-performance.md +0 -364
  10. package/documentation/08-adapters.md +0 -470
  11. package/documentation/09-api-reference.md +0 -548
  12. package/documentation/10-examples.md +0 -582
  13. package/documentation/11-deployment.md +0 -477
  14. package/documentation/12-sentry.md +0 -620
  15. package/documentation/13-sentry-data-storage.md +0 -996
  16. package/documentation/14-sentry-data-reference.md +0 -457
  17. package/documentation/15-sentry-summary.md +0 -409
  18. package/documentation/16-alerts-system.md +0 -745
  19. package/documentation/17-alert-adapters.md +0 -696
  20. package/documentation/18-alerts-implementation-summary.md +0 -385
  21. package/documentation/19-class-based-routing.md +0 -840
  22. package/documentation/20-websocket-realtime.md +0 -813
  23. package/documentation/21-cache-system.md +0 -510
  24. package/documentation/22-job-queue.md +0 -772
  25. package/documentation/23-sentry-plugin.md +0 -551
  26. package/documentation/24-testing-utilities.md +0 -1287
  27. package/documentation/25-api-versioning.md +0 -533
  28. package/documentation/26-context-store.md +0 -607
  29. package/documentation/27-dependency-injection.md +0 -329
  30. package/documentation/28-lifecycle-hooks.md +0 -521
  31. package/documentation/29-package-structure.md +0 -196
  32. package/documentation/30-plugin-system.md +0 -414
  33. package/documentation/31-jwt-authentication.md +0 -597
  34. package/documentation/32-cli.md +0 -268
  35. package/documentation/ALERTS-COMPLETE-SUMMARY.md +0 -429
  36. package/documentation/ALERTS-INDEX.md +0 -330
  37. package/documentation/ALERTS-QUICK-REFERENCE.md +0 -286
  38. package/documentation/README.md +0 -178
  39. package/documentation/index.html +0 -34
  40. package/modern_framework_paper.md +0 -1870
  41. package/public/css/style.css +0 -87
  42. package/public/index.html +0 -34
  43. package/public/js/app.js +0 -27
  44. package/src/advanced/cache/InMemoryCacheStore.ts +0 -68
  45. package/src/advanced/cache/MultiTierCache.ts +0 -194
  46. package/src/advanced/cache/RedisCacheStore.ts +0 -341
  47. package/src/advanced/cache/index.ts +0 -5
  48. package/src/advanced/cache/types.ts +0 -40
  49. package/src/advanced/graphql/SimpleDataLoader.ts +0 -42
  50. package/src/advanced/graphql/index.ts +0 -22
  51. package/src/advanced/graphql/server.ts +0 -252
  52. package/src/advanced/graphql/types.ts +0 -42
  53. package/src/advanced/jobs/InMemoryQueueStore.ts +0 -68
  54. package/src/advanced/jobs/JobQueue.ts +0 -556
  55. package/src/advanced/jobs/RedisQueueStore.ts +0 -367
  56. package/src/advanced/jobs/index.ts +0 -5
  57. package/src/advanced/jobs/types.ts +0 -70
  58. package/src/advanced/observability/APMManager.ts +0 -163
  59. package/src/advanced/observability/AlertManager.ts +0 -109
  60. package/src/advanced/observability/MetricRegistry.ts +0 -151
  61. package/src/advanced/observability/ObservabilityCenter.ts +0 -304
  62. package/src/advanced/observability/StructuredLogger.ts +0 -154
  63. package/src/advanced/observability/TracingManager.ts +0 -117
  64. package/src/advanced/observability/adapters.ts +0 -304
  65. package/src/advanced/observability/createObservabilityMiddleware.ts +0 -63
  66. package/src/advanced/observability/index.ts +0 -11
  67. package/src/advanced/observability/types.ts +0 -174
  68. package/src/advanced/playground/extractPathParams.ts +0 -6
  69. package/src/advanced/playground/generateFieldExample.ts +0 -31
  70. package/src/advanced/playground/generatePlaygroundHTML.ts +0 -1956
  71. package/src/advanced/playground/generateSummary.ts +0 -19
  72. package/src/advanced/playground/getTagFromPath.ts +0 -9
  73. package/src/advanced/playground/index.ts +0 -8
  74. package/src/advanced/playground/playground.ts +0 -250
  75. package/src/advanced/playground/types.ts +0 -49
  76. package/src/advanced/playground/zodToExample.ts +0 -16
  77. package/src/advanced/playground/zodToParams.ts +0 -15
  78. package/src/advanced/postman/buildAuth.ts +0 -31
  79. package/src/advanced/postman/buildBody.ts +0 -15
  80. package/src/advanced/postman/buildQueryParams.ts +0 -27
  81. package/src/advanced/postman/buildRequestItem.ts +0 -36
  82. package/src/advanced/postman/buildResponses.ts +0 -11
  83. package/src/advanced/postman/buildUrl.ts +0 -33
  84. package/src/advanced/postman/capitalize.ts +0 -4
  85. package/src/advanced/postman/generateCollection.ts +0 -59
  86. package/src/advanced/postman/generateEnvironment.ts +0 -34
  87. package/src/advanced/postman/generateExampleFromZod.ts +0 -21
  88. package/src/advanced/postman/generateFieldExample.ts +0 -45
  89. package/src/advanced/postman/generateName.ts +0 -20
  90. package/src/advanced/postman/generateUUID.ts +0 -11
  91. package/src/advanced/postman/getTagFromPath.ts +0 -10
  92. package/src/advanced/postman/index.ts +0 -28
  93. package/src/advanced/postman/postman.ts +0 -156
  94. package/src/advanced/postman/slugify.ts +0 -7
  95. package/src/advanced/postman/types.ts +0 -140
  96. package/src/advanced/realtime/index.ts +0 -18
  97. package/src/advanced/realtime/websocket.ts +0 -231
  98. package/src/advanced/sentry/index.ts +0 -1236
  99. package/src/advanced/sentry/types.ts +0 -355
  100. package/src/advanced/static/generateDirectoryListing.ts +0 -47
  101. package/src/advanced/static/generateETag.ts +0 -7
  102. package/src/advanced/static/getMimeType.ts +0 -9
  103. package/src/advanced/static/index.ts +0 -32
  104. package/src/advanced/static/isSafePath.ts +0 -13
  105. package/src/advanced/static/publicDir.ts +0 -21
  106. package/src/advanced/static/serveStatic.ts +0 -225
  107. package/src/advanced/static/spa.ts +0 -24
  108. package/src/advanced/static/types.ts +0 -159
  109. package/src/advanced/swagger/SwaggerGenerator.ts +0 -66
  110. package/src/advanced/swagger/buildOperation.ts +0 -61
  111. package/src/advanced/swagger/buildParameters.ts +0 -61
  112. package/src/advanced/swagger/buildRequestBody.ts +0 -21
  113. package/src/advanced/swagger/buildResponses.ts +0 -54
  114. package/src/advanced/swagger/capitalize.ts +0 -5
  115. package/src/advanced/swagger/convertPath.ts +0 -9
  116. package/src/advanced/swagger/createSwagger.ts +0 -12
  117. package/src/advanced/swagger/generateOperationId.ts +0 -21
  118. package/src/advanced/swagger/generateSpec.ts +0 -105
  119. package/src/advanced/swagger/generateSummary.ts +0 -24
  120. package/src/advanced/swagger/generateSwaggerUI.ts +0 -70
  121. package/src/advanced/swagger/generateThemeCss.ts +0 -53
  122. package/src/advanced/swagger/index.ts +0 -25
  123. package/src/advanced/swagger/swagger.ts +0 -237
  124. package/src/advanced/swagger/types.ts +0 -206
  125. package/src/advanced/swagger/zodFieldToOpenAPI.ts +0 -94
  126. package/src/advanced/swagger/zodSchemaToOpenAPI.ts +0 -50
  127. package/src/advanced/swagger/zodToOpenAPI.ts +0 -22
  128. package/src/advanced/testing/factory.ts +0 -509
  129. package/src/advanced/testing/harness.ts +0 -612
  130. package/src/advanced/testing/index.ts +0 -430
  131. package/src/advanced/testing/load-test.ts +0 -618
  132. package/src/advanced/testing/mock-server.ts +0 -498
  133. package/src/advanced/testing/mock.ts +0 -670
  134. package/src/cli/bin.ts +0 -9
  135. package/src/cli/cli.ts +0 -158
  136. package/src/cli/commands/add.ts +0 -178
  137. package/src/cli/commands/build.ts +0 -73
  138. package/src/cli/commands/create.ts +0 -166
  139. package/src/cli/commands/dev.ts +0 -85
  140. package/src/cli/commands/generate.ts +0 -99
  141. package/src/cli/commands/help.ts +0 -95
  142. package/src/cli/commands/init.ts +0 -91
  143. package/src/cli/commands/version.ts +0 -38
  144. package/src/cli/index.ts +0 -6
  145. package/src/cli/templates/generators.ts +0 -359
  146. package/src/cli/templates/index.ts +0 -680
  147. package/src/cli/utils/exec.ts +0 -52
  148. package/src/cli/utils/file-system.ts +0 -78
  149. package/src/cli/utils/logger.ts +0 -111
  150. package/src/core/adapter.ts +0 -88
  151. package/src/core/application.ts +0 -1453
  152. package/src/core/context-pool.ts +0 -79
  153. package/src/core/context.ts +0 -856
  154. package/src/core/index.ts +0 -94
  155. package/src/core/middleware.ts +0 -272
  156. package/src/core/performance/buffer-pool.ts +0 -108
  157. package/src/core/performance/middleware-optimizer.ts +0 -162
  158. package/src/core/plugin/PluginManager.ts +0 -435
  159. package/src/core/plugin/builder.ts +0 -358
  160. package/src/core/plugin/index.ts +0 -50
  161. package/src/core/plugin/types.ts +0 -214
  162. package/src/core/router/file-router.ts +0 -623
  163. package/src/core/router/index.ts +0 -260
  164. package/src/core/router/radix-tree.ts +0 -242
  165. package/src/core/serializer.ts +0 -397
  166. package/src/core/store/index.ts +0 -30
  167. package/src/core/store/registry.ts +0 -178
  168. package/src/core/store/request-store.ts +0 -240
  169. package/src/core/store/types.ts +0 -233
  170. package/src/core/types.ts +0 -616
  171. package/src/database/adapter.ts +0 -35
  172. package/src/database/adapters/index.ts +0 -1
  173. package/src/database/adapters/mysql.ts +0 -669
  174. package/src/database/database.ts +0 -70
  175. package/src/database/dialect.ts +0 -388
  176. package/src/database/index.ts +0 -12
  177. package/src/database/migrations.ts +0 -86
  178. package/src/database/optimizer.ts +0 -125
  179. package/src/database/query-builder.ts +0 -404
  180. package/src/database/realtime.ts +0 -53
  181. package/src/database/schema.ts +0 -71
  182. package/src/database/transactions.ts +0 -56
  183. package/src/database/types.ts +0 -87
  184. package/src/deployment/cluster.ts +0 -471
  185. package/src/deployment/config.ts +0 -454
  186. package/src/deployment/docker.ts +0 -599
  187. package/src/deployment/graceful-shutdown.ts +0 -373
  188. package/src/deployment/index.ts +0 -56
  189. package/src/index.ts +0 -281
  190. package/src/security/adapter.ts +0 -318
  191. package/src/security/auth/JWTPlugin.ts +0 -234
  192. package/src/security/auth/JWTProvider.ts +0 -316
  193. package/src/security/auth/adapter.ts +0 -12
  194. package/src/security/auth/jwt.ts +0 -234
  195. package/src/security/auth/middleware.ts +0 -188
  196. package/src/security/csrf.ts +0 -220
  197. package/src/security/headers.ts +0 -108
  198. package/src/security/index.ts +0 -60
  199. package/src/security/rate-limit/adapter.ts +0 -7
  200. package/src/security/rate-limit/memory.ts +0 -108
  201. package/src/security/rate-limit/middleware.ts +0 -181
  202. package/src/security/sanitization.ts +0 -75
  203. package/src/security/types.ts +0 -240
  204. package/src/security/utils.ts +0 -52
  205. package/tsconfig.json +0 -39
package/src/core/types.ts DELETED
@@ -1,616 +0,0 @@
1
- /**
2
- * Core type definitions for the Nexus Framework
3
- * Provides type-safe interfaces for requests, responses, middleware, and routing
4
- */
5
-
6
- import { IncomingMessage, ServerResponse } from 'http';
7
- import { ZodSchema } from 'zod';
8
- import { Application } from './application';
9
- import { ContextStore, StoreConstructor, StoreRegistry, RequestStore, RequestStoreConstructor } from './store';
10
- import { JSONSchema, ResponseSchemaConfig, SerializerFunction } from './serializer';
11
-
12
- /**
13
- * HTTP methods supported by the framework
14
- */
15
- export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
16
-
17
- /**
18
- * HTTP headers type-safe wrapper
19
- */
20
- export interface Headers {
21
- [key: string]: string | string[] | undefined;
22
- }
23
-
24
- /**
25
- * Cookie parser and manager
26
- */
27
- export interface Cookies {
28
- get(name: string): string | undefined;
29
- set(name: string, value: string, options?: CookieOptions): void;
30
- delete(name: string): void;
31
- }
32
-
33
- /**
34
- * Cookie configuration options
35
- */
36
- export interface CookieOptions {
37
- maxAge?: number;
38
- expires?: Date;
39
- path?: string;
40
- domain?: string;
41
- secure?: boolean;
42
- httpOnly?: boolean;
43
- sameSite?: 'strict' | 'lax' | 'none';
44
- }
45
-
46
- /**
47
- * Response builder for fluent API
48
- */
49
- export interface ResponseBuilder {
50
- status(code: number): ResponseBuilder;
51
- header(name: string, value: string): ResponseBuilder;
52
- json<T>(data: T): Response;
53
- html(content: string): Response;
54
- text(content: string): Response;
55
- redirect(url: string, status?: number): Response;
56
- stream(readable: NodeJS.ReadableStream): Response;
57
- }
58
-
59
- /**
60
- * Framework response object
61
- */
62
- export interface Response {
63
- statusCode: number;
64
- headers: Headers;
65
- body: any;
66
- stream?: NodeJS.ReadableStream;
67
- }
68
-
69
- /**
70
- * Unified context object containing request and response data
71
- * This replaces the traditional req/res pattern with an immutable context
72
- */
73
- export interface Context {
74
- // Request metadata
75
- method: HTTPMethod;
76
- path: string;
77
- url: URL;
78
-
79
- // Request data
80
- params: Record<string, string>;
81
- query: Record<string, any>;
82
- body: any;
83
- headers: Headers;
84
- cookies: Cookies;
85
-
86
- // Raw Node.js objects for advanced use cases
87
- raw: {
88
- req: IncomingMessage;
89
- res: ServerResponse;
90
- };
91
-
92
- // Response builder
93
- response: ResponseBuilder;
94
-
95
- // Store access
96
- /** Access a registered global store by its class (singleton, persist across requests) */
97
- store<T extends ContextStore<any>>(StoreClass: StoreConstructor<T>): T;
98
-
99
- /** Access a request-scoped store by its class (per-request, disposed after response) */
100
- requestStore<T extends RequestStore<any>>(StoreClass: RequestStoreConstructor<T>): T;
101
-
102
- // Request-scoped data (simple key-value storage)
103
- /** Set a value in request-scoped storage */
104
- set<T = any>(key: string, value: T): void;
105
-
106
- /** Get a value from request-scoped storage */
107
- get<T = any>(key: string): T | undefined;
108
-
109
- // Body methods (for sync access after pre-parsing)
110
- /** Check if body is ready for sync access (no await needed) */
111
- isBodyReady: boolean;
112
-
113
- /** Wait for body to be parsed (internal use, rarely needed by user) */
114
- waitForBody(): Promise<any>;
115
-
116
- /** Async body getter - use for POST/PUT/PATCH if body might not be ready */
117
- getBody<T = any>(): Promise<T>;
118
-
119
- // Utility methods
120
- json<T>(data: T, status?: number): Response;
121
- html(content: string, status?: number): Response;
122
- text(content: string, status?: number): Response;
123
- redirect(url: string, status?: number): Response;
124
- stream(readable: NodeJS.ReadableStream): Response;
125
-
126
- // Custom properties added by middleware
127
- [key: string]: any;
128
- }
129
-
130
- /**
131
- * Next function for middleware chain
132
- */
133
- export type Next<TContext = Context> = (ctx: TContext) => Promise<Response>;
134
-
135
- /**
136
- * Middleware function signature
137
- * Middleware can transform the context and pass it to the next handler
138
- * Now supports optional dependency injection as the third parameter.
139
- *
140
- * @template TIn - Input context type
141
- * @template TOut - Output context type (after transformation)
142
- * @template TDeps - Dependencies type (injected from app.provide())
143
- *
144
- * @example
145
- * ```typescript
146
- * // Simple middleware (no deps)
147
- * const loggerMiddleware: Middleware = async (ctx, next) => {
148
- * console.log(`${ctx.method} ${ctx.path}`);
149
- * return next(ctx);
150
- * };
151
- *
152
- * // Middleware with dependencies
153
- * const authMiddleware: Middleware<Context, Context, { jwt: JWTService; db: Database }> =
154
- * async (ctx, next, { jwt, db }) => {
155
- * const token = ctx.headers.authorization?.replace('Bearer ', '');
156
- * const payload = await jwt.verify(token);
157
- * ctx.user = await db.findUser(payload.userId);
158
- * return next(ctx);
159
- * };
160
- * ```
161
- */
162
- export type Middleware<TIn = Context, TOut = Context, TDeps = any> = (
163
- ctx: TIn,
164
- next: Next<TOut>,
165
- deps: TDeps
166
- ) => Promise<Response>;
167
-
168
- /**
169
- * Route handler function signature
170
- * Handlers can return data directly or a Response object
171
- * Supports both sync and async handlers
172
- */
173
- export type Handler<TContext = Context, TDeps = any> = (
174
- ctx: TContext,
175
- deps: TDeps
176
- ) => Response | any | Promise<Response | any>;
177
-
178
- /**
179
- * Dependency container type
180
- * Maps dependency names to their instances
181
- */
182
- export type DependencyContainer = Record<string, any>;
183
-
184
- /**
185
- * Extract dependency types from container
186
- */
187
- export type ExtractDeps<T extends DependencyContainer, K extends keyof T> = {
188
- [P in K]: T[P];
189
- };
190
-
191
- /**
192
- * Route configuration with dependency injection
193
- */
194
- export interface InjectedRouteConfig<
195
- TContext = Context,
196
- TDeps extends DependencyContainer = DependencyContainer,
197
- TKeys extends keyof TDeps = keyof TDeps
198
- > {
199
- /** Dependencies to inject into handler */
200
- inject?: TKeys[];
201
- /** Route handler with injected dependencies */
202
- handler: (ctx: TContext, deps: Pick<TDeps, TKeys>) => Promise<Response | any>;
203
- /** Middleware chain */
204
- middlewares?: Middleware<any, any>[];
205
- /** Schema validation */
206
- schema?: SchemaConfig;
207
- /** Route metadata */
208
- meta?: RouteMeta;
209
- }
210
-
211
- /**
212
- * Validation error detail from Zod
213
- */
214
- export interface ValidationErrorDetail {
215
- path: (string | number)[];
216
- message: string;
217
- code: string;
218
- }
219
-
220
- /**
221
- * Custom validation error handler
222
- */
223
- export type ValidationErrorHandler = (
224
- errors: ValidationErrorDetail[],
225
- ctx: Context
226
- ) => Response | any;
227
-
228
- /**
229
- * Schema validation configuration
230
- */
231
- export interface SchemaConfig {
232
- params?: ZodSchema;
233
- query?: ZodSchema;
234
- body?: ZodSchema;
235
- headers?: ZodSchema;
236
- /**
237
- * Response schema for fast JSON serialization
238
- * When provided, uses fast-json-stringify for 2-3x faster serialization
239
- *
240
- * @example
241
- * ```typescript
242
- * app.get('/users', {
243
- * schema: {
244
- * response: {
245
- * 200: {
246
- * type: 'array',
247
- * items: {
248
- * type: 'object',
249
- * properties: {
250
- * id: { type: 'number' },
251
- * name: { type: 'string' }
252
- * }
253
- * }
254
- * }
255
- * }
256
- * },
257
- * handler: async (ctx) => users
258
- * });
259
- * ```
260
- */
261
- response?: ResponseSchemaConfig;
262
- onValidationError?: ValidationErrorHandler;
263
- }
264
-
265
- /**
266
- * Route metadata for documentation and API generation
267
- */
268
- export interface RouteMeta {
269
- description?: string;
270
- tags?: string[];
271
- responses?: Record<number, string>;
272
- deprecated?: boolean;
273
- summary?: string;
274
- example?: string;
275
- }
276
-
277
- /**
278
- * Route configuration object
279
- */
280
- export interface RouteConfig<TContext = Context> {
281
- method: HTTPMethod;
282
- path: string;
283
- handler: Handler<TContext>;
284
- middlewares?: Middleware<any, any>[];
285
- schema?: SchemaConfig;
286
- meta?: RouteMeta;
287
- /** Pre-compiled serializer function (internal use) */
288
- _serializer?: Map<number | string, SerializerFunction>;
289
- }
290
-
291
- /**
292
- * Route match result from router
293
- */
294
- export interface RouteMatch {
295
- handler: Handler;
296
- params: Record<string, string>;
297
- middlewares: Middleware[];
298
- schema?: SchemaConfig;
299
- /** Pre-compiled serializer for response (internal use) */
300
- _serializer?: Map<number | string, SerializerFunction>;
301
- }
302
-
303
- /**
304
- * Error handler function signature
305
- */
306
- export type ErrorHandler = (
307
- error: Error,
308
- ctx: Context
309
- ) => Response | Promise<Response>;
310
-
311
- /**
312
- * Application configuration options
313
- */
314
- export interface AppConfig {
315
- // Performance options
316
- contextPoolSize?: number;
317
- enableJIT?: boolean;
318
-
319
- // Error handling
320
- onError?: ErrorHandler;
321
-
322
- // Development options
323
- debug?: boolean;
324
- logRequests?: boolean;
325
- }
326
-
327
- /**
328
- * Plugin interface for extensibility
329
- */
330
- export interface Plugin {
331
- name: string;
332
- version: string;
333
- install: (app: Application) => void | Promise<void>;
334
- }
335
-
336
- /**
337
- * Base interface for class-based route definitions
338
- *
339
- * @example
340
- * ```typescript
341
- * class UserRegister implements RouteBase {
342
- * pathName = '/api/users/register';
343
- *
344
- * schema() {
345
- * return { body: z.object({ email: z.string().email() }) };
346
- * }
347
- *
348
- * meta() {
349
- * return { summary: 'Register user', tags: ['Users'] };
350
- * }
351
- *
352
- * async handler(ctx: Context) {
353
- * return { success: true };
354
- * }
355
- * }
356
- *
357
- * app.post(new UserRegister());
358
- * ```
359
- */
360
- export interface RouteBase<TContext = Context> {
361
- /** The route path (e.g., '/api/users/:id') - Optional for file-based routing */
362
- pathName?: string;
363
-
364
- /**
365
- * HTTP method(s) this route handles - Optional for file-based routing
366
- * When using file-based routing, you can define method handlers (GET, POST, etc.) as methods
367
- */
368
- method?: HTTPMethod | HTTPMethod[];
369
-
370
- /** Optional schema validation */
371
- schema?: () => SchemaConfig;
372
-
373
- /** Optional route metadata for documentation */
374
- meta?: () => RouteMeta;
375
-
376
- /** Optional route-specific middlewares */
377
- middlewares?: () => Middleware<any, any>[];
378
-
379
- /** The route handler (can be omitted if using method-named handlers like GET, POST, etc.) */
380
- handler?: Handler<TContext>;
381
-
382
- /** Method-specific handlers for file-based routing */
383
- GET?: Handler<TContext>;
384
- POST?: Handler<TContext>;
385
- PUT?: Handler<TContext>;
386
- DELETE?: Handler<TContext>;
387
- PATCH?: Handler<TContext>;
388
- HEAD?: Handler<TContext>;
389
- OPTIONS?: Handler<TContext>;
390
- }
391
-
392
- /**
393
- * Abstract base class for class-based routes with REQUIRED handler implementation.
394
- * Use this when you want TypeScript to enforce that the handler method is implemented.
395
- * Also provides lifecycle hooks for request processing and dependency injection.
396
- *
397
- * @example
398
- * ```typescript
399
- * // With dependency injection
400
- * class UserRegister extends Route<Context, { db: Database; cache: Redis }> {
401
- * pathName = '/api/users/register';
402
- *
403
- * // Optional: run before handler (with deps)
404
- * async onBefore(ctx: Context, { db }: { db: Database }) {
405
- * console.log('Before handler, db connected:', db.isConnected);
406
- * }
407
- *
408
- * // Optional: transform response after handler (with deps)
409
- * async onAfter(ctx: Context, result: any, { cache }: { cache: Redis }) {
410
- * await cache.set('last-register', JSON.stringify(result));
411
- * return { ...result, timestamp: Date.now() };
412
- * }
413
- *
414
- * // Optional: custom error handling (with deps)
415
- * async onError(ctx: Context, error: Error, deps) {
416
- * return { error: error.message, code: 'CUSTOM_ERROR' };
417
- * }
418
- *
419
- * // REQUIRED: handler with dependencies
420
- * async handler(ctx: Context, { db, cache }) {
421
- * const user = await db.query('INSERT INTO users...');
422
- * await cache.set(`user:${user.id}`, user);
423
- * return { success: true, user };
424
- * }
425
- * }
426
- *
427
- * app.provide({ db, cache }).post(new UserRegister());
428
- * ```
429
- */
430
- export abstract class Route<TContext = Context, TDeps = any> {
431
- pathName?: string;
432
-
433
- /**
434
- * The main route handler - REQUIRED!
435
- * TypeScript will enforce this is implemented.
436
- * @param ctx - Request context
437
- * @param deps - Injected dependencies from app.provide()
438
- */
439
- abstract handler(ctx: TContext, deps: TDeps): Promise<any> | any;
440
-
441
- // ─────────────────────────────────────────────────────────────────────────
442
- // Helper Methods for cleaner response handling
443
- // ─────────────────────────────────────────────────────────────────────────
444
-
445
- /**
446
- * Return a successful JSON response
447
- * @param data - The response data to send
448
- * @returns Object with success: true merged with data
449
- *
450
- * @example
451
- * ```typescript
452
- * return this.ok({ user: { id: 1, name: 'John' } });
453
- * // Returns: { success: true, user: { id: 1, name: 'John' } }
454
- * ```
455
- */
456
- protected ok<T extends Record<string, any>>(data: T): { success: true } & T {
457
- return { success: true, ...data };
458
- }
459
-
460
- /**
461
- * Return a failed JSON response with status code
462
- * @param ctx - The request context
463
- * @param status - HTTP status code (e.g., 400, 404, 500)
464
- * @param message - Error message
465
- * @param data - Optional additional error data
466
- * @returns Response object with error details
467
- *
468
- * @example
469
- * ```typescript
470
- * return this.fail(ctx, 404, 'User not found');
471
- * // Returns 404 with: { success: false, message: 'User not found' }
472
- *
473
- * return this.fail(ctx, 400, 'Validation failed', { errors: [...] });
474
- * // Returns 400 with: { success: false, message: 'Validation failed', data: { errors: [...] } }
475
- * ```
476
- */
477
- protected fail(ctx: TContext, status: number, message: string, data?: any): Response {
478
- return (ctx as Context).response
479
- .status(status)
480
- .json({ success: false, message, ...(data !== undefined ? { data } : {}) });
481
- }
482
-
483
- /**
484
- * HTTP method(s) this route handles - Optional
485
- * When using file-based routing, you can also define method handlers (GET, POST, etc.)
486
- */
487
- method?: HTTPMethod | HTTPMethod[];
488
-
489
- /**
490
- * Hook: Called BEFORE the handler.
491
- * - Return undefined/void to continue to handler
492
- * - Return a value to skip handler and use that as response
493
- * - Throw an error to trigger onError
494
- * @param ctx - Request context
495
- * @param deps - Injected dependencies from app.provide()
496
- */
497
- onBefore?(ctx: TContext, deps: TDeps): Promise<any | void> | any | void;
498
-
499
- /**
500
- * Hook: Called AFTER the handler completes successfully.
501
- * - Receives the handler result
502
- * - Can transform/modify the response
503
- * - Return the (modified) result
504
- * @param ctx - Request context
505
- * @param result - Handler result
506
- * @param deps - Injected dependencies from app.provide()
507
- */
508
- onAfter?(ctx: TContext, result: any, deps: TDeps): Promise<any> | any;
509
-
510
- /**
511
- * Hook: Called when handler or onBefore throws an error.
512
- * - Can return a custom error response
513
- * - If not defined, error propagates to global error handler
514
- * @param ctx - Request context
515
- * @param error - Error thrown
516
- * @param deps - Injected dependencies from app.provide()
517
- */
518
- onError?(ctx: TContext, error: Error, deps: TDeps): Promise<any> | any;
519
-
520
- /** Optional schema validation */
521
- schema?(): SchemaConfig;
522
-
523
- /** Optional route metadata for documentation */
524
- meta?(): RouteMeta;
525
-
526
- /** Optional route-specific middlewares */
527
- middlewares?(): Middleware<any, any>[];
528
- }
529
-
530
- /**
531
- * Type guard to check if a route is a Route class instance (with hooks support)
532
- */
533
- export function isRouteClass(route: RouteBase | Route): route is Route {
534
- return route instanceof Route ||
535
- (typeof (route as Route).handler === 'function' &&
536
- 'pathName' in route &&
537
- (typeof (route as Route).onBefore === 'function' ||
538
- typeof (route as Route).onAfter === 'function' ||
539
- typeof (route as Route).onError === 'function'));
540
- }
541
-
542
- /**
543
- * Lifecycle hooks for request processing
544
- *
545
- * @example
546
- * ```typescript
547
- * app.hooks({
548
- * onRequest: async (ctx) => {
549
- * ctx.requestId = crypto.randomUUID();
550
- * },
551
- * beforeHandler: async (ctx) => {
552
- * ctx.user = await getUser(ctx.headers.authorization);
553
- * },
554
- * afterHandler: async (ctx, result) => {
555
- * return { ...result, timestamp: Date.now() };
556
- * },
557
- * onError: async (ctx, error) => {
558
- * await logToSentry(error);
559
- * }
560
- * });
561
- * ```
562
- */
563
- export interface LifecycleHooks {
564
- /** Called when request is received, before any processing */
565
- onRequest?: (ctx: Context) => Promise<void | Response> | void | Response;
566
-
567
- /** Called before schema validation */
568
- beforeValidation?: (ctx: Context) => Promise<void | Response> | void | Response;
569
-
570
- /** Called after schema validation succeeds (ctx.body, ctx.query, ctx.params are validated) */
571
- afterValidation?: (ctx: Context) => Promise<void | Response> | void | Response;
572
-
573
- /** Called before route handler executes */
574
- beforeHandler?: (ctx: Context) => Promise<void | Response> | void | Response;
575
-
576
- /** Called after handler, can transform result. Return new result to override */
577
- afterHandler?: (ctx: Context, result: any) => Promise<any> | any;
578
-
579
- /** Called when an error occurs. Can return Response to handle error */
580
- onError?: (ctx: Context, error: Error) => Promise<void | Response> | void | Response;
581
-
582
- /** Called before response is sent (after all processing) */
583
- onResponse?: (ctx: Context, response: Response) => Promise<void | Response> | void | Response;
584
- }
585
-
586
- /**
587
- * Versioning strategy types
588
- */
589
- export type VersioningStrategy = 'path' | 'header' | 'query';
590
-
591
- /**
592
- * Versioning configuration for API versioning
593
- *
594
- * @example
595
- * ```typescript
596
- * app.configVersions({
597
- * strategies: ['header', 'query'],
598
- * header: 'api-version',
599
- * queryParam: 'v',
600
- * defaultVersion: 'v1',
601
- * register: ['v1', 'v2']
602
- * });
603
- * ```
604
- */
605
- export interface VersioningConfig {
606
- /** Versioning strategies to use */
607
- strategies: VersioningStrategy[];
608
- /** Header name for version (default: 'api-version') */
609
- header?: string;
610
- /** Query param name for version (default: 'v') */
611
- queryParam?: string;
612
- /** Default version when not specified */
613
- defaultVersion: string;
614
- /** List of versions to register */
615
- register: string[];
616
- }
@@ -1,35 +0,0 @@
1
- import { QueryContext } from './types';
2
-
3
- export interface QueryResult<T = unknown> {
4
- rows: T[];
5
- rowCount: number;
6
- fields?: string[];
7
- meta?: Record<string, unknown>;
8
- }
9
-
10
- export interface DatabaseAdapter {
11
- name: string;
12
- connect(): Promise<void>;
13
- disconnect(): Promise<void>;
14
- query<T = unknown>(sql: string, params?: unknown[], context?: QueryContext): Promise<QueryResult<T>>;
15
- stream?<T = unknown>(sql: string, params?: unknown[], context?: QueryContext): AsyncGenerator<T, void, unknown>;
16
- beginTransaction?(): Promise<void>;
17
- commitTransaction?(): Promise<void>;
18
- rollbackTransaction?(savepoint?: string): Promise<void>;
19
- createSavepoint?(name: string): Promise<void>;
20
- releaseSavepoint?(name: string): Promise<void>;
21
- listen?(channel: string): Promise<void>;
22
- notify?(channel: string, payload: unknown): Promise<void>;
23
- capabilities?: {
24
- json?: boolean;
25
- streaming?: boolean;
26
- realtime?: boolean;
27
- transactional?: boolean;
28
- };
29
- }
30
-
31
- export interface MigrationAdapter extends DatabaseAdapter {
32
- runMigration(sql: string): Promise<void>;
33
- ensureMigrationsTable(): Promise<void>;
34
- }
35
-
@@ -1 +0,0 @@
1
- export * from './mysql';