@webpieces/http-server 0.2.10 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -4
- package/src/WebpiecesServer.d.ts +23 -0
- package/src/WebpiecesServer.js +124 -57
- package/src/WebpiecesServer.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.12",
|
|
4
4
|
"description": "WebPieces server with filter chain and dependency injection",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@webpieces/core-meta": "0.2.
|
|
26
|
-
"@webpieces/http-routing": "0.2.
|
|
27
|
-
"@webpieces/http-filters": "0.2.
|
|
25
|
+
"@webpieces/core-meta": "0.2.12",
|
|
26
|
+
"@webpieces/http-routing": "0.2.12",
|
|
27
|
+
"@webpieces/http-filters": "0.2.12"
|
|
28
28
|
}
|
|
29
29
|
}
|
package/src/WebpiecesServer.d.ts
CHANGED
|
@@ -94,10 +94,33 @@ export declare class WebpiecesServer {
|
|
|
94
94
|
* Start the HTTP server with Express.
|
|
95
95
|
*/
|
|
96
96
|
start(port?: number): void;
|
|
97
|
+
/**
|
|
98
|
+
* Handle an incoming HTTP request through the filter chain and controller.
|
|
99
|
+
* This is the main request processing logic.
|
|
100
|
+
*
|
|
101
|
+
* NO try-catch here - errors are handled by:
|
|
102
|
+
* 1. JsonFilter - catches and returns JSON error responses
|
|
103
|
+
* 2. GlobalErrorHandler middleware - catches any unhandled errors and returns HTML 500
|
|
104
|
+
*
|
|
105
|
+
* @param req - Express request
|
|
106
|
+
* @param res - Express response
|
|
107
|
+
* @param route - The registered route to execute
|
|
108
|
+
* @param matchingFilters - Filters that apply to this route
|
|
109
|
+
* @param key - Route key (method:path)
|
|
110
|
+
*/
|
|
111
|
+
private handleRequest;
|
|
97
112
|
/**
|
|
98
113
|
* Register all routes with Express.
|
|
99
114
|
*/
|
|
100
115
|
private registerExpressRoutes;
|
|
116
|
+
/**
|
|
117
|
+
* Setup a single route with Express.
|
|
118
|
+
* Finds matching filters, creates handler, and registers with Express.
|
|
119
|
+
*
|
|
120
|
+
* @param key - Route key (method:path)
|
|
121
|
+
* @param route - The registered route definition
|
|
122
|
+
*/
|
|
123
|
+
private setupRoute;
|
|
101
124
|
/**
|
|
102
125
|
* Stop the HTTP server.
|
|
103
126
|
*/
|
package/src/WebpiecesServer.js
CHANGED
|
@@ -4,11 +4,13 @@ exports.WebpiecesServer = void 0;
|
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const express_1 = tslib_1.__importDefault(require("express"));
|
|
6
6
|
const inversify_1 = require("inversify");
|
|
7
|
+
const binding_decorators_1 = require("@inversifyjs/binding-decorators");
|
|
7
8
|
const core_meta_1 = require("@webpieces/core-meta");
|
|
8
9
|
const http_filters_1 = require("@webpieces/http-filters");
|
|
9
10
|
const http_routing_1 = require("@webpieces/http-routing");
|
|
10
11
|
const RouteBuilderImpl_1 = require("./RouteBuilderImpl");
|
|
11
12
|
const FilterMatcher_1 = require("./FilterMatcher");
|
|
13
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
12
14
|
/**
|
|
13
15
|
* WebpiecesServer - Main bootstrap class for WebPieces applications.
|
|
14
16
|
*
|
|
@@ -91,6 +93,8 @@ class WebpiecesServer {
|
|
|
91
93
|
*/
|
|
92
94
|
loadDIModules() {
|
|
93
95
|
const modules = this.meta.getDIModules();
|
|
96
|
+
// Load buildProviderModule to auto-scan for @provideSingleton decorators
|
|
97
|
+
this.appContainer.load((0, binding_decorators_1.buildProviderModule)());
|
|
94
98
|
// Load all modules into application container
|
|
95
99
|
// (webpiecesContainer is currently empty, reserved for future framework bindings)
|
|
96
100
|
for (const module of modules) {
|
|
@@ -124,10 +128,48 @@ class WebpiecesServer {
|
|
|
124
128
|
this.initialize();
|
|
125
129
|
// Create Express app
|
|
126
130
|
this.app = (0, express_1.default)();
|
|
127
|
-
//
|
|
131
|
+
// Layer 1: Global Error Handler (OUTERMOST - runs FIRST)
|
|
132
|
+
// Wraps all subsequent middleware with try-catch
|
|
133
|
+
// IMPORTANT: Use async/await to catch BOTH synchronous throws AND async rejections
|
|
134
|
+
this.app.use(async (req, res, next) => {
|
|
135
|
+
console.log('🔴 [Layer 1: GlobalErrorHandler] Request START:', req.method, req.path);
|
|
136
|
+
try {
|
|
137
|
+
// await next() catches BOTH:
|
|
138
|
+
// 1. Synchronous throws from next() itself
|
|
139
|
+
// 2. Rejected promises from downstream async middleware
|
|
140
|
+
await next();
|
|
141
|
+
console.log('🔴 [Layer 1: GlobalErrorHandler] Request END (success):', req.method, req.path);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
const error = (0, core_util_1.toError)(err);
|
|
145
|
+
console.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);
|
|
146
|
+
if (!res.headersSent) {
|
|
147
|
+
// Return HTML error page (not JSON - JsonFilter handles JSON errors)
|
|
148
|
+
res.status(500).send(`
|
|
149
|
+
<!DOCTYPE html>
|
|
150
|
+
<html>
|
|
151
|
+
<head><title>Server Error</title></head>
|
|
152
|
+
<body>
|
|
153
|
+
<h1>You hit a server error</h1>
|
|
154
|
+
<p>An unexpected error occurred while processing your request.</p>
|
|
155
|
+
<pre>${error.message}</pre>
|
|
156
|
+
</body>
|
|
157
|
+
</html>
|
|
158
|
+
`);
|
|
159
|
+
}
|
|
160
|
+
console.log('🔴 [Layer 1: GlobalErrorHandler] Request END (error):', req.method, req.path);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
// Layer 2: Log Next Layer (runs SECOND)
|
|
164
|
+
this.app.use((req, res, next) => {
|
|
165
|
+
console.log('🟡 [Layer 2: LogNextLayer] Before next() -', req.method, req.path);
|
|
166
|
+
next();
|
|
167
|
+
console.log('🟡 [Layer 2: LogNextLayer] After next() -', req.method, req.path);
|
|
168
|
+
});
|
|
169
|
+
// Layer 3+: Standard Express middleware
|
|
128
170
|
this.app.use(express_1.default.json());
|
|
129
171
|
this.app.use(express_1.default.urlencoded({ extended: true }));
|
|
130
|
-
// Register routes
|
|
172
|
+
// Register routes (these become the innermost handlers)
|
|
131
173
|
this.registerExpressRoutes();
|
|
132
174
|
// Start listening
|
|
133
175
|
this.server = this.app.listen(this.port, () => {
|
|
@@ -136,6 +178,44 @@ class WebpiecesServer {
|
|
|
136
178
|
console.log(`[WebpiecesServer] Registered ${this.filterRegistry.length} filters`);
|
|
137
179
|
});
|
|
138
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Handle an incoming HTTP request through the filter chain and controller.
|
|
183
|
+
* This is the main request processing logic.
|
|
184
|
+
*
|
|
185
|
+
* NO try-catch here - errors are handled by:
|
|
186
|
+
* 1. JsonFilter - catches and returns JSON error responses
|
|
187
|
+
* 2. GlobalErrorHandler middleware - catches any unhandled errors and returns HTML 500
|
|
188
|
+
*
|
|
189
|
+
* @param req - Express request
|
|
190
|
+
* @param res - Express response
|
|
191
|
+
* @param route - The registered route to execute
|
|
192
|
+
* @param matchingFilters - Filters that apply to this route
|
|
193
|
+
* @param key - Route key (method:path)
|
|
194
|
+
*/
|
|
195
|
+
async handleRequest(req, res, route, matchingFilters, key) {
|
|
196
|
+
// Create method metadata
|
|
197
|
+
const meta = new http_filters_1.MethodMeta(route.method, route.path, key, [req.body], new core_meta_1.RouteRequest(req.body, req.query, req.params, req.headers), undefined, new Map());
|
|
198
|
+
// Create filter chain with matched filters
|
|
199
|
+
const filterChain = new http_filters_1.FilterChain(matchingFilters);
|
|
200
|
+
// Execute the filter chain
|
|
201
|
+
// Errors thrown here are caught by JsonFilter or bubble to GlobalErrorHandler
|
|
202
|
+
const action = await filterChain.execute(meta, async () => {
|
|
203
|
+
// Create typed route context
|
|
204
|
+
// Use appContainer which has access to both app and framework bindings
|
|
205
|
+
const routeContext = new core_meta_1.RouteContext(this.appContainer, [req.body], meta.request);
|
|
206
|
+
// Final handler: invoke the controller method via route handler
|
|
207
|
+
const result = await route.handler.execute(routeContext);
|
|
208
|
+
// Wrap result in a JSON action
|
|
209
|
+
return (0, http_filters_1.jsonAction)(result);
|
|
210
|
+
});
|
|
211
|
+
// Send response
|
|
212
|
+
if (action.type === 'json') {
|
|
213
|
+
res.json(action.data);
|
|
214
|
+
}
|
|
215
|
+
else if (action.type === 'error') {
|
|
216
|
+
res.status(500).json({ error: action.data });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
139
219
|
/**
|
|
140
220
|
* Register all routes with Express.
|
|
141
221
|
*/
|
|
@@ -144,61 +224,48 @@ class WebpiecesServer {
|
|
|
144
224
|
throw new Error('Express app not initialized');
|
|
145
225
|
}
|
|
146
226
|
for (const [key, route] of this.routes.entries()) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
break;
|
|
190
|
-
case 'put':
|
|
191
|
-
this.app.put(path, handler);
|
|
192
|
-
break;
|
|
193
|
-
case 'delete':
|
|
194
|
-
this.app.delete(path, handler);
|
|
195
|
-
break;
|
|
196
|
-
case 'patch':
|
|
197
|
-
this.app.patch(path, handler);
|
|
198
|
-
break;
|
|
199
|
-
default:
|
|
200
|
-
console.warn(`[WebpiecesServer] Unknown HTTP method: ${method}`);
|
|
201
|
-
}
|
|
227
|
+
this.setupRoute(key, route);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Setup a single route with Express.
|
|
232
|
+
* Finds matching filters, creates handler, and registers with Express.
|
|
233
|
+
*
|
|
234
|
+
* @param key - Route key (method:path)
|
|
235
|
+
* @param route - The registered route definition
|
|
236
|
+
*/
|
|
237
|
+
setupRoute(key, route) {
|
|
238
|
+
if (!this.app) {
|
|
239
|
+
throw new Error('Express app not initialized');
|
|
240
|
+
}
|
|
241
|
+
const method = route.method.toLowerCase();
|
|
242
|
+
const path = route.path;
|
|
243
|
+
console.log(`[WebpiecesServer] Registering route: ${method.toUpperCase()} ${path}`);
|
|
244
|
+
// Find matching filters for this route
|
|
245
|
+
const matchingFilters = FilterMatcher_1.FilterMatcher.findMatchingFilters(route.controllerFilepath, this.filterRegistry);
|
|
246
|
+
// Create Express route handler - delegates to handleRequest
|
|
247
|
+
const handler = async (req, res, next) => {
|
|
248
|
+
await this.handleRequest(req, res, route, matchingFilters, key);
|
|
249
|
+
};
|
|
250
|
+
// Register with Express
|
|
251
|
+
switch (method) {
|
|
252
|
+
case 'get':
|
|
253
|
+
this.app.get(path, handler);
|
|
254
|
+
break;
|
|
255
|
+
case 'post':
|
|
256
|
+
this.app.post(path, handler);
|
|
257
|
+
break;
|
|
258
|
+
case 'put':
|
|
259
|
+
this.app.put(path, handler);
|
|
260
|
+
break;
|
|
261
|
+
case 'delete':
|
|
262
|
+
this.app.delete(path, handler);
|
|
263
|
+
break;
|
|
264
|
+
case 'patch':
|
|
265
|
+
this.app.patch(path, handler);
|
|
266
|
+
break;
|
|
267
|
+
default:
|
|
268
|
+
console.warn(`[WebpiecesServer] Unknown HTTP method: ${method}`);
|
|
202
269
|
}
|
|
203
270
|
}
|
|
204
271
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebpiecesServer.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesServer.ts"],"names":[],"mappings":";;;;AAAA,8DAA4E;AAC5E,yCAAsC;AACtC,oDAAgG;AAChG,0DAAsF;AACtF,0DAAmE;AACnE,yDAAuE;AACvE,mDAAgD;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAa,eAAe;IAqC1B,YAAY,IAAgB;QApB5B;;;;;;WAMG;QACK,WAAM,GAA0C,IAAI,GAAG,EAAE,CAAC;QAElE;;;WAGG;QACK,mBAAc,GAA4D,EAAE,CAAC;QAE7E,gBAAW,GAAG,KAAK,CAAC;QAGpB,SAAI,GAAW,IAAI,CAAC;QAG1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,0DAA0D;QAC1D,IAAI,CAAC,kBAAkB,GAAG,IAAI,qBAAS,EAAE,CAAC;QAE1C,iEAAiE;QACjE,yDAAyD;QACzD,IAAI,CAAC,YAAY,GAAG,IAAI,qBAAS,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACzE,CAAC;IAED;;;OAGG;IACH,UAAU;QACR,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QAED,qBAAqB;QACrB,IAAI,CAAC,aAAa,EAAE,CAAC;QAErB,iCAAiC;QACjC,IAAI,CAAC,cAAc,EAAE,CAAC;QAEtB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAED;;;;;;;;;OASG;IACK,aAAa;QACnB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;QAEzC,8CAA8C;QAC9C,kFAAkF;QAClF,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,YAAY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YAC5B,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/C,CAAC;QAED,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,YAAY;QACV,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,qBAAqB;QACnB,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;CAGF;AAtVD,0CAsVC","sourcesContent":["import express, { Express, Request, Response, NextFunction } from 'express';\nimport { Container } from 'inversify';\nimport { WebAppMeta, RouteContext, RouteRequest, FilterDefinition } from '@webpieces/core-meta';\nimport { FilterChain, Filter, MethodMeta, jsonAction } from '@webpieces/http-filters';\nimport { getRoutes, RouteMetadata } from '@webpieces/http-routing';\nimport { RouteBuilderImpl, RegisteredRoute } from './RouteBuilderImpl';\nimport { FilterMatcher } from './FilterMatcher';\n\n/**\n * WebpiecesServer - Main bootstrap class for WebPieces applications.\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 * Usage for testing (no HTTP):\n * ```typescript\n * const server = new WebpiecesServer(new ProdServerMeta());\n * server.initialize();\n * const saveApi = server.createApiClient<SaveApi>(SaveApiPrototype);\n * const response = await saveApi.save(request);\n * ```\n *\n * Usage for production (HTTP server):\n * ```typescript\n * const server = new WebpiecesServer(new ProdServerMeta());\n * server.start(); // Starts Express server\n * ```\n */\nexport class WebpiecesServer {\n private meta: WebAppMeta;\n\n /**\n * WebPieces container: Core WebPieces framework bindings.\n * This includes framework-level services like filters, routing infrastructure,\n * logging, metrics, etc. Similar to Java WebPieces platform container.\n */\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 /**\n * Routes registry: Maps \"METHOD:path\" -> RegisteredRoute\n * Example: \"POST:/search/item\" -> { method: \"POST\", path: \"/search/item\", handler: ... }\n *\n * We use unknown instead of any for type safety - each route has its own return type,\n * but we can't have different generic types in the same Map.\n */\n private routes: Map<string, RegisteredRoute<unknown>> = new Map();\n\n /**\n * Registered filters with their definitions.\n * Used by FilterMatcher to match filters to routes based on filepath patterns.\n */\n private filterRegistry: Array<{ filter: Filter; definition: FilterDefinition }> = [];\n\n private initialized = false;\n private app?: Express;\n private server?: any;\n private port: number = 8080;\n\n constructor(meta: WebAppMeta) {\n this.meta = meta;\n\n // Create WebPieces container for framework-level bindings\n this.webpiecesContainer = new Container();\n\n // Create application container as a child of WebPieces container\n // This allows app container to access framework bindings\n this.appContainer = new Container({ parent: this.webpiecesContainer });\n }\n\n /**\n * Initialize the server (DI container, routes, filters).\n * This is called automatically by start() or can be called manually for testing.\n */\n initialize(): void {\n if (this.initialized) {\n return;\n }\n\n // 1. Load DI modules\n this.loadDIModules();\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 private loadDIModules(): void {\n const modules = this.meta.getDIModules();\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 this.appContainer.load(module);\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 // Create explicit RouteBuilder implementation\n // Filters are resolved from appContainer (which has access to platformContainer too)\n const routeBuilder = new RouteBuilderImpl(\n this.routes,\n this.filterRegistry,\n this.appContainer\n );\n\n // Configure routes using the explicit RouteBuilder\n for (const routeConfig of routeConfigs) {\n routeConfig.configure(routeBuilder);\n }\n }\n\n /**\n * Start the HTTP server with Express.\n */\n start(port: number = 8080): void {\n this.port = port;\n this.initialize();\n\n // Create Express app\n this.app = express();\n\n // Middleware\n this.app.use(express.json());\n this.app.use(express.urlencoded({ extended: true }));\n\n // Register routes\n this.registerExpressRoutes();\n\n // Start listening\n this.server = this.app.listen(this.port, () => {\n console.log(`[WebpiecesServer] Server listening on http://localhost:${this.port}`);\n console.log(`[WebpiecesServer] Registered ${this.routes.size} routes`);\n console.log(`[WebpiecesServer] Registered ${this.filterRegistry.length} filters`);\n });\n }\n\n /**\n * Register all routes with Express.\n */\n private registerExpressRoutes(): void {\n if (!this.app) {\n throw new Error('Express app not initialized');\n }\n\n for (const [key, route] of this.routes.entries()) {\n const method = route.method.toLowerCase();\n const path = route.path;\n\n console.log(`[WebpiecesServer] Registering route: ${method.toUpperCase()} ${path}`);\n\n // Find matching filters for this route\n const matchingFilters = FilterMatcher.findMatchingFilters(\n route.controllerFilepath,\n this.filterRegistry\n );\n\n // Create Express route handler\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n try {\n // Create method metadata\n const meta = new MethodMeta(\n route.method,\n route.path,\n key,\n [req.body],\n new RouteRequest(req.body, req.query, req.params, req.headers),\n undefined,\n new Map()\n );\n\n // Create filter chain with matched filters\n const filterChain = new FilterChain(matchingFilters);\n\n // Execute the filter chain\n const action = await filterChain.execute(meta, async () => {\n // Create typed route context\n // Use appContainer which has access to both app and framework bindings\n const routeContext = new RouteContext(\n this.appContainer,\n [req.body],\n meta.request\n );\n\n // Final handler: invoke the controller method via route handler\n const result = await route.handler.execute(routeContext);\n\n // Wrap result in a JSON action\n return jsonAction(result);\n });\n\n // Send response\n if (action.type === 'json') {\n res.json(action.data);\n } else if (action.type === 'error') {\n res.status(500).json({ error: action.data });\n }\n } catch (error: any) {\n console.error('[WebpiecesServer] Error handling request:', error);\n res.status(500).json({ error: error.message });\n }\n };\n\n // Register with Express\n switch (method) {\n case 'get':\n this.app.get(path, handler);\n break;\n case 'post':\n this.app.post(path, handler);\n break;\n case 'put':\n this.app.put(path, handler);\n break;\n case 'delete':\n this.app.delete(path, handler);\n break;\n case 'patch':\n this.app.patch(path, handler);\n break;\n default:\n console.warn(`[WebpiecesServer] Unknown HTTP method: ${method}`);\n }\n }\n }\n\n /**\n * Stop the HTTP server.\n */\n stop(): void {\n if (this.server) {\n this.server.close(() => {\n console.log('[WebpiecesServer] Server stopped');\n });\n }\n }\n\n /**\n * Create an API client proxy for testing (no HTTP).\n *\n * This creates a proxy object that implements the API interface\n * and routes method calls through the full filter chain to the controller.\n *\n * @param apiMetaClass - The API interface class with decorators\n * @returns Proxy object implementing the API interface\n */\n createApiClient<T>(apiMetaClass: any): T {\n this.initialize();\n\n // Get routes from the API metadata\n const routes = getRoutes(apiMetaClass);\n\n // Create a proxy object\n const proxy: any = {};\n\n for (const route of routes) {\n const methodName = route.methodName;\n\n // Create a function that routes through the filter chain\n proxy[methodName] = async (...args: any[]) => {\n return this.invokeRoute(route, args);\n };\n }\n\n return proxy as T;\n }\n\n /**\n * Invoke a route through the filter chain.\n */\n private async invokeRoute(route: RouteMetadata, args: any[]): Promise<any> {\n // Find the registered route\n const key = `${route.httpMethod}:${route.path}`;\n const registeredRoute = this.routes.get(key);\n\n if (!registeredRoute) {\n throw new Error(`Route not found: ${key}`);\n }\n\n // Find matching filters for this route\n const matchingFilters = FilterMatcher.findMatchingFilters(\n registeredRoute.controllerFilepath,\n this.filterRegistry\n );\n\n // Create method metadata\n const meta = new MethodMeta(\n route.httpMethod,\n route.path,\n route.methodName,\n [...args],\n new RouteRequest(args[0]), // Assume first arg is the request body\n undefined,\n new Map()\n );\n\n // Create filter chain with matched filters\n const filterChain = new FilterChain(matchingFilters);\n\n // Execute the filter chain\n const action = await filterChain.execute(meta, async () => {\n // Create typed route context\n // Use appContainer which has access to both app and framework bindings\n const routeContext = new RouteContext(\n this.appContainer,\n meta.params,\n meta.request\n );\n\n // Final handler: invoke the controller method via route handler\n const result = await registeredRoute.handler.execute(routeContext);\n\n // Wrap result in a JSON action\n return jsonAction(result);\n });\n\n // Return the data from the action\n if (action.type === 'error') {\n throw new Error(JSON.stringify(action.data));\n }\n\n return action.data;\n }\n\n /**\n * Get the application DI container (for testing).\n * Returns appContainer which has access to both app and framework bindings.\n */\n getContainer(): Container {\n this.initialize();\n return this.appContainer;\n }\n\n /**\n * Get the WebPieces framework container (for advanced testing/debugging).\n */\n getWebpiecesContainer(): Container {\n this.initialize();\n return this.webpiecesContainer;\n }\n\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"WebpiecesServer.js","sourceRoot":"","sources":["../../../../../packages/http/http-server/src/WebpiecesServer.ts"],"names":[],"mappings":";;;;AAAA,8DAA4E;AAC5E,yCAAsC;AACtC,wEAAsE;AACtE,oDAAgG;AAChG,0DAAsF;AACtF,0DAAmE;AACnE,yDAAuE;AACvE,mDAAgD;AAChD,oDAA+C;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAa,eAAe;IAqC1B,YAAY,IAAgB;QApB5B;;;;;;WAMG;QACK,WAAM,GAA0C,IAAI,GAAG,EAAE,CAAC;QAElE;;;WAGG;QACK,mBAAc,GAA4D,EAAE,CAAC;QAE7E,gBAAW,GAAG,KAAK,CAAC;QAGpB,SAAI,GAAW,IAAI,CAAC;QAG1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAEjB,0DAA0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CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,qBAAqB;QACnB,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;CAGF;AApaD,0CAoaC","sourcesContent":["import express, { Express, Request, Response, NextFunction } from 'express';\nimport { Container } from 'inversify';\nimport { buildProviderModule } from '@inversifyjs/binding-decorators';\nimport { WebAppMeta, RouteContext, RouteRequest, FilterDefinition } from '@webpieces/core-meta';\nimport { FilterChain, Filter, MethodMeta, jsonAction } from '@webpieces/http-filters';\nimport { getRoutes, RouteMetadata } from '@webpieces/http-routing';\nimport { RouteBuilderImpl, RegisteredRoute } from './RouteBuilderImpl';\nimport { FilterMatcher } from './FilterMatcher';\nimport { toError } from '@webpieces/core-util';\n\n/**\n * WebpiecesServer - Main bootstrap class for WebPieces applications.\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 * Usage for testing (no HTTP):\n * ```typescript\n * const server = new WebpiecesServer(new ProdServerMeta());\n * server.initialize();\n * const saveApi = server.createApiClient<SaveApi>(SaveApiPrototype);\n * const response = await saveApi.save(request);\n * ```\n *\n * Usage for production (HTTP server):\n * ```typescript\n * const server = new WebpiecesServer(new ProdServerMeta());\n * server.start(); // Starts Express server\n * ```\n */\nexport class WebpiecesServer {\n private meta: WebAppMeta;\n\n /**\n * WebPieces container: Core WebPieces framework bindings.\n * This includes framework-level services like filters, routing infrastructure,\n * logging, metrics, etc. Similar to Java WebPieces platform container.\n */\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 /**\n * Routes registry: Maps \"METHOD:path\" -> RegisteredRoute\n * Example: \"POST:/search/item\" -> { method: \"POST\", path: \"/search/item\", handler: ... }\n *\n * We use unknown instead of any for type safety - each route has its own return type,\n * but we can't have different generic types in the same Map.\n */\n private routes: Map<string, RegisteredRoute<unknown>> = new Map();\n\n /**\n * Registered filters with their definitions.\n * Used by FilterMatcher to match filters to routes based on filepath patterns.\n */\n private filterRegistry: Array<{ filter: Filter; definition: FilterDefinition }> = [];\n\n private initialized = false;\n private app?: Express;\n private server?: any;\n private port: number = 8080;\n\n constructor(meta: WebAppMeta) {\n this.meta = meta;\n\n // Create WebPieces container for framework-level bindings\n this.webpiecesContainer = new Container();\n\n // Create application container as a child of WebPieces container\n // This allows app container to access framework bindings\n this.appContainer = new Container({ parent: this.webpiecesContainer });\n }\n\n /**\n * Initialize the server (DI container, routes, filters).\n * This is called automatically by start() or can be called manually for testing.\n */\n initialize(): void {\n if (this.initialized) {\n return;\n }\n\n // 1. Load DI modules\n this.loadDIModules();\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 private loadDIModules(): void {\n const modules = this.meta.getDIModules();\n\n // Load buildProviderModule to auto-scan for @provideSingleton decorators\n 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 this.appContainer.load(module);\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 // Create explicit RouteBuilder implementation\n // Filters are resolved from appContainer (which has access to platformContainer too)\n const routeBuilder = new RouteBuilderImpl(\n this.routes,\n this.filterRegistry,\n this.appContainer\n );\n\n // Configure routes using the explicit RouteBuilder\n for (const routeConfig of routeConfigs) {\n routeConfig.configure(routeBuilder);\n }\n }\n\n /**\n * Start the HTTP server with Express.\n */\n start(port: number = 8080): void {\n this.port = port;\n this.initialize();\n\n // Create Express app\n this.app = express();\n\n // Layer 1: Global Error Handler (OUTERMOST - runs FIRST)\n // Wraps all subsequent middleware with try-catch\n // IMPORTANT: Use async/await to catch BOTH synchronous throws AND async rejections\n this.app.use(async (req: Request, res: Response, next: NextFunction) => {\n console.log('🔴 [Layer 1: GlobalErrorHandler] Request START:', req.method, req.path);\n\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 console.log('🔴 [Layer 1: GlobalErrorHandler] Request END (success):', req.method, req.path);\n } catch (err: any) {\n const error = toError(err);\n console.error('🔴 [Layer 1: GlobalErrorHandler] Caught unhandled error:', error);\n if (!res.headersSent) {\n // Return HTML error page (not JSON - JsonFilter 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 console.log('🔴 [Layer 1: GlobalErrorHandler] Request END (error):', req.method, req.path);\n }\n });\n\n // Layer 2: Log Next Layer (runs SECOND)\n this.app.use((req: Request, res: Response, next: NextFunction) => {\n console.log('🟡 [Layer 2: LogNextLayer] Before next() -', req.method, req.path);\n next();\n console.log('🟡 [Layer 2: LogNextLayer] After next() -', req.method, req.path);\n });\n\n // Layer 3+: Standard Express middleware\n this.app.use(express.json());\n this.app.use(express.urlencoded({ extended: true }));\n\n // Register routes (these become the innermost handlers)\n this.registerExpressRoutes();\n\n // Start listening\n this.server = this.app.listen(this.port, () => {\n console.log(`[WebpiecesServer] Server listening on http://localhost:${this.port}`);\n console.log(`[WebpiecesServer] Registered ${this.routes.size} routes`);\n console.log(`[WebpiecesServer] Registered ${this.filterRegistry.length} filters`);\n });\n }\n\n /**\n * Handle an incoming HTTP request through the filter chain and controller.\n * This is the main request processing logic.\n *\n * NO try-catch here - errors are handled by:\n * 1. JsonFilter - catches and returns JSON error responses\n * 2. GlobalErrorHandler middleware - catches any unhandled errors and returns HTML 500\n *\n * @param req - Express request\n * @param res - Express response\n * @param route - The registered route to execute\n * @param matchingFilters - Filters that apply to this route\n * @param key - Route key (method:path)\n */\n private async handleRequest(\n req: Request,\n res: Response,\n route: RegisteredRoute<unknown>,\n matchingFilters: Filter[],\n key: string\n ): Promise<void> {\n // Create method metadata\n const meta = new MethodMeta(\n route.method,\n route.path,\n key,\n [req.body],\n new RouteRequest(req.body, req.query, req.params, req.headers),\n undefined,\n new Map()\n );\n\n // Create filter chain with matched filters\n const filterChain = new FilterChain(matchingFilters);\n\n // Execute the filter chain\n // Errors thrown here are caught by JsonFilter or bubble to GlobalErrorHandler\n const action = await filterChain.execute(meta, async () => {\n // Create typed route context\n // Use appContainer which has access to both app and framework bindings\n const routeContext = new RouteContext(\n this.appContainer,\n [req.body],\n meta.request\n );\n\n // Final handler: invoke the controller method via route handler\n const result = await route.handler.execute(routeContext);\n\n // Wrap result in a JSON action\n return jsonAction(result);\n });\n\n // Send response\n if (action.type === 'json') {\n res.json(action.data);\n } else if (action.type === 'error') {\n res.status(500).json({ error: action.data });\n }\n }\n\n /**\n * Register all routes with Express.\n */\n private registerExpressRoutes(): void {\n if (!this.app) {\n throw new Error('Express app not initialized');\n }\n\n for (const [key, route] of this.routes.entries()) {\n this.setupRoute(key, route);\n }\n }\n\n /**\n * Setup a single route with Express.\n * Finds matching filters, creates handler, and registers with Express.\n *\n * @param key - Route key (method:path)\n * @param route - The registered route definition\n */\n private setupRoute(key: string, route: RegisteredRoute<unknown>): void {\n if (!this.app) {\n throw new Error('Express app not initialized');\n }\n\n const method = route.method.toLowerCase();\n const path = route.path;\n\n console.log(`[WebpiecesServer] Registering route: ${method.toUpperCase()} ${path}`);\n\n // Find matching filters for this route\n const matchingFilters = FilterMatcher.findMatchingFilters(\n route.controllerFilepath,\n this.filterRegistry\n );\n\n // Create Express route handler - delegates to handleRequest\n const handler = async (req: Request, res: Response, next: NextFunction) => {\n await this.handleRequest(req, res, route, matchingFilters, key);\n };\n\n // Register with Express\n switch (method) {\n case 'get':\n this.app.get(path, handler);\n break;\n case 'post':\n this.app.post(path, handler);\n break;\n case 'put':\n this.app.put(path, handler);\n break;\n case 'delete':\n this.app.delete(path, handler);\n break;\n case 'patch':\n this.app.patch(path, handler);\n break;\n default:\n console.warn(`[WebpiecesServer] Unknown HTTP method: ${method}`);\n }\n }\n\n /**\n * Stop the HTTP server.\n */\n stop(): void {\n if (this.server) {\n this.server.close(() => {\n console.log('[WebpiecesServer] Server stopped');\n });\n }\n }\n\n /**\n * Create an API client proxy for testing (no HTTP).\n *\n * This creates a proxy object that implements the API interface\n * and routes method calls through the full filter chain to the controller.\n *\n * @param apiMetaClass - The API interface class with decorators\n * @returns Proxy object implementing the API interface\n */\n createApiClient<T>(apiMetaClass: any): T {\n this.initialize();\n\n // Get routes from the API metadata\n const routes = getRoutes(apiMetaClass);\n\n // Create a proxy object\n const proxy: any = {};\n\n for (const route of routes) {\n const methodName = route.methodName;\n\n // Create a function that routes through the filter chain\n proxy[methodName] = async (...args: any[]) => {\n return this.invokeRoute(route, args);\n };\n }\n\n return proxy as T;\n }\n\n /**\n * Invoke a route through the filter chain.\n */\n private async invokeRoute(route: RouteMetadata, args: any[]): Promise<any> {\n // Find the registered route\n const key = `${route.httpMethod}:${route.path}`;\n const registeredRoute = this.routes.get(key);\n\n if (!registeredRoute) {\n throw new Error(`Route not found: ${key}`);\n }\n\n // Find matching filters for this route\n const matchingFilters = FilterMatcher.findMatchingFilters(\n registeredRoute.controllerFilepath,\n this.filterRegistry\n );\n\n // Create method metadata\n const meta = new MethodMeta(\n route.httpMethod,\n route.path,\n route.methodName,\n [...args],\n new RouteRequest(args[0]), // Assume first arg is the request body\n undefined,\n new Map()\n );\n\n // Create filter chain with matched filters\n const filterChain = new FilterChain(matchingFilters);\n\n // Execute the filter chain\n const action = await filterChain.execute(meta, async () => {\n // Create typed route context\n // Use appContainer which has access to both app and framework bindings\n const routeContext = new RouteContext(\n this.appContainer,\n meta.params,\n meta.request\n );\n\n // Final handler: invoke the controller method via route handler\n const result = await registeredRoute.handler.execute(routeContext);\n\n // Wrap result in a JSON action\n return jsonAction(result);\n });\n\n // Return the data from the action\n if (action.type === 'error') {\n throw new Error(JSON.stringify(action.data));\n }\n\n return action.data;\n }\n\n /**\n * Get the application DI container (for testing).\n * Returns appContainer which has access to both app and framework bindings.\n */\n getContainer(): Container {\n this.initialize();\n return this.appContainer;\n }\n\n /**\n * Get the WebPieces framework container (for advanced testing/debugging).\n */\n getWebpiecesContainer(): Container {\n this.initialize();\n return this.webpiecesContainer;\n }\n\n\n}\n"]}
|