navis.js 5.2.2 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  A lightweight, serverless-first, microservice API framework designed for AWS Lambda and Node.js.
4
4
 
5
5
  **Author:** Syed Imran Ali
6
- **Version:** 5.2.1
6
+ **Version:** 5.3.0
7
7
  **License:** MIT
8
8
 
9
9
  ## Philosophy
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Navis.js TypeScript Example - AWS Lambda Handler
3
+ */
4
+
5
+ import { NavisApp } from 'navis.js';
6
+
7
+ const app = new NavisApp();
8
+
9
+ // Lambda route handlers
10
+ app.get('/hello', (req, res) => {
11
+ res.statusCode = 200;
12
+ res.body = {
13
+ message: 'Hello from Lambda with TypeScript!',
14
+ timestamp: new Date().toISOString()
15
+ };
16
+ });
17
+
18
+ app.get('/users/:id', (req, res) => {
19
+ const userId = req.params?.id;
20
+ res.statusCode = 200;
21
+ res.body = {
22
+ userId,
23
+ name: 'John Doe',
24
+ email: 'john@example.com'
25
+ };
26
+ });
27
+
28
+ // Export Lambda handler
29
+ export const handler = async (event: any) => {
30
+ return await app.handleLambda(event);
31
+ };
32
+
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Navis.js TypeScript Example - Node.js HTTP Server
3
+ */
4
+
5
+ import { NavisApp, response } from 'navis.js';
6
+
7
+ const app = new NavisApp();
8
+
9
+ // Basic route with TypeScript types
10
+ app.get('/', (req, res) => {
11
+ response.success(res, {
12
+ message: 'Hello from Navis.js with TypeScript!',
13
+ version: '5.3.0'
14
+ });
15
+ });
16
+
17
+ // Route with parameters
18
+ app.get('/users/:id', (req, res) => {
19
+ const userId = req.params?.id;
20
+ response.success(res, {
21
+ userId,
22
+ message: `User ${userId} found`
23
+ });
24
+ });
25
+
26
+ // POST route with body validation
27
+ app.post('/users', (req, res) => {
28
+ const { name, email } = req.body || {};
29
+
30
+ if (!name || !email) {
31
+ response.error(res, 'Name and email are required', 400);
32
+ return;
33
+ }
34
+
35
+ response.success(res, {
36
+ id: Math.random().toString(36).substr(2, 9),
37
+ name,
38
+ email
39
+ }, 201);
40
+ });
41
+
42
+ // Start server
43
+ const PORT = 3000;
44
+ app.listen(PORT, () => {
45
+ console.log(`🚀 Navis.js TypeScript server running on http://localhost:${PORT}`);
46
+ });
47
+
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Navis.js TypeScript Features Demo
3
+ * Demonstrates TypeScript usage with all v5.3 features
4
+ */
5
+
6
+ import {
7
+ NavisApp,
8
+ response,
9
+ ServiceClient,
10
+ Cache,
11
+ cache,
12
+ cors,
13
+ security,
14
+ compress,
15
+ createHealthChecker,
16
+ gracefulShutdown,
17
+ swagger,
18
+ createVersionManager,
19
+ headerVersioning,
20
+ upload,
21
+ testApp,
22
+ WebSocketServer,
23
+ sse,
24
+ createPool,
25
+ Logger,
26
+ Metrics,
27
+ validate,
28
+ authenticateJWT,
29
+ rateLimit,
30
+ errorHandler,
31
+ } from 'navis.js';
32
+
33
+ const app = new NavisApp();
34
+
35
+ // ============================================
36
+ // TypeScript with CORS
37
+ // ============================================
38
+ app.use(cors({
39
+ origin: ['http://localhost:3000'],
40
+ credentials: true,
41
+ }));
42
+
43
+ // ============================================
44
+ // TypeScript with Security Headers
45
+ // ============================================
46
+ app.use(security({
47
+ helmet: true,
48
+ hsts: true,
49
+ noSniff: true,
50
+ }));
51
+
52
+ // ============================================
53
+ // TypeScript with Compression
54
+ // ============================================
55
+ app.use(compress({
56
+ level: 6,
57
+ threshold: 1024,
58
+ }));
59
+
60
+ // ============================================
61
+ // TypeScript with Caching
62
+ // ============================================
63
+ const cacheStore = new Cache({
64
+ maxSize: 1000,
65
+ defaultTTL: 3600000,
66
+ });
67
+
68
+ app.get('/users/:id', cache({
69
+ cacheStore,
70
+ ttl: 1800,
71
+ keyGenerator: (req) => `user:${req.params?.id}`,
72
+ }), (req, res) => {
73
+ const userId = req.params?.id;
74
+ response.success(res, {
75
+ id: userId,
76
+ name: 'John Doe',
77
+ email: 'john@example.com',
78
+ });
79
+ });
80
+
81
+ // ============================================
82
+ // TypeScript with Validation
83
+ // ============================================
84
+ app.post('/users', validate({
85
+ body: {
86
+ name: { type: 'string', required: true, minLength: 2 },
87
+ email: { type: 'string', required: true, format: 'email' },
88
+ },
89
+ }), (req, res) => {
90
+ const { name, email } = req.body || {};
91
+ response.success(res, {
92
+ id: Math.random().toString(36).substr(2, 9),
93
+ name,
94
+ email,
95
+ }, 201);
96
+ });
97
+
98
+ // ============================================
99
+ // TypeScript with Authentication
100
+ // ============================================
101
+ app.get('/protected', authenticateJWT({
102
+ secret: process.env.JWT_SECRET || 'secret',
103
+ }), (req, res) => {
104
+ response.success(res, {
105
+ message: 'This is a protected route',
106
+ user: (req as any).user,
107
+ });
108
+ });
109
+
110
+ // ============================================
111
+ // TypeScript with Rate Limiting
112
+ // ============================================
113
+ app.post('/api/endpoint', rateLimit({
114
+ windowMs: 60000,
115
+ max: 10,
116
+ }), (req, res) => {
117
+ response.success(res, { message: 'Rate limited endpoint' });
118
+ });
119
+
120
+ // ============================================
121
+ // TypeScript with Observability
122
+ // ============================================
123
+ const logger = new Logger({ level: 'INFO' });
124
+ const metrics = new Metrics();
125
+
126
+ app.use((req, res, next) => {
127
+ logger.info('Request received', {
128
+ method: req.method,
129
+ path: req.path,
130
+ });
131
+ metrics.increment('http_requests', 1, {
132
+ method: req.method,
133
+ path: req.path || '/',
134
+ });
135
+ next();
136
+ });
137
+
138
+ // ============================================
139
+ // TypeScript with Service Client
140
+ // ============================================
141
+ const client = new ServiceClient('http://api.example.com', {
142
+ timeout: 5000,
143
+ maxRetries: 3,
144
+ });
145
+
146
+ app.get('/external', async (req, res) => {
147
+ try {
148
+ const result = await client.get('/data');
149
+ response.success(res, result.body);
150
+ } catch (error) {
151
+ response.error(res, 'External service error', 502);
152
+ }
153
+ });
154
+
155
+ // ============================================
156
+ // TypeScript with Health Checks
157
+ // ============================================
158
+ const healthChecker = createHealthChecker({
159
+ checks: {
160
+ cache: async () => cacheStore.size() >= 0,
161
+ database: async () => true, // Mock check
162
+ },
163
+ });
164
+
165
+ app.use(healthChecker.middleware());
166
+
167
+ // ============================================
168
+ // TypeScript with Swagger
169
+ // ============================================
170
+ const swaggerMiddleware = swagger({
171
+ title: 'Navis.js TypeScript API',
172
+ version: '5.3.0',
173
+ description: 'API with full TypeScript support',
174
+ });
175
+
176
+ app.use(swaggerMiddleware.middleware);
177
+
178
+ // ============================================
179
+ // TypeScript with API Versioning
180
+ // ============================================
181
+ app.use(headerVersioning({
182
+ header: 'X-API-Version',
183
+ defaultVersion: 'v1',
184
+ }));
185
+
186
+ const versionManager = createVersionManager();
187
+ const v1 = versionManager.version('v1');
188
+ v1.get('/users/:id', (req, res) => {
189
+ response.success(res, { version: 'v1', userId: req.params?.id });
190
+ });
191
+
192
+ // ============================================
193
+ // TypeScript with SSE
194
+ // ============================================
195
+ app.get('/events', sse(), (req, res) => {
196
+ res.sse?.send({ message: 'Connected' }, 'connection');
197
+
198
+ let count = 0;
199
+ const interval = setInterval(() => {
200
+ count++;
201
+ res.sse?.send({ count, timestamp: new Date().toISOString() }, 'update');
202
+
203
+ if (count >= 10) {
204
+ clearInterval(interval);
205
+ res.sse?.close();
206
+ }
207
+ }, 1000);
208
+
209
+ (req as any).on('close', () => {
210
+ clearInterval(interval);
211
+ });
212
+ });
213
+
214
+ // ============================================
215
+ // TypeScript with Error Handling
216
+ // ============================================
217
+ app.use(errorHandler());
218
+
219
+ // ============================================
220
+ // Routes
221
+ // ============================================
222
+ app.get('/', (req, res) => {
223
+ response.success(res, {
224
+ message: 'Navis.js TypeScript Features Demo',
225
+ version: '5.3.0',
226
+ features: [
227
+ 'Full TypeScript support',
228
+ 'Type-safe API',
229
+ 'IntelliSense',
230
+ 'Type checking',
231
+ ],
232
+ });
233
+ });
234
+
235
+ // ============================================
236
+ // Start Server
237
+ // ============================================
238
+ const PORT = 3000;
239
+ const server = app.listen(PORT, () => {
240
+ console.log(`\n🚀 Navis.js TypeScript Demo Server`);
241
+ console.log(`📡 Listening on http://localhost:${PORT}\n`);
242
+ console.log('Available endpoints:');
243
+ console.log(' GET /');
244
+ console.log(' GET /users/:id (cached)');
245
+ console.log(' POST /users (validated)');
246
+ console.log(' GET /protected (authenticated)');
247
+ console.log(' GET /events (SSE)');
248
+ console.log(' GET /swagger.json (OpenAPI)');
249
+ console.log(' GET /docs (Swagger UI)');
250
+ console.log(' GET /health/ready (health check)');
251
+ });
252
+
253
+ // ============================================
254
+ // Graceful Shutdown
255
+ // ============================================
256
+ gracefulShutdown(server, {
257
+ timeout: 10000,
258
+ onShutdown: async () => {
259
+ console.log('Cleaning up...');
260
+ cacheStore.destroy();
261
+ console.log('Cleanup complete');
262
+ },
263
+ });
264
+
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "navis.js",
3
- "version": "5.2.2",
3
+ "version": "5.3.0",
4
4
  "description": "A lightweight, serverless-first, microservice API framework designed for AWS Lambda and Node.js",
5
5
  "main": "src/index.js",
6
+ "types": "types/index.d.ts",
7
+ "typings": "types/index.d.ts",
6
8
  "bin": {
7
9
  "navis": "bin/navis.js"
8
10
  },
9
11
  "files": [
10
12
  "src/",
13
+ "types/",
11
14
  "bin/",
12
15
  "examples/",
13
16
  "README.md",
@@ -0,0 +1,711 @@
1
+ /**
2
+ * Navis.js TypeScript Definitions
3
+ * v5.3: Full TypeScript support
4
+ */
5
+
6
+ // ============================================
7
+ // Core Types
8
+ // ============================================
9
+
10
+ export interface NavisRequest {
11
+ method: string;
12
+ path: string;
13
+ url?: string;
14
+ headers: Record<string, string>;
15
+ body?: any;
16
+ query?: Record<string, string>;
17
+ params?: Record<string, string>;
18
+ event?: any;
19
+ apiVersion?: string;
20
+ files?: FileUpload[];
21
+ }
22
+
23
+ export interface NavisResponse {
24
+ statusCode: number;
25
+ headers?: Record<string, string>;
26
+ body?: any;
27
+ writeHead?: (statusCode: number, headers?: Record<string, string>) => void;
28
+ setHeader?: (name: string, value: string) => void;
29
+ end?: (body?: any) => void;
30
+ finish?: (...args: any[]) => void;
31
+ sse?: {
32
+ send: (data: any, event?: string, id?: string) => boolean;
33
+ close: () => void;
34
+ };
35
+ }
36
+
37
+ export type Middleware = (req: NavisRequest, res: NavisResponse, next: () => Promise<void>) => Promise<void> | void;
38
+ export type RouteHandler = (req: NavisRequest, res: NavisResponse) => Promise<void> | void | Promise<any> | any;
39
+
40
+ export interface NavisAppOptions {
41
+ useAdvancedRouter?: boolean;
42
+ }
43
+
44
+ export interface NavisApp {
45
+ use(fn: Middleware): void;
46
+ get(path: string, ...handlers: (Middleware | RouteHandler)[]): void;
47
+ post(path: string, ...handlers: (Middleware | RouteHandler)[]): void;
48
+ put(path: string, ...handlers: (Middleware | RouteHandler)[]): void;
49
+ delete(path: string, ...handlers: (Middleware | RouteHandler)[]): void;
50
+ patch(path: string, ...handlers: (Middleware | RouteHandler)[]): void;
51
+ listen(port?: number, callback?: () => void): any;
52
+ handleLambda(event: any): Promise<any>;
53
+ getServer(): any;
54
+ }
55
+
56
+ // ============================================
57
+ // Service Client Types
58
+ // ============================================
59
+
60
+ export interface ServiceClientOptions {
61
+ timeout?: number;
62
+ maxRetries?: number;
63
+ retryBaseDelay?: number;
64
+ retryMaxDelay?: number;
65
+ retryStatusCodes?: number[];
66
+ circuitBreaker?: CircuitBreakerOptions;
67
+ }
68
+
69
+ export interface CircuitBreakerOptions {
70
+ failureThreshold?: number;
71
+ resetTimeout?: number;
72
+ halfOpenMaxAttempts?: number;
73
+ }
74
+
75
+ export interface ServiceClientResponse {
76
+ statusCode: number;
77
+ body: any;
78
+ headers: Record<string, string>;
79
+ }
80
+
81
+ export interface ServiceClient {
82
+ get(path: string, options?: ServiceClientOptions): Promise<ServiceClientResponse>;
83
+ post(path: string, data?: any, options?: ServiceClientOptions): Promise<ServiceClientResponse>;
84
+ put(path: string, data?: any, options?: ServiceClientOptions): Promise<ServiceClientResponse>;
85
+ delete(path: string, options?: ServiceClientOptions): Promise<ServiceClientResponse>;
86
+ patch(path: string, data?: any, options?: ServiceClientOptions): Promise<ServiceClientResponse>;
87
+ getCircuitBreakerState(): string;
88
+ resetCircuitBreaker(): void;
89
+ }
90
+
91
+ // ============================================
92
+ // Response Types
93
+ // ============================================
94
+
95
+ export interface ResponseHelpers {
96
+ success(context: NavisResponse, data: any, statusCode?: number, isLambda?: boolean): void;
97
+ error(context: NavisResponse, message: string, statusCode?: number, isLambda?: boolean): void;
98
+ }
99
+
100
+ // ============================================
101
+ // Retry Types
102
+ // ============================================
103
+
104
+ export interface RetryOptions {
105
+ maxRetries?: number;
106
+ baseDelay?: number;
107
+ maxDelay?: number;
108
+ retryCondition?: (error: any, response?: any) => boolean;
109
+ }
110
+
111
+ export interface RetryHelpers {
112
+ retry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
113
+ shouldRetryHttpStatus(statusCode: number): boolean;
114
+ }
115
+
116
+ // ============================================
117
+ // Circuit Breaker Types
118
+ // ============================================
119
+
120
+ export interface CircuitBreaker {
121
+ execute<T>(fn: () => Promise<T>): Promise<T>;
122
+ getState(): 'CLOSED' | 'OPEN' | 'HALF_OPEN';
123
+ isOpen(): boolean;
124
+ reset(): void;
125
+ }
126
+
127
+ // ============================================
128
+ // Service Config Types
129
+ // ============================================
130
+
131
+ export interface ServiceConfigOptions {
132
+ defaultOptions?: ServiceClientOptions;
133
+ }
134
+
135
+ export interface ServiceConfig {
136
+ register(name: string, baseUrl: string, options?: ServiceClientOptions): void;
137
+ get(name: string): { baseUrl: string; options?: ServiceClientOptions } | null;
138
+ getAll(): Record<string, { baseUrl: string; options?: ServiceClientOptions }>;
139
+ unregister(name: string): void;
140
+ }
141
+
142
+ // ============================================
143
+ // Service Discovery Types
144
+ // ============================================
145
+
146
+ export interface ServiceDiscoveryOptions {
147
+ healthCheckInterval?: number;
148
+ healthCheckTimeout?: number;
149
+ healthCheckPath?: string;
150
+ }
151
+
152
+ export interface ServiceDiscovery {
153
+ register(name: string, urls: string[], options?: ServiceDiscoveryOptions): void;
154
+ getNext(name: string): string | null;
155
+ getAll(name: string): string[];
156
+ unregister(name: string): void;
157
+ getHealthyUrls(name: string): string[];
158
+ }
159
+
160
+ // ============================================
161
+ // Observability Types
162
+ // ============================================
163
+
164
+ export interface LoggerOptions {
165
+ level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
166
+ context?: Record<string, any>;
167
+ }
168
+
169
+ export interface Logger {
170
+ debug(message: string, meta?: Record<string, any>): void;
171
+ info(message: string, meta?: Record<string, any>): void;
172
+ warn(message: string, meta?: Record<string, any>): void;
173
+ error(message: string, meta?: Record<string, any>): void;
174
+ setLevel(level: string): void;
175
+ getLevel(): string;
176
+ }
177
+
178
+ export interface Metrics {
179
+ increment(name: string, value?: number, labels?: Record<string, string>): void;
180
+ decrement(name: string, value?: number, labels?: Record<string, string>): void;
181
+ gauge(name: string, value: number, labels?: Record<string, string>): void;
182
+ histogram(name: string, value: number, labels?: Record<string, string>): void;
183
+ recordRequest(method: string, path: string, duration: number, statusCode: number): void;
184
+ toPrometheus(): string;
185
+ reset(): void;
186
+ }
187
+
188
+ export interface TracerOptions {
189
+ serviceName?: string;
190
+ }
191
+
192
+ export interface Tracer {
193
+ startTrace(name: string, meta?: Record<string, any>): string;
194
+ startSpan(name: string, options?: { traceId?: string; meta?: Record<string, any> }): string;
195
+ finishSpan(spanId: string, meta?: Record<string, any>): void;
196
+ getTrace(traceId: string): { traceId: string; spans: any[] } | null;
197
+ }
198
+
199
+ // ============================================
200
+ // Messaging Types
201
+ // ============================================
202
+
203
+ export interface SQSMessagingOptions {
204
+ region?: string;
205
+ queueUrl?: string;
206
+ }
207
+
208
+ export interface SQSMessaging {
209
+ connect(): Promise<void>;
210
+ disconnect(): Promise<void>;
211
+ publish(queueUrl: string, message: any, options?: any): Promise<void>;
212
+ subscribe(queueUrl: string, handler: (message: any, metadata: any) => Promise<void>): Promise<void>;
213
+ }
214
+
215
+ export interface KafkaMessagingOptions {
216
+ brokers: string[];
217
+ clientId?: string;
218
+ consumerGroupId?: string;
219
+ }
220
+
221
+ export interface KafkaMessaging {
222
+ connect(): Promise<void>;
223
+ disconnect(): Promise<void>;
224
+ publish(topic: string, message: any, options?: any): Promise<void>;
225
+ subscribe(topic: string, handler: (message: any, metadata: any) => Promise<void>): Promise<void>;
226
+ }
227
+
228
+ export interface NATSMessagingOptions {
229
+ servers: string[];
230
+ }
231
+
232
+ export interface NATSMessaging {
233
+ connect(): Promise<void>;
234
+ disconnect(): Promise<void>;
235
+ publish(subject: string, message: any): Promise<void>;
236
+ subscribe(subject: string, handler: (message: any) => Promise<void>): Promise<void>;
237
+ }
238
+
239
+ // ============================================
240
+ // Lambda Optimization Types
241
+ // ============================================
242
+
243
+ export interface ServiceClientPool {
244
+ get(baseUrl: string, options?: ServiceClientOptions): ServiceClient;
245
+ clear(): void;
246
+ size(): number;
247
+ }
248
+
249
+ export interface LazyInitOptions {
250
+ timeout?: number;
251
+ }
252
+
253
+ export interface LazyInit {
254
+ init<T>(initFn: () => Promise<T>): Promise<T>;
255
+ reset(): void;
256
+ isInitialized(): boolean;
257
+ }
258
+
259
+ export interface LambdaHandlerOptions {
260
+ enableMetrics?: boolean;
261
+ warmupPath?: string;
262
+ }
263
+
264
+ export interface LambdaHandler {
265
+ handle(event: any, context?: any): Promise<any>;
266
+ getStats(): any;
267
+ isWarm(): boolean;
268
+ }
269
+
270
+ // ============================================
271
+ // Advanced Features Types (v4)
272
+ // ============================================
273
+
274
+ export interface ValidationSchema {
275
+ body?: Record<string, ValidationRule>;
276
+ query?: Record<string, ValidationRule>;
277
+ params?: Record<string, ValidationRule>;
278
+ headers?: Record<string, ValidationRule>;
279
+ }
280
+
281
+ export interface ValidationRule {
282
+ type: 'string' | 'number' | 'boolean' | 'array' | 'object';
283
+ required?: boolean;
284
+ min?: number;
285
+ max?: number;
286
+ minLength?: number;
287
+ maxLength?: number;
288
+ pattern?: string | RegExp;
289
+ format?: 'email' | 'uuid' | 'url';
290
+ enum?: any[];
291
+ items?: ValidationRule;
292
+ properties?: Record<string, ValidationRule>;
293
+ custom?: (value: any) => boolean | string;
294
+ }
295
+
296
+ export interface ValidationError extends Error {
297
+ field: string;
298
+ message: string;
299
+ code: string;
300
+ }
301
+
302
+ export interface AuthOptions {
303
+ secret?: string;
304
+ algorithm?: string;
305
+ issuer?: string;
306
+ audience?: string;
307
+ }
308
+
309
+ export interface RateLimitOptions {
310
+ windowMs?: number;
311
+ max?: number;
312
+ message?: string;
313
+ skipSuccessfulRequests?: boolean;
314
+ skipFailedRequests?: boolean;
315
+ }
316
+
317
+ export interface RateLimiter {
318
+ check(key: string): { allowed: boolean; remaining: number; resetTime: number };
319
+ reset(key: string): void;
320
+ clear(): void;
321
+ }
322
+
323
+ // ============================================
324
+ // Enterprise Features Types (v5)
325
+ // ============================================
326
+
327
+ export interface CacheOptions {
328
+ maxSize?: number;
329
+ defaultTTL?: number;
330
+ cleanupInterval?: number;
331
+ }
332
+
333
+ export interface Cache {
334
+ set(key: string, value: any, ttl?: number): void;
335
+ get(key: string): any;
336
+ has(key: string): boolean;
337
+ delete(key: string): boolean;
338
+ clear(): void;
339
+ size(): number;
340
+ keys(): string[];
341
+ destroy(): void;
342
+ }
343
+
344
+ export interface RedisCacheOptions {
345
+ url?: string;
346
+ defaultTTL?: number;
347
+ prefix?: string;
348
+ }
349
+
350
+ export interface RedisCache {
351
+ connect(options?: any): Promise<void>;
352
+ disconnect(): Promise<void>;
353
+ set(key: string, value: any, ttl?: number): Promise<void>;
354
+ get(key: string): Promise<any>;
355
+ has(key: string): Promise<boolean>;
356
+ delete(key: string): Promise<boolean>;
357
+ clear(): Promise<void>;
358
+ size(): Promise<number>;
359
+ }
360
+
361
+ export interface CacheMiddlewareOptions {
362
+ cacheStore: Cache | RedisCache;
363
+ ttl?: number;
364
+ keyGenerator?: (req: NavisRequest) => string;
365
+ skipCache?: (req: NavisRequest, res: NavisResponse) => boolean;
366
+ vary?: string[];
367
+ }
368
+
369
+ export interface CORSOptions {
370
+ origin?: string | string[];
371
+ methods?: string[];
372
+ allowedHeaders?: string[];
373
+ exposedHeaders?: string[];
374
+ credentials?: boolean;
375
+ maxAge?: number;
376
+ preflightContinue?: boolean;
377
+ }
378
+
379
+ export interface SecurityOptions {
380
+ helmet?: boolean;
381
+ hsts?: boolean;
382
+ hstsMaxAge?: number;
383
+ hstsIncludeSubDomains?: boolean;
384
+ hstsPreload?: boolean;
385
+ noSniff?: boolean;
386
+ xssFilter?: boolean;
387
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
388
+ contentSecurityPolicy?: boolean | Record<string, string[]>;
389
+ referrerPolicy?: string;
390
+ permissionsPolicy?: Record<string, string>;
391
+ }
392
+
393
+ export interface CompressionOptions {
394
+ level?: number;
395
+ threshold?: number;
396
+ algorithm?: 'gzip' | 'brotli';
397
+ filter?: (req: NavisRequest, res: NavisResponse) => boolean;
398
+ }
399
+
400
+ export interface HealthCheckOptions {
401
+ livenessPath?: string;
402
+ readinessPath?: string;
403
+ checks?: Record<string, () => Promise<boolean>>;
404
+ enabled?: boolean;
405
+ }
406
+
407
+ export interface HealthChecker {
408
+ addCheck(name: string, checkFn: () => Promise<boolean>): void;
409
+ removeCheck(name: string): void;
410
+ runChecks(includeReadiness?: boolean): Promise<any>;
411
+ middleware(): Middleware;
412
+ }
413
+
414
+ export interface GracefulShutdownOptions {
415
+ timeout?: number;
416
+ onShutdown?: () => Promise<void>;
417
+ signals?: string[];
418
+ log?: (message: string) => void;
419
+ }
420
+
421
+ // ============================================
422
+ // Developer Experience Types (v5.1)
423
+ // ============================================
424
+
425
+ export interface SwaggerOptions {
426
+ title?: string;
427
+ version?: string;
428
+ description?: string;
429
+ path?: string;
430
+ uiPath?: string;
431
+ servers?: Array<{ url: string; description?: string }>;
432
+ tags?: Array<{ name: string; description?: string }>;
433
+ }
434
+
435
+ export interface SwaggerGenerator {
436
+ addRoute(method: string, path: string, spec?: any): void;
437
+ addSchema(name: string, schema: any): void;
438
+ addSecurityScheme(name: string, scheme: any): void;
439
+ generate(): any;
440
+ toJSON(): string;
441
+ }
442
+
443
+ export interface SwaggerMiddleware {
444
+ generator: SwaggerGenerator;
445
+ middleware: Middleware;
446
+ }
447
+
448
+ export interface VersionManager {
449
+ version(version: string): {
450
+ get: (path: string, handler: RouteHandler) => void;
451
+ post: (path: string, handler: RouteHandler) => void;
452
+ put: (path: string, handler: RouteHandler) => void;
453
+ delete: (path: string, handler: RouteHandler) => void;
454
+ patch: (path: string, handler: RouteHandler) => void;
455
+ use: (middleware: Middleware) => void;
456
+ };
457
+ setDefaultVersion(version: string): void;
458
+ getRoutes(version: string): any;
459
+ getVersions(): string[];
460
+ }
461
+
462
+ export interface HeaderVersioningOptions {
463
+ header?: string;
464
+ defaultVersion?: string;
465
+ }
466
+
467
+ export interface FileUploadOptions {
468
+ dest?: string;
469
+ limits?: {
470
+ fileSize?: number;
471
+ files?: number;
472
+ };
473
+ fileFilter?: (file: FileUpload) => boolean;
474
+ preserveExtension?: boolean;
475
+ generateFilename?: (file: FileUpload) => string;
476
+ }
477
+
478
+ export interface FileUpload {
479
+ fieldname: string;
480
+ originalname: string;
481
+ encoding: string;
482
+ mimetype: string;
483
+ size: number;
484
+ destination: string;
485
+ filename: string;
486
+ path: string;
487
+ buffer?: Buffer;
488
+ stream?: any;
489
+ }
490
+
491
+ export interface TestApp {
492
+ get(path: string, options?: any): Promise<TestResponse>;
493
+ post(path: string, data?: any, options?: any): Promise<TestResponse>;
494
+ put(path: string, data?: any, options?: any): Promise<TestResponse>;
495
+ delete(path: string, options?: any): Promise<TestResponse>;
496
+ patch(path: string, data?: any, options?: any): Promise<TestResponse>;
497
+ }
498
+
499
+ export interface TestResponse {
500
+ statusCode: number;
501
+ headers: Record<string, string>;
502
+ body: any;
503
+ json(): any;
504
+ text(): string;
505
+ }
506
+
507
+ // ============================================
508
+ // Real-time Features Types (v5.2)
509
+ // ============================================
510
+
511
+ export interface WebSocketServerOptions {
512
+ server?: any;
513
+ path?: string;
514
+ }
515
+
516
+ export interface WebSocketClient {
517
+ id: string;
518
+ socket: any;
519
+ request: any;
520
+ send(data: any): boolean;
521
+ close(): void;
522
+ }
523
+
524
+ export interface WebSocketServer {
525
+ attach(server: any): void;
526
+ on(path: string, handler: (message: any, client: WebSocketClient) => void): void;
527
+ onConnection(handler: (client: WebSocketClient) => void): void;
528
+ onDisconnection(handler: (client: WebSocketClient) => void): void;
529
+ broadcast(data: any): void;
530
+ getClients(): WebSocketClient[];
531
+ }
532
+
533
+ export interface SSEServer {
534
+ middleware(): Middleware;
535
+ broadcast(data: any, event?: string): void;
536
+ getClients(): any[];
537
+ }
538
+
539
+ export interface DatabasePoolOptions {
540
+ type?: 'postgres' | 'postgresql' | 'mysql' | 'mariadb' | 'mongodb';
541
+ connectionString?: string;
542
+ maxConnections?: number;
543
+ minConnections?: number;
544
+ idleTimeout?: number;
545
+ }
546
+
547
+ export interface DatabasePool {
548
+ connect(): Promise<void>;
549
+ query(query: string, params?: any[]): Promise<any>;
550
+ getConnection(): Promise<any>;
551
+ close(): Promise<void>;
552
+ ping(): Promise<boolean>;
553
+ }
554
+
555
+ // ============================================
556
+ // Main Exports
557
+ // ============================================
558
+
559
+ export const NavisApp: {
560
+ new (options?: NavisAppOptions): NavisApp;
561
+ };
562
+
563
+ export const ServiceClient: {
564
+ new (baseUrl: string, options?: ServiceClientOptions): ServiceClient;
565
+ };
566
+
567
+ export const ServiceConfig: {
568
+ new (options?: ServiceConfigOptions): ServiceConfig;
569
+ };
570
+
571
+ export const ServiceDiscovery: {
572
+ new (): ServiceDiscovery;
573
+ };
574
+
575
+ export const CircuitBreaker: {
576
+ new (options?: CircuitBreakerOptions): CircuitBreaker;
577
+ };
578
+
579
+ export const Logger: {
580
+ new (options?: LoggerOptions): Logger;
581
+ };
582
+
583
+ export const Metrics: {
584
+ new (): Metrics;
585
+ };
586
+
587
+ export const Tracer: {
588
+ new (options?: TracerOptions): Tracer;
589
+ };
590
+
591
+ export const SQSMessaging: {
592
+ new (options?: SQSMessagingOptions): SQSMessaging;
593
+ };
594
+
595
+ export const KafkaMessaging: {
596
+ new (options?: KafkaMessagingOptions): KafkaMessaging;
597
+ };
598
+
599
+ export const NATSMessaging: {
600
+ new (options?: NATSMessagingOptions): NATSMessaging;
601
+ };
602
+
603
+ export const ServiceClientPool: {
604
+ new (): ServiceClientPool;
605
+ };
606
+
607
+ export const LazyInit: {
608
+ new (options?: LazyInitOptions): LazyInit;
609
+ };
610
+
611
+ export const LambdaHandler: {
612
+ new (app: NavisApp, options?: LambdaHandlerOptions): LambdaHandler;
613
+ };
614
+
615
+ export const AdvancedRouter: {
616
+ new (): any;
617
+ };
618
+
619
+ export const RateLimiter: {
620
+ new (options?: RateLimitOptions): RateLimiter;
621
+ };
622
+
623
+ export const Cache: {
624
+ new (options?: CacheOptions): Cache;
625
+ };
626
+
627
+ export const RedisCache: {
628
+ new (options?: RedisCacheOptions): RedisCache;
629
+ };
630
+
631
+ export const HealthChecker: {
632
+ new (options?: HealthCheckOptions): HealthChecker;
633
+ };
634
+
635
+ export const SwaggerGenerator: {
636
+ new (options?: SwaggerOptions): SwaggerGenerator;
637
+ };
638
+
639
+ export const VersionManager: {
640
+ new (): VersionManager;
641
+ };
642
+
643
+ export const TestApp: {
644
+ new (app: NavisApp): TestApp;
645
+ };
646
+
647
+ export const WebSocketServer: {
648
+ new (options?: WebSocketServerOptions): WebSocketServer;
649
+ };
650
+
651
+ export const SSEServer: {
652
+ new (): SSEServer;
653
+ };
654
+
655
+ export const DatabasePool: {
656
+ new (options?: DatabasePoolOptions): DatabasePool;
657
+ };
658
+
659
+ // Functions
660
+ export function retry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
661
+ export function shouldRetryHttpStatus(statusCode: number): boolean;
662
+ export function validate(schema: ValidationSchema): Middleware;
663
+ export function authenticateJWT(options?: AuthOptions): Middleware;
664
+ export function authenticateAPIKey(options?: AuthOptions): Middleware;
665
+ export function authorize(roles: string[]): Middleware;
666
+ export function optionalAuth(options?: AuthOptions): Middleware;
667
+ export function rateLimit(options?: RateLimitOptions): Middleware;
668
+ export function errorHandler(): Middleware;
669
+ export function asyncHandler(fn: RouteHandler): RouteHandler;
670
+ export function notFoundHandler(): RouteHandler;
671
+ export function cache(options: CacheMiddlewareOptions): Middleware;
672
+ export function cors(options?: CORSOptions): Middleware;
673
+ export function security(options?: SecurityOptions): Middleware;
674
+ export function compress(options?: CompressionOptions): Middleware;
675
+ export function swagger(options?: SwaggerOptions): SwaggerMiddleware;
676
+ export function createVersionManager(): VersionManager;
677
+ export function headerVersioning(options?: HeaderVersioningOptions): Middleware;
678
+ export function upload(options?: FileUploadOptions): Middleware;
679
+ export function saveFile(file: FileUpload, dest: string, generateFilename?: (file: FileUpload) => string): Promise<string>;
680
+ export function testApp(app: NavisApp): TestApp;
681
+ export function sse(): Middleware;
682
+ export function createSSEServer(): SSEServer;
683
+ export function createPool(options?: DatabasePoolOptions): DatabasePool;
684
+ export function createHealthChecker(options?: HealthCheckOptions): HealthChecker;
685
+ export function gracefulShutdown(server: any, options?: GracefulShutdownOptions): any;
686
+ export function getPool(): ServiceClientPool;
687
+ export function createLazyInit(initFn: () => Promise<any>, options?: LazyInitOptions): LazyInit;
688
+ export function coldStartTracker(): Middleware;
689
+
690
+ // Error Classes
691
+ export class ValidationError extends Error {
692
+ field: string;
693
+ code: string;
694
+ }
695
+
696
+ export class AuthenticationError extends Error {}
697
+ export class AuthorizationError extends Error {}
698
+ export class AppError extends Error {
699
+ statusCode: number;
700
+ }
701
+ export class NotFoundError extends AppError {}
702
+ export class BadRequestError extends AppError {}
703
+ export class UnauthorizedError extends AppError {}
704
+ export class ForbiddenError extends AppError {}
705
+ export class ConflictError extends AppError {}
706
+ export class InternalServerError extends AppError {}
707
+
708
+ // Response and Retry helpers
709
+ export const response: ResponseHelpers;
710
+ export const retry: RetryHelpers;
711
+