@webpieces/http-server 0.3.262 → 0.3.271

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 (36) hide show
  1. package/package.json +8 -4
  2. package/src/WebpiecesMiddleware.d.ts +1 -1
  3. package/src/WebpiecesMiddleware.js +34 -34
  4. package/src/WebpiecesMiddleware.js.map +1 -1
  5. package/src/WebpiecesRouteCreator.js +2 -2
  6. package/src/WebpiecesRouteCreator.js.map +1 -1
  7. package/src/WebpiecesServerImpl.js +3 -4
  8. package/src/WebpiecesServerImpl.js.map +1 -1
  9. package/src/filters/ContextFilter.d.ts +1 -1
  10. package/src/filters/ContextFilter.js +5 -5
  11. package/src/filters/ContextFilter.js.map +1 -1
  12. package/src/filters/LogApiFilter.d.ts +1 -1
  13. package/src/filters/LogApiFilter.js +8 -8
  14. package/src/filters/LogApiFilter.js.map +1 -1
  15. package/src/filters/RecordingFilter.d.ts +1 -1
  16. package/src/filters/RecordingFilter.js +10 -10
  17. package/src/filters/RecordingFilter.js.map +1 -1
  18. package/src/filters/ServiceAuthFilter.d.ts +19 -0
  19. package/src/filters/ServiceAuthFilter.js +83 -0
  20. package/src/filters/ServiceAuthFilter.js.map +1 -0
  21. package/src/headers/WebpiecesCoreHeaders.d.ts +2 -2
  22. package/src/headers/WebpiecesCoreHeaders.js +3 -3
  23. package/src/headers/WebpiecesCoreHeaders.js.map +1 -1
  24. package/src/index.d.ts +2 -1
  25. package/src/index.js +6 -4
  26. package/src/index.js.map +1 -1
  27. package/src/modules/WebpiecesModule.js +9 -9
  28. package/src/modules/WebpiecesModule.js.map +1 -1
  29. package/src/recorder/SpecGenerator.d.ts +1 -1
  30. package/src/recorder/SpecGenerator.js +1 -1
  31. package/src/recorder/SpecGenerator.js.map +1 -1
  32. package/src/recorder/TestCaseRecorderImpl.d.ts +1 -1
  33. package/src/recorder/TestCaseRecorderImpl.js +7 -7
  34. package/src/recorder/TestCaseRecorderImpl.js.map +1 -1
  35. package/src/recorder/recordable.js +5 -5
  36. package/src/recorder/recordable.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-server",
3
- "version": "0.3.262",
3
+ "version": "0.3.271",
4
4
  "description": "WebPieces server with filter chain and dependency injection",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -22,9 +22,13 @@
22
22
  "access": "public"
23
23
  },
24
24
  "dependencies": {
25
- "@webpieces/http-routing": "0.3.262",
26
- "@webpieces/wp-logging": "0.3.262",
27
- "cors": "2.8.5"
25
+ "@webpieces/core-context": "0.3.271",
26
+ "@webpieces/core-util": "0.3.271",
27
+ "@webpieces/gcp-identity": "0.3.271",
28
+ "@webpieces/http-filters": "0.3.271",
29
+ "@webpieces/http-routing": "0.3.271",
30
+ "cors": "2.8.5",
31
+ "inversify": "7.10.4"
28
32
  },
29
33
  "devDependencies": {
30
34
  "@types/cors": "2.8.19"
@@ -1,6 +1,6 @@
1
1
  import { Request, Response, NextFunction, RequestHandler } from 'express';
2
2
  import { MethodMeta } from '@webpieces/http-routing';
3
- import { RouteMetadata } from '@webpieces/http-api';
3
+ import { RouteMetadata } from '@webpieces/core-util';
4
4
  import { Service, WpResponse } from '@webpieces/http-filters';
5
5
  export declare class ExpressWrapper {
6
6
  private service;
@@ -5,11 +5,11 @@ const tslib_1 = require("tslib");
5
5
  const cors_1 = tslib_1.__importDefault(require("cors"));
6
6
  const inversify_1 = require("inversify");
7
7
  const http_routing_1 = require("@webpieces/http-routing");
8
- const http_api_1 = require("@webpieces/http-api");
9
8
  const core_util_1 = require("@webpieces/core-util");
9
+ const core_util_2 = require("@webpieces/core-util");
10
10
  const core_context_1 = require("@webpieces/core-context");
11
- const wp_logging_1 = require("@webpieces/wp-logging");
12
- const log = wp_logging_1.LogManager.getLogger('WebpiecesMiddleware');
11
+ const core_util_3 = require("@webpieces/core-util");
12
+ const log = core_util_3.LogManager.getLogger('WebpiecesMiddleware');
13
13
  class ExpressWrapper {
14
14
  service;
15
15
  routeMeta;
@@ -30,7 +30,7 @@ class ExpressWrapper {
30
30
  await this.executeImpl(req, res, next);
31
31
  }
32
32
  catch (err) {
33
- const error = (0, core_util_1.toError)(err);
33
+ const error = (0, core_util_2.toError)(err);
34
34
  // 5. Handle errors
35
35
  this.handleError(res, error);
36
36
  }
@@ -116,49 +116,49 @@ class ExpressWrapper {
116
116
  if (res.headersSent) {
117
117
  return;
118
118
  }
119
- const protocolError = new http_api_1.ProtocolError();
120
- if (error instanceof http_api_1.HttpError) {
119
+ const protocolError = new core_util_1.ProtocolError();
120
+ if (error instanceof core_util_1.HttpError) {
121
121
  // Set common fields for all HttpError types
122
122
  protocolError.message = error.message;
123
123
  protocolError.subType = error.subType;
124
124
  protocolError.name = error.name;
125
125
  // Set type-specific fields (MUST match ClientErrorTranslator)
126
- if (error instanceof http_api_1.HttpUserError) {
127
- log.info('[ExpressWrapper] User Error:', error.message);
126
+ if (error instanceof core_util_1.HttpUserError) {
127
+ log.info(`[ExpressWrapper] User Error: ${error.message}`);
128
128
  protocolError.errorCode = error.errorCode;
129
129
  }
130
- else if (error instanceof http_api_1.HttpBadRequestError) {
131
- log.info('[ExpressWrapper] Bad Request:', error.message);
130
+ else if (error instanceof core_util_1.HttpBadRequestError) {
131
+ log.info(`[ExpressWrapper] Bad Request: ${error.message}`);
132
132
  protocolError.field = error.field;
133
133
  protocolError.guiAlertMessage = error.guiMessage;
134
134
  }
135
- else if (error instanceof http_api_1.HttpNotFoundError) {
136
- log.info('[ExpressWrapper] Not Found:', error.message);
135
+ else if (error instanceof core_util_1.HttpNotFoundError) {
136
+ log.info(`[ExpressWrapper] Not Found: ${error.message}`);
137
137
  }
138
- else if (error instanceof http_api_1.HttpTimeoutError) {
139
- log.error('[ExpressWrapper] Timeout Error:', error.message);
138
+ else if (error instanceof core_util_1.HttpTimeoutError) {
139
+ log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);
140
140
  }
141
- else if (error instanceof http_api_1.HttpVendorError) {
142
- log.error('[ExpressWrapper] Vendor Error:', error.message);
141
+ else if (error instanceof core_util_1.HttpVendorError) {
142
+ log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);
143
143
  protocolError.waitSeconds = error.waitSeconds;
144
144
  }
145
- else if (error instanceof http_api_1.HttpUnauthorizedError) {
146
- log.info('[ExpressWrapper] Unauthorized:', error.message);
145
+ else if (error instanceof core_util_1.HttpUnauthorizedError) {
146
+ log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);
147
147
  }
148
- else if (error instanceof http_api_1.HttpForbiddenError) {
149
- log.info('[ExpressWrapper] Forbidden:', error.message);
148
+ else if (error instanceof core_util_1.HttpForbiddenError) {
149
+ log.info(`[ExpressWrapper] Forbidden: ${error.message}`);
150
150
  }
151
- else if (error instanceof http_api_1.HttpInternalServerError) {
152
- log.error('[ExpressWrapper] Internal Server Error:', error.message);
151
+ else if (error instanceof core_util_1.HttpInternalServerError) {
152
+ log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);
153
153
  }
154
- else if (error instanceof http_api_1.HttpBadGatewayError) {
155
- log.error('[ExpressWrapper] Bad Gateway:', error.message);
154
+ else if (error instanceof core_util_1.HttpBadGatewayError) {
155
+ log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);
156
156
  }
157
- else if (error instanceof http_api_1.HttpGatewayTimeoutError) {
158
- log.error('[ExpressWrapper] Gateway Timeout:', error.message);
157
+ else if (error instanceof core_util_1.HttpGatewayTimeoutError) {
158
+ log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);
159
159
  }
160
160
  else {
161
- log.info('[ExpressWrapper] Generic HttpError:', error.message);
161
+ log.info(`[ExpressWrapper] Generic HttpError: ${error.message}`);
162
162
  }
163
163
  // Serialize ProtocolError to JSON (SYMMETRIC with client)
164
164
  const responseJson = JSON.stringify(protocolError);
@@ -166,7 +166,7 @@ class ExpressWrapper {
166
166
  }
167
167
  else {
168
168
  // Unknown error - 500
169
- const err = (0, core_util_1.toError)(error);
169
+ const err = (0, core_util_2.toError)(error);
170
170
  protocolError.message = 'Internal Server Error';
171
171
  log.error('[ExpressWrapper] Unexpected error:', err);
172
172
  const responseJson = JSON.stringify(protocolError);
@@ -208,17 +208,17 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
208
208
  * this catches everything else.
209
209
  */
210
210
  async globalErrorHandler(req, res, next) {
211
- log.info('🔴 [Layer 1: GlobalErrorHandler] Request START:', req.method, req.path);
211
+ log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);
212
212
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all
213
213
  try {
214
214
  // await next() catches BOTH:
215
215
  // 1. Synchronous throws from next() itself
216
216
  // 2. Rejected promises from downstream async middleware
217
217
  await next();
218
- log.info('🔴 [Layer 1: GlobalErrorHandler] Request END (success):', req.method, req.path);
218
+ log.info(`🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`);
219
219
  }
220
220
  catch (err) {
221
- const error = (0, core_util_1.toError)(err);
221
+ const error = (0, core_util_2.toError)(err);
222
222
  log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);
223
223
  if (!res.headersSent) {
224
224
  // Return HTML error page (not JSON - JsonTranslator handles JSON errors)
@@ -234,7 +234,7 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
234
234
  </html>
235
235
  `);
236
236
  }
237
- log.info('🔴 [Layer 1: GlobalErrorHandler] Request END (error):', req.method, req.path);
237
+ log.info(`🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`);
238
238
  }
239
239
  }
240
240
  /**
@@ -243,9 +243,9 @@ let WebpiecesMiddleware = class WebpiecesMiddleware {
243
243
  * IMPORTANT: Must be async and await next() to properly chain with async middleware.
244
244
  */
245
245
  async logNextLayer(req, res, next) {
246
- log.info('🟡 [Layer 2: LogNextLayer] Before next() -', req.method, req.path);
246
+ log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);
247
247
  await next();
248
- log.info('🟡 [Layer 2: LogNextLayer] After next() -', req.method, req.path);
248
+ log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);
249
249
  }
250
250
  /**
251
251
  * CORS middleware for localhost development.
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAA4F;AAC5F,kDAc6B;AAE7B,oDAA+C;AAC/C,0DAAyD;AACzD,sDAAmD;AAEnD,MAAM,GAAG,GAAG,uBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD,MAAa,cAAc;IAEX;IACA;IAFZ,YACY,OAAiD,EACjD,SAAwB;QADxB,YAAO,GAAP,OAAO,CAA0C;QACjD,cAAS,GAAT,SAAS,CAAe;IAEpC,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAChC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACP,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QACxE,8HAA8H;QAC9H,IAAI,CAAC;YACD,MAAM,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,mBAAmB;YACnB,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,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HY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;GACA,mBAAmB,CAmH/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideSingleton, MethodMeta, ExpressRouteHandler } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n RouteMetadata,\n} from '@webpieces/http-api';\nimport { Service, WpResponse } from '@webpieces/http-filters';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/wp-logging';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n\nexport class ExpressWrapper {\n constructor(\n private service: Service<MethodMeta, WpResponse<unknown>>,\n private routeMeta: RouteMetadata\n ) {\n }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction) {\n // 1. Read HTTP headers from Express request\n const requestHeaders = this.readExpressHeaders(req);\n\n // 2. Parse JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n }\n\n // 3. Create MethodMeta with headers and request DTO\n const methodMeta = new MethodMeta(this.routeMeta, requestHeaders, requestDto);\n\n // 4. Invoke the service (filter chain + controller)\n const wpResponse = await this.service.invoke(methodMeta);\n if (!wpResponse.response) {\n throw new Error(\n `Route chain(filters & all) is not returning a response. ${this.routeMeta.controllerClassName}.${this.routeMeta.methodName}`\n );\n }\n\n // 5. Serialize response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(wpResponse.response);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read raw request body as text.\n * Used to manually parse JSON (instead of express.json() middleware).\n */\n private async readRequestBody(req: Request): Promise<string> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\n */\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info('[ExpressWrapper] User Error:', error.message);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info('[ExpressWrapper] Bad Request:', error.message);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info('[ExpressWrapper] Not Found:', error.message);\n } else if (error instanceof HttpTimeoutError) {\n log.error('[ExpressWrapper] Timeout Error:', error.message);\n } else if (error instanceof HttpVendorError) {\n log.error('[ExpressWrapper] Vendor Error:', error.message);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info('[ExpressWrapper] Unauthorized:', error.message);\n } else if (error instanceof HttpForbiddenError) {\n log.info('[ExpressWrapper] Forbidden:', error.message);\n } else if (error instanceof HttpInternalServerError) {\n log.error('[ExpressWrapper] Internal Server Error:', error.message);\n } else if (error instanceof HttpBadGatewayError) {\n log.error('[ExpressWrapper] Bad Gateway:', error.message);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error('[ExpressWrapper] Gateway Timeout:', error.message);\n } else {\n log.info('[ExpressWrapper] Generic HttpError:', error.message);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideSingleton()\n@injectable()\nexport class WebpiecesMiddleware {\n\n /**\n * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info('🔴 [Layer 1: GlobalErrorHandler] Request START:', req.method, req.path);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n '🔴 [Layer 1: GlobalErrorHandler] Request END (success):',\n req.method,\n req.path,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n log.info(\n '🔴 [Layer 1: GlobalErrorHandler] Request END (error):',\n req.method,\n req.path,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info('🟡 [Layer 2: LogNextLayer] Before next() -', req.method, req.path);\n await next();\n log.info('🟡 [Layer 2: LogNextLayer] After next() -', req.method, req.path);\n }\n\n /**\n * CORS middleware for localhost development.\n * Only enables CORS when request origin is localhost:*.\n *\n * Wide open for all headers/methods in dev mode.\n * Non-localhost origins are blocked.\n *\n * @returns Express middleware handler for CORS\n */\n corsForLocalhost(): RequestHandler {\n log.info('[WebpiecesMiddleware] CORS enabled for localhost:* origins');\n\n return cors({\n origin: function (origin, callback) {\n // Allow requests with no origin (same-origin, Postman, curl)\n if (!origin) {\n callback(null, true);\n return;\n }\n\n // Only allow localhost origins\n if (origin.startsWith('http://localhost:') || origin.startsWith('https://localhost:')) {\n callback(null, true);\n } else {\n log.info(`[CORS] Blocked origin: ${origin} (only localhost:* allowed)`);\n callback(new Error(`CORS not allowed for origin: ${origin}`));\n }\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*', // Wide open for dev\n exposedHeaders: '*', // Expose all response headers to browser JS\n maxAge: 3600,\n });\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design).\n *\n * NEW: Simplified - no longer passes headers (ContextFilter handles it now)\n *\n * @param service - The service wrapping the filter chain and controller\n * @param routeMeta - Route metadata for MethodMeta and DTO type\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n service: Service<MethodMeta, WpResponse<unknown>>,\n routeMeta: RouteMetadata,\n ): ExpressWrapper {\n return new ExpressWrapper(service, routeMeta);\n }\n}\n"]}
1
+ {"version":3,"file":"WebpiecesMiddleware.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesMiddleware.ts"],"names":[],"mappings":";;;;AACA,wDAAwB;AACxB,yCAAuC;AACvC,0DAA4F;AAC5F,oDAc8B;AAE9B,oDAA+C;AAC/C,0DAAyD;AACzD,oDAAkD;AAElD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD,MAAa,cAAc;IAEX;IACA;IAFZ,YACY,OAAiD,EACjD,SAAwB;QADxB,YAAO,GAAP,OAAO,CAA0C;QACjD,cAAS,GAAT,SAAS,CAAe;IAEpC,CAAC;IAEM,KAAK,CAAC,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QAChE,qDAAqD;QACrD,6DAA6D;QAC7D,MAAM,6BAAc,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YAChC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACP,CAAC;IAEM,KAAK,CAAC,eAAe,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QACxE,8HAA8H;QAC9H,IAAI,CAAC;YACD,MAAM,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,mBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,mBAAmB;YACnB,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC;IACL,CAAC;IAEM,KAAK,CAAC,WAAW,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;QACpE,4C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B,CA+G/B","sourcesContent":["import { Request, Response, NextFunction, RequestHandler } from 'express';\nimport cors from 'cors';\nimport { injectable } from 'inversify';\nimport { provideSingleton, MethodMeta, ExpressRouteHandler } from '@webpieces/http-routing';\nimport {\n ProtocolError,\n HttpError,\n HttpBadRequestError,\n HttpVendorError,\n HttpUserError,\n HttpNotFoundError,\n HttpTimeoutError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpInternalServerError,\n HttpBadGatewayError,\n HttpGatewayTimeoutError,\n RouteMetadata,\n} from '@webpieces/core-util';\nimport { Service, WpResponse } from '@webpieces/http-filters';\nimport { toError } from '@webpieces/core-util';\nimport { RequestContext } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\n\nconst log = LogManager.getLogger('WebpiecesMiddleware');\n\nexport class ExpressWrapper {\n constructor(\n private service: Service<MethodMeta, WpResponse<unknown>>,\n private routeMeta: RouteMetadata\n ) {\n }\n\n public async execute(req: Request, res: Response, next: NextFunction) {\n // MOVED: Wrap entire request in RequestContext.run()\n // This establishes AsyncLocalStorage context for the request\n await RequestContext.run(async () => {\n await this.executeTryCatch(req, res, next);\n });\n }\n\n public async executeTryCatch(req: Request, res: Response, next: NextFunction): Promise<void> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- ExpressWrapper catches errors to translate to HTTP responses\n try {\n await this.executeImpl(req, res, next);\n } catch (err: unknown) {\n const error = toError(err);\n // 5. Handle errors\n this.handleError(res, error);\n }\n }\n\n public async executeImpl(req: Request, res: Response, next: NextFunction) {\n // 1. Read HTTP headers from Express request\n const requestHeaders = this.readExpressHeaders(req);\n\n // 2. Parse JSON request body manually (SYMMETRIC with client's JSON.stringify)\n let requestDto: unknown = {};\n if (['POST', 'PUT', 'PATCH'].includes(req.method)) {\n // Read raw body as text\n const bodyText = await this.readRequestBody(req);\n // Parse JSON\n requestDto = bodyText ? JSON.parse(bodyText) : {};\n }\n\n // 3. Create MethodMeta with headers and request DTO\n const methodMeta = new MethodMeta(this.routeMeta, requestHeaders, requestDto);\n\n // 4. Invoke the service (filter chain + controller)\n const wpResponse = await this.service.invoke(methodMeta);\n if (!wpResponse.response) {\n throw new Error(\n `Route chain(filters & all) is not returning a response. ${this.routeMeta.controllerClassName}.${this.routeMeta.methodName}`\n );\n }\n\n // 5. Serialize response DTO to JSON (SYMMETRIC with client's response.json())\n const responseJson = JSON.stringify(wpResponse.response);\n res.status(200).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n\n /**\n * Read HTTP headers from Express request.\n * Returns Map of header name (lowercase) -> array of values.\n *\n * HTTP spec allows multiple values for same header name.\n */\n private readExpressHeaders(req: Request): Map<string, string[]> {\n const headers = new Map<string, string[]>();\n\n // Express stores headers in req.headers as Record<string, string | string[]>\n for (const [name, value] of Object.entries(req.headers)) {\n const lowerName = name.toLowerCase();\n\n if (typeof value === 'string') {\n headers.set(lowerName, [value]);\n } else if (Array.isArray(value)) {\n headers.set(lowerName, value);\n }\n }\n\n return headers;\n }\n\n /**\n * Read raw request body as text.\n * Used to manually parse JSON (instead of express.json() middleware).\n */\n private async readRequestBody(req: Request): Promise<string> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n resolve(body);\n });\n req.on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Handle errors - translate to JSON ProtocolError (SYMMETRIC with ClientErrorTranslator).\n * PUBLIC so wrapExpress can call it for symmetric error handling.\n * Maps HttpError subclasses to appropriate HTTP status codes and ProtocolError response.\n *\n * Maps all HttpError types (must match ClientErrorTranslator.translateError()):\n * - HttpUserError → 266 (with errorCode)\n * - HttpBadRequestError → 400 (with field, guiAlertMessage)\n * - HttpUnauthorizedError → 401\n * - HttpForbiddenError → 403\n * - HttpNotFoundError → 404\n * - HttpTimeoutError → 408\n * - HttpInternalServerError → 500\n * - HttpBadGatewayError → 502\n * - HttpGatewayTimeoutError → 504\n * - HttpVendorError → 598 (with waitSeconds)\n */\n public handleError(res: Response, error: unknown): void {\n if (res.headersSent) {\n return;\n }\n\n const protocolError = new ProtocolError();\n\n if (error instanceof HttpError) {\n // Set common fields for all HttpError types\n protocolError.message = error.message;\n protocolError.subType = error.subType;\n protocolError.name = error.name;\n\n // Set type-specific fields (MUST match ClientErrorTranslator)\n if (error instanceof HttpUserError) {\n log.info(`[ExpressWrapper] User Error: ${error.message}`);\n protocolError.errorCode = error.errorCode;\n } else if (error instanceof HttpBadRequestError) {\n log.info(`[ExpressWrapper] Bad Request: ${error.message}`);\n protocolError.field = error.field;\n protocolError.guiAlertMessage = error.guiMessage;\n } else if (error instanceof HttpNotFoundError) {\n log.info(`[ExpressWrapper] Not Found: ${error.message}`);\n } else if (error instanceof HttpTimeoutError) {\n log.error(`[ExpressWrapper] Timeout Error: ${error.message}`);\n } else if (error instanceof HttpVendorError) {\n log.error(`[ExpressWrapper] Vendor Error: ${error.message}`);\n protocolError.waitSeconds = error.waitSeconds;\n } else if (error instanceof HttpUnauthorizedError) {\n log.info(`[ExpressWrapper] Unauthorized: ${error.message}`);\n } else if (error instanceof HttpForbiddenError) {\n log.info(`[ExpressWrapper] Forbidden: ${error.message}`);\n } else if (error instanceof HttpInternalServerError) {\n log.error(`[ExpressWrapper] Internal Server Error: ${error.message}`);\n } else if (error instanceof HttpBadGatewayError) {\n log.error(`[ExpressWrapper] Bad Gateway: ${error.message}`);\n } else if (error instanceof HttpGatewayTimeoutError) {\n log.error(`[ExpressWrapper] Gateway Timeout: ${error.message}`);\n } else {\n log.info(`[ExpressWrapper] Generic HttpError: ${error.message}`);\n }\n\n // Serialize ProtocolError to JSON (SYMMETRIC with client)\n const responseJson = JSON.stringify(protocolError);\n res.status(error.code).setHeader('Content-Type', 'application/json').send(responseJson);\n } else {\n // Unknown error - 500\n const err = toError(error);\n protocolError.message = 'Internal Server Error';\n log.error('[ExpressWrapper] Unexpected error:', err);\n const responseJson = JSON.stringify(protocolError);\n res.status(500).setHeader('Content-Type', 'application/json').send(responseJson);\n }\n }\n}\n\n/**\n * WebpiecesMiddleware - Express middleware for WebPieces server.\n *\n * This class contains all Express middleware used by WebpiecesServer:\n * 1. globalErrorHandler - Outermost error handler, returns HTML 500 page\n * 2. logNextLayer - Request/response logging\n * 3. jsonTranslator - JSON Content-Type validation and error translation\n *\n * The middleware is injected into WebpiecesServerImpl and registered with Express\n * in the start() method.\n *\n * IMPORTANT: jsonTranslator does NOT dispatch routes - route dispatch happens via\n * Express's registered route handlers (created by RouteBuilder.createHandler()).\n * jsonTranslator only validates Content-Type and translates errors to JSON.\n *\n * NEW: ExpressWrapper simplified - no longer handles JSON or headers\n * - JSON parsing/serialization moved to JsonFilter\n * - Header transfer moved to ContextFilter (injects PlatformHeadersExtension directly)\n * - ExpressWrapper just creates RouterReqResp and invokes filter chain\n *\n * Extension vs Plugin pattern:\n * - Extensions (DI-level): Contribute capabilities to framework (headers, converters, etc.)\n * - Plugins (App-level): Provide complete features with modules + routes (Hibernate, Jackson, etc.)\n */\n@provideSingleton()\n@injectable()\nexport class WebpiecesMiddleware {\n\n /**\n * Global error handler middleware - catches ALL unhandled errors.\n * Returns HTML 500 error page for any errors that escape the filter chain.\n *\n * This is the outermost safety net - JsonTranslator catches JSON API errors,\n * this catches everything else.\n */\n async globalErrorHandler(\n req: Request,\n res: Response,\n next: NextFunction,\n ): Promise<void> {\n log.info(`🔴 [Layer 1: GlobalErrorHandler] Request START: ${req.method} ${req.path}`);\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- Global error handler IS the top-level catch-all\n try {\n // await next() catches BOTH:\n // 1. Synchronous throws from next() itself\n // 2. Rejected promises from downstream async middleware\n await next();\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (success): ${req.method} ${req.path}`,\n );\n } catch (err: unknown) {\n const error = toError(err);\n log.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonTranslator handles JSON errors)\n res.status(500).send(`\n <!DOCTYPE html>\n <html>\n <head><title>Server Error</title></head>\n <body>\n <h1>You hit a server error</h1>\n <p>An unexpected error occurred while processing your request.</p>\n <pre>${error.message}</pre>\n </body>\n </html>\n `);\n }\n log.info(\n `🔴 [Layer 1: GlobalErrorHandler] Request END (error): ${req.method} ${req.path}`,\n );\n }\n }\n\n /**\n * Logging middleware - logs request/response flow.\n * Demonstrates middleware execution order.\n * IMPORTANT: Must be async and await next() to properly chain with async middleware.\n */\n async logNextLayer(req: Request, res: Response, next: NextFunction): Promise<void> {\n log.info(`🟡 [Layer 2: LogNextLayer] Before next() - ${req.method} ${req.path}`);\n await next();\n log.info(`🟡 [Layer 2: LogNextLayer] After next() - ${req.method} ${req.path}`);\n }\n\n /**\n * CORS middleware for localhost development.\n * Only enables CORS when request origin is localhost:*.\n *\n * Wide open for all headers/methods in dev mode.\n * Non-localhost origins are blocked.\n *\n * @returns Express middleware handler for CORS\n */\n corsForLocalhost(): RequestHandler {\n log.info('[WebpiecesMiddleware] CORS enabled for localhost:* origins');\n\n return cors({\n origin: function (origin, callback) {\n // Allow requests with no origin (same-origin, Postman, curl)\n if (!origin) {\n callback(null, true);\n return;\n }\n\n // Only allow localhost origins\n if (origin.startsWith('http://localhost:') || origin.startsWith('https://localhost:')) {\n callback(null, true);\n } else {\n log.info(`[CORS] Blocked origin: ${origin} (only localhost:* allowed)`);\n callback(new Error(`CORS not allowed for origin: ${origin}`));\n }\n },\n credentials: true,\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowedHeaders: '*', // Wide open for dev\n exposedHeaders: '*', // Expose all response headers to browser JS\n maxAge: 3600,\n });\n }\n\n /**\n * Create an ExpressWrapper for a route.\n * The wrapper handles the full request/response cycle (symmetric design).\n *\n * NEW: Simplified - no longer passes headers (ContextFilter handles it now)\n *\n * @param service - The service wrapping the filter chain and controller\n * @param routeMeta - Route metadata for MethodMeta and DTO type\n * @returns ExpressWrapper instance\n */\n createExpressWrapper(\n service: Service<MethodMeta, WpResponse<unknown>>,\n routeMeta: RouteMetadata,\n ): ExpressWrapper {\n return new ExpressWrapper(service, routeMeta);\n }\n}\n"]}
@@ -4,7 +4,7 @@ exports.WebpiecesRouteCreator = void 0;
4
4
  const http_routing_1 = require("@webpieces/http-routing");
5
5
  const WebpiecesMiddleware_1 = require("./WebpiecesMiddleware");
6
6
  const InProcessApiClientFactory_1 = require("./InProcessApiClientFactory");
7
- const wp_logging_1 = require("@webpieces/wp-logging");
7
+ const core_util_1 = require("@webpieces/core-util");
8
8
  /**
9
9
  * WebpiecesRouteCreator - Embeddable adapter that mounts the webpieces
10
10
  * api -> filters -> controller pipeline onto ANY existing Express app.
@@ -43,7 +43,7 @@ const wp_logging_1 = require("@webpieces/wp-logging");
43
43
  * This same class is used internally by WebpiecesServerImpl.start(), so the
44
44
  * full server and the embeddable adapter share one code path.
45
45
  */
46
- const log = wp_logging_1.LogManager.getLogger('WebpiecesRouteCreator');
46
+ const log = core_util_1.LogManager.getLogger('WebpiecesRouteCreator');
47
47
  class WebpiecesRouteCreator {
48
48
  app;
49
49
  routeBuilder;
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesRouteCreator.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesRouteCreator.ts"],"names":[],"mappings":";;;AAEA,0DAOiC;AACjC,+DAA4D;AAC5D,2EAAwE;AACxE,sDAAmD;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,GAAG,GAAG,uBAAU,CAAC,SAAS,CAAC,uBAAuB,CAAC,CAAC;AAE1D,MAAa,qBAAqB;IAelB;IAdJ,YAAY,CAAmB;IAC/B,UAAU,CAAsB;IAChC,aAAa,CAA4B;IAEjD,gFAAgF;IACxE,SAAS,GAAG,KAAK,CAAC;IAE1B;;;;;OAKG;IACH,YACY,GAAY,EACpB,SAAoB,EACpB,YAA+B,EAC/B,UAAgC;QAHxB,QAAG,GAAH,GAAG,CAAS;QAKpB,I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c,CAAC,CAAC;gBACnC,MAAM;YACV,KAAK,QAAQ;gBACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACtC,MAAM;YACV,KAAK,OAAO;gBACR,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACrC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,gDAAgD,UAAU,EAAE,CAAC,CAAC;QAC/E,CAAC;IACL,CAAC;CACJ;AAxID,sDAwIC","sourcesContent":["import { Express } from 'express';\nimport { Container } from 'inversify';\nimport {\n ApiRoutingFactory,\n ClassType,\n ExpressRouteHandler,\n FilterDefinition,\n RouteBuilderImpl,\n RouteHandlerWithMeta,\n} from '@webpieces/http-routing';\nimport { WebpiecesMiddleware } from './WebpiecesMiddleware';\nimport { InProcessApiClientFactory } from './InProcessApiClientFactory';\nimport { LogManager } from '@webpieces/wp-logging';\n\n/**\n * WebpiecesRouteCreator - Embeddable adapter that mounts the webpieces\n * api -> filters -> controller pipeline onto ANY existing Express app.\n *\n * Legacy Express apps can adopt webpieces incrementally: existing routes and\n * middleware keep working untouched; each wired webpieces route is fully\n * self-contained (own body parsing, own RequestContext, own error->JSON mapping).\n * This class never calls app.use() - it only registers per-route handlers.\n *\n * Usage:\n * ```typescript\n * const app = express(); // your existing legacy app\n * const container = new Container();\n * await container.load(buildProviderModule()); // picks up @provideSingleton classes\n * await container.load(WebpiecesModule); // required if you use ContextFilter\n *\n * const creator = new WebpiecesRouteCreator(app, container);\n * creator.wireFilters(\n * new FilterDefinition(2000, ContextFilter, '*'),\n * new FilterDefinition(1900, AuthFilter, 'src/controllers/admin/**'),\n * );\n * creator.wireApi(SaveApi, SaveController); // controller resolved from container\n * creator.wireApi(PublicApi, PublicController);\n * app.listen(8080);\n * ```\n *\n * Notes:\n * - ALL wireFilters() calls must come BEFORE the first wireApi() call. Filter\n * chains are composed per-route at wireApi time, so late filters would be\n * silently ignored - we throw instead.\n * - Scoped filter glob patterns match the controller filepath from the\n * @SourceFile decorator, falling back to the pattern `**\\/{ClassName}.ts`.\n * - Want webpieces' localhost CORS? Opt in yourself:\n * `app.use(new WebpiecesMiddleware().corsForLocalhost())`.\n *\n * This same class is used internally by WebpiecesServerImpl.start(), so the\n * full server and the embeddable adapter share one code path.\n */\nconst log = LogManager.getLogger('WebpiecesRouteCreator');\n\nexport class WebpiecesRouteCreator {\n private routeBuilder: RouteBuilderImpl;\n private middleware: WebpiecesMiddleware;\n private clientFactory: InProcessApiClientFactory;\n\n /** Locks wireFilters() once the first wireApi() has composed a filter chain. */\n private apisWired = false;\n\n /**\n * @param app - The Express app to mount routes on (yours - never taken over)\n * @param container - Inversify container used to resolve controllers and filters\n * @param routeBuilder - Internal: WebpiecesServerImpl passes its DI singleton; standalone users omit\n * @param middleware - Internal: WebpiecesServerImpl passes its DI singleton; standalone users omit\n */\n constructor(\n private app: Express,\n container: Container,\n routeBuilder?: RouteBuilderImpl,\n middleware?: WebpiecesMiddleware,\n ) {\n this.routeBuilder = routeBuilder ?? new RouteBuilderImpl();\n this.routeBuilder.setContainer(container);\n this.middleware = middleware ?? new WebpiecesMiddleware();\n this.clientFactory = new InProcessApiClientFactory(this.routeBuilder);\n }\n\n /**\n * Register filters that wrap every matching route (glob pattern vs controller filepath).\n * Must be called before the first wireApi() - filter chains are composed per-route.\n */\n wireFilters(...defs: FilterDefinition[]): void {\n if (this.apisWired) {\n throw new Error(\n 'wireFilters() must be called before wireApi() - filter chains are composed per-route at wireApi time, so filters added later would never run.',\n );\n }\n for (const def of defs) {\n this.routeBuilder.addFilter(def);\n }\n }\n\n /**\n * Wire an API prototype class (with @ApiPath/@Endpoint decorators) to its\n * controller, mounting one Express route per endpoint with the full filter\n * chain. The controller is resolved from the Inversify container.\n */\n wireApi<TApi, TController extends TApi>(\n apiPrototype: ClassType<TApi>,\n controllerClass: ClassType<TController>,\n ): void {\n this.apisWired = true;\n\n // Reuses all existing validation: @ApiPath present, controller extends\n // api prototype, every endpoint implemented + has @Authentication.\n const factory = new ApiRoutingFactory(apiPrototype, controllerClass);\n\n // Mount only the routes added by THIS call\n const routesBefore = this.routeBuilder.getRoutes().length;\n factory.configure(this.routeBuilder);\n const routes = this.routeBuilder.getRoutes();\n\n for (let i = routesBefore; i < routes.length; i++) {\n this.mountRoute(routes[i]);\n }\n }\n\n /**\n * Mount every route currently registered on the RouteBuilder.\n * Used by WebpiecesServerImpl.start() where routes were registered up front\n * from WebAppMeta.getRoutes().\n *\n * @returns Number of routes mounted\n */\n mountRegisteredRoutes(): number {\n const routes = this.routeBuilder.getRoutes();\n for (const routeWithMeta of routes) {\n this.mountRoute(routeWithMeta);\n }\n return routes.length;\n }\n\n /**\n * Create an in-process API client (full filter chain + controller, no HTTP).\n * Same testing story as WebpiecesServer.createApiClient().\n */\n // webpieces-disable no-any-unknown -- abstract constructor signature requires any[] args\n createApiClient<T>(apiPrototype: abstract new (...args: any[]) => T): T {\n return this.clientFactory.createApiClient(apiPrototype);\n }\n\n /**\n * Escape hatch for advanced wiring (e.g. addRoute with a hand-built RouteDefinition).\n */\n getRouteBuilder(): RouteBuilderImpl {\n return this.routeBuilder;\n }\n\n /**\n * Compose the filter chain for one route and register it on the Express app.\n */\n private mountRoute(routeWithMeta: RouteHandlerWithMeta): void {\n const service = this.routeBuilder.createRouteHandler(routeWithMeta);\n const routeMeta = routeWithMeta.definition.routeMeta;\n\n // ExpressWrapper handles the full request/response cycle per route:\n // RequestContext.run, header read, manual JSON body parse, error->ProtocolError\n const wrapper = this.middleware.createExpressWrapper(service, routeMeta);\n\n this.registerHandler(\n routeMeta.httpMethod,\n routeMeta.path,\n wrapper.execute.bind(wrapper),\n );\n }\n\n private registerHandler(httpMethod: string, path: string, expressHandler: ExpressRouteHandler): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n this.app.get(path, expressHandler);\n break;\n case 'post':\n this.app.post(path, expressHandler);\n break;\n case 'put':\n this.app.put(path, expressHandler);\n break;\n case 'delete':\n this.app.delete(path, expressHandler);\n break;\n case 'patch':\n this.app.patch(path, expressHandler);\n break;\n default:\n log.warn(`[WebpiecesRouteCreator] Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"WebpiecesRouteCreator.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesRouteCreator.ts"],"names":[],"mappings":";;;AAEA,0DAOiC;AACjC,+DAA4D;AAC5D,2EAAwE;AACxE,oDAAkD;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,uBAAuB,CAAC,CAAC;AAE1D,MAAa,qBAAqB;IAelB;IAdJ,YAAY,CAAmB;IAC/B,UAAU,CAAsB;IAChC,aAAa,CAA4B;IAEjD,gFAAgF;IACxE,SAAS,GAAG,KAAK,CAAC;IAE1B;;;;;OAKG;IACH,YACY,GAAY,EACpB,SAAoB,EACpB,YAA+B,EAC/B,UAAgC;QAHxB,QAAG,GAAH,GAAG,CAAS;QAKpB,IAAI,CAAC,YAAY,GAAG,YAAY,IAAI,IAAI,+BAAgB,EAAE,CAAC;QAC3D,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,UAAU,GAAG,UAAU,IAAI,IAAI,yCAAmB,EAAE,CAAC;QAC1D,IAAI,CAAC,aAAa,GAAG,IAAI,qDAAyB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1E,CAAC;IAED;;;OAGG;IACH,WAAW,CAAC,GAAG,IAAwB;QACnC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CACX,+IAA+I,CAClJ,CAAC;QACN,CAAC;QACD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACrB,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QAC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aAAa,CAAC,UAAU,CAAC,SAAS,CAAC;QAErD,oEAAoE;QACpE,gFAAgF;QAChF,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,oBAAoB,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;QAEzE,IAAI,CAAC,eAAe,CAChB,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,IAAI,EACd,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAChC,CAAC;IACN,CAAC;IAEO,eAAe,CAAC,UAAkB,EAAE,IAAY,EAAE,cAAmC;QACzF,QAAQ,UAAU,CAAC,WAAW,EAAE,EAAE,CAAC;YAC/B,KAAK,KAAK;gBACN,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACnC,MAAM;YACV,KAAK,MAAM;gBACP,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACpC,MAAM;YACV,KAAK,KAAK;gBACN,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACnC,MAAM;YACV,KAAK,QAAQ;gBACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACtC,MAAM;YACV,KAAK,OAAO;gBACR,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;gBACrC,MAAM;YACV;gBACI,GAAG,CAAC,IAAI,CAAC,gDAAgD,UAAU,EAAE,CAAC,CAAC;QAC/E,CAAC;IACL,CAAC;CACJ;AAxID,sDAwIC","sourcesContent":["import { Express } from 'express';\nimport { Container } from 'inversify';\nimport {\n ApiRoutingFactory,\n ClassType,\n ExpressRouteHandler,\n FilterDefinition,\n RouteBuilderImpl,\n RouteHandlerWithMeta,\n} from '@webpieces/http-routing';\nimport { WebpiecesMiddleware } from './WebpiecesMiddleware';\nimport { InProcessApiClientFactory } from './InProcessApiClientFactory';\nimport { LogManager } from '@webpieces/core-util';\n\n/**\n * WebpiecesRouteCreator - Embeddable adapter that mounts the webpieces\n * api -> filters -> controller pipeline onto ANY existing Express app.\n *\n * Legacy Express apps can adopt webpieces incrementally: existing routes and\n * middleware keep working untouched; each wired webpieces route is fully\n * self-contained (own body parsing, own RequestContext, own error->JSON mapping).\n * This class never calls app.use() - it only registers per-route handlers.\n *\n * Usage:\n * ```typescript\n * const app = express(); // your existing legacy app\n * const container = new Container();\n * await container.load(buildProviderModule()); // picks up @provideSingleton classes\n * await container.load(WebpiecesModule); // required if you use ContextFilter\n *\n * const creator = new WebpiecesRouteCreator(app, container);\n * creator.wireFilters(\n * new FilterDefinition(2000, ContextFilter, '*'),\n * new FilterDefinition(1900, AuthFilter, 'src/controllers/admin/**'),\n * );\n * creator.wireApi(SaveApi, SaveController); // controller resolved from container\n * creator.wireApi(PublicApi, PublicController);\n * app.listen(8080);\n * ```\n *\n * Notes:\n * - ALL wireFilters() calls must come BEFORE the first wireApi() call. Filter\n * chains are composed per-route at wireApi time, so late filters would be\n * silently ignored - we throw instead.\n * - Scoped filter glob patterns match the controller filepath from the\n * @SourceFile decorator, falling back to the pattern `**\\/{ClassName}.ts`.\n * - Want webpieces' localhost CORS? Opt in yourself:\n * `app.use(new WebpiecesMiddleware().corsForLocalhost())`.\n *\n * This same class is used internally by WebpiecesServerImpl.start(), so the\n * full server and the embeddable adapter share one code path.\n */\nconst log = LogManager.getLogger('WebpiecesRouteCreator');\n\nexport class WebpiecesRouteCreator {\n private routeBuilder: RouteBuilderImpl;\n private middleware: WebpiecesMiddleware;\n private clientFactory: InProcessApiClientFactory;\n\n /** Locks wireFilters() once the first wireApi() has composed a filter chain. */\n private apisWired = false;\n\n /**\n * @param app - The Express app to mount routes on (yours - never taken over)\n * @param container - Inversify container used to resolve controllers and filters\n * @param routeBuilder - Internal: WebpiecesServerImpl passes its DI singleton; standalone users omit\n * @param middleware - Internal: WebpiecesServerImpl passes its DI singleton; standalone users omit\n */\n constructor(\n private app: Express,\n container: Container,\n routeBuilder?: RouteBuilderImpl,\n middleware?: WebpiecesMiddleware,\n ) {\n this.routeBuilder = routeBuilder ?? new RouteBuilderImpl();\n this.routeBuilder.setContainer(container);\n this.middleware = middleware ?? new WebpiecesMiddleware();\n this.clientFactory = new InProcessApiClientFactory(this.routeBuilder);\n }\n\n /**\n * Register filters that wrap every matching route (glob pattern vs controller filepath).\n * Must be called before the first wireApi() - filter chains are composed per-route.\n */\n wireFilters(...defs: FilterDefinition[]): void {\n if (this.apisWired) {\n throw new Error(\n 'wireFilters() must be called before wireApi() - filter chains are composed per-route at wireApi time, so filters added later would never run.',\n );\n }\n for (const def of defs) {\n this.routeBuilder.addFilter(def);\n }\n }\n\n /**\n * Wire an API prototype class (with @ApiPath/@Endpoint decorators) to its\n * controller, mounting one Express route per endpoint with the full filter\n * chain. The controller is resolved from the Inversify container.\n */\n wireApi<TApi, TController extends TApi>(\n apiPrototype: ClassType<TApi>,\n controllerClass: ClassType<TController>,\n ): void {\n this.apisWired = true;\n\n // Reuses all existing validation: @ApiPath present, controller extends\n // api prototype, every endpoint implemented + has @Authentication.\n const factory = new ApiRoutingFactory(apiPrototype, controllerClass);\n\n // Mount only the routes added by THIS call\n const routesBefore = this.routeBuilder.getRoutes().length;\n factory.configure(this.routeBuilder);\n const routes = this.routeBuilder.getRoutes();\n\n for (let i = routesBefore; i < routes.length; i++) {\n this.mountRoute(routes[i]);\n }\n }\n\n /**\n * Mount every route currently registered on the RouteBuilder.\n * Used by WebpiecesServerImpl.start() where routes were registered up front\n * from WebAppMeta.getRoutes().\n *\n * @returns Number of routes mounted\n */\n mountRegisteredRoutes(): number {\n const routes = this.routeBuilder.getRoutes();\n for (const routeWithMeta of routes) {\n this.mountRoute(routeWithMeta);\n }\n return routes.length;\n }\n\n /**\n * Create an in-process API client (full filter chain + controller, no HTTP).\n * Same testing story as WebpiecesServer.createApiClient().\n */\n // webpieces-disable no-any-unknown -- abstract constructor signature requires any[] args\n createApiClient<T>(apiPrototype: abstract new (...args: any[]) => T): T {\n return this.clientFactory.createApiClient(apiPrototype);\n }\n\n /**\n * Escape hatch for advanced wiring (e.g. addRoute with a hand-built RouteDefinition).\n */\n getRouteBuilder(): RouteBuilderImpl {\n return this.routeBuilder;\n }\n\n /**\n * Compose the filter chain for one route and register it on the Express app.\n */\n private mountRoute(routeWithMeta: RouteHandlerWithMeta): void {\n const service = this.routeBuilder.createRouteHandler(routeWithMeta);\n const routeMeta = routeWithMeta.definition.routeMeta;\n\n // ExpressWrapper handles the full request/response cycle per route:\n // RequestContext.run, header read, manual JSON body parse, error->ProtocolError\n const wrapper = this.middleware.createExpressWrapper(service, routeMeta);\n\n this.registerHandler(\n routeMeta.httpMethod,\n routeMeta.path,\n wrapper.execute.bind(wrapper),\n );\n }\n\n private registerHandler(httpMethod: string, path: string, expressHandler: ExpressRouteHandler): void {\n switch (httpMethod.toLowerCase()) {\n case 'get':\n this.app.get(path, expressHandler);\n break;\n case 'post':\n this.app.post(path, expressHandler);\n break;\n case 'put':\n this.app.put(path, expressHandler);\n break;\n case 'delete':\n this.app.delete(path, expressHandler);\n break;\n case 'patch':\n this.app.patch(path, expressHandler);\n break;\n default:\n log.warn(`[WebpiecesRouteCreator] Unknown HTTP method: ${httpMethod}`);\n }\n }\n}\n"]}
@@ -9,7 +9,7 @@ const http_routing_1 = require("@webpieces/http-routing");
9
9
  const WebpiecesMiddleware_1 = require("./WebpiecesMiddleware");
10
10
  const WebpiecesRouteCreator_1 = require("./WebpiecesRouteCreator");
11
11
  const InProcessApiClientFactory_1 = require("./InProcessApiClientFactory");
12
- const wp_logging_1 = require("@webpieces/wp-logging");
12
+ const core_util_1 = require("@webpieces/core-util");
13
13
  /**
14
14
  * WebpiecesServerImpl - Internal server implementation.
15
15
  *
@@ -34,7 +34,7 @@ const wp_logging_1 = require("@webpieces/wp-logging");
34
34
  * DI Pattern: This class is registered in webpiecesContainer via @provideSingleton()
35
35
  * and resolved by WebpiecesFactory. It receives RouteBuilder via constructor injection.
36
36
  */
37
- const log = wp_logging_1.LogManager.getLogger('WebpiecesServer');
37
+ const log = core_util_1.LogManager.getLogger('WebpiecesServer');
38
38
  let WebpiecesServerImpl = class WebpiecesServerImpl {
39
39
  meta;
40
40
  routeBuilder;
@@ -78,8 +78,7 @@ let WebpiecesServerImpl = class WebpiecesServerImpl {
78
78
  // buildProviderModule bound a SEPARATE RouteBuilderImpl into appContainer; make
79
79
  // app-side singletons resolve the SAME framework instance that actually holds the
80
80
  // registered routes (setContainer + addRoute happen on `this.routeBuilder`). Without
81
- // this, an app singleton that injects RouteBuilderImpl (e.g. LocalTaskDispatcherImpl,
82
- // used by InMemoryTaskInvoker) would see an empty route table.
81
+ // this, an app singleton that injects RouteBuilderImpl would see an empty route table.
83
82
  (await this.appContainer.rebind(http_routing_1.RouteBuilderImpl)).toConstantValue(this.routeBuilder);
84
83
  // 2. Register routes and filters
85
84
  this.registerRoutes();
@@ -1 +1 @@
1
- {"version":3,"file":"WebpiecesServerImpl.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesServerImpl.ts"],"names":[],"mappings":";;;;AAAA,8DAAyC;AACzC,yCAAyE;AACzE,wEAAoE;AACpE,0DAKiC;AAEjC,+DAA0D;AAC1D,mEAA8D;AAC9D,2EAAsE;AACtE,sDAAiD;AAEjD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,GAAG,GAAG,uBAAU,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC;AAI7C,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAgBW;IACD;IACG;IAjBjC,kBAAkB,CAAa;IAEvC;;;;OAIG;IACK,YAAY,CAAa;IAEzB,WAAW,GAAG,KAAK,CAAC;IACpB,GAAG,CAAW;IACd,MAAM,CAAiC;IACvC,IAAI,GAAW,IAAI,CAAC;IAE5B,YACuC,IAAgB,EACjB,YAA8B,EAC3B,UAA+B;QAFjC,SAAI,G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AAC;gBAC7C,OAAO,EAAE,CAAC;YACd,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;;;OAMG;IACH,YAAY;QACR,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,yFAAyF;IACzF,eAAe,CAAI,YAAgD;QAC/D,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,qEAAqE,CAAC,CAAC;QAC3F,CAAC;QAED,4FAA4F;QAC5F,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,IAAI,CAAC,aAAa,GAAG,IAAI,qDAAyB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5D,CAAC;IAEO,aAAa,CAA6B;CACrD,CAAA;AAnPY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;IAiBJ,mBAAA,IAAA,kBAAM,EAAC,gCAAiB,CAAC,CAAA;IACzB,mBAAA,IAAA,kBAAM,EAAC,+BAAgB,CAAC,CAAA;IACxB,mBAAA,IAAA,kBAAM,EAAC,yCAAmB,CAAC,CAAA;qDADoB,+BAAgB;QACf,yCAAmB;GAlB/D,mBAAmB,CAmP/B","sourcesContent":["import express, {Express} from 'express';\nimport {Container, ContainerModule, inject, injectable} from 'inversify';\nimport {buildProviderModule} from '@inversifyjs/binding-decorators';\nimport {\n provideSingleton,\n RouteBuilderImpl,\n WebAppMeta,\n WEBAPP_META_TOKEN,\n} from '@webpieces/http-routing';\nimport {WebpiecesServer} from './WebpiecesServer';\nimport {WebpiecesMiddleware} from './WebpiecesMiddleware';\nimport {WebpiecesRouteCreator} from './WebpiecesRouteCreator';\nimport {InProcessApiClientFactory} from './InProcessApiClientFactory';\nimport {LogManager} from '@webpieces/wp-logging';\n\n/**\n * WebpiecesServerImpl - Internal server implementation.\n *\n * This class implements the WebpiecesServer interface and contains\n * all the actual server logic. It is created by WebpiecesFactory.create().\n *\n * This class uses a two-container pattern similar to Java WebPieces:\n * 1. webpiecesContainer: Core WebPieces framework bindings\n * 2. appContainer: User's application bindings (child of webpiecesContainer)\n *\n * This separation allows:\n * - Clean separation of concerns\n * - Better testability\n * - Ability to override framework bindings in tests\n *\n * The server:\n * 1. Initializes both DI containers from WebAppMeta.getDIModules()\n * 2. Registers routes using explicit RouteBuilderImpl\n * 3. Creates filter chains\n * 4. Supports both HTTP server mode and testing mode (no HTTP)\n *\n * DI Pattern: This class is registered in webpiecesContainer via @provideSingleton()\n * and resolved by WebpiecesFactory. It receives RouteBuilder via constructor injection.\n */\nconst log = LogManager.getLogger('WebpiecesServer');\n\n@provideSingleton()\n@injectable()\nexport class WebpiecesServerImpl implements WebpiecesServer {\n private webpiecesContainer!: Container;\n\n /**\n * Application container: User's application bindings.\n * This is a child container of webpiecesContainer, so it can access\n * framework bindings while keeping app bindings separate.\n */\n private appContainer!: Container;\n\n private initialized = false;\n private app?: Express;\n private server?: ReturnType<Express['listen']>;\n private port: number = 8200;\n\n constructor(\n @inject(WEBAPP_META_TOKEN) private meta: WebAppMeta,\n @inject(RouteBuilderImpl) private routeBuilder: RouteBuilderImpl,\n @inject(WebpiecesMiddleware) private middleware: WebpiecesMiddleware,\n ) {}\n\n /**\n * Initialize the server asynchronously.\n * This is called by WebpiecesFactory.create() after resolving this class from DI.\n * This method is internal and not exposed on the WebpiecesServer interface.\n *\n * @param webpiecesContainer - The framework container\n * @param meta - User-provided WebAppMeta with DI modules and routes\n * @param appOverrides - Optional ContainerModule for app test overrides (loaded LAST)\n */\n async initialize(\n webpiecesContainer: Container,\n appOverrides?: ContainerModule\n ): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n this.webpiecesContainer = webpiecesContainer;\n\n // Create application container as child of framework container\n this.appContainer = new Container({ parent: this.webpiecesContainer });\n\n // Set container on RouteBuilder (late binding - appContainer didn't exist in constructor)\n this.routeBuilder.setContainer(this.appContainer);\n\n // 1. Load DI modules asynchronously\n await this.loadDIModules(appOverrides);\n\n // buildProviderModule bound a SEPARATE RouteBuilderImpl into appContainer; make\n // app-side singletons resolve the SAME framework instance that actually holds the\n // registered routes (setContainer + addRoute happen on `this.routeBuilder`). Without\n // this, an app singleton that injects RouteBuilderImpl (e.g. LocalTaskDispatcherImpl,\n // used by InMemoryTaskInvoker) would see an empty route table.\n (await this.appContainer.rebind(RouteBuilderImpl)).toConstantValue(this.routeBuilder);\n\n // 2. Register routes and filters\n this.registerRoutes();\n\n this.initialized = true;\n }\n\n /**\n * Load DI modules from WebAppMeta.\n *\n * Currently, all user modules are loaded into the application container.\n * In the future, we could separate:\n * - WebPieces framework modules -> webpiecesContainer\n * - Application modules -> appContainer\n *\n * For now, everything goes into appContainer which has access to webpiecesContainer.\n *\n * @param appOverrides - Optional ContainerModule for app test overrides (loaded LAST to override bindings)\n */\n private async loadDIModules(appOverrides?: ContainerModule): Promise<void> {\n const modules = this.meta.getDIModules();\n\n // Load buildProviderModule to auto-scan for @provideSingleton decorators\n await this.appContainer.load(buildProviderModule());\n\n // Load all modules into application container\n // (webpiecesContainer is currently empty, reserved for future framework bindings)\n for (const module of modules) {\n await this.appContainer.load(module);\n }\n\n // Load appOverrides LAST so they can override existing bindings\n if (appOverrides) {\n await this.appContainer.load(appOverrides);\n }\n }\n\n /**\n * Register routes from WebAppMeta.\n *\n * Creates an explicit RouteBuilderImpl instead of an anonymous object.\n * This improves:\n * - Traceability: Can Cmd+Click on addRoute to see implementation\n * - Debugging: Explicit class shows up in stack traces\n * - Understanding: Clear class name vs anonymous object\n */\n private registerRoutes(): void {\n const routeConfigs = this.meta.getRoutes();\n\n // Configure routes using the explicit RouteBuilder\n for (const routeConfig of routeConfigs) {\n routeConfig.configure(this.routeBuilder);\n }\n }\n\n /**\n * Start the HTTP server with Express.\n * Returns a Promise that resolves when the server is listening,\n * or rejects if the server fails to start.\n *\n * @param port - The port to listen on (default: 8080)\n * @returns Promise that resolves when server is ready\n */\n async start(port: number = 8200, testMode?: boolean): Promise<void> {\n if (!this.initialized) {\n throw new Error('Server not initialized. Call initialize() before start().');\n }\n\n this.port = port;\n\n if(testMode) {\n //In testMode, we eliminate express ENTIRELY and use\n //Router, method filters and controllers so that we can test full stack\n return;\n }\n\n // Create Express app\n this.app = express();\n\n // Layer 1: Global Error Handler (OUTERMOST - runs FIRST)\n // Catches all unhandled errors and returns HTML 500 page\n this.app.use(this.middleware.globalErrorHandler.bind(this.middleware));\n\n // Layer 2: CORS for localhost development\n this.app.use(this.middleware.corsForLocalhost());\n\n // Layer 3: Request/Response Logging\n this.app.use(this.middleware.logNextLayer.bind(this.middleware));\n\n // Register routes via the shared adapter (same code path as the\n // embeddable WebpiecesRouteCreator used by legacy Express apps)\n const routeCreator = new WebpiecesRouteCreator(\n this.app,\n this.appContainer,\n this.routeBuilder,\n this.middleware,\n );\n const routeCount = routeCreator.mountRegisteredRoutes();\n\n // Start listening - wrap in Promise\n const promise = new Promise<void>((resolve, reject) => {\n this.server = this.app!.listen(this.port, (error?: Error) => {\n if (error) {\n log.error(`[WebpiecesServer] Failed to start server:`, error);\n reject(error);\n return;\n }\n log.info(`[WebpiecesServer] Server listening on http://localhost:${this.port}`);\n log.info(`[WebpiecesServer] Registered ${routeCount} routes`);\n resolve();\n });\n });\n\n await promise;\n }\n\n /**\n * Stop the HTTP server.\n * Returns a Promise that resolves when the server is stopped,\n * or rejects if there's an error stopping the server.\n *\n * @returns Promise that resolves when server is stopped\n */\n async stop(): Promise<void> {\n if (!this.server) {\n return;\n }\n\n return new Promise<void>((resolve, reject) => {\n this.server!.close((err?: Error) => {\n if (err) {\n log.error('[WebpiecesServer] Error stopping server:', err);\n reject(err);\n return;\n }\n log.info('[WebpiecesServer] Server stopped');\n resolve();\n });\n });\n }\n\n /**\n * Get the application DI container.\n *\n * Useful for testing to verify state or access services directly.\n *\n * @returns The application Container\n */\n getContainer(): Container {\n return this.appContainer;\n }\n\n /**\n * Create an API client proxy for testing.\n *\n * This creates a client that routes calls through the full filter chain\n * and controller, but WITHOUT any HTTP overhead. Perfect for testing!\n *\n * The client uses the ApiPrototype class to discover routes via decorators,\n * then creates pre-configured invoker functions for each API method.\n *\n * IMPORTANT: This loops over the API methods (from decorators), NOT all routes.\n * For each API method, it sets up the filter chain ONCE during proxy creation,\n * so subsequent calls reuse the same filter chain (efficient!).\n *\n * @param apiPrototype - The abstract API prototype whose routing decorators declare the routes\n * @returns A proxy that implements the API interface\n *\n * Example:\n * ```typescript\n * const saveApi = server.createApiClient<SaveApi>(SaveApi);\n * const response = await saveApi.save(request);\n * ```\n */\n // webpieces-disable no-any-unknown -- abstract constructor signature requires any[] args\n createApiClient<T>(apiPrototype: abstract new (...args: any[]) => T): T {\n if (!this.initialized) {\n throw new Error('Server not initialized. Call initialize() before createApiClient().');\n }\n\n // Delegates to the shared factory (same code path as WebpiecesRouteCreator.createApiClient)\n if (!this.clientFactory) {\n this.clientFactory = new InProcessApiClientFactory(this.routeBuilder);\n }\n return this.clientFactory.createApiClient(apiPrototype);\n }\n\n private clientFactory?: InProcessApiClientFactory;\n}\n"]}
1
+ {"version":3,"file":"WebpiecesServerImpl.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesServerImpl.ts"],"names":[],"mappings":";;;;AAAA,8DAAyC;AACzC,yCAAyE;AACzE,wEAAoE;AACpE,0DAKiC;AAEjC,+DAA0D;AAC1D,mEAA8D;AAC9D,2EAAsE;AACtE,oDAAgD;AAEhD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC;AAI7C,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAgBW;IACD;IACG;IAjBjC,kBAAkB,CAAa;IAEvC;;;;OAIG;IACK,YAA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AAK,CAAC,0CAA0C,EAAE,GAAG,CAAC,CAAC;oBAC3D,MAAM,CAAC,GAAG,CAAC,CAAC;oBACZ,OAAO;gBACX,CAAC;gBACD,GAAG,CAAC,IAAI,CAAC,kCAAkC,CAAC,CAAC;gBAC7C,OAAO,EAAE,CAAC;YACd,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;IAED;;;;;;OAMG;IACH,YAAY;QACR,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,yFAAyF;IACzF,eAAe,CAAI,YAAgD;QAC/D,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,qEAAqE,CAAC,CAAC;QAC3F,CAAC;QAED,4FAA4F;QAC5F,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,IAAI,CAAC,aAAa,GAAG,IAAI,qDAAyB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5D,CAAC;IAEO,aAAa,CAA6B;CACrD,CAAA;AAlPY,kDAAmB;8BAAnB,mBAAmB;IAF/B,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;IAiBJ,mBAAA,IAAA,kBAAM,EAAC,gCAAiB,CAAC,CAAA;IACzB,mBAAA,IAAA,kBAAM,EAAC,+BAAgB,CAAC,CAAA;IACxB,mBAAA,IAAA,kBAAM,EAAC,yCAAmB,CAAC,CAAA;qDADoB,+BAAgB;QACf,yCAAmB;GAlB/D,mBAAmB,CAkP/B","sourcesContent":["import express, {Express} from 'express';\nimport {Container, ContainerModule, inject, injectable} from 'inversify';\nimport {buildProviderModule} from '@inversifyjs/binding-decorators';\nimport {\n provideSingleton,\n RouteBuilderImpl,\n WebAppMeta,\n WEBAPP_META_TOKEN,\n} from '@webpieces/http-routing';\nimport {WebpiecesServer} from './WebpiecesServer';\nimport {WebpiecesMiddleware} from './WebpiecesMiddleware';\nimport {WebpiecesRouteCreator} from './WebpiecesRouteCreator';\nimport {InProcessApiClientFactory} from './InProcessApiClientFactory';\nimport {LogManager} from '@webpieces/core-util';\n\n/**\n * WebpiecesServerImpl - Internal server implementation.\n *\n * This class implements the WebpiecesServer interface and contains\n * all the actual server logic. It is created by WebpiecesFactory.create().\n *\n * This class uses a two-container pattern similar to Java WebPieces:\n * 1. webpiecesContainer: Core WebPieces framework bindings\n * 2. appContainer: User's application bindings (child of webpiecesContainer)\n *\n * This separation allows:\n * - Clean separation of concerns\n * - Better testability\n * - Ability to override framework bindings in tests\n *\n * The server:\n * 1. Initializes both DI containers from WebAppMeta.getDIModules()\n * 2. Registers routes using explicit RouteBuilderImpl\n * 3. Creates filter chains\n * 4. Supports both HTTP server mode and testing mode (no HTTP)\n *\n * DI Pattern: This class is registered in webpiecesContainer via @provideSingleton()\n * and resolved by WebpiecesFactory. It receives RouteBuilder via constructor injection.\n */\nconst log = LogManager.getLogger('WebpiecesServer');\n\n@provideSingleton()\n@injectable()\nexport class WebpiecesServerImpl implements WebpiecesServer {\n private webpiecesContainer!: Container;\n\n /**\n * Application container: User's application bindings.\n * This is a child container of webpiecesContainer, so it can access\n * framework bindings while keeping app bindings separate.\n */\n private appContainer!: Container;\n\n private initialized = false;\n private app?: Express;\n private server?: ReturnType<Express['listen']>;\n private port: number = 8200;\n\n constructor(\n @inject(WEBAPP_META_TOKEN) private meta: WebAppMeta,\n @inject(RouteBuilderImpl) private routeBuilder: RouteBuilderImpl,\n @inject(WebpiecesMiddleware) private middleware: WebpiecesMiddleware,\n ) {}\n\n /**\n * Initialize the server asynchronously.\n * This is called by WebpiecesFactory.create() after resolving this class from DI.\n * This method is internal and not exposed on the WebpiecesServer interface.\n *\n * @param webpiecesContainer - The framework container\n * @param meta - User-provided WebAppMeta with DI modules and routes\n * @param appOverrides - Optional ContainerModule for app test overrides (loaded LAST)\n */\n async initialize(\n webpiecesContainer: Container,\n appOverrides?: ContainerModule\n ): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n this.webpiecesContainer = webpiecesContainer;\n\n // Create application container as child of framework container\n this.appContainer = new Container({ parent: this.webpiecesContainer });\n\n // Set container on RouteBuilder (late binding - appContainer didn't exist in constructor)\n this.routeBuilder.setContainer(this.appContainer);\n\n // 1. Load DI modules asynchronously\n await this.loadDIModules(appOverrides);\n\n // buildProviderModule bound a SEPARATE RouteBuilderImpl into appContainer; make\n // app-side singletons resolve the SAME framework instance that actually holds the\n // registered routes (setContainer + addRoute happen on `this.routeBuilder`). Without\n // this, an app singleton that injects RouteBuilderImpl would see an empty route table.\n (await this.appContainer.rebind(RouteBuilderImpl)).toConstantValue(this.routeBuilder);\n\n // 2. Register routes and filters\n this.registerRoutes();\n\n this.initialized = true;\n }\n\n /**\n * Load DI modules from WebAppMeta.\n *\n * Currently, all user modules are loaded into the application container.\n * In the future, we could separate:\n * - WebPieces framework modules -> webpiecesContainer\n * - Application modules -> appContainer\n *\n * For now, everything goes into appContainer which has access to webpiecesContainer.\n *\n * @param appOverrides - Optional ContainerModule for app test overrides (loaded LAST to override bindings)\n */\n private async loadDIModules(appOverrides?: ContainerModule): Promise<void> {\n const modules = this.meta.getDIModules();\n\n // Load buildProviderModule to auto-scan for @provideSingleton decorators\n await this.appContainer.load(buildProviderModule());\n\n // Load all modules into application container\n // (webpiecesContainer is currently empty, reserved for future framework bindings)\n for (const module of modules) {\n await this.appContainer.load(module);\n }\n\n // Load appOverrides LAST so they can override existing bindings\n if (appOverrides) {\n await this.appContainer.load(appOverrides);\n }\n }\n\n /**\n * Register routes from WebAppMeta.\n *\n * Creates an explicit RouteBuilderImpl instead of an anonymous object.\n * This improves:\n * - Traceability: Can Cmd+Click on addRoute to see implementation\n * - Debugging: Explicit class shows up in stack traces\n * - Understanding: Clear class name vs anonymous object\n */\n private registerRoutes(): void {\n const routeConfigs = this.meta.getRoutes();\n\n // Configure routes using the explicit RouteBuilder\n for (const routeConfig of routeConfigs) {\n routeConfig.configure(this.routeBuilder);\n }\n }\n\n /**\n * Start the HTTP server with Express.\n * Returns a Promise that resolves when the server is listening,\n * or rejects if the server fails to start.\n *\n * @param port - The port to listen on (default: 8080)\n * @returns Promise that resolves when server is ready\n */\n async start(port: number = 8200, testMode?: boolean): Promise<void> {\n if (!this.initialized) {\n throw new Error('Server not initialized. Call initialize() before start().');\n }\n\n this.port = port;\n\n if(testMode) {\n //In testMode, we eliminate express ENTIRELY and use\n //Router, method filters and controllers so that we can test full stack\n return;\n }\n\n // Create Express app\n this.app = express();\n\n // Layer 1: Global Error Handler (OUTERMOST - runs FIRST)\n // Catches all unhandled errors and returns HTML 500 page\n this.app.use(this.middleware.globalErrorHandler.bind(this.middleware));\n\n // Layer 2: CORS for localhost development\n this.app.use(this.middleware.corsForLocalhost());\n\n // Layer 3: Request/Response Logging\n this.app.use(this.middleware.logNextLayer.bind(this.middleware));\n\n // Register routes via the shared adapter (same code path as the\n // embeddable WebpiecesRouteCreator used by legacy Express apps)\n const routeCreator = new WebpiecesRouteCreator(\n this.app,\n this.appContainer,\n this.routeBuilder,\n this.middleware,\n );\n const routeCount = routeCreator.mountRegisteredRoutes();\n\n // Start listening - wrap in Promise\n const promise = new Promise<void>((resolve, reject) => {\n this.server = this.app!.listen(this.port, (error?: Error) => {\n if (error) {\n log.error(`[WebpiecesServer] Failed to start server:`, error);\n reject(error);\n return;\n }\n log.info(`[WebpiecesServer] Server listening on http://localhost:${this.port}`);\n log.info(`[WebpiecesServer] Registered ${routeCount} routes`);\n resolve();\n });\n });\n\n await promise;\n }\n\n /**\n * Stop the HTTP server.\n * Returns a Promise that resolves when the server is stopped,\n * or rejects if there's an error stopping the server.\n *\n * @returns Promise that resolves when server is stopped\n */\n async stop(): Promise<void> {\n if (!this.server) {\n return;\n }\n\n return new Promise<void>((resolve, reject) => {\n this.server!.close((err?: Error) => {\n if (err) {\n log.error('[WebpiecesServer] Error stopping server:', err);\n reject(err);\n return;\n }\n log.info('[WebpiecesServer] Server stopped');\n resolve();\n });\n });\n }\n\n /**\n * Get the application DI container.\n *\n * Useful for testing to verify state or access services directly.\n *\n * @returns The application Container\n */\n getContainer(): Container {\n return this.appContainer;\n }\n\n /**\n * Create an API client proxy for testing.\n *\n * This creates a client that routes calls through the full filter chain\n * and controller, but WITHOUT any HTTP overhead. Perfect for testing!\n *\n * The client uses the ApiPrototype class to discover routes via decorators,\n * then creates pre-configured invoker functions for each API method.\n *\n * IMPORTANT: This loops over the API methods (from decorators), NOT all routes.\n * For each API method, it sets up the filter chain ONCE during proxy creation,\n * so subsequent calls reuse the same filter chain (efficient!).\n *\n * @param apiPrototype - The abstract API prototype whose routing decorators declare the routes\n * @returns A proxy that implements the API interface\n *\n * Example:\n * ```typescript\n * const saveApi = server.createApiClient<SaveApi>(SaveApi);\n * const response = await saveApi.save(request);\n * ```\n */\n // webpieces-disable no-any-unknown -- abstract constructor signature requires any[] args\n createApiClient<T>(apiPrototype: abstract new (...args: any[]) => T): T {\n if (!this.initialized) {\n throw new Error('Server not initialized. Call initialize() before createApiClient().');\n }\n\n // Delegates to the shared factory (same code path as WebpiecesRouteCreator.createApiClient)\n if (!this.clientFactory) {\n this.clientFactory = new InProcessApiClientFactory(this.routeBuilder);\n }\n return this.clientFactory.createApiClient(apiPrototype);\n }\n\n private clientFactory?: InProcessApiClientFactory;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { MethodMeta } from '@webpieces/http-routing';
2
2
  import { Filter, WpResponse, Service } from '@webpieces/http-filters';
3
- import { HeaderRegistry } from '@webpieces/http-api';
3
+ import { HeaderRegistry } from '@webpieces/core-util';
4
4
  export declare class ContextFilter extends Filter<MethodMeta, WpResponse<unknown>> {
5
5
  private transferredHeaders;
6
6
  constructor(registry: HeaderRegistry);
@@ -6,10 +6,10 @@ const inversify_1 = require("inversify");
6
6
  const http_routing_1 = require("@webpieces/http-routing");
7
7
  const core_context_1 = require("@webpieces/core-context");
8
8
  const http_filters_1 = require("@webpieces/http-filters");
9
- const http_api_1 = require("@webpieces/http-api");
9
+ const core_util_1 = require("@webpieces/core-util");
10
10
  const WebpiecesCoreHeaders_1 = require("../headers/WebpiecesCoreHeaders");
11
11
  const ContextKeys_1 = require("../headers/ContextKeys");
12
- const wp_logging_1 = require("@webpieces/wp-logging");
12
+ const core_util_2 = require("@webpieces/core-util");
13
13
  /**
14
14
  * ContextFilter - Transfers platform headers and stores request metadata in RequestContext.
15
15
  * Priority: 2000 (executes first in filter chain)
@@ -29,7 +29,7 @@ const wp_logging_1 = require("@webpieces/wp-logging");
29
29
  * 6. Downstream filters and controller can access headers + metadata
30
30
  * 7. Context auto-clears when RequestContext.run() completes
31
31
  */
32
- const log = wp_logging_1.LogManager.getLogger('ContextFilter');
32
+ const log = core_util_2.LogManager.getLogger('ContextFilter');
33
33
  let ContextFilter = class ContextFilter extends http_filters_1.Filter {
34
34
  transferredHeaders;
35
35
  constructor(registry) {
@@ -96,7 +96,7 @@ exports.ContextFilter = ContextFilter;
96
96
  exports.ContextFilter = ContextFilter = tslib_1.__decorate([
97
97
  (0, http_routing_1.provideSingleton)(),
98
98
  (0, inversify_1.injectable)(),
99
- tslib_1.__param(0, (0, inversify_1.inject)(http_api_1.HeaderRegistry)),
100
- tslib_1.__metadata("design:paramtypes", [http_api_1.HeaderRegistry])
99
+ tslib_1.__param(0, (0, inversify_1.inject)(core_util_1.HeaderRegistry)),
100
+ tslib_1.__metadata("design:paramtypes", [core_util_1.HeaderRegistry])
101
101
  ], ContextFilter);
102
102
  //# sourceMappingURL=ContextFilter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ContextFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/ContextFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAA6C;AAC7C,0DAAuE;AACvE,0DAAyD;AACzD,0DAAsE;AACtE,kDAAqE;AACrE,0EAAqE;AACrE,wDAAmD;AACnD,s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AG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;YACxE,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC9B,oEAAoE;gBACpE,6BAAc,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAChD,CAAC;QACL,CAAC;QAED,gFAAgF;QAChF,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAEhC,8DAA8D;QAC9D,IAAI,CAAC,eAAe,EAAE,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACK,eAAe;QACnB,IAAI,CAAC,6BAAc,CAAC,SAAS,CAAC,2CAAoB,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7D,MAAM,SAAS,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3C,6BAAc,CAAC,SAAS,CAAC,2CAAoB,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;QACzE,CAAC;IACL,CAAC;IAED;;;OAGG;IACK,iBAAiB;QACrB,OAAO,eAAe,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;CACJ,CAAA;AA9EY,sCAAa;wBAAb,aAAa;IAFzB,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;IAKJ,mBAAA,IAAA,kBAAM,EAAC,yBAAc,CAAC,CAAA;6CAAW,yBAAc;GAJ3C,aAAa,CA8EzB","sourcesContent":["import {inject, injectable} from 'inversify';\nimport { provideSingleton, MethodMeta } from '@webpieces/http-routing';\nimport { RequestContext } from '@webpieces/core-context';\nimport { Filter, WpResponse, Service } from '@webpieces/http-filters';\nimport { PlatformHeader, HeaderRegistry } from '@webpieces/http-api';\nimport {WebpiecesCoreHeaders} from \"../headers/WebpiecesCoreHeaders\";\nimport {ContextKeys} from \"../headers/ContextKeys\";\nimport { LogManager } from '@webpieces/wp-logging';\n\n/**\n * ContextFilter - Transfers platform headers and stores request metadata in RequestContext.\n * Priority: 2000 (executes first in filter chain)\n *\n * NEW: Now handles header transfer from RouterRequest to RequestContext\n * - Injects PlatformHeadersExtension instances via @multiInject (safe because filter created after modules load)\n * - Reads headers from RouterRequest (Express-independent)\n * - Transfers only headers marked with isWantTransferred=true\n * - Generates REQUEST_ID if not present\n *\n * RequestContext lifecycle:\n * 1. ExpressWrapper.execute() calls RequestContext.run() (establishes context)\n * 2. ExpressWrapper creates RouterReqResp and MethodMeta\n * 3. Filter chain executes, starting with ContextFilter\n * 4. ContextFilter transfers headers from RouterRequest to RequestContext\n * 5. ContextFilter stores metadata (METHOD_META, REQUEST_PATH, HTTP_METHOD)\n * 6. Downstream filters and controller can access headers + metadata\n * 7. Context auto-clears when RequestContext.run() completes\n */\nconst log = LogManager.getLogger('ContextFilter');\n\n@provideSingleton()\n@injectable()\nexport class ContextFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n private transferredHeaders: PlatformHeader[];\n\n constructor(\n @inject(HeaderRegistry) registry: HeaderRegistry\n ) {\n super();\n\n // The registry is the single source of truth (all modules' extensions,\n // duplicate-validated at startup)\n this.transferredHeaders = registry.getTransferredHeaders();\n\n log.info(`[ContextFilter] Using ${registry.getHeaders().length} platform headers from HeaderRegistry (${this.transferredHeaders.length} transferred)`);\n }\n\n async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n // Transfer platform headers from MethodMeta.requestHeaders to RequestContext\n this.transferHeaders(meta);\n\n // Store request metadata in context for other filters/controllers to access\n RequestContext.putHeader(ContextKeys.METHOD_META, meta);\n RequestContext.putHeader(ContextKeys.REQUEST_PATH, meta.path);\n RequestContext.putHeader(ContextKeys.HTTP_METHOD, meta.httpMethod);\n\n // Execute next filter/controller\n return await nextFilter.invoke(meta);\n // RequestContext is auto-cleared by ExpressWrapper when request completes\n }\n\n /**\n * Transfer platform headers from MethodMeta.requestHeaders to RequestContext.\n * Uses HeaderMethods.findTransferHeaders() to filter by isWantTransferred=true.\n */\n private transferHeaders(meta: MethodMeta): void {\n if (!meta.requestHeaders) {\n // No headers in test mode (createApiClient creates context but not headers)\n this.ensureRequestId();\n return;\n }\n\n // Transfer each header to RequestContext using RequestContext.putHeader()\n for (const header of this.transferredHeaders) {\n // Get values from requestHeaders (case-insensitive lookup)\n const values = meta.requestHeaders.get(header.headerName.toLowerCase());\n if (values && values.length > 0) {\n // Use RequestContext.putHeader() which calls header.getHeaderName()\n RequestContext.putHeader(header, values[0]);\n }\n }\n\n // Clear request headers from MethodMeta - MUST FORCE USAGE of RequestContext!!!\n meta.requestHeaders = undefined;\n\n // Generate REQUEST_ID if not present (first service in chain)\n this.ensureRequestId();\n }\n\n /**\n * Ensure REQUEST_ID is set in RequestContext.\n * Generates one if not present.\n */\n private ensureRequestId(): void {\n if (!RequestContext.hasHeader(WebpiecesCoreHeaders.REQUEST_ID)) {\n const requestId = this.generateRequestId();\n RequestContext.putHeader(WebpiecesCoreHeaders.REQUEST_ID, requestId);\n }\n }\n\n /**\n * Generate a unique request ID.\n * Format: req-{timestamp}-{random}\n */\n private generateRequestId(): string {\n return `svrGenReqId-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;\n }\n}\n\n"]}
1
+ {"version":3,"file":"ContextFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-server/src/filters/ContextFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAA6C;AAC7C,0DAAuE;AACvE,0DAAyD;AACzD,0DAAsE;AACtE,oDAAsE;AACtE,0EAAqE;AACrE,wDAAmD;AACnD,oDAAkD;AAElD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;AAI3C,IAAM,aAAa,GAAn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AG,CAAC,EAAE,CAAC;gBAC9B,oEAAoE;gBACpE,6BAAc,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAChD,CAAC;QACL,CAAC;QAED,gFAAgF;QAChF,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAEhC,8DAA8D;QAC9D,IAAI,CAAC,eAAe,EAAE,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACK,eAAe;QACnB,IAAI,CAAC,6BAAc,CAAC,SAAS,CAAC,2CAAoB,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7D,MAAM,SAAS,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC3C,6BAAc,CAAC,SAAS,CAAC,2CAAoB,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;QACzE,CAAC;IACL,CAAC;IAED;;;OAGG;IACK,iBAAiB;QACrB,OAAO,eAAe,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;CACJ,CAAA;AA9EY,sCAAa;wBAAb,aAAa;IAFzB,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;IAKJ,mBAAA,IAAA,kBAAM,EAAC,0BAAc,CAAC,CAAA;6CAAW,0BAAc;GAJ3C,aAAa,CA8EzB","sourcesContent":["import {inject, injectable} from 'inversify';\nimport { provideSingleton, MethodMeta } from '@webpieces/http-routing';\nimport { RequestContext } from '@webpieces/core-context';\nimport { Filter, WpResponse, Service } from '@webpieces/http-filters';\nimport { PlatformHeader, HeaderRegistry } from '@webpieces/core-util';\nimport {WebpiecesCoreHeaders} from \"../headers/WebpiecesCoreHeaders\";\nimport {ContextKeys} from \"../headers/ContextKeys\";\nimport { LogManager } from '@webpieces/core-util';\n\n/**\n * ContextFilter - Transfers platform headers and stores request metadata in RequestContext.\n * Priority: 2000 (executes first in filter chain)\n *\n * NEW: Now handles header transfer from RouterRequest to RequestContext\n * - Injects PlatformHeadersExtension instances via @multiInject (safe because filter created after modules load)\n * - Reads headers from RouterRequest (Express-independent)\n * - Transfers only headers marked with isWantTransferred=true\n * - Generates REQUEST_ID if not present\n *\n * RequestContext lifecycle:\n * 1. ExpressWrapper.execute() calls RequestContext.run() (establishes context)\n * 2. ExpressWrapper creates RouterReqResp and MethodMeta\n * 3. Filter chain executes, starting with ContextFilter\n * 4. ContextFilter transfers headers from RouterRequest to RequestContext\n * 5. ContextFilter stores metadata (METHOD_META, REQUEST_PATH, HTTP_METHOD)\n * 6. Downstream filters and controller can access headers + metadata\n * 7. Context auto-clears when RequestContext.run() completes\n */\nconst log = LogManager.getLogger('ContextFilter');\n\n@provideSingleton()\n@injectable()\nexport class ContextFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n private transferredHeaders: PlatformHeader[];\n\n constructor(\n @inject(HeaderRegistry) registry: HeaderRegistry\n ) {\n super();\n\n // The registry is the single source of truth (all modules' extensions,\n // duplicate-validated at startup)\n this.transferredHeaders = registry.getTransferredHeaders();\n\n log.info(`[ContextFilter] Using ${registry.getHeaders().length} platform headers from HeaderRegistry (${this.transferredHeaders.length} transferred)`);\n }\n\n async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n // Transfer platform headers from MethodMeta.requestHeaders to RequestContext\n this.transferHeaders(meta);\n\n // Store request metadata in context for other filters/controllers to access\n RequestContext.putHeader(ContextKeys.METHOD_META, meta);\n RequestContext.putHeader(ContextKeys.REQUEST_PATH, meta.path);\n RequestContext.putHeader(ContextKeys.HTTP_METHOD, meta.httpMethod);\n\n // Execute next filter/controller\n return await nextFilter.invoke(meta);\n // RequestContext is auto-cleared by ExpressWrapper when request completes\n }\n\n /**\n * Transfer platform headers from MethodMeta.requestHeaders to RequestContext.\n * Uses HeaderMethods.findTransferHeaders() to filter by isWantTransferred=true.\n */\n private transferHeaders(meta: MethodMeta): void {\n if (!meta.requestHeaders) {\n // No headers in test mode (createApiClient creates context but not headers)\n this.ensureRequestId();\n return;\n }\n\n // Transfer each header to RequestContext using RequestContext.putHeader()\n for (const header of this.transferredHeaders) {\n // Get values from requestHeaders (case-insensitive lookup)\n const values = meta.requestHeaders.get(header.headerName.toLowerCase());\n if (values && values.length > 0) {\n // Use RequestContext.putHeader() which calls header.getHeaderName()\n RequestContext.putHeader(header, values[0]);\n }\n }\n\n // Clear request headers from MethodMeta - MUST FORCE USAGE of RequestContext!!!\n meta.requestHeaders = undefined;\n\n // Generate REQUEST_ID if not present (first service in chain)\n this.ensureRequestId();\n }\n\n /**\n * Ensure REQUEST_ID is set in RequestContext.\n * Generates one if not present.\n */\n private ensureRequestId(): void {\n if (!RequestContext.hasHeader(WebpiecesCoreHeaders.REQUEST_ID)) {\n const requestId = this.generateRequestId();\n RequestContext.putHeader(WebpiecesCoreHeaders.REQUEST_ID, requestId);\n }\n }\n\n /**\n * Generate a unique request ID.\n * Format: req-{timestamp}-{random}\n */\n private generateRequestId(): string {\n return `svrGenReqId-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;\n }\n}\n\n"]}
@@ -1,6 +1,6 @@
1
1
  import { MethodMeta } from '@webpieces/http-routing';
2
2
  import { Filter, WpResponse, Service } from '@webpieces/http-filters';
3
- import { HeaderMethods, HeaderRegistry } from '@webpieces/http-api';
3
+ import { HeaderMethods, HeaderRegistry } from '@webpieces/core-util';
4
4
  export declare class LogApiFilter extends Filter<MethodMeta, WpResponse<unknown>> {
5
5
  private headerMethods;
6
6
  private logApiCall;
@@ -5,8 +5,8 @@ const tslib_1 = require("tslib");
5
5
  const inversify_1 = require("inversify");
6
6
  const http_routing_1 = require("@webpieces/http-routing");
7
7
  const http_filters_1 = require("@webpieces/http-filters");
8
- const wp_logging_1 = require("@webpieces/wp-logging");
9
- const http_api_1 = require("@webpieces/http-api");
8
+ const core_util_1 = require("@webpieces/core-util");
9
+ const core_util_2 = require("@webpieces/core-util");
10
10
  /**
11
11
  * LogApiFilter - Structured API logging for all requests/responses.
12
12
  * Priority: 1800 (after ContextFilter at 2000, before custom filters)
@@ -23,7 +23,7 @@ const http_api_1 = require("@webpieces/http-api");
23
23
  * User errors (HttpBadRequestError, etc.) are logged as OTHER, not FAIL,
24
24
  * because they are expected behavior from the server's perspective.
25
25
  */
26
- const log = wp_logging_1.LogManager.getLogger('LogApiFilter');
26
+ const log = core_util_1.LogManager.getLogger('LogApiFilter');
27
27
  let LogApiFilter = class LogApiFilter extends http_filters_1.Filter {
28
28
  headerMethods;
29
29
  logApiCall;
@@ -35,7 +35,7 @@ let LogApiFilter = class LogApiFilter extends http_filters_1.Filter {
35
35
  // duplicate-validated at startup). Log map keys use loggerMdcKey when set.
36
36
  this.allHeaders = registry.getHeaders();
37
37
  log.info(`[LogApiFilter] Using ${this.allHeaders.length} platform headers from HeaderRegistry`);
38
- this.logApiCall = new http_api_1.LogApiCall();
38
+ this.logApiCall = new core_util_2.LogApiCall();
39
39
  }
40
40
  async filter(meta, nextFilter) {
41
41
  // Build header map from RequestContext (headers are already transferred by ContextFilter)
@@ -54,9 +54,9 @@ exports.LogApiFilter = LogApiFilter;
54
54
  exports.LogApiFilter = LogApiFilter = tslib_1.__decorate([
55
55
  (0, http_routing_1.provideSingleton)(),
56
56
  (0, inversify_1.injectable)(),
57
- tslib_1.__param(0, (0, inversify_1.inject)(http_api_1.HeaderRegistry)),
58
- tslib_1.__param(1, (0, inversify_1.inject)(http_api_1.HeaderMethods)),
59
- tslib_1.__metadata("design:paramtypes", [http_api_1.HeaderRegistry,
60
- http_api_1.HeaderMethods])
57
+ tslib_1.__param(0, (0, inversify_1.inject)(core_util_2.HeaderRegistry)),
58
+ tslib_1.__param(1, (0, inversify_1.inject)(core_util_2.HeaderMethods)),
59
+ tslib_1.__metadata("design:paramtypes", [core_util_2.HeaderRegistry,
60
+ core_util_2.HeaderMethods])
61
61
  ], LogApiFilter);
62
62
  //# sourceMappingURL=LogApiFilter.js.map