@noony-serverless/core 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +7 -7
  2. package/build/core/core.d.ts +18 -50
  3. package/build/core/core.js +5 -67
  4. package/build/core/handler.d.ts +37 -16
  5. package/build/core/handler.js +131 -42
  6. package/build/core/index.d.ts +0 -1
  7. package/build/core/index.js +0 -1
  8. package/build/middlewares/ConsolidatedValidationMiddleware.d.ts +126 -0
  9. package/build/middlewares/ConsolidatedValidationMiddleware.js +330 -0
  10. package/build/middlewares/ProcessingMiddleware.d.ts +138 -0
  11. package/build/middlewares/ProcessingMiddleware.js +425 -0
  12. package/build/middlewares/SecurityMiddleware.d.ts +157 -0
  13. package/build/middlewares/SecurityMiddleware.js +307 -0
  14. package/build/middlewares/bodyValidationMiddleware.d.ts +12 -10
  15. package/build/middlewares/bodyValidationMiddleware.js +10 -8
  16. package/build/middlewares/dependencyInjectionMiddleware.js +1 -1
  17. package/build/middlewares/guards/RouteGuards.d.ts +239 -4
  18. package/build/middlewares/guards/RouteGuards.js +301 -8
  19. package/build/middlewares/guards/adapters/CustomTokenVerificationPortAdapter.d.ts +271 -0
  20. package/build/middlewares/guards/adapters/CustomTokenVerificationPortAdapter.js +301 -0
  21. package/build/middlewares/guards/config/GuardConfiguration.d.ts +50 -0
  22. package/build/middlewares/guards/config/GuardConfiguration.js +59 -0
  23. package/build/middlewares/guards/guards/FastAuthGuard.d.ts +5 -5
  24. package/build/middlewares/guards/guards/PermissionGuardFactory.d.ts +5 -13
  25. package/build/middlewares/guards/guards/PermissionGuardFactory.js +4 -4
  26. package/build/middlewares/guards/index.d.ts +43 -1
  27. package/build/middlewares/guards/index.js +46 -1
  28. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.d.ts +1 -1
  29. package/build/middlewares/guards/resolvers/ExpressionPermissionResolver.js +1 -1
  30. package/build/middlewares/guards/resolvers/PermissionResolver.d.ts +1 -1
  31. package/build/middlewares/guards/resolvers/PlainPermissionResolver.d.ts +1 -1
  32. package/build/middlewares/guards/resolvers/WildcardPermissionResolver.d.ts +1 -1
  33. package/build/middlewares/guards/services/FastUserContextService.d.ts +20 -33
  34. package/build/middlewares/guards/services/FastUserContextService.js +17 -4
  35. package/build/middlewares/httpAttributesMiddleware.js +1 -1
  36. package/build/middlewares/index.d.ts +3 -1
  37. package/build/middlewares/index.js +6 -1
  38. package/build/middlewares/rateLimitingMiddleware.d.ts +492 -4
  39. package/build/middlewares/rateLimitingMiddleware.js +514 -6
  40. package/package.json +11 -9
  41. package/build/core/containerPool.d.ts +0 -44
  42. package/build/core/containerPool.js +0 -103
  43. package/build/middlewares/validationMiddleware.d.ts +0 -154
  44. package/build/middlewares/validationMiddleware.js +0 -185
package/README.md CHANGED
@@ -9,7 +9,7 @@ A powerful and flexible serverless middleware framework for Google Cloud Functio
9
9
  The `Handler` class manages the middleware execution pipeline with `before`, `after`, and `onError` lifecycle hooks:
10
10
 
11
11
  ```typescript
12
- const handler = new Handler<RequestType, UserType>()
12
+ const handler = new Handler<RequestType>()
13
13
  .use(errorHandler())
14
14
  .use(bodyParser())
15
15
  .use(bodyValidator(schema))
@@ -23,7 +23,7 @@ const handler = new Handler<RequestType, UserType>()
23
23
  The context system provides full TypeScript support with generic typing:
24
24
 
25
25
  ```typescript
26
- interface Context<T = unknown, U = unknown> {
26
+ interface Context<T = unknown> {
27
27
  req: CustomRequest<T>; // Request with parsedBody and validatedBody
28
28
  res: CustomResponse; // Response object
29
29
  container?: Container; // TypeDI dependency injection
@@ -72,7 +72,7 @@ const userSchema = z.object({
72
72
  type UserRequest = z.infer<typeof userSchema>;
73
73
 
74
74
  // Create handler with full type safety
75
- const createUserHandler = new Handler<UserRequest, unknown>()
75
+ const createUserHandler = new Handler<UserRequest>()
76
76
  .use(new ErrorHandlerMiddleware())
77
77
  .use(new BodyValidationMiddleware(userSchema))
78
78
  .use(new ResponseWrapperMiddleware())
@@ -117,7 +117,7 @@ const messageSchema = z.object({
117
117
  type PubSubMessage = z.infer<typeof messageSchema>;
118
118
 
119
119
  // Create Pub/Sub handler
120
- const pubsubHandler = new Handler<PubSubMessage, unknown>()
120
+ const pubsubHandler = new Handler<PubSubMessage>()
121
121
  .use(new ErrorHandlerMiddleware())
122
122
  .use(new BodyParserMiddleware()) // Decodes base64 Pub/Sub messages
123
123
  .use(new BodyValidationMiddleware(messageSchema))
@@ -296,7 +296,7 @@ app.post('/users', async (req, res) => {
296
296
  ### 1. Middleware Order
297
297
 
298
298
  ```typescript
299
- const handler = new Handler<RequestType, UserType>()
299
+ const handler = new Handler<RequestType>()
300
300
  .use(new ErrorHandlerMiddleware()) // Always first
301
301
  .use(new HeaderVariablesMiddleware(...)) // Required headers
302
302
  .use(new AuthenticationMiddleware(...)) // Authentication
@@ -324,7 +324,7 @@ interface UserContext {
324
324
  }
325
325
 
326
326
  // Use throughout the handler
327
- const handler = new Handler<UserRequest, UserContext>();
327
+ const handler = new Handler<UserRequest>();
328
328
  ```
329
329
 
330
330
  ### 3. Error Handling
@@ -361,7 +361,7 @@ import {
361
361
  } from '@noony/serverless';
362
362
 
363
363
  // No type casting needed with proper generics
364
- const handler = new Handler<UserRequest, UserContext>()
364
+ const handler = new Handler<UserRequest>()
365
365
  .handle(async (context) => {
366
366
  // TypeScript knows validatedBody is UserRequest
367
367
  const { name, email } = context.req.validatedBody!;
@@ -1,5 +1,4 @@
1
- import { Request, Response } from '@google-cloud/functions-framework';
2
- import Container from 'typedi';
1
+ import { ContainerInstance } from 'typedi';
3
2
  /**
4
3
  * Framework-agnostic HTTP method enum
5
4
  */
@@ -15,7 +14,7 @@ export declare enum HttpMethod {
15
14
  /**
16
15
  * Framework-agnostic request interface that can work with any HTTP framework
17
16
  */
18
- export interface GenericRequest<T = unknown> {
17
+ export interface NoonyRequest<T = unknown> {
19
18
  method: HttpMethod | string;
20
19
  url: string;
21
20
  path?: string;
@@ -32,30 +31,20 @@ export interface GenericRequest<T = unknown> {
32
31
  /**
33
32
  * Framework-agnostic response interface that can work with any HTTP framework
34
33
  */
35
- export interface GenericResponse {
36
- status(code: number): GenericResponse;
37
- json(data: unknown): GenericResponse | void;
38
- send(data: unknown): GenericResponse | void;
39
- header(name: string, value: string): GenericResponse;
40
- headers(headers: Record<string, string>): GenericResponse;
34
+ export interface NoonyResponse {
35
+ status(code: number): NoonyResponse;
36
+ json(data: unknown): NoonyResponse | void;
37
+ send(data: unknown): NoonyResponse | void;
38
+ header(name: string, value: string): NoonyResponse;
39
+ headers(headers: Record<string, string>): NoonyResponse;
41
40
  end(): void;
42
41
  statusCode?: number;
43
42
  headersSent?: boolean;
44
43
  }
45
- /**
46
- * Legacy GCP Functions-specific request interface for backward compatibility
47
- * @deprecated Use GenericRequest instead
48
- */
49
- export interface CustomRequest<T = unknown> extends Request {
50
- parsedBody?: T;
51
- validatedBody?: T;
52
- }
53
- /**
54
- * Legacy GCP Functions-specific response interface for backward compatibility
55
- * @deprecated Use GenericResponse instead
56
- */
57
- export interface CustomResponse extends Response {
58
- }
44
+ /** @deprecated Use NoonyRequest instead */
45
+ export type GenericRequest<T = unknown> = NoonyRequest<T>;
46
+ /** @deprecated Use NoonyResponse instead */
47
+ export type GenericResponse = NoonyResponse;
59
48
  /**
60
49
  * Security configuration for request processing
61
50
  */
@@ -78,46 +67,25 @@ export interface HandlerOptions {
78
67
  * Represents the execution context for handling a request and response in an application.
79
68
  *
80
69
  * @template T Specifies the type of the custom request payload.
81
- * @template V Specifies the type of the user-related information.
82
70
  */
83
- export interface Context<T = unknown, V = unknown> {
84
- readonly req: GenericRequest<T>;
85
- readonly res: GenericResponse;
86
- container?: Container;
71
+ export interface Context<T = unknown> {
72
+ readonly req: NoonyRequest<T>;
73
+ readonly res: NoonyResponse;
74
+ container?: ContainerInstance;
87
75
  error?: Error | null;
88
76
  readonly businessData: Map<string, unknown>;
89
- user?: V;
77
+ user?: unknown;
90
78
  readonly startTime: number;
91
79
  readonly requestId: string;
92
80
  timeoutSignal?: AbortSignal;
93
81
  responseData?: unknown;
94
82
  }
95
- /**
96
- * Legacy context interface for backward compatibility
97
- * @deprecated Use Context with GenericRequest/GenericResponse instead
98
- */
99
- export interface LegacyContext<T = unknown, V = unknown> {
100
- req: CustomRequest<T>;
101
- res: CustomResponse;
102
- container?: Container;
103
- error?: Error | null;
104
- businessData: Map<string, unknown>;
105
- user?: V;
106
- }
107
83
  /**
108
84
  * Utility function to generate unique request IDs
109
85
  */
110
86
  export declare function generateRequestId(): string;
111
- /**
112
- * Adapter to convert GCP Functions Request to GenericRequest
113
- */
114
- export declare function adaptGCPRequest<T = unknown>(gcpRequest: Request): GenericRequest<T>;
115
- /**
116
- * Adapter to convert GCP Functions Response to GenericResponse
117
- */
118
- export declare function adaptGCPResponse(gcpResponse: Response): GenericResponse;
119
87
  /**
120
88
  * Creates a context object for framework-agnostic handlers
121
89
  */
122
- export declare function createContext<T = unknown, V = unknown>(req: GenericRequest<T>, res: GenericResponse, options?: Partial<Context<T, V>>): Context<T, V>;
90
+ export declare function createContext<T = unknown>(req: NoonyRequest<T>, res: NoonyResponse, options?: Partial<Context<T>>): Context<T>;
123
91
  //# sourceMappingURL=core.d.ts.map
@@ -1,14 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.HttpMethod = void 0;
7
4
  exports.generateRequestId = generateRequestId;
8
- exports.adaptGCPRequest = adaptGCPRequest;
9
- exports.adaptGCPResponse = adaptGCPResponse;
10
5
  exports.createContext = createContext;
11
- const typedi_1 = __importDefault(require("typedi"));
6
+ const typedi_1 = require("typedi");
12
7
  /**
13
8
  * Framework-agnostic HTTP method enum
14
9
  */
@@ -22,71 +17,14 @@ var HttpMethod;
22
17
  HttpMethod["OPTIONS"] = "OPTIONS";
23
18
  HttpMethod["HEAD"] = "HEAD";
24
19
  })(HttpMethod || (exports.HttpMethod = HttpMethod = {}));
20
+ // Legacy context interface removed - use Context with NoonyRequest/NoonyResponse instead
25
21
  /**
26
22
  * Utility function to generate unique request IDs
27
23
  */
28
24
  function generateRequestId() {
29
- return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
30
- }
31
- /**
32
- * Adapter to convert GCP Functions Request to GenericRequest
33
- */
34
- function adaptGCPRequest(gcpRequest) {
35
- return {
36
- method: gcpRequest.method || HttpMethod.GET,
37
- url: gcpRequest.url || '/',
38
- path: gcpRequest.path,
39
- headers: gcpRequest.headers || {},
40
- query: gcpRequest.query || {},
41
- params: gcpRequest.params || {},
42
- body: gcpRequest.body,
43
- rawBody: gcpRequest.rawBody,
44
- ip: gcpRequest.ip,
45
- userAgent: gcpRequest.get?.('user-agent'),
46
- };
47
- }
48
- /**
49
- * Adapter to convert GCP Functions Response to GenericResponse
50
- */
51
- function adaptGCPResponse(gcpResponse) {
52
- let currentStatusCode = 200;
53
- let isHeadersSent = false;
54
- return {
55
- status: (code) => {
56
- currentStatusCode = code;
57
- gcpResponse.status(code);
58
- return adaptGCPResponse(gcpResponse);
59
- },
60
- json: (data) => {
61
- isHeadersSent = true;
62
- gcpResponse.json(data);
63
- },
64
- send: (data) => {
65
- isHeadersSent = true;
66
- gcpResponse.send(data);
67
- },
68
- header: (name, value) => {
69
- gcpResponse.header(name, value);
70
- return adaptGCPResponse(gcpResponse);
71
- },
72
- headers: (headers) => {
73
- Object.entries(headers).forEach(([key, value]) => {
74
- gcpResponse.header(key, value);
75
- });
76
- return adaptGCPResponse(gcpResponse);
77
- },
78
- end: () => {
79
- isHeadersSent = true;
80
- gcpResponse.end();
81
- },
82
- get statusCode() {
83
- return gcpResponse.statusCode || currentStatusCode;
84
- },
85
- get headersSent() {
86
- return gcpResponse.headersSent || isHeadersSent;
87
- },
88
- };
25
+ return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
89
26
  }
27
+ // Complex adapter functions removed - using smart universal adapter in Handler instead
90
28
  /**
91
29
  * Creates a context object for framework-agnostic handlers
92
30
  */
@@ -94,7 +32,7 @@ function createContext(req, res, options = {}) {
94
32
  return {
95
33
  req,
96
34
  res,
97
- container: options.container || typedi_1.default.of(),
35
+ container: options.container || typedi_1.Container.of(),
98
36
  error: options.error || null,
99
37
  businessData: options.businessData || new Map(),
100
38
  user: options.user,
@@ -1,4 +1,4 @@
1
- import { Context, CustomRequest, CustomResponse, GenericRequest, GenericResponse } from './core';
1
+ import { Context, NoonyRequest, NoonyResponse } from './core';
2
2
  /**
3
3
  * Interface representing a base structure for middleware with optional lifecycle methods.
4
4
  *
@@ -7,13 +7,12 @@ import { Context, CustomRequest, CustomResponse, GenericRequest, GenericResponse
7
7
  * executed before and after a process, as well as handling errors that
8
8
  * occur during the process.
9
9
  *
10
- * @template T - The type of the request or input context. Defaults to unknown.
11
- * @template U - The type of the response or output context. Defaults to unknown.
10
+ * @template T - The type of the request data. Defaults to unknown.
12
11
  */
13
- export interface BaseMiddleware<T = unknown, U = unknown> {
14
- before?: (context: Context<T, U>) => Promise<void>;
15
- after?: (context: Context<T, U>) => Promise<void>;
16
- onError?: (error: Error, context: Context<T, U>) => Promise<void>;
12
+ export interface BaseMiddleware<T = unknown> {
13
+ before?: (context: Context<T>) => Promise<void>;
14
+ after?: (context: Context<T>) => Promise<void>;
15
+ onError?: (error: Error, context: Context<T>) => Promise<void>;
17
16
  }
18
17
  /**
19
18
  * The Handler class is responsible for managing and executing middleware functions
@@ -23,6 +22,8 @@ export interface BaseMiddleware<T = unknown, U = unknown> {
23
22
  * process a request/response flow either before the main handler (via `before`),
24
23
  * after the main handler (via `after`), or handle errors (via `onError`).
25
24
  *
25
+ * @example
26
+ * ```typescript
26
27
  * interface MessagePayload {
27
28
  * action: string;
28
29
  * data: Record<string, unknown>;
@@ -33,25 +34,29 @@ export interface BaseMiddleware<T = unknown, U = unknown> {
33
34
  * .use(bodyParser())
34
35
  * .handle(async (context) => {
35
36
  * const { req } = context;
36
- * // Handle the request
37
+ * // Handle the request with type-safe access to req.validatedBody
37
38
  * });
39
+ * ```
38
40
  * @template T Type for the input request data.
39
- * @template U Type for the additional context or response data.
40
41
  */
41
- export declare class Handler<T = unknown, U = unknown> {
42
+ export declare class Handler<T = unknown> {
42
43
  private baseMiddlewares;
43
44
  private handler;
44
45
  private reversedMiddlewares;
45
46
  private errorMiddlewares;
46
47
  private middlewaresPrecomputed;
47
- static use<T = unknown, U = unknown>(middleware: BaseMiddleware<T, U>): Handler<T, U>;
48
- use<NewT = T, NewU = U>(middleware: BaseMiddleware<NewT, NewU>): Handler<NewT, NewU>;
49
- handle(handler: (context: Context<T, U>) => Promise<void>): Handler<T, U>;
48
+ static use<T = unknown>(middleware: BaseMiddleware<T>): Handler<T>;
49
+ use(middleware: BaseMiddleware<T>): Handler<T>;
50
+ handle(handler: (context: Context<T>) => Promise<void>): Handler<T>;
50
51
  /**
51
52
  * Performance optimization: Pre-compute middleware arrays to avoid runtime array operations
52
53
  */
53
54
  private precomputeMiddlewareArrays;
54
- execute(req: CustomRequest<T>, res: CustomResponse): Promise<void>;
55
+ /**
56
+ * Universal execute method that works with any HTTP framework
57
+ * Automatically detects and adapts GCP, Express, AWS Lambda, Fastify, etc.
58
+ */
59
+ execute(nativeReq: unknown, nativeRes: unknown): Promise<void>;
55
60
  /**
56
61
  * Execute before middlewares with optimized batching for independent middlewares
57
62
  */
@@ -65,8 +70,24 @@ export declare class Handler<T = unknown, U = unknown> {
65
70
  */
66
71
  private executeErrorMiddlewares;
67
72
  /**
68
- * Framework-agnostic execute method that works with GenericRequest/GenericResponse
73
+ * Universal request adapter - converts any framework's request to NoonyRequest
74
+ */
75
+ private adaptToNoonyRequest;
76
+ /**
77
+ * Universal response adapter - converts any framework's response to NoonyResponse
78
+ */
79
+ private adaptToNoonyResponse;
80
+ /**
81
+ * Create response adapter for AWS Lambda
82
+ */
83
+ private createAWSLambdaResponse;
84
+ /**
85
+ * Create response adapter for standard HTTP frameworks (GCP, Express, Fastify)
86
+ */
87
+ private createStandardHTTPResponse;
88
+ /**
89
+ * @deprecated Use execute() instead - automatically detects framework
69
90
  */
70
- executeGeneric(req: GenericRequest<T>, res: GenericResponse): Promise<void>;
91
+ executeGeneric(req: NoonyRequest<T>, res: NoonyResponse): Promise<void>;
71
92
  }
72
93
  //# sourceMappingURL=handler.d.ts.map
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.Handler = void 0;
4
- // Container import removed - now using containerPool for performance
7
+ // Container import for direct container creation (no pooling needed)
8
+ const typedi_1 = __importDefault(require("typedi"));
5
9
  const core_1 = require("./core");
6
- const containerPool_1 = require("./containerPool");
7
10
  /**
8
11
  * The Handler class is responsible for managing and executing middleware functions
9
12
  * and a main handler function in a sequential and controlled manner.
@@ -12,6 +15,8 @@ const containerPool_1 = require("./containerPool");
12
15
  * process a request/response flow either before the main handler (via `before`),
13
16
  * after the main handler (via `after`), or handle errors (via `onError`).
14
17
  *
18
+ * @example
19
+ * ```typescript
15
20
  * interface MessagePayload {
16
21
  * action: string;
17
22
  * data: Record<string, unknown>;
@@ -22,10 +27,10 @@ const containerPool_1 = require("./containerPool");
22
27
  * .use(bodyParser())
23
28
  * .handle(async (context) => {
24
29
  * const { req } = context;
25
- * // Handle the request
30
+ * // Handle the request with type-safe access to req.validatedBody
26
31
  * });
32
+ * ```
27
33
  * @template T Type for the input request data.
28
- * @template U Type for the additional context or response data.
29
34
  */
30
35
  class Handler {
31
36
  baseMiddlewares = [];
@@ -40,12 +45,9 @@ class Handler {
40
45
  return handler;
41
46
  }
42
47
  use(middleware) {
43
- const handler = new Handler();
44
- handler.baseMiddlewares = [
45
- ...this.baseMiddlewares,
46
- middleware,
47
- ];
48
- return handler;
48
+ // Simple middleware chaining without complex type transformations
49
+ this.baseMiddlewares.push(middleware);
50
+ return this;
49
51
  }
50
52
  handle(handler) {
51
53
  this.handler = handler;
@@ -63,12 +65,17 @@ class Handler {
63
65
  this.errorMiddlewares = this.reversedMiddlewares.filter((m) => m.onError);
64
66
  this.middlewaresPrecomputed = true;
65
67
  }
66
- async execute(req, res) {
67
- const genericReq = (0, core_1.adaptGCPRequest)(req);
68
- const genericRes = (0, core_1.adaptGCPResponse)(res);
69
- // Performance optimization: Use container pool instead of creating new containers
70
- const container = containerPool_1.containerPool.acquire();
71
- const context = (0, core_1.createContext)(genericReq, genericRes, {
68
+ /**
69
+ * Universal execute method that works with any HTTP framework
70
+ * Automatically detects and adapts GCP, Express, AWS Lambda, Fastify, etc.
71
+ */
72
+ async execute(nativeReq, nativeRes) {
73
+ // Smart universal adapter - convert any framework's request/response to Noony format
74
+ const req = this.adaptToNoonyRequest(nativeReq);
75
+ const res = this.adaptToNoonyResponse(nativeRes, nativeReq);
76
+ // Direct container creation - simpler and appropriate for serverless
77
+ const container = typedi_1.default.of();
78
+ const context = (0, core_1.createContext)(req, res, {
72
79
  container,
73
80
  });
74
81
  try {
@@ -83,10 +90,7 @@ class Handler {
83
90
  // Execute error handlers using pre-computed array
84
91
  await this.executeErrorMiddlewares(error, context);
85
92
  }
86
- finally {
87
- // Always return container to pool for reuse
88
- containerPool_1.containerPool.release(container);
89
- }
93
+ // No cleanup needed - container will be garbage collected automatically
90
94
  }
91
95
  /**
92
96
  * Execute before middlewares with optimized batching for independent middlewares
@@ -121,30 +125,115 @@ class Handler {
121
125
  }
122
126
  }
123
127
  /**
124
- * Framework-agnostic execute method that works with GenericRequest/GenericResponse
128
+ * Universal request adapter - converts any framework's request to NoonyRequest
125
129
  */
126
- async executeGeneric(req, res) {
127
- // Performance optimization: Use container pool instead of creating new containers
128
- const container = containerPool_1.containerPool.acquire();
129
- const context = (0, core_1.createContext)(req, res, {
130
- container,
131
- });
132
- try {
133
- // Execute before middlewares with performance optimizations
134
- await this.executeBeforeMiddlewares(context);
135
- await this.handler(context);
136
- // Execute after middlewares in reverse order using pre-computed array
137
- await this.executeAfterMiddlewares(context);
138
- }
139
- catch (error) {
140
- context.error = error;
141
- // Execute error handlers using pre-computed array
142
- await this.executeErrorMiddlewares(error, context);
143
- }
144
- finally {
145
- // Always return container to pool for reuse
146
- containerPool_1.containerPool.release(container);
130
+ adaptToNoonyRequest(nativeReq) {
131
+ const req = nativeReq;
132
+ // Universal property mapping that works with any HTTP framework
133
+ return {
134
+ method: req.method || req.httpMethod || core_1.HttpMethod.GET,
135
+ url: req.url || req.originalUrl || req.path || '/',
136
+ path: req.path || req.resource,
137
+ headers: req.headers || {},
138
+ query: req.query || req.queryStringParameters || {},
139
+ params: req.params || req.pathParameters || {},
140
+ body: req.body,
141
+ rawBody: req.rawBody || req.body,
142
+ parsedBody: req.parsedBody,
143
+ validatedBody: req.validatedBody,
144
+ ip: req.ip || req.requestContext?.identity?.sourceIp,
145
+ userAgent: (typeof req.headers?.['user-agent'] === 'string'
146
+ ? req.headers['user-agent']
147
+ : Array.isArray(req.headers?.['user-agent'])
148
+ ? req.headers['user-agent'][0]
149
+ : undefined) || req.get?.('user-agent'),
150
+ };
151
+ }
152
+ /**
153
+ * Universal response adapter - converts any framework's response to NoonyResponse
154
+ */
155
+ adaptToNoonyResponse(nativeRes, nativeReq) {
156
+ const req = nativeReq;
157
+ // Detect AWS Lambda pattern (different from standard HTTP)
158
+ if (req?.requestContext && typeof nativeRes === 'function') {
159
+ return this.createAWSLambdaResponse(nativeRes);
147
160
  }
161
+ // Standard HTTP response (GCP, Express, Fastify, etc.)
162
+ return this.createStandardHTTPResponse(nativeRes);
163
+ }
164
+ /**
165
+ * Create response adapter for AWS Lambda
166
+ */
167
+ createAWSLambdaResponse(lambdaCallback) {
168
+ let statusCode = 200;
169
+ const headers = {};
170
+ let body;
171
+ return {
172
+ status: (code) => {
173
+ statusCode = code;
174
+ return this.createAWSLambdaResponse(lambdaCallback);
175
+ },
176
+ json: (data) => {
177
+ body = JSON.stringify(data);
178
+ headers['Content-Type'] = 'application/json';
179
+ lambdaCallback(null, { statusCode, headers, body });
180
+ },
181
+ send: (data) => {
182
+ body = data;
183
+ lambdaCallback(null, { statusCode, headers, body });
184
+ },
185
+ header: (name, value) => {
186
+ headers[name] = value;
187
+ return this.createAWSLambdaResponse(lambdaCallback);
188
+ },
189
+ headers: (newHeaders) => {
190
+ Object.assign(headers, newHeaders);
191
+ return this.createAWSLambdaResponse(lambdaCallback);
192
+ },
193
+ end: () => lambdaCallback(null, { statusCode, headers, body }),
194
+ statusCode,
195
+ headersSent: false,
196
+ };
197
+ }
198
+ /**
199
+ * Create response adapter for standard HTTP frameworks (GCP, Express, Fastify)
200
+ */
201
+ createStandardHTTPResponse(nativeRes) {
202
+ const res = nativeRes;
203
+ return {
204
+ status: (code) => {
205
+ res.status(code);
206
+ return this.createStandardHTTPResponse(nativeRes);
207
+ },
208
+ json: (data) => res.json(data),
209
+ send: (data) => res.send(data),
210
+ header: (name, value) => {
211
+ res.header(name, value);
212
+ return this.createStandardHTTPResponse(nativeRes);
213
+ },
214
+ headers: (headers) => {
215
+ if (res.set) {
216
+ res.set(headers); // Express style
217
+ }
218
+ else {
219
+ Object.entries(headers).forEach(([k, v]) => res.header(k, v)); // GCP style
220
+ }
221
+ return this.createStandardHTTPResponse(nativeRes);
222
+ },
223
+ end: () => res.end(),
224
+ get statusCode() {
225
+ return res.statusCode;
226
+ },
227
+ get headersSent() {
228
+ return res.headersSent;
229
+ },
230
+ };
231
+ }
232
+ /**
233
+ * @deprecated Use execute() instead - automatically detects framework
234
+ */
235
+ async executeGeneric(req, res) {
236
+ return this.execute(req, res);
148
237
  }
149
238
  }
150
239
  exports.Handler = Handler;
@@ -2,7 +2,6 @@ export * from './core';
2
2
  export * from './errors';
3
3
  export * from './handler';
4
4
  export * from './logger';
5
- export * from './containerPool';
6
5
  export * from './performanceMonitor';
7
6
  export * from '../middlewares';
8
7
  //# sourceMappingURL=index.d.ts.map
@@ -18,7 +18,6 @@ __exportStar(require("./core"), exports);
18
18
  __exportStar(require("./errors"), exports);
19
19
  __exportStar(require("./handler"), exports);
20
20
  __exportStar(require("./logger"), exports);
21
- __exportStar(require("./containerPool"), exports);
22
21
  __exportStar(require("./performanceMonitor"), exports);
23
22
  __exportStar(require("../middlewares"), exports);
24
23
  //# sourceMappingURL=index.js.map