ai.matey.http.core 0.2.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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/auth.js +173 -0
  3. package/dist/cjs/auth.js.map +1 -0
  4. package/dist/cjs/cors.js +140 -0
  5. package/dist/cjs/cors.js.map +1 -0
  6. package/dist/cjs/error-handler.js +147 -0
  7. package/dist/cjs/error-handler.js.map +1 -0
  8. package/dist/cjs/handler.js +335 -0
  9. package/dist/cjs/handler.js.map +1 -0
  10. package/dist/cjs/health.js +218 -0
  11. package/dist/cjs/health.js.map +1 -0
  12. package/dist/cjs/index.js +83 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/rate-limiter.js +163 -0
  15. package/dist/cjs/rate-limiter.js.map +1 -0
  16. package/dist/cjs/request-parser.js +141 -0
  17. package/dist/cjs/request-parser.js.map +1 -0
  18. package/dist/cjs/response-formatter.js +218 -0
  19. package/dist/cjs/response-formatter.js.map +1 -0
  20. package/dist/cjs/route-matcher.js +178 -0
  21. package/dist/cjs/route-matcher.js.map +1 -0
  22. package/dist/cjs/streaming-handler.js +120 -0
  23. package/dist/cjs/streaming-handler.js.map +1 -0
  24. package/dist/cjs/types.js +11 -0
  25. package/dist/cjs/types.js.map +1 -0
  26. package/dist/esm/auth.js +163 -0
  27. package/dist/esm/auth.js.map +1 -0
  28. package/dist/esm/cors.js +134 -0
  29. package/dist/esm/cors.js.map +1 -0
  30. package/dist/esm/error-handler.js +137 -0
  31. package/dist/esm/error-handler.js.map +1 -0
  32. package/dist/esm/handler.js +331 -0
  33. package/dist/esm/handler.js.map +1 -0
  34. package/dist/esm/health.js +210 -0
  35. package/dist/esm/health.js.map +1 -0
  36. package/dist/esm/index.js +30 -0
  37. package/dist/esm/index.js.map +1 -0
  38. package/dist/esm/rate-limiter.js +156 -0
  39. package/dist/esm/rate-limiter.js.map +1 -0
  40. package/dist/esm/request-parser.js +136 -0
  41. package/dist/esm/request-parser.js.map +1 -0
  42. package/dist/esm/response-formatter.js +206 -0
  43. package/dist/esm/response-formatter.js.map +1 -0
  44. package/dist/esm/route-matcher.js +171 -0
  45. package/dist/esm/route-matcher.js.map +1 -0
  46. package/dist/esm/streaming-handler.js +112 -0
  47. package/dist/esm/streaming-handler.js.map +1 -0
  48. package/dist/esm/types.js +10 -0
  49. package/dist/esm/types.js.map +1 -0
  50. package/dist/types/auth.d.ts +37 -0
  51. package/dist/types/auth.d.ts.map +1 -0
  52. package/dist/types/cors.d.ts +26 -0
  53. package/dist/types/cors.d.ts.map +1 -0
  54. package/dist/types/error-handler.d.ts +38 -0
  55. package/dist/types/error-handler.d.ts.map +1 -0
  56. package/dist/types/handler.d.ts +45 -0
  57. package/dist/types/handler.d.ts.map +1 -0
  58. package/dist/types/health.d.ts +164 -0
  59. package/dist/types/health.d.ts.map +1 -0
  60. package/dist/types/index.d.ts +21 -0
  61. package/dist/types/index.d.ts.map +1 -0
  62. package/dist/types/rate-limiter.d.ts +56 -0
  63. package/dist/types/rate-limiter.d.ts.map +1 -0
  64. package/dist/types/request-parser.d.ts +22 -0
  65. package/dist/types/request-parser.d.ts.map +1 -0
  66. package/dist/types/response-formatter.d.ts +49 -0
  67. package/dist/types/response-formatter.d.ts.map +1 -0
  68. package/dist/types/route-matcher.d.ts +45 -0
  69. package/dist/types/route-matcher.d.ts.map +1 -0
  70. package/dist/types/streaming-handler.d.ts +40 -0
  71. package/dist/types/streaming-handler.d.ts.map +1 -0
  72. package/dist/types/types.d.ts +398 -0
  73. package/dist/types/types.d.ts.map +1 -0
  74. package/package.json +73 -0
  75. package/readme.md +60 -0
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+ /**
3
+ * Core HTTP Handler
4
+ *
5
+ * Framework-agnostic HTTP request handler that can be adapted to any framework.
6
+ * Contains all the core logic for CORS, auth, rate limiting, routing, and streaming.
7
+ *
8
+ * @module
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.CoreHTTPHandler = void 0;
12
+ const rate_limiter_js_1 = require("./rate-limiter.js");
13
+ const route_matcher_js_1 = require("./route-matcher.js");
14
+ const cors_js_1 = require("./cors.js");
15
+ const response_formatter_js_1 = require("./response-formatter.js");
16
+ /**
17
+ * Core HTTP request handler (framework-agnostic)
18
+ */
19
+ class CoreHTTPHandler {
20
+ bridge;
21
+ options;
22
+ rateLimiter;
23
+ routeMatcher;
24
+ constructor(options) {
25
+ this.bridge = options.bridge;
26
+ // Normalize options
27
+ const corsOptions = (0, cors_js_1.normalizeCORSOptions)(options.cors);
28
+ // Apply path prefix to routes if provided
29
+ let routes = options.routes;
30
+ if (routes && options.pathPrefix) {
31
+ routes = (0, route_matcher_js_1.applyPathPrefix)(routes, options.pathPrefix);
32
+ }
33
+ this.options = {
34
+ bridge: this.bridge,
35
+ corsOptions,
36
+ validateAuth: options.validateAuth,
37
+ onError: options.onError,
38
+ headers: options.headers || {},
39
+ timeout: options.timeout ?? 30000,
40
+ pathPrefix: options.pathPrefix ?? '',
41
+ rateLimit: options.rateLimit,
42
+ routes,
43
+ logging: options.logging ?? false,
44
+ log: options.log ?? (() => { }), // no-op by default
45
+ maxBodySize: options.maxBodySize ?? 10 * 1024 * 1024, // 10MB
46
+ streaming: options.streaming ?? true,
47
+ };
48
+ // Create rate limiter if configured
49
+ // TODO: Refactor RateLimiter to use generic types
50
+ this.rateLimiter = this.options.rateLimit
51
+ ? new rate_limiter_js_1.RateLimiter(this.options.rateLimit)
52
+ : null;
53
+ // Create route matcher if routes configured
54
+ this.routeMatcher = this.options.routes ? new route_matcher_js_1.RouteMatcher(this.options.routes) : null;
55
+ }
56
+ /**
57
+ * Dispose of the handler and release resources.
58
+ * Call this when the handler is no longer needed to prevent memory leaks.
59
+ */
60
+ dispose() {
61
+ if (this.rateLimiter) {
62
+ this.rateLimiter.dispose();
63
+ }
64
+ }
65
+ /**
66
+ * Handle HTTP request
67
+ */
68
+ async handle(req, res) {
69
+ try {
70
+ // Handle CORS if enabled
71
+ if (this.options.corsOptions) {
72
+ const origin = req.headers.origin || req.headers['Origin'] || '';
73
+ // Check if origin is allowed
74
+ if (!this.isOriginAllowed(origin, this.options.corsOptions.origin)) {
75
+ res.status(403);
76
+ res.send({ error: 'Origin not allowed' });
77
+ return;
78
+ }
79
+ // Set CORS headers
80
+ if (typeof this.options.corsOptions.origin === 'string' &&
81
+ this.options.corsOptions.origin === '*') {
82
+ res.header('Access-Control-Allow-Origin', '*');
83
+ }
84
+ else if (origin) {
85
+ res.header('Access-Control-Allow-Origin', origin);
86
+ res.header('Vary', 'Origin');
87
+ }
88
+ if (this.options.corsOptions.credentials) {
89
+ res.header('Access-Control-Allow-Credentials', 'true');
90
+ }
91
+ if (this.options.corsOptions.exposedHeaders &&
92
+ this.options.corsOptions.exposedHeaders.length > 0) {
93
+ res.header('Access-Control-Expose-Headers', Array.isArray(this.options.corsOptions.exposedHeaders)
94
+ ? this.options.corsOptions.exposedHeaders.join(', ')
95
+ : this.options.corsOptions.exposedHeaders);
96
+ }
97
+ // Handle preflight
98
+ const isPreflightRequest = req.method === 'OPTIONS' &&
99
+ origin &&
100
+ (req.headers['access-control-request-method'] ||
101
+ req.headers['Access-Control-Request-Method']);
102
+ if (isPreflightRequest) {
103
+ // Set preflight headers
104
+ res.header('Access-Control-Allow-Methods', Array.isArray(this.options.corsOptions.methods)
105
+ ? this.options.corsOptions.methods.join(', ')
106
+ : this.options.corsOptions.methods);
107
+ const requestHeaders = req.headers['access-control-request-headers'] ||
108
+ req.headers['Access-Control-Request-Headers'];
109
+ if (requestHeaders) {
110
+ res.header('Access-Control-Allow-Headers', requestHeaders);
111
+ }
112
+ else if (this.options.corsOptions.allowedHeaders) {
113
+ res.header('Access-Control-Allow-Headers', Array.isArray(this.options.corsOptions.allowedHeaders)
114
+ ? this.options.corsOptions.allowedHeaders.join(', ')
115
+ : this.options.corsOptions.allowedHeaders);
116
+ }
117
+ res.header('Access-Control-Max-Age', String(this.options.corsOptions.maxAge));
118
+ // Send successful preflight response
119
+ res.status(204);
120
+ res.send('');
121
+ return;
122
+ }
123
+ }
124
+ // Check rate limit
125
+ if (this.rateLimiter && res.isWritable()) {
126
+ // Create minimal Node.js-like request/response for rate limiter
127
+ // TODO: Refactor rate limiter to use generic types
128
+ const nodeReq = {
129
+ headers: req.headers,
130
+ socket: { remoteAddress: req.ip },
131
+ };
132
+ const nodeRes = {
133
+ setHeader: (name, value) => res.header(name, value),
134
+ end: (data) => {
135
+ if (data) {
136
+ res.send(JSON.parse(data));
137
+ }
138
+ },
139
+ get statusCode() {
140
+ return this._statusCode || 200;
141
+ },
142
+ set statusCode(value) {
143
+ this._statusCode = value;
144
+ res.status(value);
145
+ },
146
+ _statusCode: 200,
147
+ };
148
+ const isLimited = await this.rateLimiter.check(nodeReq, nodeRes);
149
+ if (isLimited) {
150
+ return; // Rate limiter already sent response
151
+ }
152
+ }
153
+ // Validate authentication
154
+ if (this.options.validateAuth) {
155
+ const isAuthenticated = await this.options.validateAuth(req);
156
+ if (!isAuthenticated) {
157
+ const format = (0, response_formatter_js_1.detectProviderFormat)(req.url || '');
158
+ res.status(401);
159
+ res.send(this.formatErrorResponse(new Error('Unauthorized'), 401, format));
160
+ return;
161
+ }
162
+ }
163
+ // Parse request (create explicit object instead of spread to ensure all properties are copied)
164
+ const parsedRequest = {
165
+ method: req.method,
166
+ url: req.url,
167
+ headers: req.headers,
168
+ body: req.body,
169
+ params: req.params,
170
+ query: req.query,
171
+ ip: req.ip,
172
+ stream: req.body?.stream === true,
173
+ };
174
+ // Log request if enabled
175
+ if (this.options.logging && this.options.log) {
176
+ this.options.log(`${parsedRequest.method} ${parsedRequest.url}`, parsedRequest.body);
177
+ }
178
+ // Check if request body exists for POST/PUT/PATCH
179
+ if (['POST', 'PUT', 'PATCH'].includes(parsedRequest.method) && !parsedRequest.body) {
180
+ const format = (0, response_formatter_js_1.detectProviderFormat)(parsedRequest.url || '');
181
+ res.status(400);
182
+ res.send(this.formatErrorResponse(new Error('Request body is required'), 400, format));
183
+ return;
184
+ }
185
+ // Match route if route matcher configured
186
+ let activeBridge = this.bridge;
187
+ if (this.routeMatcher) {
188
+ // Create minimal Node.js-like request for route matcher
189
+ // TODO: Refactor route matcher to use generic types
190
+ const nodeReq = {
191
+ url: req.url,
192
+ method: req.method,
193
+ };
194
+ const matchedRoute = this.routeMatcher.match(nodeReq);
195
+ if (!matchedRoute) {
196
+ res.status(404);
197
+ res.send({ error: 'Route not found' });
198
+ return;
199
+ }
200
+ // Use route-specific bridge if provided
201
+ if (matchedRoute.config.bridge) {
202
+ activeBridge = matchedRoute.config.bridge;
203
+ }
204
+ }
205
+ // Apply custom headers
206
+ if (this.options.headers) {
207
+ for (const [key, value] of Object.entries(this.options.headers)) {
208
+ res.header(key, value);
209
+ }
210
+ }
211
+ // Handle streaming or non-streaming request
212
+ if (this.options.streaming && parsedRequest.stream) {
213
+ // Handle streaming request
214
+ const stream = activeBridge.chatStream(parsedRequest.body);
215
+ // Convert to async generator for generic response
216
+ async function* convertStream() {
217
+ for await (const chunk of stream) {
218
+ yield chunk;
219
+ }
220
+ }
221
+ await res.stream(convertStream());
222
+ }
223
+ else {
224
+ // Handle non-streaming request
225
+ const response = await activeBridge.chat(parsedRequest.body);
226
+ // Send response
227
+ res.status(200);
228
+ res.send(response);
229
+ }
230
+ // Log response if enabled
231
+ if (this.options.logging && this.options.log) {
232
+ this.options.log(`${parsedRequest.method} ${parsedRequest.url} - 200 OK`);
233
+ }
234
+ }
235
+ catch (error) {
236
+ // Handle errors
237
+ await this.handleError(error, req, res);
238
+ }
239
+ }
240
+ /**
241
+ * Handle errors
242
+ */
243
+ async handleError(error, req, res) {
244
+ // Log error if enabled
245
+ if (this.options.logging && this.options.log) {
246
+ this.options.log(`Error: ${req.method} ${req.url}`, error);
247
+ }
248
+ // Call error handler
249
+ if (this.options.onError) {
250
+ await this.options.onError(error, req, res);
251
+ }
252
+ else {
253
+ // Use built-in error formatting
254
+ const format = (0, response_formatter_js_1.detectProviderFormat)(req.url || '');
255
+ const statusCode = this.getErrorStatusCode(error);
256
+ res.status(statusCode);
257
+ res.send(this.formatErrorResponse(error, statusCode, format));
258
+ }
259
+ }
260
+ /**
261
+ * Check if origin is allowed
262
+ */
263
+ isOriginAllowed(origin, allowedOrigin) {
264
+ if (!origin) {
265
+ return true; // Allow requests without origin header
266
+ }
267
+ if (typeof allowedOrigin === 'string') {
268
+ return allowedOrigin === '*' || allowedOrigin === origin;
269
+ }
270
+ if (Array.isArray(allowedOrigin)) {
271
+ return allowedOrigin.includes(origin) || allowedOrigin.includes('*');
272
+ }
273
+ if (typeof allowedOrigin === 'function') {
274
+ return allowedOrigin(origin);
275
+ }
276
+ return false;
277
+ }
278
+ /**
279
+ * Get HTTP status code from error
280
+ */
281
+ getErrorStatusCode(error) {
282
+ // Check for common error patterns
283
+ const message = error.message.toLowerCase();
284
+ if (message.includes('unauthorized') || message.includes('authentication')) {
285
+ return 401;
286
+ }
287
+ if (message.includes('forbidden') || message.includes('permission')) {
288
+ return 403;
289
+ }
290
+ if (message.includes('not found')) {
291
+ return 404;
292
+ }
293
+ if (message.includes('timeout')) {
294
+ return 408;
295
+ }
296
+ if (message.includes('conflict')) {
297
+ return 409;
298
+ }
299
+ if (message.includes('validation') || message.includes('invalid')) {
300
+ return 400;
301
+ }
302
+ // Default to 500 for unknown errors
303
+ return 500;
304
+ }
305
+ /**
306
+ * Format error response in provider-specific format
307
+ */
308
+ formatErrorResponse(error, statusCode, format) {
309
+ if (format === 'openai') {
310
+ return {
311
+ error: {
312
+ message: error.message,
313
+ type: 'server_error',
314
+ code: statusCode >= 500 ? 'internal_server_error' : 'invalid_request_error',
315
+ },
316
+ };
317
+ }
318
+ if (format === 'anthropic') {
319
+ return {
320
+ type: 'error',
321
+ error: {
322
+ type: statusCode >= 500 ? 'api_error' : 'invalid_request_error',
323
+ message: error.message,
324
+ },
325
+ };
326
+ }
327
+ // Generic format
328
+ return {
329
+ error: error.message,
330
+ statusCode,
331
+ };
332
+ }
333
+ }
334
+ exports.CoreHTTPHandler = CoreHTTPHandler;
335
+ //# sourceMappingURL=handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../src/handler.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AASH,uDAAgD;AAChD,yDAAmE;AACnE,uCAAiD;AACjD,mEAA+D;AAE/D;;GAEG;AACH,MAAa,eAAe;IACT,MAAM,CAAS;IACf,OAAO,CAQtB;IACe,WAAW,CAAqB;IAChC,YAAY,CAAsB;IAEnD,YAAY,OAA2B;QACrC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAE7B,oBAAoB;QACpB,MAAM,WAAW,GAAG,IAAA,8BAAoB,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAEvD,0CAA0C;QAC1C,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC5B,IAAI,MAAM,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACjC,MAAM,GAAG,IAAA,kCAAe,EAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACvD,CAAC;QAED,IAAI,CAAC,OAAO,GAAG;YACb,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,WAAW;YACX,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE;YAC9B,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,KAAK;YACjC,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE;YACpC,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,MAAM;YACN,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,KAAK;YACjC,GAAG,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,EAAE,mBAAmB;YACnD,WAAW,EAAE,OAAO,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7YD,0CA6YC"}
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ /**
3
+ * Health Check Utilities
4
+ *
5
+ * Health check endpoint for monitoring and load balancers.
6
+ *
7
+ * @module
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.HealthCheck = void 0;
11
+ exports.createHealthCheck = createHealthCheck;
12
+ exports.createHealthCheckMiddleware = createHealthCheckMiddleware;
13
+ exports.createReadinessCheck = createReadinessCheck;
14
+ exports.createLivenessCheck = createLivenessCheck;
15
+ /**
16
+ * Health check handler
17
+ */
18
+ class HealthCheck {
19
+ config;
20
+ customChecks;
21
+ metadata;
22
+ startTime;
23
+ router;
24
+ constructor(bridgeOrRouter, config = {}) {
25
+ this.config = {
26
+ serviceName: 'ai.matey',
27
+ version: '1.0.0',
28
+ includeUptime: true,
29
+ includeChecks: true,
30
+ checkBackends: true,
31
+ ...config,
32
+ };
33
+ this.customChecks = config.customChecks || {};
34
+ this.metadata = config.metadata || {};
35
+ this.startTime = Date.now();
36
+ // Detect if bridge or router
37
+ if ('getBackends' in bridgeOrRouter) {
38
+ this.router = bridgeOrRouter;
39
+ }
40
+ // Bridge support can be added in the future
41
+ }
42
+ /**
43
+ * Perform health check
44
+ */
45
+ async check() {
46
+ const checks = {};
47
+ // Basic system check
48
+ if (this.config.includeChecks) {
49
+ checks.system = {
50
+ status: 'healthy',
51
+ message: 'System operational',
52
+ };
53
+ // Check backend health (router only)
54
+ if (this.router && this.config.checkBackends) {
55
+ try {
56
+ // For now, assume healthy if router exists
57
+ // In the future, we can add a getBackends() method to Router
58
+ checks.backends = {
59
+ status: 'healthy',
60
+ message: 'Router operational',
61
+ };
62
+ }
63
+ catch (error) {
64
+ checks.backends = {
65
+ status: 'unhealthy',
66
+ message: 'Unable to check backends',
67
+ details: { error: error.message },
68
+ };
69
+ }
70
+ }
71
+ // Run custom checks
72
+ for (const [name, checkFn] of Object.entries(this.customChecks)) {
73
+ try {
74
+ checks[name] = await checkFn();
75
+ }
76
+ catch (error) {
77
+ checks[name] = {
78
+ status: 'unhealthy',
79
+ message: `Check failed: ${error.message}`,
80
+ };
81
+ }
82
+ }
83
+ }
84
+ // Determine overall status
85
+ const statuses = Object.values(checks).map((c) => c.status);
86
+ let overallStatus = 'healthy';
87
+ if (statuses.includes('unhealthy')) {
88
+ overallStatus = 'unhealthy';
89
+ }
90
+ else if (statuses.includes('degraded')) {
91
+ overallStatus = 'degraded';
92
+ }
93
+ const result = {
94
+ status: overallStatus,
95
+ timestamp: new Date().toISOString(),
96
+ service: this.config.serviceName,
97
+ version: this.config.version,
98
+ };
99
+ if (this.config.includeUptime) {
100
+ result.uptime = Date.now() - this.startTime;
101
+ }
102
+ if (this.config.includeChecks && Object.keys(checks).length > 0) {
103
+ result.checks = checks;
104
+ }
105
+ if (Object.keys(this.metadata).length > 0) {
106
+ result.metadata = this.metadata;
107
+ }
108
+ return result;
109
+ }
110
+ /**
111
+ * Handle health check request
112
+ */
113
+ async handle(_req, res) {
114
+ const result = await this.check();
115
+ // Set status code based on health
116
+ const statusCode = result.status === 'healthy' ? 200 : result.status === 'degraded' ? 200 : 503;
117
+ res.status(statusCode);
118
+ res.header('Content-Type', 'application/json');
119
+ res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
120
+ res.send(result);
121
+ }
122
+ }
123
+ exports.HealthCheck = HealthCheck;
124
+ /**
125
+ * Create health check handler
126
+ *
127
+ * @param bridgeOrRouter - Bridge or Router instance
128
+ * @param config - Health check configuration
129
+ * @returns Health check handler
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * import { createHealthCheck } from 'ai.matey.http';
134
+ *
135
+ * const healthCheck = createHealthCheck(bridge, {
136
+ * serviceName: 'my-ai-service',
137
+ * version: '1.0.0',
138
+ * });
139
+ *
140
+ * // In your HTTP server:
141
+ * if (req.url === '/health') {
142
+ * await healthCheck.handle(req, res);
143
+ * }
144
+ * ```
145
+ */
146
+ function createHealthCheck(bridgeOrRouter, config) {
147
+ return new HealthCheck(bridgeOrRouter, config);
148
+ }
149
+ /**
150
+ * Create simple health check middleware
151
+ *
152
+ * @param bridgeOrRouter - Bridge or Router instance
153
+ * @param path - Health check path (default: '/health')
154
+ * @param config - Health check configuration
155
+ * @returns Middleware function
156
+ *
157
+ * @example
158
+ * ```typescript
159
+ * import { createHealthCheckMiddleware } from 'ai.matey.http';
160
+ *
161
+ * const healthMiddleware = createHealthCheckMiddleware(bridge);
162
+ *
163
+ * // Use in HTTP server
164
+ * app.use(healthMiddleware);
165
+ * ```
166
+ */
167
+ function createHealthCheckMiddleware(bridgeOrRouter, path = '/health', config) {
168
+ const healthCheck = new HealthCheck(bridgeOrRouter, config);
169
+ return async (req, res) => {
170
+ if (req.url === path || req.url?.startsWith(`${path}?`)) {
171
+ await healthCheck.handle(req, res);
172
+ return true; // Handled
173
+ }
174
+ return false; // Not handled
175
+ };
176
+ }
177
+ /**
178
+ * Readiness check (for Kubernetes)
179
+ *
180
+ * Returns 200 when service is ready to accept traffic.
181
+ */
182
+ function createReadinessCheck(bridgeOrRouter) {
183
+ const healthCheck = new HealthCheck(bridgeOrRouter, {
184
+ includeUptime: false,
185
+ includeChecks: true,
186
+ checkBackends: true,
187
+ });
188
+ return async (_req, res) => {
189
+ const result = await healthCheck.check();
190
+ // Only ready if all checks are healthy
191
+ const isReady = result.status === 'healthy';
192
+ res.status(isReady ? 200 : 503);
193
+ res.header('Content-Type', 'application/json');
194
+ res.send({
195
+ ready: isReady,
196
+ timestamp: result.timestamp,
197
+ checks: result.checks,
198
+ });
199
+ };
200
+ }
201
+ /**
202
+ * Liveness check (for Kubernetes)
203
+ *
204
+ * Returns 200 if service is alive (even if degraded).
205
+ */
206
+ function createLivenessCheck() {
207
+ const startTime = Date.now();
208
+ return (_req, res) => {
209
+ res.status(200);
210
+ res.header('Content-Type', 'application/json');
211
+ res.send({
212
+ alive: true,
213
+ timestamp: new Date().toISOString(),
214
+ uptime: Date.now() - startTime,
215
+ });
216
+ };
217
+ }
218
+ //# sourceMappingURL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C,GAAG,CAAC,IAAI,CAAC;YACP,KAAK,EAAE,OAAO;YACd,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,MAAM,EAAE,MAAM,CAAC,MAAM;SACtB,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB;IACjC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAE7B,OAAO,CAAC,IAAoB,EAAE,GAAoB,EAAQ,EAAE;QAC1D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChB,GAAG,CAAC,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QAC/C,GAAG,CAAC,IAAI,CAAC;YACP,KAAK,EAAE,IAAI;YACX,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ /**
3
+ * HTTP Core Module
4
+ *
5
+ * Framework-agnostic HTTP utilities for the Universal AI Adapter System.
6
+ * This package provides the core logic for HTTP request handling that can
7
+ * be adapted to any HTTP framework.
8
+ *
9
+ * @module
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createLivenessCheck = exports.createReadinessCheck = exports.createHealthCheckMiddleware = exports.createHealthCheck = exports.HealthCheck = exports.applyPathPrefix = exports.normalizePath = exports.createDefaultRoutes = exports.RouteMatcher = exports.createAbortController = exports.supportsStreaming = exports.onClientDisconnect = exports.SSEKeepAlive = exports.handleStreamingRequest = exports.isServerError = exports.isClientError = exports.isRetryableError = exports.wrapErrorHandler = exports.createReportingErrorHandler = exports.createLoggingErrorHandler = exports.defaultErrorHandler = exports.combineKeyGenerators = exports.tokenKeyGenerator = exports.userIDKeyGenerator = exports.RateLimiter = exports.skipAuthForPaths = exports.requireAllAuth = exports.combineAuthValidators = exports.createBasicAuthValidator = exports.createAPIKeyValidator = exports.createBearerTokenValidator = exports.defaultAuthValidator = exports.isPreflight = exports.handlePreflight = exports.handleCORS = exports.normalizeCORSOptions = exports.detectProviderFormat = exports.sendNoContent = exports.sendText = exports.sendSSEError = exports.sendSSEDone = exports.sendSSEEvent = exports.sendSSEChunk = exports.sendSSEHeaders = exports.sendError = exports.sendJSON = exports.getClientIP = exports.extractBearerToken = exports.parseRequest = exports.CoreHTTPHandler = void 0;
13
+ // Core handler
14
+ var handler_js_1 = require("./handler.js");
15
+ Object.defineProperty(exports, "CoreHTTPHandler", { enumerable: true, get: function () { return handler_js_1.CoreHTTPHandler; } });
16
+ // Request parsing
17
+ var request_parser_js_1 = require("./request-parser.js");
18
+ Object.defineProperty(exports, "parseRequest", { enumerable: true, get: function () { return request_parser_js_1.parseRequest; } });
19
+ Object.defineProperty(exports, "extractBearerToken", { enumerable: true, get: function () { return request_parser_js_1.extractBearerToken; } });
20
+ Object.defineProperty(exports, "getClientIP", { enumerable: true, get: function () { return request_parser_js_1.getClientIP; } });
21
+ // Response formatting
22
+ var response_formatter_js_1 = require("./response-formatter.js");
23
+ Object.defineProperty(exports, "sendJSON", { enumerable: true, get: function () { return response_formatter_js_1.sendJSON; } });
24
+ Object.defineProperty(exports, "sendError", { enumerable: true, get: function () { return response_formatter_js_1.sendError; } });
25
+ Object.defineProperty(exports, "sendSSEHeaders", { enumerable: true, get: function () { return response_formatter_js_1.sendSSEHeaders; } });
26
+ Object.defineProperty(exports, "sendSSEChunk", { enumerable: true, get: function () { return response_formatter_js_1.sendSSEChunk; } });
27
+ Object.defineProperty(exports, "sendSSEEvent", { enumerable: true, get: function () { return response_formatter_js_1.sendSSEEvent; } });
28
+ Object.defineProperty(exports, "sendSSEDone", { enumerable: true, get: function () { return response_formatter_js_1.sendSSEDone; } });
29
+ Object.defineProperty(exports, "sendSSEError", { enumerable: true, get: function () { return response_formatter_js_1.sendSSEError; } });
30
+ Object.defineProperty(exports, "sendText", { enumerable: true, get: function () { return response_formatter_js_1.sendText; } });
31
+ Object.defineProperty(exports, "sendNoContent", { enumerable: true, get: function () { return response_formatter_js_1.sendNoContent; } });
32
+ Object.defineProperty(exports, "detectProviderFormat", { enumerable: true, get: function () { return response_formatter_js_1.detectProviderFormat; } });
33
+ // CORS
34
+ var cors_js_1 = require("./cors.js");
35
+ Object.defineProperty(exports, "normalizeCORSOptions", { enumerable: true, get: function () { return cors_js_1.normalizeCORSOptions; } });
36
+ Object.defineProperty(exports, "handleCORS", { enumerable: true, get: function () { return cors_js_1.handleCORS; } });
37
+ Object.defineProperty(exports, "handlePreflight", { enumerable: true, get: function () { return cors_js_1.handlePreflight; } });
38
+ Object.defineProperty(exports, "isPreflight", { enumerable: true, get: function () { return cors_js_1.isPreflight; } });
39
+ // Authentication
40
+ var auth_js_1 = require("./auth.js");
41
+ Object.defineProperty(exports, "defaultAuthValidator", { enumerable: true, get: function () { return auth_js_1.defaultAuthValidator; } });
42
+ Object.defineProperty(exports, "createBearerTokenValidator", { enumerable: true, get: function () { return auth_js_1.createBearerTokenValidator; } });
43
+ Object.defineProperty(exports, "createAPIKeyValidator", { enumerable: true, get: function () { return auth_js_1.createAPIKeyValidator; } });
44
+ Object.defineProperty(exports, "createBasicAuthValidator", { enumerable: true, get: function () { return auth_js_1.createBasicAuthValidator; } });
45
+ Object.defineProperty(exports, "combineAuthValidators", { enumerable: true, get: function () { return auth_js_1.combineAuthValidators; } });
46
+ Object.defineProperty(exports, "requireAllAuth", { enumerable: true, get: function () { return auth_js_1.requireAllAuth; } });
47
+ Object.defineProperty(exports, "skipAuthForPaths", { enumerable: true, get: function () { return auth_js_1.skipAuthForPaths; } });
48
+ // Rate limiting
49
+ var rate_limiter_js_1 = require("./rate-limiter.js");
50
+ Object.defineProperty(exports, "RateLimiter", { enumerable: true, get: function () { return rate_limiter_js_1.RateLimiter; } });
51
+ Object.defineProperty(exports, "userIDKeyGenerator", { enumerable: true, get: function () { return rate_limiter_js_1.userIDKeyGenerator; } });
52
+ Object.defineProperty(exports, "tokenKeyGenerator", { enumerable: true, get: function () { return rate_limiter_js_1.tokenKeyGenerator; } });
53
+ Object.defineProperty(exports, "combineKeyGenerators", { enumerable: true, get: function () { return rate_limiter_js_1.combineKeyGenerators; } });
54
+ // Error handling
55
+ var error_handler_js_1 = require("./error-handler.js");
56
+ Object.defineProperty(exports, "defaultErrorHandler", { enumerable: true, get: function () { return error_handler_js_1.defaultErrorHandler; } });
57
+ Object.defineProperty(exports, "createLoggingErrorHandler", { enumerable: true, get: function () { return error_handler_js_1.createLoggingErrorHandler; } });
58
+ Object.defineProperty(exports, "createReportingErrorHandler", { enumerable: true, get: function () { return error_handler_js_1.createReportingErrorHandler; } });
59
+ Object.defineProperty(exports, "wrapErrorHandler", { enumerable: true, get: function () { return error_handler_js_1.wrapErrorHandler; } });
60
+ Object.defineProperty(exports, "isRetryableError", { enumerable: true, get: function () { return error_handler_js_1.isRetryableError; } });
61
+ Object.defineProperty(exports, "isClientError", { enumerable: true, get: function () { return error_handler_js_1.isClientError; } });
62
+ Object.defineProperty(exports, "isServerError", { enumerable: true, get: function () { return error_handler_js_1.isServerError; } });
63
+ // Streaming
64
+ var streaming_handler_js_1 = require("./streaming-handler.js");
65
+ Object.defineProperty(exports, "handleStreamingRequest", { enumerable: true, get: function () { return streaming_handler_js_1.handleStreamingRequest; } });
66
+ Object.defineProperty(exports, "SSEKeepAlive", { enumerable: true, get: function () { return streaming_handler_js_1.SSEKeepAlive; } });
67
+ Object.defineProperty(exports, "onClientDisconnect", { enumerable: true, get: function () { return streaming_handler_js_1.onClientDisconnect; } });
68
+ Object.defineProperty(exports, "supportsStreaming", { enumerable: true, get: function () { return streaming_handler_js_1.supportsStreaming; } });
69
+ Object.defineProperty(exports, "createAbortController", { enumerable: true, get: function () { return streaming_handler_js_1.createAbortController; } });
70
+ // Routing
71
+ var route_matcher_js_1 = require("./route-matcher.js");
72
+ Object.defineProperty(exports, "RouteMatcher", { enumerable: true, get: function () { return route_matcher_js_1.RouteMatcher; } });
73
+ Object.defineProperty(exports, "createDefaultRoutes", { enumerable: true, get: function () { return route_matcher_js_1.createDefaultRoutes; } });
74
+ Object.defineProperty(exports, "normalizePath", { enumerable: true, get: function () { return route_matcher_js_1.normalizePath; } });
75
+ Object.defineProperty(exports, "applyPathPrefix", { enumerable: true, get: function () { return route_matcher_js_1.applyPathPrefix; } });
76
+ // Health checks
77
+ var health_js_1 = require("./health.js");
78
+ Object.defineProperty(exports, "HealthCheck", { enumerable: true, get: function () { return health_js_1.HealthCheck; } });
79
+ Object.defineProperty(exports, "createHealthCheck", { enumerable: true, get: function () { return health_js_1.createHealthCheck; } });
80
+ Object.defineProperty(exports, "createHealthCheckMiddleware", { enumerable: true, get: function () { return health_js_1.createHealthCheckMiddleware; } });
81
+ Object.defineProperty(exports, "createReadinessCheck", { enumerable: true, get: function () { return health_js_1.createReadinessCheck; } });
82
+ Object.defineProperty(exports, "createLivenessCheck", { enumerable: true, get: function () { return health_js_1.createLivenessCheck; } });
83
+ //# sourceMappingURL=index.js.map