@engjts/nexus 0.1.8 → 0.1.10

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 (221) hide show
  1. package/dist/advanced/playground/playground.js.map +1 -1
  2. package/dist/advanced/static/generateDirectoryListing.d.ts +1 -1
  3. package/dist/advanced/static/generateDirectoryListing.d.ts.map +1 -1
  4. package/dist/advanced/static/generateDirectoryListing.js +12 -6
  5. package/dist/advanced/static/generateDirectoryListing.js.map +1 -1
  6. package/dist/advanced/static/index.d.ts +2 -0
  7. package/dist/advanced/static/index.d.ts.map +1 -1
  8. package/dist/advanced/static/index.js +4 -1
  9. package/dist/advanced/static/index.js.map +1 -1
  10. package/dist/advanced/static/serveStatic.d.ts.map +1 -1
  11. package/dist/advanced/static/serveStatic.js +7 -1
  12. package/dist/advanced/static/serveStatic.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +3 -1
  16. package/dist/index.js.map +1 -1
  17. package/package.json +1 -1
  18. package/BENCHMARK_REPORT.md +0 -343
  19. package/documentation/01-getting-started.md +0 -240
  20. package/documentation/02-context.md +0 -335
  21. package/documentation/03-routing.md +0 -397
  22. package/documentation/04-middleware.md +0 -483
  23. package/documentation/05-validation.md +0 -514
  24. package/documentation/06-error-handling.md +0 -465
  25. package/documentation/07-performance.md +0 -364
  26. package/documentation/08-adapters.md +0 -470
  27. package/documentation/09-api-reference.md +0 -548
  28. package/documentation/10-examples.md +0 -582
  29. package/documentation/11-deployment.md +0 -477
  30. package/documentation/12-sentry.md +0 -620
  31. package/documentation/13-sentry-data-storage.md +0 -996
  32. package/documentation/14-sentry-data-reference.md +0 -457
  33. package/documentation/15-sentry-summary.md +0 -409
  34. package/documentation/16-alerts-system.md +0 -745
  35. package/documentation/17-alert-adapters.md +0 -696
  36. package/documentation/18-alerts-implementation-summary.md +0 -385
  37. package/documentation/19-class-based-routing.md +0 -840
  38. package/documentation/20-websocket-realtime.md +0 -813
  39. package/documentation/21-cache-system.md +0 -510
  40. package/documentation/22-job-queue.md +0 -772
  41. package/documentation/23-sentry-plugin.md +0 -551
  42. package/documentation/24-testing-utilities.md +0 -1287
  43. package/documentation/25-api-versioning.md +0 -533
  44. package/documentation/26-context-store.md +0 -607
  45. package/documentation/27-dependency-injection.md +0 -329
  46. package/documentation/28-lifecycle-hooks.md +0 -521
  47. package/documentation/29-package-structure.md +0 -196
  48. package/documentation/30-plugin-system.md +0 -414
  49. package/documentation/31-jwt-authentication.md +0 -597
  50. package/documentation/32-cli.md +0 -268
  51. package/documentation/ALERTS-COMPLETE-SUMMARY.md +0 -429
  52. package/documentation/ALERTS-INDEX.md +0 -330
  53. package/documentation/ALERTS-QUICK-REFERENCE.md +0 -286
  54. package/documentation/README.md +0 -178
  55. package/documentation/index.html +0 -34
  56. package/modern_framework_paper.md +0 -1870
  57. package/public/css/style.css +0 -87
  58. package/public/index.html +0 -34
  59. package/public/js/app.js +0 -27
  60. package/src/advanced/cache/InMemoryCacheStore.ts +0 -68
  61. package/src/advanced/cache/MultiTierCache.ts +0 -194
  62. package/src/advanced/cache/RedisCacheStore.ts +0 -341
  63. package/src/advanced/cache/index.ts +0 -5
  64. package/src/advanced/cache/types.ts +0 -40
  65. package/src/advanced/graphql/SimpleDataLoader.ts +0 -42
  66. package/src/advanced/graphql/index.ts +0 -22
  67. package/src/advanced/graphql/server.ts +0 -252
  68. package/src/advanced/graphql/types.ts +0 -42
  69. package/src/advanced/jobs/InMemoryQueueStore.ts +0 -68
  70. package/src/advanced/jobs/JobQueue.ts +0 -556
  71. package/src/advanced/jobs/RedisQueueStore.ts +0 -367
  72. package/src/advanced/jobs/index.ts +0 -5
  73. package/src/advanced/jobs/types.ts +0 -70
  74. package/src/advanced/observability/APMManager.ts +0 -163
  75. package/src/advanced/observability/AlertManager.ts +0 -109
  76. package/src/advanced/observability/MetricRegistry.ts +0 -151
  77. package/src/advanced/observability/ObservabilityCenter.ts +0 -304
  78. package/src/advanced/observability/StructuredLogger.ts +0 -154
  79. package/src/advanced/observability/TracingManager.ts +0 -117
  80. package/src/advanced/observability/adapters.ts +0 -304
  81. package/src/advanced/observability/createObservabilityMiddleware.ts +0 -63
  82. package/src/advanced/observability/index.ts +0 -11
  83. package/src/advanced/observability/types.ts +0 -174
  84. package/src/advanced/playground/extractPathParams.ts +0 -6
  85. package/src/advanced/playground/generateFieldExample.ts +0 -31
  86. package/src/advanced/playground/generatePlaygroundHTML.ts +0 -1956
  87. package/src/advanced/playground/generateSummary.ts +0 -19
  88. package/src/advanced/playground/getTagFromPath.ts +0 -9
  89. package/src/advanced/playground/index.ts +0 -8
  90. package/src/advanced/playground/playground.ts +0 -250
  91. package/src/advanced/playground/types.ts +0 -49
  92. package/src/advanced/playground/zodToExample.ts +0 -16
  93. package/src/advanced/playground/zodToParams.ts +0 -15
  94. package/src/advanced/postman/buildAuth.ts +0 -31
  95. package/src/advanced/postman/buildBody.ts +0 -15
  96. package/src/advanced/postman/buildQueryParams.ts +0 -27
  97. package/src/advanced/postman/buildRequestItem.ts +0 -36
  98. package/src/advanced/postman/buildResponses.ts +0 -11
  99. package/src/advanced/postman/buildUrl.ts +0 -33
  100. package/src/advanced/postman/capitalize.ts +0 -4
  101. package/src/advanced/postman/generateCollection.ts +0 -59
  102. package/src/advanced/postman/generateEnvironment.ts +0 -34
  103. package/src/advanced/postman/generateExampleFromZod.ts +0 -21
  104. package/src/advanced/postman/generateFieldExample.ts +0 -45
  105. package/src/advanced/postman/generateName.ts +0 -20
  106. package/src/advanced/postman/generateUUID.ts +0 -11
  107. package/src/advanced/postman/getTagFromPath.ts +0 -10
  108. package/src/advanced/postman/index.ts +0 -28
  109. package/src/advanced/postman/postman.ts +0 -156
  110. package/src/advanced/postman/slugify.ts +0 -7
  111. package/src/advanced/postman/types.ts +0 -140
  112. package/src/advanced/realtime/index.ts +0 -18
  113. package/src/advanced/realtime/websocket.ts +0 -231
  114. package/src/advanced/sentry/index.ts +0 -1236
  115. package/src/advanced/sentry/types.ts +0 -355
  116. package/src/advanced/static/generateDirectoryListing.ts +0 -47
  117. package/src/advanced/static/generateETag.ts +0 -7
  118. package/src/advanced/static/getMimeType.ts +0 -9
  119. package/src/advanced/static/index.ts +0 -32
  120. package/src/advanced/static/isSafePath.ts +0 -13
  121. package/src/advanced/static/publicDir.ts +0 -21
  122. package/src/advanced/static/serveStatic.ts +0 -225
  123. package/src/advanced/static/spa.ts +0 -24
  124. package/src/advanced/static/types.ts +0 -159
  125. package/src/advanced/swagger/SwaggerGenerator.ts +0 -66
  126. package/src/advanced/swagger/buildOperation.ts +0 -61
  127. package/src/advanced/swagger/buildParameters.ts +0 -61
  128. package/src/advanced/swagger/buildRequestBody.ts +0 -21
  129. package/src/advanced/swagger/buildResponses.ts +0 -54
  130. package/src/advanced/swagger/capitalize.ts +0 -5
  131. package/src/advanced/swagger/convertPath.ts +0 -9
  132. package/src/advanced/swagger/createSwagger.ts +0 -12
  133. package/src/advanced/swagger/generateOperationId.ts +0 -21
  134. package/src/advanced/swagger/generateSpec.ts +0 -105
  135. package/src/advanced/swagger/generateSummary.ts +0 -24
  136. package/src/advanced/swagger/generateSwaggerUI.ts +0 -70
  137. package/src/advanced/swagger/generateThemeCss.ts +0 -53
  138. package/src/advanced/swagger/index.ts +0 -25
  139. package/src/advanced/swagger/swagger.ts +0 -237
  140. package/src/advanced/swagger/types.ts +0 -206
  141. package/src/advanced/swagger/zodFieldToOpenAPI.ts +0 -94
  142. package/src/advanced/swagger/zodSchemaToOpenAPI.ts +0 -50
  143. package/src/advanced/swagger/zodToOpenAPI.ts +0 -22
  144. package/src/advanced/testing/factory.ts +0 -509
  145. package/src/advanced/testing/harness.ts +0 -612
  146. package/src/advanced/testing/index.ts +0 -430
  147. package/src/advanced/testing/load-test.ts +0 -618
  148. package/src/advanced/testing/mock-server.ts +0 -498
  149. package/src/advanced/testing/mock.ts +0 -670
  150. package/src/cli/bin.ts +0 -9
  151. package/src/cli/cli.ts +0 -158
  152. package/src/cli/commands/add.ts +0 -178
  153. package/src/cli/commands/build.ts +0 -73
  154. package/src/cli/commands/create.ts +0 -166
  155. package/src/cli/commands/dev.ts +0 -85
  156. package/src/cli/commands/generate.ts +0 -99
  157. package/src/cli/commands/help.ts +0 -95
  158. package/src/cli/commands/init.ts +0 -91
  159. package/src/cli/commands/version.ts +0 -38
  160. package/src/cli/index.ts +0 -6
  161. package/src/cli/templates/generators.ts +0 -359
  162. package/src/cli/templates/index.ts +0 -680
  163. package/src/cli/utils/exec.ts +0 -52
  164. package/src/cli/utils/file-system.ts +0 -78
  165. package/src/cli/utils/logger.ts +0 -111
  166. package/src/core/adapter.ts +0 -88
  167. package/src/core/application.ts +0 -1453
  168. package/src/core/context-pool.ts +0 -79
  169. package/src/core/context.ts +0 -856
  170. package/src/core/index.ts +0 -94
  171. package/src/core/middleware.ts +0 -272
  172. package/src/core/performance/buffer-pool.ts +0 -108
  173. package/src/core/performance/middleware-optimizer.ts +0 -162
  174. package/src/core/plugin/PluginManager.ts +0 -435
  175. package/src/core/plugin/builder.ts +0 -358
  176. package/src/core/plugin/index.ts +0 -50
  177. package/src/core/plugin/types.ts +0 -214
  178. package/src/core/router/file-router.ts +0 -623
  179. package/src/core/router/index.ts +0 -260
  180. package/src/core/router/radix-tree.ts +0 -242
  181. package/src/core/serializer.ts +0 -397
  182. package/src/core/store/index.ts +0 -30
  183. package/src/core/store/registry.ts +0 -178
  184. package/src/core/store/request-store.ts +0 -240
  185. package/src/core/store/types.ts +0 -233
  186. package/src/core/types.ts +0 -616
  187. package/src/database/adapter.ts +0 -35
  188. package/src/database/adapters/index.ts +0 -1
  189. package/src/database/adapters/mysql.ts +0 -669
  190. package/src/database/database.ts +0 -70
  191. package/src/database/dialect.ts +0 -388
  192. package/src/database/index.ts +0 -12
  193. package/src/database/migrations.ts +0 -86
  194. package/src/database/optimizer.ts +0 -125
  195. package/src/database/query-builder.ts +0 -404
  196. package/src/database/realtime.ts +0 -53
  197. package/src/database/schema.ts +0 -71
  198. package/src/database/transactions.ts +0 -56
  199. package/src/database/types.ts +0 -87
  200. package/src/deployment/cluster.ts +0 -471
  201. package/src/deployment/config.ts +0 -454
  202. package/src/deployment/docker.ts +0 -599
  203. package/src/deployment/graceful-shutdown.ts +0 -373
  204. package/src/deployment/index.ts +0 -56
  205. package/src/index.ts +0 -281
  206. package/src/security/adapter.ts +0 -318
  207. package/src/security/auth/JWTPlugin.ts +0 -234
  208. package/src/security/auth/JWTProvider.ts +0 -316
  209. package/src/security/auth/adapter.ts +0 -12
  210. package/src/security/auth/jwt.ts +0 -234
  211. package/src/security/auth/middleware.ts +0 -188
  212. package/src/security/csrf.ts +0 -220
  213. package/src/security/headers.ts +0 -108
  214. package/src/security/index.ts +0 -60
  215. package/src/security/rate-limit/adapter.ts +0 -7
  216. package/src/security/rate-limit/memory.ts +0 -108
  217. package/src/security/rate-limit/middleware.ts +0 -181
  218. package/src/security/sanitization.ts +0 -75
  219. package/src/security/types.ts +0 -240
  220. package/src/security/utils.ts +0 -52
  221. package/tsconfig.json +0 -39
@@ -1,623 +0,0 @@
1
- /**
2
- * File-Based Router for Nexus Framework
3
- *
4
- * Automatically scans a directory and registers routes based on file/folder structure.
5
- * Designed for class-based routing: 1 file = 1 class = 1 route.
6
- *
7
- * Smart filename conventions (only if no body schema):
8
- * - `index.ts` → GET (default), maps to parent path
9
- * - `create.ts` → POST, maps to parent path (not /create)
10
- * - `update.ts` → PUT, maps to parent path (not /update)
11
- * - `delete.ts` → DELETE, maps to parent path (not /delete)
12
- * - `patch.ts` → PATCH, maps to parent path (not /patch)
13
- * - Other files → GET (default)
14
- *
15
- * Smart body detection (HIGHEST PRIORITY after explicit method):
16
- * - If schema() returns object with `body` property → POST
17
- * - Works with inheritance (parent class schema is checked too)
18
- * - Overrides smart filename detection!
19
- * - Override by explicitly setting `method` property in class
20
- *
21
- * @example
22
- * ```
23
- * routes/
24
- * api/
25
- * auth/
26
- * register.ts → POST /api/auth/register (auto-detected via ctx.body!)
27
- * login.ts → POST /api/auth/login
28
- * users/
29
- * index.ts → GET /api/users
30
- * create.ts → POST /api/users (auto!)
31
- * [id]/
32
- * index.ts → GET /api/users/:id
33
- * update.ts → PUT /api/users/:id (auto!)
34
- * delete.ts → DELETE /api/users/:id (auto!)
35
- * ```
36
- *
37
- * Each file exports a class:
38
- * ```typescript
39
- * export default class RegisterRoute {
40
- * // No need to specify method = 'POST' if schema has body!
41
- *
42
- * schema() {
43
- * return {
44
- * body: z.object({ ... }) // ← auto-detects POST!
45
- * };
46
- * }
47
- *
48
- * async handler(ctx: Context) {
49
- * const data = ctx.body;
50
- * ...
51
- * }
52
- * }
53
- * ```
54
- */
55
-
56
- import { readdir, stat } from 'fs/promises';
57
- import { join, parse, extname } from 'path';
58
- import { pathToFileURL } from 'url';
59
- import { Application } from '../application';
60
- import {
61
- HTTPMethod,
62
- Handler,
63
- Context,
64
- SchemaConfig,
65
- RouteMeta,
66
- Middleware,
67
- RouteBase,
68
- Route
69
- } from '../types';
70
-
71
- /**
72
- * Supported HTTP methods for file-based routing
73
- */
74
- const HTTP_METHODS: HTTPMethod[] = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
75
-
76
- /**
77
- * Default HTTP method when not specified
78
- */
79
- const DEFAULT_METHOD: HTTPMethod = 'GET';
80
-
81
- /**
82
- * Smart filename to HTTP method mapping
83
- * These filenames auto-set the method AND don't become part of the route path
84
- */
85
- const SMART_FILENAME_METHODS: Record<string, HTTPMethod> = {
86
- 'create': 'POST',
87
- 'update': 'PUT',
88
- 'delete': 'DELETE',
89
- 'patch': 'PATCH',
90
- 'index': 'GET'
91
- };
92
-
93
- /**
94
- * Check if filename is a "smart" filename that implies method
95
- */
96
- function isSmartFilename(filename: string): boolean {
97
- return filename in SMART_FILENAME_METHODS;
98
- }
99
-
100
- /**
101
- * Get implied method from smart filename
102
- */
103
- function getSmartMethod(filename: string): HTTPMethod {
104
- return SMART_FILENAME_METHODS[filename] || DEFAULT_METHOD;
105
- }
106
-
107
- /**
108
- * Options for file-based routing
109
- */
110
- export interface FileRouterOptions {
111
- /** Root directory for routes (relative to project root or absolute) */
112
- dir: string;
113
- /** Optional prefix for all routes (e.g., '/api/v1') */
114
- prefix?: string;
115
- /** File extensions to scan (default: ['.ts', '.js']) */
116
- extensions?: string[];
117
- /** Enable debug logging */
118
- debug?: boolean;
119
- /** Custom middleware file name (default: '_middleware') */
120
- middlewareFileName?: string;
121
- /** Custom error handler file name (default: '_error') */
122
- errorFileName?: string;
123
- }
124
-
125
- /**
126
- * Class-based route export (1 file = 1 class = 1 route)
127
- */
128
- export interface FileRouteClass {
129
- /** HTTP method for this route (default: 'GET') */
130
- method?: HTTPMethod;
131
- /** Optional schema validation */
132
- schema?: () => SchemaConfig;
133
- /** Optional route metadata for documentation */
134
- meta?: () => RouteMeta;
135
- /** Optional route-specific middlewares */
136
- middlewares?: () => Middleware[];
137
- /** The route handler */
138
- handler: Handler;
139
- }
140
-
141
- /**
142
- * Route file module export
143
- */
144
- export interface RouteModule {
145
- /** Default export: the route class */
146
- default?: FileRouteClass | (new () => FileRouteClass);
147
- }
148
-
149
- /**
150
- * Parsed route information
151
- */
152
- interface ParsedRoute {
153
- path: string;
154
- method: HTTPMethod;
155
- handler: Handler;
156
- middlewares: Middleware[];
157
- schema?: SchemaConfig;
158
- meta?: RouteMeta;
159
- filePath: string;
160
- }
161
-
162
- /**
163
- * Middleware stack for directory hierarchy
164
- */
165
- interface MiddlewareStack {
166
- path: string;
167
- middleware: Middleware;
168
- }
169
-
170
- /**
171
- * File-based router implementation
172
- *
173
- * Philosophy:
174
- * - 1 file = 1 class = 1 route
175
- * - Folder structure determines the path (pathName in class is IGNORED)
176
- * - HTTP method is defined via `method` property (default: GET)
177
- * - Clean, scalable, easy to navigate
178
- */
179
- export class FileRouter {
180
- private options: Required<FileRouterOptions>;
181
- private routes: ParsedRoute[] = [];
182
- private middlewareStack: MiddlewareStack[] = [];
183
-
184
- constructor(options: FileRouterOptions) {
185
- this.options = {
186
- dir: options.dir,
187
- prefix: options.prefix || '',
188
- extensions: options.extensions || ['.ts', '.js'],
189
- debug: options.debug || false,
190
- middlewareFileName: options.middlewareFileName || '_middleware',
191
- errorFileName: options.errorFileName || '_error'
192
- };
193
- }
194
-
195
- /**
196
- * Scan directory and collect all routes
197
- */
198
- async scan(): Promise<ParsedRoute[]> {
199
- this.routes = [];
200
- this.middlewareStack = [];
201
-
202
- await this.scanDirectory(this.options.dir, '');
203
-
204
- if (this.options.debug) {
205
- console.log('\n📁 File-Based Routes Discovered:');
206
- console.log('─'.repeat(60));
207
- for (const route of this.routes) {
208
- console.log(` ${route.method.padEnd(7)} ${route.path}`);
209
- console.log(` └─ ${route.filePath}`);
210
- }
211
- console.log('─'.repeat(60));
212
- console.log(` Total: ${this.routes.length} routes\n`);
213
- }
214
-
215
- return this.routes;
216
- }
217
-
218
- /**
219
- * Register all discovered routes to the application
220
- */
221
- async register(app: Application): Promise<void> {
222
- const routes = await this.scan();
223
-
224
- // Get dependencies from app for injection
225
- const deps = (app as any).getDeps?.() || {};
226
-
227
- // Get router directly to avoid double-wrapping
228
- const router = (app as any).router;
229
-
230
- for (const route of routes) {
231
- // Wrap handler to inject dependencies
232
- const originalHandler = route.handler;
233
- const wrappedHandler: Handler = async (ctx) => originalHandler(ctx, deps);
234
-
235
- // Register directly to router to avoid double-wrapping by app methods
236
- router.addRoute({
237
- method: route.method,
238
- path: route.path,
239
- handler: wrappedHandler,
240
- middlewares: route.middlewares,
241
- schema: route.schema,
242
- meta: route.meta
243
- });
244
-
245
- if (this.options.debug) {
246
- console.log(`✅ Registered: ${route.method} ${route.path}`);
247
- }
248
- }
249
- }
250
-
251
- /**
252
- * Recursively scan a directory for route files
253
- */
254
- private async scanDirectory(dirPath: string, routePath: string): Promise<void> {
255
- let entries;
256
-
257
- try {
258
- entries = await readdir(dirPath, { withFileTypes: true });
259
- } catch (error) {
260
- if (this.options.debug) {
261
- console.warn(`⚠️ Cannot read directory: ${dirPath}`);
262
- }
263
- return;
264
- }
265
-
266
- // Sort entries: directories first, then files
267
- entries.sort((a, b) => {
268
- if (a.isDirectory() && !b.isDirectory()) return -1;
269
- if (!a.isDirectory() && b.isDirectory()) return 1;
270
- return a.name.localeCompare(b.name);
271
- });
272
-
273
- // First, check for _middleware file
274
- const middlewareFile = entries.find(e =>
275
- e.isFile() && this.isMiddlewareFile(e.name)
276
- );
277
-
278
- if (middlewareFile) {
279
- await this.loadMiddleware(join(dirPath, middlewareFile.name), routePath);
280
- }
281
-
282
- // Process all entries
283
- for (const entry of entries) {
284
- const fullPath = join(dirPath, entry.name);
285
-
286
- if (entry.isDirectory()) {
287
- // Handle directory (potential route segment or dynamic param)
288
- const segment = this.parseSegment(entry.name);
289
- const newRoutePath = routePath + segment;
290
- await this.scanDirectory(fullPath, newRoutePath);
291
- } else if (entry.isFile() && this.isRouteFile(entry.name)) {
292
- // Handle route file
293
- await this.loadRouteFile(fullPath, routePath, entry.name);
294
- }
295
- }
296
- }
297
-
298
- /**
299
- * Check if file is a route file (has valid extension and not special file)
300
- */
301
- private isRouteFile(fileName: string): boolean {
302
- const ext = extname(fileName);
303
- if (!this.options.extensions.includes(ext)) return false;
304
-
305
- const nameWithoutExt = parse(fileName).name;
306
-
307
- // Skip special files
308
- if (nameWithoutExt.startsWith('_')) return false;
309
-
310
- return true;
311
- }
312
-
313
- /**
314
- * Check if file is a middleware file
315
- */
316
- private isMiddlewareFile(fileName: string): boolean {
317
- const ext = extname(fileName);
318
- if (!this.options.extensions.includes(ext)) return false;
319
-
320
- const nameWithoutExt = parse(fileName).name;
321
- return nameWithoutExt === this.options.middlewareFileName;
322
- }
323
-
324
- /**
325
- * Parse directory/file name to route segment
326
- */
327
- private parseSegment(name: string): string {
328
- // Remove file extension if present
329
- const nameWithoutExt = parse(name).name;
330
-
331
- // Catch-all parameter: [...slug] → /*slug
332
- if (nameWithoutExt.startsWith('[...') && nameWithoutExt.endsWith(']')) {
333
- const paramName = nameWithoutExt.slice(4, -1);
334
- return `/*${paramName}`;
335
- }
336
-
337
- // Optional catch-all: [[...slug]] → /*slug?
338
- if (nameWithoutExt.startsWith('[[...') && nameWithoutExt.endsWith(']]')) {
339
- const paramName = nameWithoutExt.slice(5, -2);
340
- return `/*${paramName}?`;
341
- }
342
-
343
- // Dynamic parameter: [id] → /:id
344
- if (nameWithoutExt.startsWith('[') && nameWithoutExt.endsWith(']')) {
345
- const paramName = nameWithoutExt.slice(1, -1);
346
- return `/:${paramName}`;
347
- }
348
-
349
- // Optional parameter: [[id]] → /:id?
350
- if (nameWithoutExt.startsWith('[[') && nameWithoutExt.endsWith(']]')) {
351
- const paramName = nameWithoutExt.slice(2, -2);
352
- return `/:${paramName}?`;
353
- }
354
-
355
- // Regular segment
356
- return `/${nameWithoutExt}`;
357
- }
358
-
359
- /**
360
- * Build the final route path from folder structure
361
- */
362
- private buildRoutePath(basePath: string, fileName: string): string {
363
- const nameWithoutExt = parse(fileName).name;
364
-
365
- // Build final route path
366
- // Smart filenames (index, create, update, delete, patch) don't add to path
367
- let routePath = basePath;
368
- if (!isSmartFilename(nameWithoutExt)) {
369
- routePath += this.parseSegment(fileName);
370
- }
371
-
372
- // Apply prefix
373
- if (this.options.prefix) {
374
- routePath = this.options.prefix + routePath;
375
- }
376
-
377
- // Ensure path starts with /
378
- if (!routePath.startsWith('/')) {
379
- routePath = '/' + routePath;
380
- }
381
-
382
- // Normalize double slashes
383
- routePath = routePath.replace(/\/+/g, '/');
384
-
385
- // Remove trailing slash (except for root)
386
- if (routePath.length > 1 && routePath.endsWith('/')) {
387
- routePath = routePath.slice(0, -1);
388
- }
389
-
390
- return routePath;
391
- }
392
-
393
- /**
394
- * Load a route file and extract the route class
395
- */
396
- private async loadRouteFile(filePath: string, basePath: string, fileName: string): Promise<void> {
397
- // Build route path from folder structure (this is the ONLY source of truth)
398
- const routePath = this.buildRoutePath(basePath, fileName);
399
- const nameWithoutExt = parse(fileName).name;
400
-
401
- try {
402
- // Import the file
403
- const fileUrl = pathToFileURL(filePath).href;
404
- const module = await import(fileUrl) as RouteModule;
405
-
406
- // Must have a default export
407
- if (!module.default) {
408
- if (this.options.debug) {
409
- console.warn(`⚠️ No default export in: ${filePath}`);
410
- }
411
- return;
412
- }
413
-
414
- // Instantiate if it's a class constructor
415
- let route: Route | FileRouteClass;
416
- if (typeof module.default === 'function' && module.default.prototype) {
417
- route = new (module.default as new () => Route)();
418
- } else {
419
- route = module.default as Route;
420
- }
421
-
422
- // ⚠️ ENFORCE: Route class MUST extend Route abstract class
423
- if (!(route instanceof Route)) {
424
- const className = (route as any).constructor?.name || 'Unknown';
425
- throw new Error(
426
- `Route class "${className}" in ${filePath} must extend the Route abstract class.\n` +
427
- `Example:\n` +
428
- ` import { Route } from 'nexus';\n` +
429
- ` export default class ${className} extends Route {\n` +
430
- ` async handler(ctx) { ... }\n` +
431
- ` }`
432
- );
433
- }
434
-
435
- // Must have a handler (guaranteed by Route abstract class, but double-check)
436
- if (typeof route.handler !== 'function') {
437
- if (this.options.debug) {
438
- console.warn(`⚠️ No handler method in: ${filePath}`);
439
- }
440
- return;
441
- }
442
-
443
- // Determine HTTP method:
444
- // 1. If class explicitly defines method → use it
445
- // 2. If schema has body definition → auto-detect as POST (highest priority for body!)
446
- // 3. If filename is smart (create/update/delete/patch/index) → auto-detect from filename
447
- // 4. Otherwise → default GET
448
- let method: HTTPMethod;
449
-
450
- if (route.method) {
451
- // Handle both single method and array of methods (use first one for file-based routing)
452
- method = Array.isArray(route.method) ? route.method[0] : route.method;
453
- } else {
454
- // Check schema for body definition first (works with inheritance!)
455
- const schema = route.schema?.();
456
- if (this.options.debug) {
457
- console.log(`🔍 Smart detection for ${filePath}:`);
458
- console.log(` - schema:`, schema);
459
- console.log(` - has body:`, !!schema?.body);
460
- }
461
-
462
- if (schema?.body) {
463
- // Schema has body → POST (overrides smart filename!)
464
- method = 'POST';
465
- } else if (isSmartFilename(nameWithoutExt)) {
466
- // Smart filename detection (create→POST, update→PUT, etc.)
467
- method = getSmartMethod(nameWithoutExt);
468
- } else {
469
- method = DEFAULT_METHOD;
470
- }
471
- }
472
-
473
- // Validate method
474
- if (!HTTP_METHODS.includes(method)) {
475
- if (this.options.debug) {
476
- console.warn(`⚠️ Invalid method "${method}" in: ${filePath}`);
477
- }
478
- return;
479
- }
480
-
481
- // Get middlewares that apply to this route
482
- const applicableMiddlewares = this.getApplicableMiddlewares(basePath);
483
-
484
- // Add route-specific middlewares
485
- const routeMiddlewares = route.middlewares?.() || [];
486
- const allMiddlewares = [...applicableMiddlewares, ...routeMiddlewares];
487
-
488
- // Wrap handler with lifecycle hooks support
489
- // Note: Dependencies will be injected in register() method
490
- const routeInstance = route as Route;
491
- const hasHooks = typeof routeInstance.onBefore === 'function' ||
492
- typeof routeInstance.onAfter === 'function' ||
493
- typeof routeInstance.onError === 'function';
494
-
495
- let finalHandler: Handler;
496
-
497
- if (hasHooks) {
498
- const boundOriginalHandler = route.handler.bind(route);
499
- const onBefore = routeInstance.onBefore?.bind(route);
500
- const onAfter = routeInstance.onAfter?.bind(route);
501
- const onError = routeInstance.onError?.bind(route);
502
-
503
- // Handler receives (ctx, deps) - deps passed from register()
504
- finalHandler = async (ctx: Context, deps: any) => {
505
- try {
506
- // Run onBefore hook with deps
507
- if (onBefore) {
508
- const beforeResult = await onBefore(ctx, deps);
509
- // If onBefore returns a value (not undefined), skip handler
510
- if (beforeResult !== undefined) {
511
- return beforeResult;
512
- }
513
- }
514
-
515
- // Run the main handler with deps
516
- let result = await boundOriginalHandler(ctx, deps);
517
-
518
- // Run onAfter hook with deps
519
- if (onAfter) {
520
- result = await onAfter(ctx, result, deps);
521
- }
522
-
523
- return result;
524
- } catch (error) {
525
- // Run onError hook if defined with deps
526
- if (onError) {
527
- return await onError(ctx, error as Error, deps);
528
- }
529
- // Re-throw if no onError handler
530
- throw error;
531
- }
532
- };
533
- } else {
534
- // No hooks - just bind handler (deps will be passed in register())
535
- finalHandler = route.handler.bind(route);
536
- }
537
-
538
- // Register the route
539
- this.routes.push({
540
- path: routePath,
541
- method,
542
- handler: finalHandler,
543
- middlewares: allMiddlewares,
544
- schema: route.schema?.(),
545
- meta: route.meta?.(),
546
- filePath
547
- });
548
-
549
- } catch (error) {
550
- if (this.options.debug) {
551
- console.error(`❌ Failed to load route: ${filePath}`, error);
552
- }
553
- }
554
- }
555
-
556
- /**
557
- * Load middleware from a _middleware file
558
- */
559
- private async loadMiddleware(filePath: string, routePath: string): Promise<void> {
560
- try {
561
- const fileUrl = pathToFileURL(filePath).href;
562
- const module = await import(fileUrl);
563
-
564
- const middleware = module.default || module.middleware;
565
-
566
- if (typeof middleware === 'function') {
567
- this.middlewareStack.push({
568
- path: routePath,
569
- middleware
570
- });
571
-
572
- if (this.options.debug) {
573
- console.log(`📦 Loaded middleware for: ${routePath || '/'}`);
574
- }
575
- }
576
- } catch (error) {
577
- if (this.options.debug) {
578
- console.error(`❌ Failed to load middleware: ${filePath}`, error);
579
- }
580
- }
581
- }
582
-
583
- /**
584
- * Get middlewares that apply to a given route path
585
- */
586
- private getApplicableMiddlewares(routePath: string): Middleware[] {
587
- return this.middlewareStack
588
- .filter(m => routePath.startsWith(m.path))
589
- .map(m => m.middleware);
590
- }
591
- }
592
-
593
- /**
594
- * Create a file router instance
595
- */
596
- export function createFileRouter(options: FileRouterOptions): FileRouter {
597
- return new FileRouter(options);
598
- }
599
-
600
- /**
601
- * Extension method for Application to use file-based routing
602
- * This will be called to register routes from a directory
603
- *
604
- * @example
605
- * ```typescript
606
- * const app = createApp();
607
- *
608
- * await app.useFileRoutes({
609
- * dir: './src/routes',
610
- * prefix: '',
611
- * debug: true
612
- * });
613
- *
614
- * app.listen(3000);
615
- * ```
616
- */
617
- export async function useFileRoutes(
618
- app: Application,
619
- options: FileRouterOptions
620
- ): Promise<void> {
621
- const router = new FileRouter(options);
622
- await router.register(app);
623
- }