@seedcord/services 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,816 @@
1
+ 'use strict';
2
+
3
+ var envapt = require('envapt');
4
+ var winston = require('winston');
5
+ var http = require('http');
6
+ var chalk = require('chalk');
7
+ var events = require('events');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var chalk__default = /*#__PURE__*/_interopDefault(chalk);
12
+
13
+ var __defProp = Object.defineProperty;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
+ var Logger = class _Logger {
16
+ static {
17
+ __name(this, "Logger");
18
+ }
19
+ static instances = /* @__PURE__ */ new Map();
20
+ static instance(prefix) {
21
+ let instance = this.instances.get(prefix);
22
+ if (!instance) {
23
+ instance = new _Logger(prefix);
24
+ this.instances.set(prefix, instance);
25
+ }
26
+ return instance;
27
+ }
28
+ constructor(transportName) {
29
+ const consoleTransport = this.createConsoleTransport(transportName);
30
+ this.initializeLogger(consoleTransport);
31
+ }
32
+ getFormatCustomizations() {
33
+ const padding = 7;
34
+ return [
35
+ winston.format.errors({
36
+ stack: true
37
+ }),
38
+ winston.format.splat(),
39
+ winston.format.colorize({
40
+ level: true
41
+ }),
42
+ winston.format.timestamp({
43
+ format: "D MMM, hh:mm:ss a"
44
+ }),
45
+ winston.format.printf((info) => {
46
+ const ts = String(info.timestamp ?? "");
47
+ const lvl = String(info.level).padEnd(padding);
48
+ const lbl = String(info.label ?? "");
49
+ const msg = String(info.message ?? "");
50
+ const base = `${ts} [${lvl}]: ${lbl} - ${msg}`;
51
+ const splatSym = Symbol.for("splat");
52
+ const raw = info[splatSym];
53
+ const extras = Array.isArray(raw) ? raw : [];
54
+ const cleaned = extras.filter((x) => !(x instanceof Error)).filter((x) => {
55
+ if (!x) return false;
56
+ if (typeof x !== "object") return true;
57
+ return Object.keys(x).length > 0;
58
+ });
59
+ let rendered = base;
60
+ if (typeof info.stack === "string") {
61
+ rendered += `
62
+ ${String(info.stack)}`;
63
+ }
64
+ if (cleaned.length) {
65
+ const parts = [];
66
+ for (const x of cleaned) {
67
+ if (typeof x === "string") parts.push(x);
68
+ else {
69
+ try {
70
+ parts.push(JSON.stringify(x, null, 2));
71
+ } catch {
72
+ parts.push(String(x));
73
+ }
74
+ }
75
+ }
76
+ rendered += `
77
+ ${parts.join(" ")}`;
78
+ }
79
+ return rendered;
80
+ })
81
+ ];
82
+ }
83
+ createConsoleTransport(transportName) {
84
+ return new winston.transports.Console({
85
+ format: winston.format.combine(winston.format.label({
86
+ label: transportName
87
+ }), ...this.getFormatCustomizations()),
88
+ level: envapt.Envapter.isDevelopment ? "silly" : envapt.Envapter.isStaging ? "debug" : "info"
89
+ });
90
+ }
91
+ initializeLogger(consoleTransport) {
92
+ const transportsArray = [
93
+ consoleTransport
94
+ ];
95
+ if (envapt.Envapter.isDevelopment) {
96
+ const maxSizeInMB = 10;
97
+ transportsArray.push(new winston.transports.File({
98
+ filename: "logs/application.log",
99
+ level: "debug",
100
+ format: winston.format.combine(winston.format.uncolorize(), winston.format.errors({
101
+ stack: true
102
+ }), winston.format.timestamp(), winston.format.json({
103
+ bigint: true,
104
+ space: 2
105
+ })),
106
+ maxsize: maxSizeInMB * 1024 * 1024,
107
+ maxFiles: 5,
108
+ tailable: true
109
+ }));
110
+ }
111
+ this.logger = winston.createLogger({
112
+ transports: transportsArray
113
+ });
114
+ }
115
+ /**
116
+ * Logs an error message with optional additional data.
117
+ *
118
+ * @param msg - The error message to log
119
+ * @param args - Additional data to include in the log entry
120
+ */
121
+ error(msg, ...args) {
122
+ this.logger.error(msg, ...args);
123
+ }
124
+ /**
125
+ * Logs a warning message with optional additional data.
126
+ *
127
+ * @param msg - The warning message to log
128
+ * @param args - Additional data to include in the log entry
129
+ */
130
+ warn(msg, ...args) {
131
+ this.logger.warn(msg, ...args);
132
+ }
133
+ /**
134
+ * Logs an informational message with optional additional data.
135
+ *
136
+ * @param msg - The informational message to log
137
+ * @param args - Additional data to include in the log entry
138
+ */
139
+ info(msg, ...args) {
140
+ this.logger.info(msg, ...args);
141
+ }
142
+ /**
143
+ * Logs an HTTP-related message with optional additional data.
144
+ *
145
+ * @param msg - The HTTP message to log
146
+ * @param args - Additional data to include in the log entry
147
+ */
148
+ http(msg, ...args) {
149
+ this.logger.http(msg, ...args);
150
+ }
151
+ /**
152
+ * Logs a verbose message with optional additional data.
153
+ *
154
+ * @param msg - The verbose message to log
155
+ * @param args - Additional data to include in the log entry
156
+ */
157
+ verbose(msg, ...args) {
158
+ this.logger.verbose(msg, ...args);
159
+ }
160
+ /**
161
+ * Logs a debug message with optional additional data.
162
+ *
163
+ * @param msg - The debug message to log
164
+ * @param args - Additional data to include in the log entry
165
+ */
166
+ debug(msg, ...args) {
167
+ this.logger.debug(msg, ...args);
168
+ }
169
+ /**
170
+ * Logs a silly/trace level message with optional additional data.
171
+ *
172
+ * @param msg - The silly message to log
173
+ * @param args - Additional data to include in the log entry
174
+ */
175
+ silly(msg, ...args) {
176
+ this.logger.silly(msg, ...args);
177
+ }
178
+ /**
179
+ * Static method to log an error message with a specific prefix.
180
+ * Creates or retrieves a logger instance for the given prefix.
181
+ *
182
+ * @param prefix - The logger prefix/label to use
183
+ * @param msg - The error message to log
184
+ * @param args - Additional data to include in the log entry
185
+ */
186
+ static Error(prefix, msg, ...args) {
187
+ const logger = this.instance(prefix);
188
+ logger.error(msg, ...args);
189
+ }
190
+ /**
191
+ * Static method to log an informational message with a specific prefix.
192
+ * Creates or retrieves a logger instance for the given prefix.
193
+ *
194
+ * @param prefix - The logger prefix/label to use
195
+ * @param msg - The informational message to log
196
+ * @param args - Additional data to include in the log entry
197
+ */
198
+ static Info(prefix, msg, ...args) {
199
+ const logger = this.instance(prefix);
200
+ logger.info(msg, ...args);
201
+ }
202
+ /**
203
+ * Static method to log a warning message with a specific prefix.
204
+ * Creates or retrieves a logger instance for the given prefix.
205
+ *
206
+ * @param prefix - The logger prefix/label to use
207
+ * @param msg - The warning message to log
208
+ * @param args - Additional data to include in the log entry
209
+ */
210
+ static Warn(prefix, msg, ...args) {
211
+ const logger = this.instance(prefix);
212
+ logger.warn(msg, ...args);
213
+ }
214
+ /**
215
+ * Static method to log a debug message with a specific prefix.
216
+ * Creates or retrieves a logger instance for the given prefix.
217
+ *
218
+ * @param prefix - The logger prefix/label to use
219
+ * @param msg - The debug message to log
220
+ * @param args - Additional data to include in the log entry
221
+ */
222
+ static Debug(prefix, msg, ...args) {
223
+ const logger = this.instance(prefix);
224
+ logger.debug(msg, ...args);
225
+ }
226
+ /**
227
+ * Static method to log a silly/trace level message with a specific prefix.
228
+ * Creates or retrieves a logger instance for the given prefix.
229
+ *
230
+ * @param prefix - The logger prefix/label to use
231
+ * @param msg - The silly message to log
232
+ * @param args - Additional data to include in the log entry
233
+ */
234
+ static Silly(prefix, msg, ...args) {
235
+ const logger = this.instance(prefix);
236
+ logger.silly(msg, ...args);
237
+ }
238
+ };
239
+ var CoordinatedLifecycle = class {
240
+ static {
241
+ __name(this, "CoordinatedLifecycle");
242
+ }
243
+ phaseOrder;
244
+ phaseEnum;
245
+ logger;
246
+ events = new events.EventEmitter();
247
+ tasksMap = /* @__PURE__ */ new Map();
248
+ constructor(loggerName, phaseOrder, phaseEnum) {
249
+ this.phaseOrder = phaseOrder;
250
+ this.phaseEnum = phaseEnum;
251
+ this.logger = new Logger(loggerName);
252
+ this.phaseOrder.forEach((phase) => this.tasksMap.set(phase, []));
253
+ }
254
+ /**
255
+ * Adds a lifecycle task to a specific phase.
256
+ *
257
+ * Tasks are executed in phase order during lifecycle operations.
258
+ * Each task has a timeout to prevent hanging operations.
259
+ *
260
+ * @param phase - The lifecycle phase to add the task to
261
+ * @param taskName - Unique name for the task (used for logging and removal)
262
+ * @param task - Async function to execute during the phase
263
+ * @param timeoutMs - Maximum time allowed for task execution in milliseconds
264
+ * @example
265
+ * ```typescript
266
+ * lifecycle.addTask(StartupPhase.Services, 'start-database', async () => {
267
+ * await database.connect();
268
+ * }, 10000);
269
+ * ```
270
+ */
271
+ addTask(phase, taskName, task, timeoutMs) {
272
+ if (!this.canAddTask()) return;
273
+ const tasks = this.tasksMap.get(phase);
274
+ if (!tasks) throw new Error(`Unknown phase: ${phase}`);
275
+ tasks.push({
276
+ name: taskName,
277
+ task,
278
+ timeout: timeoutMs
279
+ });
280
+ this.logger.debug(`${chalk__default.default.italic("Added")} ${this.getTaskType()} task ${chalk__default.default.bold.cyan(taskName)} to phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}`);
281
+ }
282
+ /**
283
+ * Removes a lifecycle task from a specific phase.
284
+ *
285
+ * @param phase - The lifecycle phase to remove the task from
286
+ * @param taskName - Name of the task to remove
287
+ * @returns True if the task was found and removed, false otherwise
288
+ */
289
+ removeTask(phase, taskName) {
290
+ if (!this.canRemoveTask()) return false;
291
+ const tasks = this.tasksMap.get(phase);
292
+ if (!tasks) return false;
293
+ const initialLength = tasks.length;
294
+ const filteredTasks = tasks.filter((task) => task.name !== taskName);
295
+ this.tasksMap.set(phase, filteredTasks);
296
+ const removed = initialLength !== filteredTasks.length;
297
+ if (removed) {
298
+ this.logger.debug(`${chalk__default.default.italic("Removed")} ${this.getTaskType()} task ${chalk__default.default.bold.cyan(taskName)} from phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}`);
299
+ }
300
+ return removed;
301
+ }
302
+ /**
303
+ * Run all tasks in a specific phase
304
+ */
305
+ async runPhase(phase) {
306
+ const tasks = this.tasksMap.get(phase) ?? [];
307
+ if (tasks.length === 0) {
308
+ this.logger.warn(`No tasks to run in phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}`);
309
+ return;
310
+ }
311
+ this.logger.info(`${chalk__default.default.bold.yellow("Running")} ${this.getTaskType()} phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])} with ${chalk__default.default.bold.cyan(tasks.length)} tasks`);
312
+ this.emit(`phase:${phase}:start`);
313
+ const results = await this.executeTasksInPhase(phase, tasks);
314
+ const failures = results.filter((r) => r.status === "rejected").length;
315
+ if (failures > 0) {
316
+ const errorMessage = `Phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])} completed with ${chalk__default.default.bold.red(failures)} failed tasks`;
317
+ throw new Error(errorMessage);
318
+ } else {
319
+ this.logger.info(`Phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])} ${chalk__default.default.bold.green("completed successfully")}`);
320
+ }
321
+ this.emit(`phase:${phase}:complete`);
322
+ }
323
+ /**
324
+ * Run a single task with timeout
325
+ */
326
+ async runTaskWithTimeout(phase, task) {
327
+ this.logger.info(`${chalk__default.default.italic("Starting")} task ${chalk__default.default.bold.cyan(task.name)} in phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}`);
328
+ try {
329
+ await Promise.race([
330
+ task.task(),
331
+ new Promise((_, reject) => {
332
+ setTimeout(() => {
333
+ reject(new Error(`Task '${task.name}' timed out after ${task.timeout}ms`));
334
+ }, task.timeout);
335
+ })
336
+ ]);
337
+ this.logger.info(`${chalk__default.default.italic("Completed")} task ${chalk__default.default.bold.cyan(task.name)} in phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}`);
338
+ } catch (error) {
339
+ this.logger.error(`${chalk__default.default.italic("Failed")} task ${chalk__default.default.bold.cyan(task.name)} in phase ${chalk__default.default.bold.magenta(this.phaseEnum[phase])}:`, error);
340
+ throw error;
341
+ }
342
+ }
343
+ /**
344
+ * Subscribe to lifecycle events
345
+ */
346
+ on(event, listener) {
347
+ this.events.on(event, listener);
348
+ }
349
+ /**
350
+ * Unsubscribe from lifecycle events
351
+ */
352
+ off(event, listener) {
353
+ this.events.off(event, listener);
354
+ }
355
+ emit(event, ...args) {
356
+ return this.events.emit(event, ...args);
357
+ }
358
+ };
359
+
360
+ // src/Lifecycle/CoordinatedShutdown.ts
361
+ function _ts_decorate(decorators, target, key, desc) {
362
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
363
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
364
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
365
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
366
+ }
367
+ __name(_ts_decorate, "_ts_decorate");
368
+ function _ts_metadata(k, v) {
369
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
370
+ }
371
+ __name(_ts_metadata, "_ts_metadata");
372
+ var ShutdownPhase = /* @__PURE__ */ (function(ShutdownPhase2) {
373
+ ShutdownPhase2[ShutdownPhase2["StopAcceptingRequests"] = 1] = "StopAcceptingRequests";
374
+ ShutdownPhase2[ShutdownPhase2["StopServices"] = 2] = "StopServices";
375
+ ShutdownPhase2[ShutdownPhase2["ExternalResources"] = 3] = "ExternalResources";
376
+ ShutdownPhase2[ShutdownPhase2["DiscordCleanup"] = 4] = "DiscordCleanup";
377
+ ShutdownPhase2[ShutdownPhase2["FinalCleanup"] = 5] = "FinalCleanup";
378
+ return ShutdownPhase2;
379
+ })({});
380
+ var PHASE_ORDER = [
381
+ 1,
382
+ 2,
383
+ 3,
384
+ 4,
385
+ 5
386
+ ];
387
+ var LOG_FLUSH_DELAY_MS = 500;
388
+ var CoordinatedShutdown = class extends CoordinatedLifecycle {
389
+ static {
390
+ __name(this, "CoordinatedShutdown");
391
+ }
392
+ isShuttingDown = false;
393
+ exitCode = 0;
394
+ constructor() {
395
+ super("CoordinatedShutdown", PHASE_ORDER, ShutdownPhase);
396
+ this.registerSignalHandlers();
397
+ }
398
+ canAddTask() {
399
+ return this.isShutdownEnabled;
400
+ }
401
+ canRemoveTask() {
402
+ return true;
403
+ }
404
+ getTaskType() {
405
+ return "shutdown";
406
+ }
407
+ async executeTasksInPhase(phase, tasks) {
408
+ const results = [];
409
+ for (const task of tasks) {
410
+ results.push(await Promise.resolve().then(() => this.runTaskWithTimeout(phase, task)).then(
411
+ () => ({
412
+ status: "fulfilled",
413
+ value: void 0
414
+ }),
415
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
416
+ (reason) => ({
417
+ status: "rejected",
418
+ reason
419
+ })
420
+ ));
421
+ }
422
+ return results;
423
+ }
424
+ registerSignalHandlers() {
425
+ if (!this.isShutdownEnabled) return;
426
+ process.on("SIGTERM", () => {
427
+ this.logger.info(`Received ${chalk__default.default.yellow.bold("SIGTERM")} signal`);
428
+ void this.run(0);
429
+ });
430
+ process.on("SIGINT", () => {
431
+ this.logger.info(`Received ${chalk__default.default.yellow.bold("SIGINT")} signal`);
432
+ void this.run(0);
433
+ });
434
+ }
435
+ /**
436
+ * Adds a task to a specific shutdown phase with timeout.
437
+ *
438
+ * @param phase - The shutdown phase from {@link ShutdownPhase}
439
+ * @param taskName - Unique identifier for the task
440
+ * @param task - Async function to execute
441
+ * @param timeoutMs - Task timeout in milliseconds (default: 5000)
442
+ */
443
+ addTask(phase, taskName, task, timeoutMs = 5e3) {
444
+ super.addTask(phase, taskName, task, timeoutMs);
445
+ }
446
+ /**
447
+ * Removes a task from a specific shutdown phase.
448
+ *
449
+ * @param phase - The shutdown phase to remove from
450
+ * @param taskName - Name of the task to remove
451
+ * @returns True if task was found and removed
452
+ */
453
+ removeTask(phase, taskName) {
454
+ return super.removeTask(phase, taskName);
455
+ }
456
+ /**
457
+ * Executes the coordinated shutdown sequence.
458
+ *
459
+ * Runs all registered tasks across shutdown phases in reverse order.
460
+ * Tasks within each phase are executed in parallel for faster shutdown.
461
+ * Process exits with the specified code when complete.
462
+ *
463
+ * @param exitCode - Process exit code (default: 0)
464
+ * @returns Promise that resolves when shutdown is complete
465
+ * @example
466
+ * ```typescript
467
+ * shutdown.addTask(ShutdownPhase.Services, 'database', () => db.disconnect(), 5000);
468
+ * await shutdown.run(0); // Graceful shutdown
469
+ * ```
470
+ */
471
+ async run(exitCode = 0) {
472
+ if (this.isShuttingDown) {
473
+ this.logger.warn("Shutdown sequence already in progress");
474
+ return;
475
+ }
476
+ this.isShuttingDown = true;
477
+ this.exitCode = exitCode;
478
+ this.logger.info(`${chalk__default.default.bold.yellow("Starting")} coordinated shutdown with exit code ${chalk__default.default.bold.cyan(exitCode)}`);
479
+ this.emit("shutdown:start");
480
+ try {
481
+ for (const phase of PHASE_ORDER) {
482
+ await this.runPhase(phase);
483
+ }
484
+ this.logger.info(`${chalk__default.default.bold.green("Coordinated shutdown completed")} successfully`);
485
+ this.emit("shutdown:complete");
486
+ } catch (error) {
487
+ this.logger.error(`${chalk__default.default.bold.red("Coordinated shutdown failed")}`);
488
+ this.emit("shutdown:error", error);
489
+ } finally {
490
+ this.logger.info(`${chalk__default.default.bold.red("Exiting")} process with code ${chalk__default.default.bold.cyan(this.exitCode)}`);
491
+ setTimeout(() => {
492
+ process.exit(this.exitCode);
493
+ }, LOG_FLUSH_DELAY_MS);
494
+ }
495
+ }
496
+ /**
497
+ * Subscribe to shutdown events
498
+ */
499
+ on(event, listener) {
500
+ super.on(event, listener);
501
+ }
502
+ /**
503
+ * Unsubscribe from shutdown events
504
+ */
505
+ off(event, listener) {
506
+ super.off(event, listener);
507
+ }
508
+ };
509
+ _ts_decorate([
510
+ envapt.Envapt("SHUTDOWN_IS_ENABLED", {
511
+ fallback: false
512
+ }),
513
+ _ts_metadata("design:type", Boolean)
514
+ ], CoordinatedShutdown.prototype, "isShutdownEnabled", void 0);
515
+
516
+ // src/HealthCheck.ts
517
+ function _ts_decorate2(decorators, target, key, desc) {
518
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
519
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
520
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
521
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
522
+ }
523
+ __name(_ts_decorate2, "_ts_decorate");
524
+ function _ts_metadata2(k, v) {
525
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
526
+ }
527
+ __name(_ts_metadata2, "_ts_metadata");
528
+ var HTTP_OK = 200;
529
+ var HTTP_NOT_FOUND = 404;
530
+ var HealthCheck = class {
531
+ static {
532
+ __name(this, "HealthCheck");
533
+ }
534
+ logger = new Logger("HealthCheck");
535
+ server;
536
+ constructor(shutdown) {
537
+ shutdown.addTask(ShutdownPhase.StopServices, "stop-healthcheck-server", async () => await this.stop());
538
+ }
539
+ /**
540
+ * Starts the health check server.
541
+ * @returns Promise that resolves when the server is listening
542
+ */
543
+ async init() {
544
+ return new Promise((resolve, reject) => {
545
+ this.server = http.createServer((req, res) => {
546
+ if (req.method === "GET" && req.url === this.path) {
547
+ res.writeHead(HTTP_OK, {
548
+ "Content-Type": "application/json"
549
+ });
550
+ res.end(JSON.stringify({
551
+ status: "ok",
552
+ timestamp: Date.now()
553
+ }));
554
+ } else {
555
+ res.writeHead(HTTP_NOT_FOUND, {
556
+ "Content-Type": "application/json"
557
+ });
558
+ res.end(JSON.stringify({
559
+ status: "not found"
560
+ }));
561
+ }
562
+ });
563
+ this.server.on("error", reject);
564
+ this.server.once("listening", () => resolve());
565
+ this.server.listen(this.port, () => {
566
+ this.logger.info(`${chalk__default.default.green.bold("\u2713")} Health check server listening on ${chalk__default.default.cyan(`http://localhost:${this.port}${this.path}`)}`);
567
+ });
568
+ });
569
+ }
570
+ /**
571
+ * Stops the health check server.
572
+ *
573
+ * @returns Promise that resolves when the server is closed
574
+ */
575
+ stop() {
576
+ if (this.server !== void 0) {
577
+ const server = this.server;
578
+ return new Promise((resolve) => {
579
+ server.once("close", () => resolve());
580
+ server.close(() => {
581
+ this.logger.info(chalk__default.default.bold.red("Health check server stopped"));
582
+ });
583
+ });
584
+ }
585
+ return Promise.resolve();
586
+ }
587
+ };
588
+ _ts_decorate2([
589
+ envapt.Envapt("HEALTH_CHECK_PORT", {
590
+ fallback: 6956
591
+ }),
592
+ _ts_metadata2("design:type", Number)
593
+ ], HealthCheck.prototype, "port", void 0);
594
+ _ts_decorate2([
595
+ envapt.Envapt("HEALTH_CHECK_PATH", {
596
+ fallback: "/healthcheck"
597
+ }),
598
+ _ts_metadata2("design:type", String)
599
+ ], HealthCheck.prototype, "path", void 0);
600
+ var CooldownManager = class {
601
+ static {
602
+ __name(this, "CooldownManager");
603
+ }
604
+ window;
605
+ Err;
606
+ msg;
607
+ map = /* @__PURE__ */ new Map();
608
+ /**
609
+ * Creates a new CooldownManager instance.
610
+ *
611
+ * @param opts - Configuration options for the cooldown behavior
612
+ */
613
+ constructor(opts = {}) {
614
+ this.window = opts.cooldown ?? 1e3;
615
+ this.Err = opts.err ?? Error;
616
+ this.msg = opts.message ?? "Cooldown active";
617
+ }
618
+ /**
619
+ * Records usage timestamp for a key without any cooldown checks.
620
+ *
621
+ * @param key - The unique identifier for the cooldown entry
622
+ */
623
+ set(key) {
624
+ this.map.set(key, Date.now());
625
+ }
626
+ /**
627
+ * Verifies cooldown status for a key and updates timestamp if not active.
628
+ *
629
+ * If the cooldown is still active, throws the configured error.
630
+ * If not active, updates the timestamp and returns successfully.
631
+ *
632
+ * @param key - The unique identifier to check cooldown for
633
+ * @throws An {@link Err} When the cooldown is still active for the given key
634
+ */
635
+ check(key) {
636
+ const now = Date.now();
637
+ const last = this.map.get(key);
638
+ const remaining = this.window - (now - (last ?? 0));
639
+ if (envapt.Envapter.isDevelopment && remaining > 0) {
640
+ Logger.Debug("CooldownManager", `${key} - ${remaining}ms remaining`);
641
+ }
642
+ if (last !== void 0 && remaining > 0) {
643
+ throw new this.Err(this.msg, remaining);
644
+ }
645
+ this.map.set(key, now);
646
+ }
647
+ /**
648
+ * Checks if a key is currently cooling down without updating timestamp.
649
+ *
650
+ * @param key - The unique identifier to check
651
+ * @returns True if the key is still cooling down, false otherwise
652
+ */
653
+ isActive(key) {
654
+ const last = this.map.get(key);
655
+ return last !== void 0 && Date.now() - last < this.window;
656
+ }
657
+ /**
658
+ * Removes a key from the cooldown map.
659
+ *
660
+ * @param key - The unique identifier to remove (useful for manual resets)
661
+ */
662
+ clear(key) {
663
+ this.map.delete(key);
664
+ }
665
+ };
666
+ var StartupPhase = /* @__PURE__ */ (function(StartupPhase2) {
667
+ StartupPhase2[StartupPhase2["Validation"] = 1] = "Validation";
668
+ StartupPhase2[StartupPhase2["Discovery"] = 2] = "Discovery";
669
+ StartupPhase2[StartupPhase2["Registration"] = 3] = "Registration";
670
+ StartupPhase2[StartupPhase2["Configuration"] = 4] = "Configuration";
671
+ StartupPhase2[StartupPhase2["Instantiation"] = 5] = "Instantiation";
672
+ StartupPhase2[StartupPhase2["Activation"] = 6] = "Activation";
673
+ StartupPhase2[StartupPhase2["Ready"] = 7] = "Ready";
674
+ return StartupPhase2;
675
+ })({});
676
+ var PHASE_ORDER2 = [
677
+ 1,
678
+ 2,
679
+ 3,
680
+ 4,
681
+ 5,
682
+ 6,
683
+ 7
684
+ ];
685
+ var CoordinatedStartup = class extends CoordinatedLifecycle {
686
+ static {
687
+ __name(this, "CoordinatedStartup");
688
+ }
689
+ isStartingUp = false;
690
+ hasStarted = false;
691
+ constructor() {
692
+ super("CoordinatedStartup", PHASE_ORDER2, StartupPhase);
693
+ }
694
+ /**
695
+ * Adds a task to a specific startup phase with timeout.
696
+ *
697
+ * @param phase - The startup phase from {@link StartupPhase}
698
+ * @param taskName - Unique identifier for the task
699
+ * @param task - Async function to execute
700
+ * @param timeoutMs - Task timeout in milliseconds (default: 10000)
701
+ */
702
+ addTask(phase, taskName, task, timeoutMs = 1e4) {
703
+ super.addTask(phase, taskName, task, timeoutMs);
704
+ }
705
+ canAddTask() {
706
+ if (this.hasStarted) {
707
+ throw new Error("Cannot add tasks after startup sequence has already completed");
708
+ }
709
+ if (this.isStartingUp) {
710
+ throw new Error("Cannot add tasks while startup sequence is in progress");
711
+ }
712
+ return true;
713
+ }
714
+ canRemoveTask() {
715
+ if (this.isStartingUp) {
716
+ throw new Error("Cannot remove tasks while startup sequence is in progress");
717
+ }
718
+ return true;
719
+ }
720
+ getTaskType() {
721
+ return "startup";
722
+ }
723
+ async executeTasksInPhase(phase, tasks) {
724
+ const results = [];
725
+ for (const task of tasks) {
726
+ results.push(await Promise.resolve().then(() => this.runTaskWithTimeout(phase, task)).then(
727
+ () => ({
728
+ status: "fulfilled",
729
+ value: void 0
730
+ }),
731
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
732
+ (reason) => ({
733
+ status: "rejected",
734
+ reason
735
+ })
736
+ ));
737
+ }
738
+ return results;
739
+ }
740
+ /**
741
+ * Executes the coordinated startup sequence.
742
+ *
743
+ * Runs all registered tasks across startup phases in the correct order.
744
+ * Each phase completes before the next phase begins. Tasks within a phase
745
+ * are executed sequentially to maintain predictable initialization.
746
+ *
747
+ * @returns Promise that resolves when startup is complete
748
+ * @throws An {@link Error} If startup fails or is called multiple times
749
+ * @example
750
+ * ```typescript
751
+ * const startup = new CoordinatedStartup();
752
+ * startup.addTask(StartupPhase.Services, 'database', () => db.connect(), 10000);
753
+ * await startup.run();
754
+ * ```
755
+ */
756
+ async run() {
757
+ if (this.hasStarted) {
758
+ this.logger.warn("Startup sequence has already completed");
759
+ return;
760
+ }
761
+ if (this.isStartingUp) {
762
+ this.logger.warn("Startup sequence already in progress");
763
+ return;
764
+ }
765
+ this.isStartingUp = true;
766
+ this.logger.info(`${chalk__default.default.bold.green("Starting")} coordinated startup sequence`);
767
+ this.emit("startup:start");
768
+ try {
769
+ for (const phase of PHASE_ORDER2) await this.runPhase(phase);
770
+ this.hasStarted = true;
771
+ this.logger.info(`${chalk__default.default.bold.green("Coordinated startup completed")} successfully`);
772
+ this.emit("startup:complete");
773
+ } catch (error) {
774
+ this.logger.error(`${chalk__default.default.bold.red("Coordinated startup failed")}`);
775
+ this.emit("startup:error", error);
776
+ throw error;
777
+ } finally {
778
+ this.isStartingUp = false;
779
+ }
780
+ }
781
+ /**
782
+ * Subscribe to startup events
783
+ */
784
+ on(event, listener) {
785
+ super.on(event, listener);
786
+ }
787
+ /**
788
+ * Unsubscribe from startup events
789
+ */
790
+ off(event, listener) {
791
+ super.off(event, listener);
792
+ }
793
+ /**
794
+ * Check if startup has completed
795
+ */
796
+ get isReady() {
797
+ return this.hasStarted;
798
+ }
799
+ /**
800
+ * Check if startup is currently running
801
+ */
802
+ get isRunning() {
803
+ return this.isStartingUp;
804
+ }
805
+ };
806
+
807
+ exports.CooldownManager = CooldownManager;
808
+ exports.CoordinatedLifecycle = CoordinatedLifecycle;
809
+ exports.CoordinatedShutdown = CoordinatedShutdown;
810
+ exports.CoordinatedStartup = CoordinatedStartup;
811
+ exports.HealthCheck = HealthCheck;
812
+ exports.Logger = Logger;
813
+ exports.ShutdownPhase = ShutdownPhase;
814
+ exports.StartupPhase = StartupPhase;
815
+ //# sourceMappingURL=index.cjs.map
816
+ //# sourceMappingURL=index.cjs.map