@reldens/server-utils 0.42.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/api-reference.md +333 -0
- package/.claude/package-architecture.md +177 -0
- package/CLAUDE.md +61 -202
- package/README.md +81 -2
- package/lib/app-server-factory/cors-configurer.js +10 -0
- package/lib/app-server-factory/development-mode-detector.js +25 -0
- package/lib/app-server-factory/protocol-enforcer.js +11 -0
- package/lib/app-server-factory/rate-limit-configurer.js +10 -0
- package/lib/app-server-factory/reverse-proxy-configurer.js +26 -1
- package/lib/app-server-factory/security-configurer.js +18 -0
- package/lib/app-server-factory.js +122 -10
- package/lib/cdn-request-handler.js +130 -0
- package/lib/event-dispatcher.js +26 -0
- package/lib/file-handler.js +13 -0
- package/lib/http2-cdn-server.js +156 -46
- package/lib/request-logger.js +42 -0
- package/lib/server-error-handler.js +25 -0
- package/package.json +2 -2
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# API Reference
|
|
2
|
+
|
|
3
|
+
Complete API documentation for @reldens/server-utils classes.
|
|
4
|
+
|
|
5
|
+
## Core Classes
|
|
6
|
+
|
|
7
|
+
### FileHandler
|
|
8
|
+
`lib/file-handler.js`
|
|
9
|
+
|
|
10
|
+
Singleton wrapper for Node.js fs and path modules. Used instead of direct require('fs') or require('path') throughout Reldens.
|
|
11
|
+
|
|
12
|
+
**File Operations:**
|
|
13
|
+
- `exists(filePath)` - Check if file/directory exists
|
|
14
|
+
- `readFile(filePath)` - Read file contents
|
|
15
|
+
- `writeFile(filePath, content)` - Write file
|
|
16
|
+
- `createFolder(folderPath)` - Create directory recursively
|
|
17
|
+
- `remove(fullPath)` - Remove file/folder recursively
|
|
18
|
+
- `copyFile(from, to)` - Copy file
|
|
19
|
+
- `copyFolderSync(from, to)` - Copy folder recursively
|
|
20
|
+
- `moveFile(from, to)` - Move/rename file
|
|
21
|
+
|
|
22
|
+
**Path Operations:**
|
|
23
|
+
- `joinPaths(...paths)` - Join path segments
|
|
24
|
+
- `getFileName(filePath)` - Get file name (basename)
|
|
25
|
+
- `getFolderName(filePath)` - Get directory name (dirname)
|
|
26
|
+
- `getRelativePath(from, to)` - Calculate relative path
|
|
27
|
+
- `normalizePath(filePath)` - Normalize path
|
|
28
|
+
- `isAbsolutePath(filePath)` - Check if path is absolute
|
|
29
|
+
|
|
30
|
+
**File Inspection:**
|
|
31
|
+
- `isFile(filePath)` - Check if path is a file
|
|
32
|
+
- `isFolder(dirPath)` - Check if path is a folder
|
|
33
|
+
- `getFileSize(filePath)` - Get file size in bytes
|
|
34
|
+
- `getFileStats(filePath)` - Get file stats
|
|
35
|
+
- `getFilesInFolder(dirPath, extensions)` - List files with optional filtering
|
|
36
|
+
- `fetchSubFoldersList(folder, options)` - Get subfolder list
|
|
37
|
+
|
|
38
|
+
**JSON Operations:**
|
|
39
|
+
- `fetchFileJson(filePath)` - Read and parse JSON file
|
|
40
|
+
- `isValidJson(filePath)` - Validate JSON file
|
|
41
|
+
|
|
42
|
+
**Security Features:**
|
|
43
|
+
- `generateSecureFilename(originalName)` - Generate secure random filename
|
|
44
|
+
- `validateFileType(filePath, type, allowedTypes, maxSize)` - Validate file
|
|
45
|
+
- `detectFileType(filePath)` - Detect MIME type from magic numbers
|
|
46
|
+
- `quarantineFile(filePath, reason)` - Move suspicious file to quarantine
|
|
47
|
+
- `isValidPath(filePath)` - Validate path for security
|
|
48
|
+
- `sanitizePath(filePath)` - Sanitize path string
|
|
49
|
+
|
|
50
|
+
**Advanced Operations:**
|
|
51
|
+
- `walkDirectory(dirPath, callback)` - Recursively process directory tree
|
|
52
|
+
- `getDirectorySize(dirPath)` - Calculate total directory size
|
|
53
|
+
- `emptyDirectory(dirPath)` - Remove all contents from directory
|
|
54
|
+
- `compareFiles(file1, file2)` - Compare file contents
|
|
55
|
+
- `appendToFile(filePath, content)` - Append to file
|
|
56
|
+
- `prependToFile(filePath, content)` - Prepend to file
|
|
57
|
+
- `replaceInFile(filePath, searchValue, replaceValue)` - Replace in file
|
|
58
|
+
- `createReadStream(filePath, options)` - Create readable stream for file
|
|
59
|
+
- `getFileModificationTime(filePath)` - Get file last modification time
|
|
60
|
+
|
|
61
|
+
**Important:**
|
|
62
|
+
- All methods include built-in error handling, no need for try/catch
|
|
63
|
+
- DO NOT use FileHandler.exists to validate other FileHandler methods
|
|
64
|
+
- DO NOT enclose FileHandler methods in try/catch blocks
|
|
65
|
+
|
|
66
|
+
### AppServerFactory
|
|
67
|
+
`lib/app-server-factory.js`
|
|
68
|
+
|
|
69
|
+
Creates Express app servers with modular security components. Supports HTTP, HTTPS, HTTP/2.
|
|
70
|
+
|
|
71
|
+
**Features:**
|
|
72
|
+
- Virtual host management with SNI support
|
|
73
|
+
- HTTP/2 CDN server integration
|
|
74
|
+
- Reverse proxy with WebSocket support
|
|
75
|
+
- Development mode detection and configuration
|
|
76
|
+
- Request logging middleware
|
|
77
|
+
- Lifecycle event dispatching
|
|
78
|
+
|
|
79
|
+
**Configuration Properties:**
|
|
80
|
+
- `onError` - Custom error handler callback for server errors
|
|
81
|
+
- `onRequestSuccess` - Callback for successful requests
|
|
82
|
+
- `onRequestError` - Callback for failed requests
|
|
83
|
+
- `onEvent` - Callback for lifecycle events
|
|
84
|
+
|
|
85
|
+
**Methods:**
|
|
86
|
+
- `createAppServer(config)` - Create and configure server
|
|
87
|
+
- `addDomain(domainConfig)` - Add virtual host domain
|
|
88
|
+
- `addDevelopmentDomain(domain)` - Add development domain
|
|
89
|
+
- `enableServeHome(app, callback)` - Enable homepage serving
|
|
90
|
+
- `serveStatics(app, staticPath)` - Serve static files
|
|
91
|
+
- `enableCSP(cspOptions)` - Enable Content Security Policy
|
|
92
|
+
- `listen(port)` - Start server listening
|
|
93
|
+
- `close()` - Gracefully close server
|
|
94
|
+
|
|
95
|
+
**Security Configurers:**
|
|
96
|
+
- `DevelopmentModeDetector` - Auto-detect development environment
|
|
97
|
+
- `ProtocolEnforcer` - HTTP/HTTPS protocol enforcement
|
|
98
|
+
- `SecurityConfigurer` - Helmet integration and XSS protection
|
|
99
|
+
- `CorsConfigurer` - CORS with dynamic origin validation
|
|
100
|
+
- `RateLimitConfigurer` - Global and endpoint-specific rate limiting
|
|
101
|
+
- `ReverseProxyConfigurer` - Domain-based reverse proxy
|
|
102
|
+
|
|
103
|
+
### Encryptor
|
|
104
|
+
`lib/encryptor.js`
|
|
105
|
+
|
|
106
|
+
Singleton for cryptographic operations.
|
|
107
|
+
|
|
108
|
+
**Password Hashing:**
|
|
109
|
+
- `encryptPassword(password)` - Hash password with PBKDF2 (100k iterations, SHA-512)
|
|
110
|
+
- `validatePassword(password, storedPassword)` - Validate password against hash
|
|
111
|
+
|
|
112
|
+
**Data Encryption:**
|
|
113
|
+
- `encryptData(data, key)` - Encrypt data with AES-256-GCM
|
|
114
|
+
- `decryptData(encryptedData, key)` - Decrypt AES-256-GCM data
|
|
115
|
+
- `generateSecretKey()` - Generate 256-bit secret key
|
|
116
|
+
|
|
117
|
+
**Token Generation:**
|
|
118
|
+
- `generateSecureToken(length)` - Generate cryptographically secure token
|
|
119
|
+
- `generateTOTP(secret, timeStep)` - Generate time-based OTP
|
|
120
|
+
|
|
121
|
+
**Hashing and Verification:**
|
|
122
|
+
- `hashData(data, algorithm)` - Hash with SHA-256, SHA-512, or MD5
|
|
123
|
+
- `generateHMAC(data, secret, algorithm)` - Generate HMAC signature
|
|
124
|
+
- `verifyHMAC(data, secret, signature, algorithm)` - Verify HMAC signature
|
|
125
|
+
- `constantTimeCompare(a, b)` - Constant-time string comparison
|
|
126
|
+
|
|
127
|
+
### UploaderFactory
|
|
128
|
+
`lib/uploader-factory.js`
|
|
129
|
+
|
|
130
|
+
File upload handling with Multer.
|
|
131
|
+
|
|
132
|
+
**Security Validation:**
|
|
133
|
+
- Filename security validation
|
|
134
|
+
- MIME type validation
|
|
135
|
+
- File extension validation
|
|
136
|
+
- File size validation
|
|
137
|
+
- Content validation using magic numbers
|
|
138
|
+
- Dangerous extension filtering
|
|
139
|
+
|
|
140
|
+
**Features:**
|
|
141
|
+
- Multiple file upload support with field mapping
|
|
142
|
+
- Secure filename generation option
|
|
143
|
+
- Automatic cleanup on validation failure
|
|
144
|
+
- Custom error response handling
|
|
145
|
+
- Per-field destination mapping
|
|
146
|
+
|
|
147
|
+
**Methods:**
|
|
148
|
+
- `createUploader(fields, buckets, allowedFileTypes)` - Create upload middleware
|
|
149
|
+
- `validateFilenameSecurity(filename)` - Validate filename
|
|
150
|
+
- `validateFile(file, allowedType, callback)` - Validate during upload
|
|
151
|
+
- `validateFileContents(file, allowedType)` - Validate after upload
|
|
152
|
+
- `convertToRegex(key)` - Convert MIME type patterns to regex
|
|
153
|
+
|
|
154
|
+
### Http2CdnServer
|
|
155
|
+
`lib/http2-cdn-server.js`
|
|
156
|
+
|
|
157
|
+
HTTP/2 secure server for CDN-like static file serving.
|
|
158
|
+
|
|
159
|
+
**Features:**
|
|
160
|
+
- Optimized for CSS, JavaScript, images, and fonts
|
|
161
|
+
- Dynamic CORS origin validation with regex pattern support
|
|
162
|
+
- Configurable cache headers per file extension
|
|
163
|
+
- Comprehensive MIME type detection
|
|
164
|
+
- HTTP/1.1 fallback support
|
|
165
|
+
- Security headers (X-Content-Type-Options, X-Frame-Options, Vary)
|
|
166
|
+
- Query string stripping for cache optimization
|
|
167
|
+
- Comprehensive error handling (server, TLS, session, stream errors)
|
|
168
|
+
|
|
169
|
+
**Configuration Properties:**
|
|
170
|
+
- `onError` - Custom error handler callback for server errors
|
|
171
|
+
- `onRequestSuccess` - Callback for successful requests
|
|
172
|
+
- `onRequestError` - Callback for failed requests
|
|
173
|
+
- `onEvent` - Callback for lifecycle events
|
|
174
|
+
|
|
175
|
+
**Methods:**
|
|
176
|
+
- `create()` - Create HTTP/2 secure server
|
|
177
|
+
- `listen()` - Start listening on configured port
|
|
178
|
+
- `close()` - Gracefully close server
|
|
179
|
+
- `handleStream(stream, headers)` - Handle HTTP/2 stream
|
|
180
|
+
- `handleHttp1Request(req, res)` - Handle HTTP/1.1 fallback requests
|
|
181
|
+
- `resolveFilePath(requestPath)` - Resolve file path from request
|
|
182
|
+
- `setupEventHandlers()` - Configure server error event handlers
|
|
183
|
+
|
|
184
|
+
## Utility Classes
|
|
185
|
+
|
|
186
|
+
### RequestLogger
|
|
187
|
+
`lib/request-logger.js`
|
|
188
|
+
|
|
189
|
+
Express middleware for request logging.
|
|
190
|
+
|
|
191
|
+
**Methods:**
|
|
192
|
+
- `createMiddleware(onRequestSuccess, onRequestError)` - Create logging middleware
|
|
193
|
+
|
|
194
|
+
Tracks request timing and invokes callbacks based on status code:
|
|
195
|
+
- Status < 400: calls onRequestSuccess
|
|
196
|
+
- Status >= 400: calls onRequestError
|
|
197
|
+
|
|
198
|
+
### EventDispatcher
|
|
199
|
+
`lib/event-dispatcher.js`
|
|
200
|
+
|
|
201
|
+
Static utility for dispatching lifecycle events.
|
|
202
|
+
|
|
203
|
+
**Methods:**
|
|
204
|
+
- `dispatch(onEventCallback, eventType, instanceName, instance, data)` - Dispatch event
|
|
205
|
+
|
|
206
|
+
Validates callback exists before invoking with structured event data.
|
|
207
|
+
|
|
208
|
+
### ServerErrorHandler
|
|
209
|
+
`lib/server-error-handler.js`
|
|
210
|
+
|
|
211
|
+
Centralized error handling for all server components.
|
|
212
|
+
|
|
213
|
+
**Methods:**
|
|
214
|
+
- `handleError(onErrorCallback, instanceName, instance, key, error, context)` - Handle and delegate errors
|
|
215
|
+
|
|
216
|
+
Used by Http2CdnServer, AppServerFactory, and ReverseProxyConfigurer. Provides structured error context with instance details and metadata.
|
|
217
|
+
|
|
218
|
+
### ServerDefaultConfigurations
|
|
219
|
+
`lib/server-default-configurations.js`
|
|
220
|
+
|
|
221
|
+
Static class providing default configurations.
|
|
222
|
+
|
|
223
|
+
**Properties:**
|
|
224
|
+
- `mimeTypes` - Comprehensive MIME type mappings for common file extensions
|
|
225
|
+
- `cacheConfig` - Default cache max-age settings (1 year for CSS/JS/fonts, 30 days for images)
|
|
226
|
+
|
|
227
|
+
### ServerFactoryUtils
|
|
228
|
+
`lib/server-factory-utils.js`
|
|
229
|
+
|
|
230
|
+
Static utility methods for server operations.
|
|
231
|
+
|
|
232
|
+
**Methods:**
|
|
233
|
+
- `getCacheConfigForPath(path, cacheConfig)` - Get cache config for file path
|
|
234
|
+
- `validateOrigin(origin, corsOrigins, corsAllowAll)` - Validate CORS origin (supports strings and RegExp)
|
|
235
|
+
- `stripQueryString(url)` - Remove query string from URL
|
|
236
|
+
|
|
237
|
+
### ServerHeaders
|
|
238
|
+
`lib/server-headers.js`
|
|
239
|
+
|
|
240
|
+
Centralized header management.
|
|
241
|
+
|
|
242
|
+
**Headers:**
|
|
243
|
+
- HTTP/2 headers configuration
|
|
244
|
+
- Express security headers
|
|
245
|
+
- Cache control headers
|
|
246
|
+
- Proxy forwarding headers
|
|
247
|
+
|
|
248
|
+
**Methods:**
|
|
249
|
+
- `buildCacheControlHeader(maxAge)` - Build cache control header string
|
|
250
|
+
|
|
251
|
+
## Security Configurers
|
|
252
|
+
|
|
253
|
+
Located in `lib/app-server-factory/`
|
|
254
|
+
|
|
255
|
+
### DevelopmentModeDetector
|
|
256
|
+
`development-mode-detector.js`
|
|
257
|
+
|
|
258
|
+
Auto-detects development environment.
|
|
259
|
+
|
|
260
|
+
**Methods:**
|
|
261
|
+
- `detect(config)` - Detect if in development mode
|
|
262
|
+
- `matchesPattern(domain)` - Check if domain matches development pattern
|
|
263
|
+
|
|
264
|
+
Checks NODE_ENV, domain patterns, and configured domains. Built-in patterns: localhost, 127.0.0.1, .local, .test, .dev, .staging, etc.
|
|
265
|
+
|
|
266
|
+
### ProtocolEnforcer
|
|
267
|
+
`protocol-enforcer.js`
|
|
268
|
+
|
|
269
|
+
Enforces HTTP/HTTPS protocol consistency.
|
|
270
|
+
|
|
271
|
+
**Methods:**
|
|
272
|
+
- `setup(app, config)` - Setup protocol enforcement middleware
|
|
273
|
+
|
|
274
|
+
Development mode awareness with automatic redirects when protocol doesn't match configuration.
|
|
275
|
+
|
|
276
|
+
### SecurityConfigurer
|
|
277
|
+
`security-configurer.js`
|
|
278
|
+
|
|
279
|
+
Helmet integration with CSP management.
|
|
280
|
+
|
|
281
|
+
**Methods:**
|
|
282
|
+
- `setupHelmet(app, config)` - Setup Helmet middleware
|
|
283
|
+
- `setupXssProtection(app, config)` - Setup XSS protection
|
|
284
|
+
- `enableCSP(app, cspOptions)` - Enable Content Security Policy
|
|
285
|
+
- `addExternalDomainsToCsp(directives, externalDomains)` - Add external domains to CSP
|
|
286
|
+
|
|
287
|
+
Features XSS protection with request body sanitization. Development-friendly CSP configuration with directive merging or override support.
|
|
288
|
+
|
|
289
|
+
### CorsConfigurer
|
|
290
|
+
`cors-configurer.js`
|
|
291
|
+
|
|
292
|
+
Dynamic CORS origin validation.
|
|
293
|
+
|
|
294
|
+
**Methods:**
|
|
295
|
+
- `setup(app, config)` - Setup CORS middleware
|
|
296
|
+
- `extractDevelopmentOrigins(domainMapping)` - Extract development origins
|
|
297
|
+
- `normalizeHost(originOrHost)` - Normalize host string
|
|
298
|
+
|
|
299
|
+
Development domain support with automatic port variations. Credential support configuration.
|
|
300
|
+
|
|
301
|
+
### RateLimitConfigurer
|
|
302
|
+
`rate-limit-configurer.js`
|
|
303
|
+
|
|
304
|
+
Global and endpoint-specific rate limiting.
|
|
305
|
+
|
|
306
|
+
**Methods:**
|
|
307
|
+
- `setup(app, config)` - Setup global rate limiting
|
|
308
|
+
- `createHomeLimiter()` - Create homepage-specific limiter
|
|
309
|
+
|
|
310
|
+
Development mode multiplier for lenient limits. IP-based key generation option.
|
|
311
|
+
|
|
312
|
+
### ReverseProxyConfigurer
|
|
313
|
+
`reverse-proxy-configurer.js`
|
|
314
|
+
|
|
315
|
+
Domain-based reverse proxy routing.
|
|
316
|
+
|
|
317
|
+
**Methods:**
|
|
318
|
+
- `setup(app, config)` - Setup reverse proxy
|
|
319
|
+
- `createProxyMiddleware(rule)` - Create proxy middleware for rule
|
|
320
|
+
- `handleProxyError(err, req, res)` - Handle proxy errors with status codes
|
|
321
|
+
- `validateProxyRule(rule)` - Validate proxy rule configuration
|
|
322
|
+
- `extractHostname(req)` - Extract hostname from request
|
|
323
|
+
|
|
324
|
+
**Features:**
|
|
325
|
+
- WebSocket support
|
|
326
|
+
- SSL termination
|
|
327
|
+
- Header preservation (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host)
|
|
328
|
+
- Virtual host integration
|
|
329
|
+
- Comprehensive error handling:
|
|
330
|
+
- 502 Bad Gateway for ECONNREFUSED errors
|
|
331
|
+
- 504 Gateway Timeout for ETIMEDOUT/ESOCKETTIMEDOUT errors
|
|
332
|
+
- 500 Internal Server Error for other proxy errors
|
|
333
|
+
- Custom error callback support via ServerErrorHandler
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# Package Architecture
|
|
2
|
+
|
|
3
|
+
## Design Philosophy
|
|
4
|
+
|
|
5
|
+
**@reldens/server-utils** is an independent utility package that provides server infrastructure without coupling to other Reldens packages (like @reldens/utils).
|
|
6
|
+
|
|
7
|
+
## Core Principles
|
|
8
|
+
|
|
9
|
+
### 1. Independence
|
|
10
|
+
- No dependencies on @reldens/utils or other Reldens packages
|
|
11
|
+
- Self-contained utility classes
|
|
12
|
+
- Can be used standalone or integrated into Reldens
|
|
13
|
+
|
|
14
|
+
### 2. Callback-Based Extensibility
|
|
15
|
+
The package provides **hooks via callbacks** instead of direct implementations.
|
|
16
|
+
|
|
17
|
+
**Pattern:**
|
|
18
|
+
- Package provides callback properties
|
|
19
|
+
- Package calls these callbacks at specific points
|
|
20
|
+
- Application provides callback implementations
|
|
21
|
+
- Application wires callbacks to their own logging/monitoring systems
|
|
22
|
+
|
|
23
|
+
### 3. Separation of Concerns
|
|
24
|
+
- **reldens-server-utils**: Provides server infrastructure and callback hooks
|
|
25
|
+
- **Application**: Provides implementations (logging, monitoring, error handling)
|
|
26
|
+
- **@reldens/utils**: Provides shared utilities (Logger, Shortcuts, etc.)
|
|
27
|
+
|
|
28
|
+
The package does NOT import Logger. Applications import Logger and wire it to package callbacks.
|
|
29
|
+
|
|
30
|
+
## Available Callbacks
|
|
31
|
+
|
|
32
|
+
### onError
|
|
33
|
+
Custom error handler for server errors.
|
|
34
|
+
|
|
35
|
+
**Called by:** ServerErrorHandler static class
|
|
36
|
+
|
|
37
|
+
**Data structure:**
|
|
38
|
+
- `instanceName` - Which server component had the error
|
|
39
|
+
- `instance` - The component instance
|
|
40
|
+
- `key` - Error type identifier
|
|
41
|
+
- `error` - The error object
|
|
42
|
+
- `context` - Additional contextual data
|
|
43
|
+
|
|
44
|
+
**Error points:**
|
|
45
|
+
- Virtual host resolution errors
|
|
46
|
+
- SNI certificate loading errors
|
|
47
|
+
- Server creation errors
|
|
48
|
+
- Stream errors
|
|
49
|
+
- TLS client errors
|
|
50
|
+
- Session errors
|
|
51
|
+
- HTTP/1 fallback errors
|
|
52
|
+
- Reverse proxy errors
|
|
53
|
+
|
|
54
|
+
**Example:**
|
|
55
|
+
```javascript
|
|
56
|
+
let config = {
|
|
57
|
+
onError: (errorData) => {
|
|
58
|
+
Logger.error('Server error:', errorData.key, errorData.error.message);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### onRequestSuccess
|
|
64
|
+
Called for successful HTTP requests (status code < 400).
|
|
65
|
+
|
|
66
|
+
**Called by:** RequestLogger middleware
|
|
67
|
+
|
|
68
|
+
**Data structure:**
|
|
69
|
+
- `method` - HTTP method (GET, POST, etc.)
|
|
70
|
+
- `path` - Request path
|
|
71
|
+
- `statusCode` - HTTP status code
|
|
72
|
+
- `responseTime` - Response time in milliseconds
|
|
73
|
+
- `ip` - Client IP address
|
|
74
|
+
- `userAgent` - Client user agent
|
|
75
|
+
- `timestamp` - ISO timestamp
|
|
76
|
+
|
|
77
|
+
**Example:**
|
|
78
|
+
```javascript
|
|
79
|
+
let config = {
|
|
80
|
+
onRequestSuccess: (requestData) => {
|
|
81
|
+
Logger.info('Request:', requestData.method, requestData.path, requestData.statusCode, requestData.responseTime+'ms');
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### onRequestError
|
|
87
|
+
Called for failed HTTP requests (status code >= 400).
|
|
88
|
+
|
|
89
|
+
**Called by:** RequestLogger middleware
|
|
90
|
+
|
|
91
|
+
**Data structure:**
|
|
92
|
+
- `method` - HTTP method
|
|
93
|
+
- `path` - Request path
|
|
94
|
+
- `statusCode` - HTTP status code
|
|
95
|
+
- `responseTime` - Response time in milliseconds
|
|
96
|
+
- `ip` - Client IP address
|
|
97
|
+
- `userAgent` - Client user agent
|
|
98
|
+
- `timestamp` - ISO timestamp
|
|
99
|
+
|
|
100
|
+
**Example:**
|
|
101
|
+
```javascript
|
|
102
|
+
let config = {
|
|
103
|
+
onRequestError: (errorData) => {
|
|
104
|
+
Logger.error('Request error:', errorData.method, errorData.path, errorData.statusCode);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### onEvent
|
|
110
|
+
Generic lifecycle event callback for server initialization and configuration events.
|
|
111
|
+
|
|
112
|
+
**Called by:** EventDispatcher static class
|
|
113
|
+
|
|
114
|
+
**Data structure:**
|
|
115
|
+
- `eventType` - Event type identifier
|
|
116
|
+
- `instanceName` - Which component dispatched the event
|
|
117
|
+
- `instance` - The component instance
|
|
118
|
+
- `data` - Event-specific data
|
|
119
|
+
- `timestamp` - ISO timestamp
|
|
120
|
+
|
|
121
|
+
**Event types:**
|
|
122
|
+
- `app-server-created` - Express app server created
|
|
123
|
+
- `http2-cdn-created` - HTTP/2 CDN server created
|
|
124
|
+
- `app-server-listening` - Server started listening
|
|
125
|
+
- `http-server-created` - HTTP server created
|
|
126
|
+
- `https-server-created` - HTTPS server created
|
|
127
|
+
- `sni-server-created` - SNI server created
|
|
128
|
+
- `domain-added` - Virtual host domain added
|
|
129
|
+
- `protocol-enforcement-enabled` - Protocol enforcement configured
|
|
130
|
+
- `helmet-configured` - Helmet security configured
|
|
131
|
+
- `xss-protection-enabled` - XSS protection configured
|
|
132
|
+
- `cors-configured` - CORS configured
|
|
133
|
+
- `rate-limiting-configured` - Rate limiting configured
|
|
134
|
+
- `reverse-proxy-configured` - Reverse proxy configured
|
|
135
|
+
- `development-mode-detected` - Development mode detected
|
|
136
|
+
- `cdn-server-created` - CDN server instance created
|
|
137
|
+
- `cdn-handlers-setup` - CDN event handlers configured
|
|
138
|
+
- `cdn-server-listening` - CDN server started listening
|
|
139
|
+
|
|
140
|
+
**Example:**
|
|
141
|
+
```javascript
|
|
142
|
+
let config = {
|
|
143
|
+
onEvent: (eventData) => {
|
|
144
|
+
Logger.debug('Event:', eventData.eventType, eventData.instanceName);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Integration Pattern
|
|
150
|
+
|
|
151
|
+
**Application Setup:**
|
|
152
|
+
```javascript
|
|
153
|
+
const { AppServerFactory } = require('@reldens/server-utils');
|
|
154
|
+
const { Logger } = require('@reldens/utils');
|
|
155
|
+
|
|
156
|
+
let factory = new AppServerFactory();
|
|
157
|
+
|
|
158
|
+
let config = {
|
|
159
|
+
port: 8080,
|
|
160
|
+
onError: (errorData) => {
|
|
161
|
+
Logger.error('Server error:', errorData.key, errorData.error.message);
|
|
162
|
+
},
|
|
163
|
+
onRequestSuccess: (requestData) => {
|
|
164
|
+
Logger.info('Request:', requestData.method, requestData.path, requestData.statusCode);
|
|
165
|
+
},
|
|
166
|
+
onRequestError: (errorData) => {
|
|
167
|
+
Logger.error('Request error:', errorData.method, errorData.path, errorData.statusCode);
|
|
168
|
+
},
|
|
169
|
+
onEvent: (eventData) => {
|
|
170
|
+
Logger.debug('Event:', eventData.eventType);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
let serverResult = factory.createAppServer(config);
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
This pattern keeps the utility package independent while allowing full integration with application-specific logging and monitoring systems.
|