opticore-webapp 1.0.69 → 1.0.71

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,7 +1,7 @@
1
+ import * as http from 'http';
1
2
  import { Server } from 'http';
2
- import { IEnvVariables } from 'opticore-env-access';
3
- import { TDependency } from 'opticore-dependency-inject';
4
3
  import { TFeatureRoutes } from 'opticore-router';
4
+ import { TDependency } from 'opticore-dependency-inject';
5
5
  import { express } from 'opticore-express';
6
6
  import { LoggerCore } from 'opticore-logger';
7
7
  import { CorsOptions } from 'cors';
@@ -11,528 +11,226 @@ interface WebServerConstructorInterface {
11
11
  loggerConfig: LoggerCore;
12
12
  localLanguage: string;
13
13
  environmentPath: any;
14
- corsOriginOptions?: Partial<CorsOptions>;
15
- }
16
-
17
- type TServerStatus = "READY" | "RELOADING" | "BLOCKED" | "ERROR" | "STARTING" | "STOPPING" | "STOPPED";
18
-
19
- interface IServerStateInfo {
20
- status: TServerStatus;
21
- isRunning: boolean;
22
- host: string;
23
- port: number;
24
- language: string;
25
- routesCount: number;
26
- dependenciesCount: number;
27
- startTime?: Date;
28
- currentTime?: Date;
29
- uptime?: number;
30
- uptimeFormatted?: string;
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
- };
14
+ corsOriginOptions?: Partial<CorsOptions> | null;
60
15
  }
61
16
 
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
- */
81
17
  declare class WebServerCore {
82
18
  private serverUtility;
83
- private readonly expressApp;
19
+ private expressApp;
20
+ private container;
84
21
  private readonly localLanguage;
85
22
  private readonly loggerConfig;
86
- private readonly getEnvironment;
23
+ private readonly routerExpressApp;
24
+ private readonly getEnvironmentValue;
87
25
  private readonly environmentPath;
88
26
  private serverListenEvent;
89
- private currentRoutes;
90
- private currentDependencies;
91
- private server;
92
- private errorEmitter;
93
- private serverStatus;
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
- */
27
+ private dependenciesRegistered;
127
28
  constructor(paramsConstructor: WebServerConstructorInterface);
128
29
  /**
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
30
  *
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
- * ```
31
+ * @param dependencies
159
32
  */
160
- onStartServer(routers: TFeatureRoutes[], databaseCallback?: (env: IEnvVariables) => void, dependenciesProvider?: TDependency[]): Server | undefined;
33
+ registerDependencies(dependencies: TDependency[]): void;
161
34
  /**
162
- * Validates server configuration parameters.
163
35
  *
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)
36
+ * @param routers
37
+ * @param databaseCallback
38
+ * @param dependenciesProvider
175
39
  */
176
- private validateServerParameters;
40
+ onStartServer(routers: TFeatureRoutes[], databaseCallback: (env: any) => void, dependenciesProvider?: TDependency[]): Server<typeof http.IncomingMessage, typeof http.ServerResponse> | undefined;
177
41
  /**
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
42
  *
185
- * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
186
- *
187
- * @throws {Error} If server fails to start
43
+ * @param serverWeb
188
44
  */
189
- private startHttpServer;
45
+ onListeningOnServerEvent(serverWeb: Server): void;
190
46
  /**
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
47
  *
198
- * @returns {void}
199
- *
200
- * @throws {Error} If component configuration fails
48
+ * @param serverWeb
201
49
  */
202
- private configureServerComponents;
50
+ onRequestOnServerEvent(serverWeb: Server): void;
203
51
  /**
204
- * Handles server configuration errors.
205
52
  *
206
- * @method handleServerConfigurationError
207
53
  * @private
208
- *
209
- * @param {any} err - The error that occurred
210
- *
211
- * @returns {void}
212
54
  */
213
- private handleServerConfigurationError;
55
+ private loadTranslationFiles;
214
56
  /**
215
- * Handles general startup errors.
216
57
  *
217
- * @method handleStartupError
58
+ * @param allFeatureRoutes
218
59
  * @private
219
- *
220
- * @param {any} error - The startup error
221
- *
222
- * @returns {void}
223
60
  */
224
- private handleStartupError;
61
+ private registerRoutes;
225
62
  /**
226
- * Sets up Node.js process event listeners.
227
63
  *
228
- * @method setupProcessEventListeners
229
64
  * @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
65
  */
240
- private setupProcessEventListeners;
66
+ private stackTraceErrorHandling;
241
67
  /**
242
- * Sets up HTTP server event listeners.
243
68
  *
244
- * @method setupServerEventListeners
245
69
  * @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
70
  */
261
- private setupServerEventListeners;
71
+ private infoWebApp;
72
+ }
73
+
74
+ declare const envPath: string;
75
+
76
+ interface HotReloadConfig {
262
77
  /**
263
- * Sets up error handling middleware and event emitters.
264
- *
265
- * @method setupErrorHandling
266
- * @private
267
- *
268
- * @returns {void}
78
+ * Entry point file to run (e.g. 'dist/index.js' or 'src/index.ts')
269
79
  */
270
- private setupErrorHandling;
80
+ entry: string;
271
81
  /**
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}
82
+ * Runtime to use for spawning the child process.
83
+ * - 'node' : compiled JS only, supports IPC hot reload for .env
84
+ * - 'tsx' : runs TypeScript directly via tsx
85
+ * - 'ts-node' : runs TypeScript directly via ts-node
86
+ * @default 'node'
280
87
  */
281
- private registerRoutes;
88
+ runtime?: 'node' | 'tsx' | 'ts-node';
282
89
  /**
283
- * Displays server information.
284
- *
285
- * @method infoWebApp
286
- * @private
287
- *
288
- * @returns {void}
90
+ * Extra arguments passed to the runtime before the entry file.
91
+ * Example: ['--experimental-specifier-resolution=node']
289
92
  */
290
- private infoWebApp;
93
+ runtimeArgs?: string[];
291
94
  /**
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
95
+ * Root directory to watch for file changes.
96
+ * @default process.cwd()
306
97
  */
307
- private startHMR;
98
+ rootDir?: string;
308
99
  /**
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.
100
+ * Additional directories or glob patterns to watch.
101
+ * Merged with the default watched extensions (.ts, .js, .env, .json).
102
+ * Example: ['config', 'locales']
322
103
  */
323
- private handleFileChange;
104
+ watchDirs?: string[];
324
105
  /**
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
106
+ * File extensions to watch.
107
+ * @default ['.ts', '.js', '.mjs', '.cjs', '.json', '.env']
340
108
  */
341
- private triggerHotReload;
109
+ watchExtensions?: string[];
342
110
  /**
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
111
+ * Patterns / file names to ignore in addition to the built-in ignores.
112
+ * Built-in ignores: node_modules, dist, .git, package.json, package-lock.json
113
+ * Example: ['coverage', 'tmp', 'myIgnored.json']
357
114
  */
358
- private performHotReloadActions;
115
+ ignore?: string[];
359
116
  /**
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.
117
+ * Path to the .env file that should be hot-reloaded without restarting.
118
+ * @default '.env'
372
119
  */
373
- private reloadRoutes;
120
+ envFile?: string;
374
121
  /**
375
- * Reloads dependencies dynamically.
376
- *
377
- * @method reloadDependencies
378
- * @private
379
- *
380
- * @returns {Promise<void>}
381
- *
382
- * @throws {Error} If dependency reloading fails
122
+ * File extensions that support in-process hot reload (no server restart).
123
+ * All other watched extensions trigger a full server restart.
124
+ * @default ['.env', '.json']
383
125
  */
384
- private reloadDependencies;
126
+ hotReloadExtensions?: string[];
385
127
  /**
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
128
+ * Milliseconds to wait after the last change before acting (debounce).
129
+ * Prevents rapid successive restarts when many files change at once.
130
+ * @default 300
397
131
  */
398
- private canProceedWithHMRRestart;
132
+ debounceMs?: number;
399
133
  /**
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}
134
+ * Automatically restart the child process if it exits unexpectedly.
135
+ * @default true
409
136
  */
410
- private onHMRWatcherReady;
137
+ restartOnCrash?: boolean;
411
138
  /**
412
- * Handles HMR watcher errors.
413
- *
414
- * @method onHMRWatcherError
415
- * @private
416
- *
417
- * @param {Error} error - The watcher error
418
- *
419
- * @returns {void}
139
+ * Maximum number of automatic restarts on crash before giving up.
140
+ * @default 5
420
141
  */
421
- private onHMRWatcherError;
142
+ maxCrashRestarts?: number;
143
+ }
144
+
145
+ declare class HotReloadWatcher {
146
+ private readonly cfg;
147
+ private child;
148
+ private watchers;
149
+ private debounceTimer;
150
+ private isRestarting;
151
+ private crashRestartCount;
152
+ private started;
153
+ private restartStart;
154
+ constructor(config: HotReloadConfig);
155
+ start(): Promise<void>;
156
+ stop(): Promise<void>;
157
+ private spawnChild;
158
+ private killChild;
159
+ private setupWatchers;
160
+ private watchDirectoryRecursive;
161
+ private onFileChange;
162
+ private doHotReload;
163
+ private scheduleRestart;
164
+ private sendIpc;
165
+ private shouldIgnoreDir;
166
+ private shouldIgnoreFile;
167
+ private isWatchedFile;
168
+ private isHotReloadable;
169
+ private isEnvFile;
170
+ private strip;
171
+ private ts;
422
172
  /**
423
- * Stops the HMR system.
424
- *
425
- * @method stopHMR
426
- * @private
173
+ * Startup banner — mirrors the infoServer() box style from CoreService.
427
174
  *
428
- * @returns {void}
175
+ * ╔══════════════════════════════════════════╗
176
+ * gradient title
177
+ * ╔══ bgGreen box ════════════════════════╗
178
+ * entry dist/index.js
179
+ * runtime node (IPC enabled)
180
+ * root ./src
181
+ * watching .ts .js .json .env
182
+ * debounce 300ms
183
+ * ╚══════════════════════════════════════════╝
429
184
  */
430
- private stopHMR;
185
+ private printBanner;
431
186
  /**
432
- * Stops the server and HMR system cleanly.
433
- *
434
- * @method onStopServer
435
- * @public
187
+ * HOT event in-process reload, no server restart.
436
188
  *
437
- * @returns {void}
189
+ * ✔ [ HOT ] 14:23:45 | .env → env variables reloaded
438
190
  */
439
- onStopServer(): void;
191
+ private printHot;
440
192
  /**
441
- * Gets the current server state information.
442
- *
443
- * @method getServerState
444
- * @public
445
- *
446
- * @returns {IServerStateInfo} Server state information object
193
+ * RELOAD event server restart triggered.
447
194
  *
448
- * @remarks
449
- * Includes:
450
- * - Status, host, port
451
- * - Route and dependency counts
452
- * - Uptime and memory usage
453
- * - HMR configuration and statistics
195
+ * ⚡ [ RELOAD ] 14:24:03 | src/routes/user.ts → restarting server...
454
196
  */
455
- getServerState(): IServerStateInfo;
197
+ private printReloading;
456
198
  /**
457
- * Gets the current server status.
199
+ * READY event server successfully restarted.
200
+ * Uses the same full-width bgGreen border as infoServer().
458
201
  *
459
- * @method getServerStatus
460
- * @public
461
- *
462
- * @returns {TServerStatus} Current server status
202
+ * ════════════════════════════════════════════
203
+ * READY server restarted in 245ms
204
+ * ════════════════════════════════════════════
463
205
  */
464
- getServerStatus(): TServerStatus;
206
+ private printReady;
465
207
  /**
466
- * Gets detailed server statistics.
467
- *
468
- * @method getServerStats
469
- * @public
208
+ * CRASH event unexpected child process exit.
470
209
  *
471
- * @returns {IServerStats} Server statistics object
472
- *
473
- * @remarks
474
- * Includes:
475
- * - Performance metrics (CPU, memory)
476
- * - Uptime information
477
- * - HMR statistics
210
+ * ✘ [ CRASH ] 14:24:10 | server exited with code 1
478
211
  */
479
- getServerStats(): IServerStats;
212
+ private printCrash;
480
213
  /**
481
- * Formats milliseconds into a human-readable uptime string.
214
+ * RETRY event auto-restart after crash.
482
215
  *
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"
216
+ * ↺ [ RETRY ] 14:24:11 | attempt 1 / 5
492
217
  */
493
- private formatUptime;
218
+ private printCrashRetry;
494
219
  /**
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"
220
+ * LIMIT reached give up restarting.
506
221
  */
507
- private formatBytes;
222
+ private printCrashLimit;
508
223
  /**
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
224
+ * Error miscellaneous internal error.
515
225
  */
516
- isHMRActive(): boolean;
226
+ private printError;
517
227
  /**
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
228
+ * Stopped watcher shut down.
530
229
  */
531
- getHMRInfo(): any;
230
+ private printStopped;
231
+ private setupProcessSignals;
532
232
  }
533
233
 
534
- declare const envPath: string;
535
-
536
234
  type KernelModuleType = [any[], () => void];
537
235
 
538
- export { type KernelModuleType, WebServerCore as WebServer, envPath };
236
+ export { type HotReloadConfig, HotReloadWatcher, type KernelModuleType, WebServerCore as WebServer, envPath };