opticore-webapp 1.0.68 → 1.0.69

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/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Server } from 'http';
2
+ import { IEnvVariables } from 'opticore-env-access';
2
3
  import { TDependency } from 'opticore-dependency-inject';
3
4
  import { TFeatureRoutes } from 'opticore-router';
4
5
  import { express } from 'opticore-express';
@@ -13,7 +14,7 @@ interface WebServerConstructorInterface {
13
14
  corsOriginOptions?: Partial<CorsOptions>;
14
15
  }
15
16
 
16
- type TServerStatus = "READY" | "RELOADING" | "BLOCKED" | "ERROR" | "STARTING" | "STOPPING";
17
+ type TServerStatus = "READY" | "RELOADING" | "BLOCKED" | "ERROR" | "STARTING" | "STOPPING" | "STOPPED";
17
18
 
18
19
  interface IServerStateInfo {
19
20
  status: TServerStatus;
@@ -21,28 +22,67 @@ interface IServerStateInfo {
21
22
  host: string;
22
23
  port: number;
23
24
  language: string;
24
- watcherEnabled: boolean;
25
- watcherActive?: boolean;
26
25
  routesCount: number;
27
26
  dependenciesCount: number;
28
27
  startTime?: Date;
29
28
  currentTime?: Date;
30
29
  uptime?: number;
31
- memoryUsage?: NodeJS.MemoryUsage;
32
30
  uptimeFormatted?: string;
33
- pid?: any;
34
- platform?: any;
35
- nodeVersion?: any;
36
- cwd?: any;
31
+ memoryUsage?: NodeJS.MemoryUsage;
32
+ pid?: number;
33
+ platform?: string;
34
+ nodeVersion?: string;
35
+ cwd?: string;
36
+ hmrEnabled: boolean;
37
+ hmrWatchingFiles: number;
38
+ hmrRestartCount: number;
39
+ }
40
+
41
+ interface IServerStats {
42
+ status: TServerStatus;
43
+ uptime: string;
44
+ memory: {
45
+ rss: string;
46
+ heapTotal: string;
47
+ heapUsed: string;
48
+ external: string;
49
+ };
50
+ performance: {
51
+ cpuUsage: NodeJS.CpuUsage;
52
+ resourceUsage?: NodeJS.ResourceUsage;
53
+ };
54
+ hmrStats: {
55
+ enabled: boolean;
56
+ restartCount: number;
57
+ lastRestartTime: number;
58
+ watchingFiles: number;
59
+ };
37
60
  }
38
61
 
62
+ /**
63
+ * Main server class that handles HTTP server initialization, routing,
64
+ * error handling, file watching with hot reload capabilities, and HMR.
65
+ *
66
+ * @class WebServerCore
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * const app = new WebServerCore({
71
+ * app: express(),
72
+ * loggerConfig: loggerConfig,
73
+ * environmentPath: ".env",
74
+ * localLanguage: "fr",
75
+ * corsOriginOptions: corsConfig
76
+ * });
77
+ *
78
+ * app.onStartServer(routes, databaseCallback, dependencies);
79
+ * ```
80
+ */
39
81
  declare class WebServerCore {
40
82
  private serverUtility;
41
- private expressApp;
42
- private fileWatcher;
83
+ private readonly expressApp;
43
84
  private readonly localLanguage;
44
85
  private readonly loggerConfig;
45
- private readonly routerExpressApp;
46
86
  private readonly getEnvironment;
47
87
  private readonly environmentPath;
48
88
  private serverListenEvent;
@@ -50,171 +90,445 @@ declare class WebServerCore {
50
90
  private currentDependencies;
51
91
  private server;
52
92
  private errorEmitter;
53
- private isWatcherEnabled;
54
93
  private serverStatus;
55
94
  private serverStartTime;
95
+ private fileWatcher;
96
+ private hmrRestartPending;
97
+ private hmrDebounceTimeout;
98
+ private hmrRestartCount;
99
+ private lastHmrRestartTime;
100
+ /**
101
+ * Creates a new WebServerCore instance.
102
+ *
103
+ * @constructor
104
+ * @param {WebServerConstructorInterface} paramsConstructor - Configuration parameters
105
+ *
106
+ * @param {express.Application} paramsConstructor.app - Express application instance
107
+ * @param {LoggerCore} paramsConstructor.loggerConfig - Logger configuration
108
+ * @param {string} paramsConstructor.environmentPath - Path to environment file
109
+ * @param {string} paramsConstructor.localLanguage - Default language for translations
110
+ * @param {CorsOptions} paramsConstructor.corsOriginOptions - CORS configuration
111
+ *
112
+ * @returns {WebServerCore} New WebServerCore instance
113
+ *
114
+ * @throws {Error} If environment file cannot be loaded
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const server = new WebServerCore({
119
+ * app: express(),
120
+ * loggerConfig: new LoggerCore(config),
121
+ * environmentPath: ".env",
122
+ * localLanguage: "fr",
123
+ * corsOriginOptions: { origin: "http://localhost:3000" }
124
+ * });
125
+ * ```
126
+ */
56
127
  constructor(paramsConstructor: WebServerConstructorInterface);
57
- onStartServer(routers: TFeatureRoutes[], databaseCallback?: (env: any) => void, dependenciesProvider?: TDependency[]): Server | undefined;
58
128
  /**
59
- * Error handling configuration
129
+ * Starts the HTTP server and initializes all components including HMR if enabled.
130
+ *
131
+ * @method onStartServer
132
+ * @public
133
+ *
134
+ * @param {TFeatureRoutes[]} routers - Array of feature routes to register
135
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Optional database connection callback
136
+ * @param {TDependency[]} [dependenciesProvider] - Optional dependency injection providers
137
+ *
138
+ * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
139
+ *
140
+ * @throws {ServerListenEventError} If port/host configuration is invalid
141
+ * @throws {Error} If server initialization fails
142
+ *
143
+ * @fires WebServerCore#startHttpServer - When server successfully starts
144
+ * @fires WebServerCore#startHMR - When HMR is started (if enabled)
145
+ * @fires WebServerCore#serverError - When server fails to start
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * const server = app.onStartServer(
150
+ * routes,
151
+ * (env) => connectToDatabase(env),
152
+ * dependencies
153
+ * );
154
+ *
155
+ * if (server) {
156
+ * console.log("Server started successfully");
157
+ * }
158
+ * ```
159
+ */
160
+ onStartServer(routers: TFeatureRoutes[], databaseCallback?: (env: IEnvVariables) => void, dependenciesProvider?: TDependency[]): Server | undefined;
161
+ /**
162
+ * Validates server configuration parameters.
163
+ *
164
+ * @method validateServerParameters
165
+ * @private
166
+ *
167
+ * @returns {boolean} True if all parameters are valid, false otherwise
168
+ *
169
+ * @remarks
170
+ * Validates:
171
+ * - Port number is valid and positive
172
+ * - Host is not empty
173
+ * - Local language is specified
174
+ * - HMR configuration (if enabled)
175
+ */
176
+ private validateServerParameters;
177
+ /**
178
+ * Starts the HTTP server and sets up event listeners.
179
+ *
180
+ * @method startHttpServer
181
+ * @private
182
+ *
183
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
184
+ *
185
+ * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
186
+ *
187
+ * @throws {Error} If server fails to start
188
+ */
189
+ private startHttpServer;
190
+ /**
191
+ * Configures server components (database, dependencies, routes, etc.).
192
+ *
193
+ * @method configureServerComponents
194
+ * @private
195
+ *
196
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
197
+ *
198
+ * @returns {void}
199
+ *
200
+ * @throws {Error} If component configuration fails
201
+ */
202
+ private configureServerComponents;
203
+ /**
204
+ * Handles server configuration errors.
205
+ *
206
+ * @method handleServerConfigurationError
207
+ * @private
208
+ *
209
+ * @param {any} err - The error that occurred
210
+ *
211
+ * @returns {void}
212
+ */
213
+ private handleServerConfigurationError;
214
+ /**
215
+ * Handles general startup errors.
216
+ *
217
+ * @method handleStartupError
218
+ * @private
219
+ *
220
+ * @param {any} error - The startup error
221
+ *
222
+ * @returns {void}
223
+ */
224
+ private handleStartupError;
225
+ /**
226
+ * Sets up Node.js process event listeners.
227
+ *
228
+ * @method setupProcessEventListeners
229
+ * @private
230
+ *
231
+ * @returns {void}
232
+ *
233
+ * @remarks
234
+ * Listens for:
235
+ * - Process exit events
236
+ * - Uncaught exceptions
237
+ * - Unhandled rejections
238
+ * - System signals (SIGINT, SIGTERM)
239
+ */
240
+ private setupProcessEventListeners;
241
+ /**
242
+ * Sets up HTTP server event listeners.
243
+ *
244
+ * @method setupServerEventListeners
245
+ * @private
246
+ *
247
+ * @returns {void}
248
+ *
249
+ * @remarks
250
+ * Configures listeners for:
251
+ * - Server errors
252
+ * - Connection closing
253
+ * - Connection dropping
254
+ * - HTTP requests (for logging)
255
+ *
256
+ * @listens Server#error - Server error events
257
+ * @listens Server#close - Server closing events
258
+ * @listens Server#drop - Connection drop events
259
+ * @listens Server#request - HTTP request events
260
+ */
261
+ private setupServerEventListeners;
262
+ /**
263
+ * Sets up error handling middleware and event emitters.
264
+ *
265
+ * @method setupErrorHandling
266
+ * @private
267
+ *
268
+ * @returns {void}
60
269
  */
61
270
  private setupErrorHandling;
62
271
  /**
63
- * Setup server events
64
- */
65
- private setupServerEvents;
66
- /**
67
- * Initialize file watcher
68
- */
69
- private initializeFileWatcher;
70
- /**
71
- * Setup watcher events
72
- */
73
- private setupWatcherEvents;
74
- /**
75
- * Handle file changes detected by watcher
76
- */
77
- private handleFileChange;
78
- /**
79
- * Handle hot reload requested by watcher
80
- */
81
- private handleHotReload;
82
- /**
83
- * Handle watcher errors
84
- */
85
- private handleWatcherError;
86
- /**
87
- * Notify file change without action
88
- */
89
- private notifyFileChange;
90
- /**
91
- * Reload environment configuration
92
- */
93
- private reloadEnvironmentConfig;
94
- /**
95
- * Execute hot reload for environment files
96
- */
97
- private executeHotReloadEnvironment;
98
- /**
99
- * Reload configuration files
100
- */
101
- private reloadConfigurationFiles;
102
- /**
103
- * Execute hot reload for config files
104
- */
105
- private executeHotReloadConfig;
106
- /**
107
- * Reload application routes
108
- */
109
- private reloadApplicationRoutes;
110
- /**
111
- * Execute hot reload for routes
112
- */
113
- private executeHotReloadRoutes;
114
- /**
115
- * Execute hot reload for dependencies
116
- */
117
- private executeHotReloadDependencies;
118
- /**
119
- * Notify environment reload
120
- */
121
- private notifyEnvironmentReload;
122
- /**
123
- * Reload specific route
124
- */
125
- private reloadSpecificRoute;
126
- /**
127
- * Reload router for specific file
128
- */
129
- private reloadRouterForFile;
130
- /**
131
- * Reload configurations
132
- */
133
- private reloadConfigurations;
134
- /**
135
- * Reload dependencies
136
- */
137
- private reloadDependencies;
138
- /**
139
- * Register routes
272
+ * Registers routes with the Express application.
273
+ *
274
+ * @method registerRoutes
275
+ * @private
276
+ *
277
+ * @param {any[]} allFeatureRoutes - Array of feature routes to register
278
+ *
279
+ * @returns {void}
140
280
  */
141
281
  private registerRoutes;
142
282
  /**
143
- * Parse transform error
144
- */
145
- private parseTransformError;
146
- /**
147
- * Display server info
283
+ * Displays server information.
284
+ *
285
+ * @method infoWebApp
286
+ * @private
287
+ *
288
+ * @returns {void}
148
289
  */
149
290
  private infoWebApp;
150
291
  /**
151
- * Stop file watcher
152
- */
153
- private stopFileWatcher;
154
- /**
155
- * Shutdown server
156
- */
157
- private shutdown;
158
- /**
159
- * Enable/disable watcher
292
+ * Starts the Hot Module Replacement (HMR) file watching system.
293
+ *
294
+ * @method startHMR
295
+ * @private
296
+ *
297
+ * @returns {void}
298
+ *
299
+ * @remarks
300
+ * Configures file watcher based on environment variables:
301
+ * - HMR_ENABLED: Enable/disable HMR
302
+ * - HMR_WATCH_PATTERNS: Files to watch
303
+ * - HMR_IGNORE_PATTERNS: Files to ignore
304
+ *
305
+ * @throws {Error} If HMR configuration is invalid
306
+ */
307
+ private startHMR;
308
+ /**
309
+ * Handles file change events with debouncing.
310
+ *
311
+ * @method handleFileChange
312
+ * @private
313
+ *
314
+ * @param {string} filePath - Path of the changed file
315
+ * @param {string} [action="modified"] - Type of file change (modified/added/deleted)
316
+ *
317
+ * @returns {void}
318
+ *
319
+ * @remarks
320
+ * Uses debouncing to prevent multiple rapid reloads.
321
+ * Debounce time configurable via HMR_DEBOUNCE_MS environment variable.
160
322
  */
161
- setWatcherEnabled(enabled: boolean): void;
323
+ private handleFileChange;
162
324
  /**
163
- * Get watcher status
325
+ * Triggers a hot reload operation.
326
+ *
327
+ * @method triggerHotReload
328
+ * @private
329
+ *
330
+ * @param {string} filePath - Path of the changed file
331
+ * @param {string} action - Type of file change
332
+ *
333
+ * @returns {Promise<void>}
334
+ *
335
+ * @remarks
336
+ * - Checks if reload is already in progress
337
+ * - Validates restart limits
338
+ * - Performs appropriate reload actions based on file type
339
+ * - Emits hotReload event
340
+ */
341
+ private triggerHotReload;
342
+ /**
343
+ * Performs appropriate hot reload actions based on file type.
344
+ *
345
+ * @method performHotReloadActions
346
+ * @private
347
+ *
348
+ * @param {string} filePath - Path of the changed file
349
+ *
350
+ * @returns {Promise<void>}
351
+ *
352
+ * @remarks
353
+ * Different actions for different file types:
354
+ * - .json/.env: Reload translations
355
+ * - routes/controller files: Reload routes
356
+ * - config/.env files: Reload dependencies
357
+ */
358
+ private performHotReloadActions;
359
+ /**
360
+ * Reloads routes dynamically.
361
+ *
362
+ * @method reloadRoutes
363
+ * @private
364
+ *
365
+ * @returns {Promise<void>}
366
+ *
367
+ * @throws {Error} If route reloading fails
368
+ *
369
+ * @remarks
370
+ * This method should be implemented based on your architecture.
371
+ * It should reload route modules from the filesystem.
372
+ */
373
+ private reloadRoutes;
374
+ /**
375
+ * Reloads dependencies dynamically.
376
+ *
377
+ * @method reloadDependencies
378
+ * @private
379
+ *
380
+ * @returns {Promise<void>}
381
+ *
382
+ * @throws {Error} If dependency reloading fails
164
383
  */
165
- getWatcherStatus(): {
166
- enabled: boolean;
167
- active: boolean;
168
- };
384
+ private reloadDependencies;
169
385
  /**
170
- * Get server state information
386
+ * Checks if HMR restart can proceed based on configuration limits.
387
+ *
388
+ * @method canProceedWithHMRRestart
389
+ * @private
390
+ *
391
+ * @returns {boolean} True if restart can proceed, false otherwise
392
+ *
393
+ * @remarks
394
+ * Checks:
395
+ * - Auto-restart enabled/disabled
396
+ * - Maximum restarts per minute limit
397
+ */
398
+ private canProceedWithHMRRestart;
399
+ /**
400
+ * Called when the HMR watcher is ready.
401
+ *
402
+ * @method onHMRWatcherReady
403
+ * @private
404
+ *
405
+ * @param {string[]} watchPatterns - Patterns being watched
406
+ * @param {string[]} ignorePatterns - Patterns being ignored
407
+ *
408
+ * @returns {void}
409
+ */
410
+ private onHMRWatcherReady;
411
+ /**
412
+ * Handles HMR watcher errors.
413
+ *
414
+ * @method onHMRWatcherError
415
+ * @private
416
+ *
417
+ * @param {Error} error - The watcher error
418
+ *
419
+ * @returns {void}
420
+ */
421
+ private onHMRWatcherError;
422
+ /**
423
+ * Stops the HMR system.
424
+ *
425
+ * @method stopHMR
426
+ * @private
427
+ *
428
+ * @returns {void}
429
+ */
430
+ private stopHMR;
431
+ /**
432
+ * Stops the server and HMR system cleanly.
433
+ *
434
+ * @method onStopServer
435
+ * @public
436
+ *
437
+ * @returns {void}
438
+ */
439
+ onStopServer(): void;
440
+ /**
441
+ * Gets the current server state information.
442
+ *
443
+ * @method getServerState
444
+ * @public
445
+ *
446
+ * @returns {IServerStateInfo} Server state information object
447
+ *
448
+ * @remarks
449
+ * Includes:
450
+ * - Status, host, port
451
+ * - Route and dependency counts
452
+ * - Uptime and memory usage
453
+ * - HMR configuration and statistics
171
454
  */
172
455
  getServerState(): IServerStateInfo;
173
456
  /**
174
- * Simple method to get just the status
457
+ * Gets the current server status.
458
+ *
459
+ * @method getServerStatus
460
+ * @public
461
+ *
462
+ * @returns {TServerStatus} Current server status
175
463
  */
176
464
  getServerStatus(): TServerStatus;
177
465
  /**
178
- * Get server statistics for monitoring
179
- */
180
- getServerStats(): {
181
- status: TServerStatus;
182
- uptime: string;
183
- memory: {
184
- rss: string;
185
- heapTotal: string;
186
- heapUsed: string;
187
- external: string;
188
- };
189
- performance: {
190
- cpuUsage: NodeJS.CpuUsage;
191
- resourceUsage?: NodeJS.ResourceUsage;
192
- };
193
- };
194
- /**
195
- * Format bytes to human readable string
196
- */
197
- private formatBytes;
198
- /**
199
- * Format uptime to human readable string
466
+ * Gets detailed server statistics.
467
+ *
468
+ * @method getServerStats
469
+ * @public
470
+ *
471
+ * @returns {IServerStats} Server statistics object
472
+ *
473
+ * @remarks
474
+ * Includes:
475
+ * - Performance metrics (CPU, memory)
476
+ * - Uptime information
477
+ * - HMR statistics
478
+ */
479
+ getServerStats(): IServerStats;
480
+ /**
481
+ * Formats milliseconds into a human-readable uptime string.
482
+ *
483
+ * @method formatUptime
484
+ * @private
485
+ *
486
+ * @param {number} ms - Milliseconds to format
487
+ *
488
+ * @returns {string} Formatted uptime string
489
+ *
490
+ * @example
491
+ * formatUptime(3661000) // returns "1h 1m 1s"
200
492
  */
201
493
  private formatUptime;
202
494
  /**
203
- * Add watch directories
204
- */
205
- addWatchDirectories(directories: string[]): void;
206
- /**
207
- * Clear file cache
495
+ * Formats bytes into a human-readable size string.
496
+ *
497
+ * @method formatBytes
498
+ * @private
499
+ *
500
+ * @param {number} bytes - Bytes to format
501
+ *
502
+ * @returns {string} Formatted size string
503
+ *
504
+ * @example
505
+ * formatBytes(1048576) // returns "1.00 MB"
208
506
  */
209
- clearFileCache(): void;
210
- /**
211
- * Force reload configurations
212
- */
213
- forceReloadConfig(): void;
507
+ private formatBytes;
214
508
  /**
215
- * Restart watcher
216
- */
217
- restartWatcher(): void;
509
+ * Checks if HMR is currently active.
510
+ *
511
+ * @method isHMRActive
512
+ * @public
513
+ *
514
+ * @returns {boolean} True if HMR is enabled and watching files, false otherwise
515
+ */
516
+ isHMRActive(): boolean;
517
+ /**
518
+ * Gets detailed HMR information and status.
519
+ *
520
+ * @method getHMRInfo
521
+ * @public
522
+ *
523
+ * @returns {any} HMR information object
524
+ *
525
+ * @remarks
526
+ * Includes:
527
+ * - Configuration settings from .env
528
+ * - Current restart count
529
+ * - Watcher status
530
+ */
531
+ getHMRInfo(): any;
218
532
  }
219
533
 
220
534
  declare const envPath: string;