@darthcav/ts-utils 0.10.10 → 0.12.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.
Files changed (86) hide show
  1. package/README.md +170 -39
  2. package/dist/index.d.ts +16 -9
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +8 -8
  5. package/dist/index.js.map +1 -1
  6. package/dist/loggers/getConsoleLogger.d.ts +10 -4
  7. package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
  8. package/dist/loggers/getConsoleLogger.js +36 -9
  9. package/dist/loggers/getConsoleLogger.js.map +1 -1
  10. package/dist/loggers/getDummyLogger.d.ts +14 -3
  11. package/dist/loggers/getDummyLogger.d.ts.map +1 -1
  12. package/dist/loggers/getDummyLogger.js +29 -11
  13. package/dist/loggers/getDummyLogger.js.map +1 -1
  14. package/dist/main.d.ts +83 -51
  15. package/dist/main.d.ts.map +1 -1
  16. package/dist/main.js +200 -40
  17. package/dist/main.js.map +1 -1
  18. package/dist/millisecondsToString.d.ts +1 -1
  19. package/dist/millisecondsToString.d.ts.map +1 -1
  20. package/dist/millisecondsToString.js +1 -1
  21. package/dist/millisecondsToString.js.map +1 -1
  22. package/dist/monitorMemory.d.ts +25 -7
  23. package/dist/monitorMemory.d.ts.map +1 -1
  24. package/dist/monitorMemory.js +52 -14
  25. package/dist/monitorMemory.js.map +1 -1
  26. package/dist/noop.d.ts +1 -2
  27. package/dist/noop.d.ts.map +1 -1
  28. package/dist/noop.js +1 -2
  29. package/dist/noop.js.map +1 -1
  30. package/dist/{os-utils.d.ts → osRelease.d.ts} +11 -7
  31. package/dist/osRelease.d.ts.map +1 -0
  32. package/dist/osRelease.js +153 -0
  33. package/dist/osRelease.js.map +1 -0
  34. package/dist/type-testing/Assert.d.ts +23 -0
  35. package/dist/type-testing/Assert.d.ts.map +1 -0
  36. package/dist/type-testing/Assert.js +2 -0
  37. package/dist/type-testing/Assert.js.map +1 -0
  38. package/dist/type-testing/Equal.d.ts +25 -0
  39. package/dist/type-testing/Equal.d.ts.map +1 -0
  40. package/dist/type-testing/Equal.js +2 -0
  41. package/dist/type-testing/Equal.js.map +1 -0
  42. package/dist/type-testing/Extends.d.ts +22 -0
  43. package/dist/type-testing/Extends.d.ts.map +1 -0
  44. package/dist/type-testing/Extends.js +2 -0
  45. package/dist/type-testing/Extends.js.map +1 -0
  46. package/dist/type-testing/IsAny.d.ts +17 -0
  47. package/dist/type-testing/IsAny.d.ts.map +1 -0
  48. package/dist/type-testing/IsAny.js +2 -0
  49. package/dist/type-testing/IsAny.js.map +1 -0
  50. package/dist/type-testing/IsNever.d.ts +17 -0
  51. package/dist/type-testing/IsNever.d.ts.map +1 -0
  52. package/dist/type-testing/IsNever.js +2 -0
  53. package/dist/type-testing/IsNever.js.map +1 -0
  54. package/dist/type-testing/IsUnknown.d.ts +20 -0
  55. package/dist/type-testing/IsUnknown.d.ts.map +1 -0
  56. package/dist/type-testing/IsUnknown.js +2 -0
  57. package/dist/type-testing/IsUnknown.js.map +1 -0
  58. package/dist/type-testing/Not.d.ts +17 -0
  59. package/dist/type-testing/Not.d.ts.map +1 -0
  60. package/dist/type-testing/Not.js +2 -0
  61. package/dist/type-testing/Not.js.map +1 -0
  62. package/dist/types.d.ts +42 -2
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js +61 -16
  65. package/dist/types.js.map +1 -1
  66. package/package.json +10 -12
  67. package/src/index.ts +26 -7
  68. package/src/loggers/getConsoleLogger.ts +41 -8
  69. package/src/loggers/getDummyLogger.ts +31 -11
  70. package/src/main.ts +249 -126
  71. package/src/millisecondsToString.ts +1 -4
  72. package/src/monitorMemory.ts +58 -19
  73. package/src/noop.ts +1 -3
  74. package/src/osRelease.ts +172 -0
  75. package/src/type-testing/Assert.ts +22 -0
  76. package/src/type-testing/Equal.ts +27 -0
  77. package/src/type-testing/Extends.ts +21 -0
  78. package/src/type-testing/IsAny.ts +16 -0
  79. package/src/type-testing/IsNever.ts +16 -0
  80. package/src/type-testing/IsUnknown.ts +21 -0
  81. package/src/type-testing/Not.ts +16 -0
  82. package/src/types.ts +65 -17
  83. package/dist/os-utils.d.ts.map +0 -1
  84. package/dist/os-utils.js +0 -94
  85. package/dist/os-utils.js.map +0 -1
  86. package/src/os-utils.ts +0 -110
package/dist/main.d.ts CHANGED
@@ -1,76 +1,108 @@
1
- import type { Logger } from "@logtape/logtape";
1
+ import { type Logger } from "@logtape/logtape";
2
2
  /**
3
3
  * A function that performs the actual application launch after process
4
4
  * lifecycle handlers have been set up by {@link main}. Use a closure to
5
5
  * capture any context needed (e.g. a logger).
6
+ *
7
+ * It may be asynchronous: if it throws or its promise rejects, {@link main}
8
+ * logs the failure and exits the process with status `1`.
9
+ */
10
+ export type LauncherFunction = () => void | Promise<void>;
11
+ /**
12
+ * Options for {@link main}. All of them are optional.
6
13
  */
7
- export type LauncherFunction = () => void;
14
+ export type MainOptions = {
15
+ /**
16
+ * Function invoked after all process handlers are registered. Use a
17
+ * closure to capture any context needed (e.g. a logger).
18
+ */
19
+ launcher?: LauncherFunction;
20
+ /**
21
+ * When greater than `0`, starts periodic memory logging every
22
+ * `monitorMemoryHours` hours via {@link monitorMemory} (which validates
23
+ * the value). Must be `0` or a positive finite number; negative values
24
+ * and `NaN` throw. Defaults to `0` (disabled).
25
+ */
26
+ monitorMemoryHours?: number;
27
+ /**
28
+ * When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
29
+ * log, flush the logs, and stop the process. Set to `false` when the
30
+ * application manages its own graceful shutdown (e.g. closing servers or
31
+ * database connections).
32
+ */
33
+ defaultInterruptionHandler?: boolean;
34
+ /**
35
+ * Maximum time in milliseconds to wait for the logtape sinks to flush
36
+ * before the process exits. Must be between `0` and 2³¹ − 1. Defaults to
37
+ * `3000`.
38
+ */
39
+ flushTimeoutMs?: number;
40
+ };
8
41
  /**
9
42
  * Bootstraps an application process: logs startup information, registers
10
43
  * handlers for `SIGINT`, `SIGTERM`, `uncaughtException`, and
11
- * `unhandledRejection`, then delegates to the optional launcher function.
44
+ * `unhandledRejection`, optionally starts memory monitoring, then runs the
45
+ * optional launcher function.
12
46
  *
13
- * The three optional parameters — `launcher`, `monitorMemoryHours`, and
14
- * `defaultInterruptionHandler` — have distinct types and can be supplied in
15
- * any subset and in that order, omitting whichever are not needed:
47
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
48
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
49
+ * `debug` level only, since they can reveal sensitive flags such as
50
+ * `--inspect=0.0.0.0` or `--require` paths.
16
51
  *
17
- * | Call | launcher | monitorMemoryHours | defaultInterruptionHandler |
18
- * |------|----------|--------------------|---------------------------|
19
- * | `main(name, logger)` | — | 0 | true |
20
- * | `main(name, logger, fn)` | fn | 0 | true |
21
- * | `main(name, logger, 2)` | — | 2 | true |
22
- * | `main(name, logger, false)` | — | 0 | false |
23
- * | `main(name, logger, fn, 2)` | fn | 2 | true |
24
- * | `main(name, logger, fn, false)` | fn | 0 | false |
25
- * | `main(name, logger, 2, false)` | — | 2 | false |
26
- * | `main(name, logger, fn, 2, false)` | fn | 2 | false |
52
+ * Before the process exits, the configured logtape sinks are flushed and
53
+ * disposed (for at most `flushTimeoutMs`, 3 seconds by default), so buffered
54
+ * or asynchronous sinks do not lose the final messages. On `SIGINT`/`SIGTERM`
55
+ * the signal is logged at `info` level and then re-raised, so the process ends
56
+ * as killed by that signal (exit status 130/143), which shells and
57
+ * supervisors such as systemd treat as a clean stop. If another listener for
58
+ * that signal is registered, the process exits with status
59
+ * `128 + signal number` instead. Uncaught exceptions, unhandled rejections,
60
+ * and launcher failures exit with status `1`. A second signal or error during
61
+ * the flush exits immediately.
62
+ *
63
+ * Only one `main` call can be active at a time: calling it again before
64
+ * running the returned teardown function throws, instead of registering a
65
+ * second set of handlers.
27
66
  *
28
67
  * @param name - Human-readable application name used in log output.
29
68
  * @param logger - Logger instance used for all startup and lifecycle messages.
69
+ * @param options - Optional {@link MainOptions}.
70
+ * @returns A teardown function that removes the process handlers registered
71
+ * by this call and stops the memory monitoring, allowing `main` to be called
72
+ * again (e.g. in tests). It does not exit the process; calling it more than
73
+ * once is harmless.
74
+ * @throws {TypeError} If `options` is not an object.
75
+ * @throws {Error} If another `main` call is still active.
76
+ * @throws {RangeError} If `monitorMemoryHours` or `flushTimeoutMs` is out of
77
+ * range. Nothing is registered in that case.
30
78
  *
31
- * @example Without optional parameters:
79
+ * @example Without options:
32
80
  * ```ts
33
81
  * main("my-app", logger)
34
82
  * ```
35
83
  *
36
- * @example With a launcher:
84
+ * @example With an async launcher and memory monitoring every 2 hours:
37
85
  * ```ts
38
- * main("my-app", logger, () => startServer())
86
+ * main("my-app", logger, {
87
+ * launcher: async () => {
88
+ * await connectToDatabase()
89
+ * startServer()
90
+ * },
91
+ * monitorMemoryHours: 2,
92
+ * })
39
93
  * ```
40
94
  *
41
- * @example With memory monitoring every 2 hours:
95
+ * @example Managing graceful shutdown in the application:
42
96
  * ```ts
43
- * main("my-app", logger, 2)
44
- * main("my-app", logger, () => startServer(), 2)
97
+ * const teardown = main("my-app", logger, {
98
+ * launcher: () => startServer(),
99
+ * defaultInterruptionHandler: false,
100
+ * })
101
+ * process.once("SIGTERM", async () => {
102
+ * await server.close()
103
+ * teardown()
104
+ * })
45
105
  * ```
46
- *
47
- * @example Disable the built-in interruption handler:
48
- * ```ts
49
- * main("my-app", logger, false)
50
- * main("my-app", logger, () => startServer(), false)
51
- * main("my-app", logger, 2, false)
52
- * main("my-app", logger, () => startServer(), 2, false)
53
- * ```
54
- */
55
- export declare function main(name: string, logger: Logger): void;
56
- export declare function main(name: string, logger: Logger, launcher: LauncherFunction): void;
57
- export declare function main(name: string, logger: Logger, monitorMemoryHours: number): void;
58
- export declare function main(name: string, logger: Logger, defaultInterruptionHandler: boolean): void;
59
- export declare function main(name: string, logger: Logger, launcher: LauncherFunction, monitorMemoryHours: number): void;
60
- export declare function main(name: string, logger: Logger, launcher: LauncherFunction, defaultInterruptionHandler: boolean): void;
61
- export declare function main(name: string, logger: Logger, monitorMemoryHours: number, defaultInterruptionHandler: boolean): void;
62
- /**
63
- * @param name - Human-readable application name used in log output.
64
- * @param logger - Logger instance used for all startup and lifecycle messages.
65
- * @param launcher - Optional function invoked after all process handlers are
66
- * registered. Use a closure to capture any context needed (e.g. a logger).
67
- * @param monitorMemoryHours - When greater than `0`, starts periodic memory
68
- * logging every `monitorMemoryHours` hours via {@link monitorMemory}.
69
- * Defaults to `0` (disabled).
70
- * @param defaultInterruptionHandler - When `true` (default), registers `SIGINT`
71
- * and `SIGTERM` handlers that log and exit cleanly. Set to `false` when the
72
- * application manages its own graceful shutdown (e.g. closing servers or
73
- * database connections).
74
106
  */
75
- export declare function main(name: string, logger: Logger, launcher: LauncherFunction, monitorMemoryHours: number, defaultInterruptionHandler: boolean): void;
107
+ export declare function main(name: string, logger: Logger, options?: MainOptions): () => void;
76
108
  //# sourceMappingURL=main.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAG9C;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAA;AAEzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;AACxD,wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,gBAAgB,GAC3B,IAAI,CAAA;AACP,wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,kBAAkB,EAAE,MAAM,GAC3B,IAAI,CAAA;AACP,wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,0BAA0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wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,WAAW,GACtB,MAAM,IAAI,CA0IZ"}
package/dist/main.js CHANGED
@@ -1,55 +1,215 @@
1
+ import { constants } from "node:os";
1
2
  import process, { env, execArgv, pid, title } from "node:process";
2
- import monitorMemory from "./monitorMemory.js";
3
- export function main(name, logger, arg3, arg4, arg5) {
4
- let launcher;
5
- let monitorMemoryHours = 0;
6
- let defaultInterruptionHandler = true;
7
- if (typeof arg3 === "function") {
8
- launcher = arg3;
9
- if (typeof arg4 === "number") {
10
- monitorMemoryHours = arg4;
11
- if (typeof arg5 === "boolean") {
12
- defaultInterruptionHandler = arg5;
13
- }
14
- }
15
- else if (typeof arg4 === "boolean") {
16
- defaultInterruptionHandler = arg4;
17
- }
3
+ import { dispose } from "@logtape/logtape";
4
+ import { monitorMemory } from "./monitorMemory.js";
5
+ /**
6
+ * Default upper bound for flushing log sinks before the process exits, so a
7
+ * hanging sink cannot block shutdown.
8
+ */
9
+ const DEFAULT_FLUSH_TIMEOUT_MS = 3_000;
10
+ /**
11
+ * Longest delay `setTimeout` supports (2³¹ − 1 ms). Node.js silently replaces
12
+ * larger delays with 1 ms.
13
+ */
14
+ const MAX_FLUSH_TIMEOUT_MS = 2_147_483_647;
15
+ /** Whether a {@link main} call is active, i.e. not yet torn down. */
16
+ let active = false;
17
+ /**
18
+ * Flushes and disposes the configured logtape sinks, giving up after
19
+ * `timeoutMs`. Never rejects: logging is best effort while the process is
20
+ * shutting down.
21
+ */
22
+ async function flushLogs(timeoutMs) {
23
+ let timer;
24
+ try {
25
+ await Promise.race([
26
+ dispose(),
27
+ new Promise((resolve) => {
28
+ timer = setTimeout(resolve, timeoutMs);
29
+ }),
30
+ ]);
18
31
  }
19
- else if (typeof arg3 === "number") {
20
- monitorMemoryHours = arg3;
21
- if (typeof arg4 === "boolean") {
22
- defaultInterruptionHandler = arg4;
23
- }
32
+ catch {
33
+ // Ignore sink errors: the process is exiting anyway.
34
+ }
35
+ finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
39
+ /** Renders an error (with its stack when available) or any other value. */
40
+ function describe(value) {
41
+ return value instanceof Error
42
+ ? (value.stack ?? String(value))
43
+ : String(value);
44
+ }
45
+ /**
46
+ * Bootstraps an application process: logs startup information, registers
47
+ * handlers for `SIGINT`, `SIGTERM`, `uncaughtException`, and
48
+ * `unhandledRejection`, optionally starts memory monitoring, then runs the
49
+ * optional launcher function.
50
+ *
51
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
52
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
53
+ * `debug` level only, since they can reveal sensitive flags such as
54
+ * `--inspect=0.0.0.0` or `--require` paths.
55
+ *
56
+ * Before the process exits, the configured logtape sinks are flushed and
57
+ * disposed (for at most `flushTimeoutMs`, 3 seconds by default), so buffered
58
+ * or asynchronous sinks do not lose the final messages. On `SIGINT`/`SIGTERM`
59
+ * the signal is logged at `info` level and then re-raised, so the process ends
60
+ * as killed by that signal (exit status 130/143), which shells and
61
+ * supervisors such as systemd treat as a clean stop. If another listener for
62
+ * that signal is registered, the process exits with status
63
+ * `128 + signal number` instead. Uncaught exceptions, unhandled rejections,
64
+ * and launcher failures exit with status `1`. A second signal or error during
65
+ * the flush exits immediately.
66
+ *
67
+ * Only one `main` call can be active at a time: calling it again before
68
+ * running the returned teardown function throws, instead of registering a
69
+ * second set of handlers.
70
+ *
71
+ * @param name - Human-readable application name used in log output.
72
+ * @param logger - Logger instance used for all startup and lifecycle messages.
73
+ * @param options - Optional {@link MainOptions}.
74
+ * @returns A teardown function that removes the process handlers registered
75
+ * by this call and stops the memory monitoring, allowing `main` to be called
76
+ * again (e.g. in tests). It does not exit the process; calling it more than
77
+ * once is harmless.
78
+ * @throws {TypeError} If `options` is not an object.
79
+ * @throws {Error} If another `main` call is still active.
80
+ * @throws {RangeError} If `monitorMemoryHours` or `flushTimeoutMs` is out of
81
+ * range. Nothing is registered in that case.
82
+ *
83
+ * @example Without options:
84
+ * ```ts
85
+ * main("my-app", logger)
86
+ * ```
87
+ *
88
+ * @example With an async launcher and memory monitoring every 2 hours:
89
+ * ```ts
90
+ * main("my-app", logger, {
91
+ * launcher: async () => {
92
+ * await connectToDatabase()
93
+ * startServer()
94
+ * },
95
+ * monitorMemoryHours: 2,
96
+ * })
97
+ * ```
98
+ *
99
+ * @example Managing graceful shutdown in the application:
100
+ * ```ts
101
+ * const teardown = main("my-app", logger, {
102
+ * launcher: () => startServer(),
103
+ * defaultInterruptionHandler: false,
104
+ * })
105
+ * process.once("SIGTERM", async () => {
106
+ * await server.close()
107
+ * teardown()
108
+ * })
109
+ * ```
110
+ */
111
+ export function main(name, logger, options) {
112
+ // Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
113
+ // function) from untyped callers, instead of silently ignoring them.
114
+ if (options !== undefined &&
115
+ (typeof options !== "object" || options === null)) {
116
+ throw new TypeError(`main: "options" must be a MainOptions object, received ${options === null ? "null" : typeof options}`);
117
+ }
118
+ const { launcher, monitorMemoryHours = 0, defaultInterruptionHandler = true, flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS, } = options ?? {};
119
+ // Positive values are validated further by `monitorMemory`.
120
+ if (!Number.isFinite(monitorMemoryHours) || monitorMemoryHours < 0) {
121
+ throw new RangeError(`main: "monitorMemoryHours" must be 0 (disabled) or a positive finite number, received ${monitorMemoryHours}`);
24
122
  }
25
- else if (typeof arg3 === "boolean") {
26
- defaultInterruptionHandler = arg3;
123
+ if (!Number.isFinite(flushTimeoutMs) ||
124
+ flushTimeoutMs < 0 ||
125
+ flushTimeoutMs > MAX_FLUSH_TIMEOUT_MS) {
126
+ throw new RangeError(`main: "flushTimeoutMs" must be a finite number between 0 and ${MAX_FLUSH_TIMEOUT_MS}, received ${flushTimeoutMs}`);
127
+ }
128
+ if (active) {
129
+ throw new Error("main: already active; call the teardown function returned by the previous main() call first");
27
130
  }
28
131
  const __logger = logger.getChild(["main"]);
29
132
  __logger.info `Main process launched [${title} :: ${pid}]`;
30
133
  __logger.info `Process name: ${name}`;
31
134
  __logger.info `Node.js environment: ${env["NODE_ENV"] ?? ""}`;
32
- __logger.info `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`;
33
- if (monitorMemoryHours > 0) {
34
- monitorMemory(__logger, monitorMemoryHours);
35
- }
135
+ // Process options can reveal sensitive flags (e.g. `--inspect=0.0.0.0`
136
+ // or `--require` paths), so they are only logged at debug level.
137
+ __logger.debug `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`;
138
+ // Started before any handler is registered: it throws on invalid hours.
139
+ const stopMonitoring = monitorMemoryHours > 0
140
+ ? monitorMemory(__logger, monitorMemoryHours)
141
+ : undefined;
142
+ // Set once a shutdown starts: a second signal or error while the logs are
143
+ // being flushed exits immediately instead of waiting again.
144
+ let shuttingDown = false;
145
+ const exitAfterFlush = async (exit) => {
146
+ if (!shuttingDown) {
147
+ shuttingDown = true;
148
+ await flushLogs(flushTimeoutMs);
149
+ }
150
+ exit();
151
+ };
152
+ const removeListeners = [];
36
153
  if (defaultInterruptionHandler) {
37
154
  for (const signal of ["SIGINT", "SIGTERM"]) {
38
- process.on(signal, (signal) => {
39
- __logger.error `Process interrupted. Received signal: ${signal}`;
40
- process.exit(0);
41
- });
155
+ const onSignal = () => {
156
+ __logger.info `Process interrupted. Received signal: ${signal}`;
157
+ return exitAfterFlush(() => {
158
+ // Re-raise the signal with its default disposition so the
159
+ // process ends as killed by it. Exit with the conventional
160
+ // status instead if another listener would intercept it.
161
+ process.off(signal, onSignal);
162
+ if (process.listenerCount(signal) === 0) {
163
+ process.kill(pid, signal);
164
+ }
165
+ else {
166
+ process.exit(128 + constants.signals[signal]);
167
+ }
168
+ });
169
+ };
170
+ process.on(signal, onSignal);
171
+ removeListeners.push(() => process.off(signal, onSignal));
42
172
  }
43
173
  }
44
- process.on("uncaughtException", (error, origin) => {
45
- __logger.error `Uncaught exception: ${error instanceof Error ? (error.stack ?? String(error)) : String(error)}`;
174
+ const onUncaughtException = (error, origin) => {
175
+ __logger.error `Uncaught exception: ${describe(error)}`;
46
176
  __logger.error `Exception origin: ${origin}`;
47
- process.exit(1);
48
- });
49
- process.on("unhandledRejection", (reason) => {
50
- __logger.error `Unhandled promise rejection. Reason:\n${reason instanceof Error ? (reason.stack ?? String(reason)) : String(reason)}`;
51
- process.exit(1);
52
- });
53
- launcher?.();
177
+ return exitAfterFlush(() => process.exit(1));
178
+ };
179
+ process.on("uncaughtException", onUncaughtException);
180
+ removeListeners.push(() => process.off("uncaughtException", onUncaughtException));
181
+ const onUnhandledRejection = (reason) => {
182
+ __logger.error `Unhandled promise rejection. Reason:\n${describe(reason)}`;
183
+ return exitAfterFlush(() => process.exit(1));
184
+ };
185
+ process.on("unhandledRejection", onUnhandledRejection);
186
+ removeListeners.push(() => process.off("unhandledRejection", onUnhandledRejection));
187
+ active = true;
188
+ let tornDown = false;
189
+ const teardown = () => {
190
+ if (tornDown) {
191
+ return;
192
+ }
193
+ tornDown = true;
194
+ stopMonitoring?.();
195
+ for (const remove of removeListeners) {
196
+ remove();
197
+ }
198
+ active = false;
199
+ };
200
+ const onLauncherFailure = (error) => {
201
+ __logger.error `Launcher failed: ${describe(error)}`;
202
+ return exitAfterFlush(() => process.exit(1));
203
+ };
204
+ try {
205
+ const result = launcher?.();
206
+ if (result !== undefined) {
207
+ Promise.resolve(result).catch(onLauncherFailure);
208
+ }
209
+ }
210
+ catch (error) {
211
+ void onLauncherFailure(error);
212
+ }
213
+ return teardown;
54
214
  }
55
215
  //# sourceMappingURL=main.js.map
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AAEjE,OAAO,aA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IAAI,CAAA;IACb,IAAI,QAAQ,GAAG,KAAK,CAAA;IACpB,MAAM,QAAQ,GAAG,GAAS,EAAE;QACxB,IAAI,QAAQ,EAAE,CAAC;YACX,OAAM;QACV,CAAC;QACD,QAAQ,GAAG,IAAI,CAAA;QACf,cAAc,EAAE,EAAE,CAAA;QAClB,KAAK,MAAM,MAAM,IAAI,eAAe,EAAE,CAAC;YACnC,MAAM,EAAE,CAAA;QACZ,CAAC;QACD,MAAM,GAAG,KAAK,CAAA;IAClB,CAAC,CAAA;IAED,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAiB,EAAE;QACxD,QAAQ,CAAC,KAAK,CAAA,oBAAoB,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAA;QACnD,OAAO,cAAc,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;IAChD,CAAC,CAAA;IACD,IAAI,CAAC;QACD,MAAM,MAAM,GAAG,QAAQ,EAAE,EAAE,CAAA;QAC3B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpD,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,KAAK,iBAAiB,CAAC,KAAK,CAAC,CAAA;IACjC,CAAC;IAED,OAAO,QAAQ,CAAA;AACnB,CAAC"}
@@ -25,5 +25,5 @@
25
25
  * millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
26
26
  * ```
27
27
  */
28
- export default function millisecondsToString(ms: number, locale?: string): string;
28
+ export declare function millisecondsToString(ms: number, locale?: string): string;
29
29
  //# sourceMappingURL=millisecondsToString.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"millisecondsToString.d.ts","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAmCA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CACxC,EAAE,EAAE,MAAM,EACV,MAAM,SAAO,GACd,MAAM,CAmBR"}
1
+ {"version":3,"file":"millisecondsToString.d.ts","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAmCA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,SAAO,GAAG,MAAM,CAmBtE"}
@@ -54,7 +54,7 @@ function getDurationFormatter(locale) {
54
54
  * millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
55
55
  * ```
56
56
  */
57
- export default function millisecondsToString(ms, locale = "en") {
57
+ export function millisecondsToString(ms, locale = "en") {
58
58
  if (!Number.isFinite(ms)) {
59
59
  throw new RangeError(`millisecondsToString: "ms" must be a finite number, received ${ms}`);
60
60
  }
@@ -1 +1 @@
1
- {"version":3,"file":"millisecondsToString.js","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,qBAAqB,GAAG,EAAE,CAAA;AAEhC,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAA+B,CAAA;AAEjE,SAAS,oBAAoB,CAAC,MAAc;IACxC,IAAI,SAAS,GAAG,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IAC9C,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;QAC1B,IAAI,CAAC;YACD,SAAS,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;gBACxC,KAAK,EAAE,QAAQ;aAClB,CAAC,CAAA;QACN,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAM,IAAI,UAAU,CAChB,yCAAyC,MAAM,GAAG,EAClD,EAAE,KAAK,EAAE,CACZ,CAAA;QACL,CAAC;QACD,IAAI,kBAAkB,CAAC,IAAI,IAAI,qBAAqB,EAAE,CAAC;YACnD,MAAM,MAAM,G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;IACL,CAAC;IAED,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;IACxC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAA;IAE7C,MAAM,SAAS,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC;QAClD,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,UAAU,CAAC;QACxC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,GAAG,SAAS,CAAC;QACvD,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,MAAM,CAAC;QACrD,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC;QAChD,YAAY,EAAE,SAAS,GAAG,IAAI;KACjC,CAAC,CAAA;IAEF,OAAO,iBAAiB,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AAC3E,CAAC"}
@@ -1,17 +1,33 @@
1
1
  import type { Logger } from "@logtape/logtape";
2
2
  /**
3
- * Starts a periodic interval that logs process uptime and memory usage.
3
+ * Starts a periodic interval that logs process uptime and memory usage, and
4
+ * returns a function that stops it.
4
5
  *
5
6
  * Memory figures are reported in bytes as returned by Node.js
6
7
  * {@link https://nodejs.org/api/process.html#processmemoryusage | process.memoryUsage()}.
7
8
  * Reports are emitted through a `"monitorMemory"` child category of the given
8
- * logger.
9
+ * logger as two `info` records whose figures are also attached as structured
10
+ * properties, so sinks and formatters that keep properties (e.g. JSON Lines)
11
+ * can query them:
12
+ *
13
+ * - `"Process uptime: <duration>"` with `uptime` (the duration formatted by
14
+ * `millisecondsToString`) and `uptimeMs` (integer milliseconds).
15
+ * - `"Process memory - Resident set size: {rss} | Heap total: {heapTotal} |
16
+ * Heap used: {heapUsed} | External: {external}"` with `rss`, `heapTotal`,
17
+ * `heapUsed`, and `external`.
18
+ *
19
+ * The interval timer is unreferenced, so monitoring alone does not keep the
20
+ * process alive.
9
21
  *
10
22
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
11
23
  * reports.
12
24
  * @param hours - Interval between reports in hours. Must be a finite number
13
- * greater than `0`. Defaults to `24`.
14
- * @throws {RangeError} If `hours` is not a finite number greater than `0`.
25
+ * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
26
+ * delay `setInterval` supports). Defaults to `24`.
27
+ * @returns A function that stops the monitoring. Calling it more than once is
28
+ * harmless.
29
+ * @throws {RangeError} If `hours` is not finite or the resulting interval is
30
+ * shorter than one minute or longer than 2³¹ − 1 milliseconds.
15
31
  *
16
32
  * @example
17
33
  * ```ts
@@ -19,9 +35,11 @@ import type { Logger } from "@logtape/logtape";
19
35
  *
20
36
  * const logger = await getConsoleLogger("my-app")
21
37
  *
22
- * monitorMemory(logger) // every 24 hours
23
- * monitorMemory(logger, 1) // every hour
38
+ * monitorMemory(logger) // every 24 hours
39
+ * const stop = monitorMemory(logger, 1) // every hour
40
+ * // ...
41
+ * stop()
24
42
  * ```
25
43
  */
26
- export default function monitorMemory(logger: Logger, hours?: number): void;
44
+ export declare function monitorMemory(logger: Logger, hours?: number): () => void;
27
45
  //# sourceMappingURL=monitorMemory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"monitorMemory.d.ts","sourceRoot":"","sources":["../src/monitorMemory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAG9C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,KAAK,GAAE,MAAW,GACnB,IAAI,CAkBN"}
1
+ {"version":3,"file":"monitorMemory.d.ts","sourceRoot":"","sources":["../src/monitorMemory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAY9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,GAAE,MAAW,GAAG,MAAM,IAAI,CAiC5E"}
@@ -1,18 +1,41 @@
1
1
  import { memoryUsage, uptime } from "node:process";
2
- import millisecondsToString from "./millisecondsToString.js";
2
+ import { millisecondsToString } from "./millisecondsToString.js";
3
+ /** Shortest allowed reporting interval: one minute. */
4
+ const MIN_DELAY_MS = 60 * 1_000;
3
5
  /**
4
- * Starts a periodic interval that logs process uptime and memory usage.
6
+ * Longest delay `setInterval` supports (2³¹ − 1 ms, about 596.5 hours). Node.js
7
+ * silently replaces larger delays with 1 ms, which would flood the logs.
8
+ */
9
+ const MAX_DELAY_MS = 2_147_483_647;
10
+ /**
11
+ * Starts a periodic interval that logs process uptime and memory usage, and
12
+ * returns a function that stops it.
5
13
  *
6
14
  * Memory figures are reported in bytes as returned by Node.js
7
15
  * {@link https://nodejs.org/api/process.html#processmemoryusage | process.memoryUsage()}.
8
16
  * Reports are emitted through a `"monitorMemory"` child category of the given
9
- * logger.
17
+ * logger as two `info` records whose figures are also attached as structured
18
+ * properties, so sinks and formatters that keep properties (e.g. JSON Lines)
19
+ * can query them:
20
+ *
21
+ * - `"Process uptime: <duration>"` with `uptime` (the duration formatted by
22
+ * `millisecondsToString`) and `uptimeMs` (integer milliseconds).
23
+ * - `"Process memory - Resident set size: {rss} | Heap total: {heapTotal} |
24
+ * Heap used: {heapUsed} | External: {external}"` with `rss`, `heapTotal`,
25
+ * `heapUsed`, and `external`.
26
+ *
27
+ * The interval timer is unreferenced, so monitoring alone does not keep the
28
+ * process alive.
10
29
  *
11
30
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
12
31
  * reports.
13
32
  * @param hours - Interval between reports in hours. Must be a finite number
14
- * greater than `0`. Defaults to `24`.
15
- * @throws {RangeError} If `hours` is not a finite number greater than `0`.
33
+ * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
34
+ * delay `setInterval` supports). Defaults to `24`.
35
+ * @returns A function that stops the monitoring. Calling it more than once is
36
+ * harmless.
37
+ * @throws {RangeError} If `hours` is not finite or the resulting interval is
38
+ * shorter than one minute or longer than 2³¹ − 1 milliseconds.
16
39
  *
17
40
  * @example
18
41
  * ```ts
@@ -20,20 +43,35 @@ import millisecondsToString from "./millisecondsToString.js";
20
43
  *
21
44
  * const logger = await getConsoleLogger("my-app")
22
45
  *
23
- * monitorMemory(logger) // every 24 hours
24
- * monitorMemory(logger, 1) // every hour
46
+ * monitorMemory(logger) // every 24 hours
47
+ * const stop = monitorMemory(logger, 1) // every hour
48
+ * // ...
49
+ * stop()
25
50
  * ```
26
51
  */
27
- export default function monitorMemory(logger, hours = 24) {
28
- if (!Number.isFinite(hours) || hours <= 0) {
29
- throw new RangeError(`monitorMemory: "hours" must be a finite number greater than 0, received ${hours}`);
52
+ export function monitorMemory(logger, hours = 24) {
53
+ const delay = 60 * 60 * 1_000 * hours;
54
+ if (!Number.isFinite(delay) ||
55
+ delay < MIN_DELAY_MS ||
56
+ delay > MAX_DELAY_MS) {
57
+ throw new RangeError(`monitorMemory: "hours" must be a finite number between ${MIN_DELAY_MS / 3_600_000} and ${MAX_DELAY_MS / 3_600_000} (1 minute to 2^31 - 1 ms), received ${hours}`);
30
58
  }
31
59
  const __logger = logger.getChild(["monitorMemory"]);
32
- const delay = 60 * 60 * 1_000 * hours;
33
- setInterval(() => {
60
+ const timer = setInterval(() => {
61
+ const uptimeMs = Math.round(uptime() * 1_000);
62
+ const formattedUptime = millisecondsToString(uptimeMs);
34
63
  const { rss, heapTotal, heapUsed, external } = memoryUsage();
35
- __logger.info(`Process uptime: ${millisecondsToString(uptime() * 1_000)}`);
36
- __logger.info(`Process memory - Resident set size: ${rss} | Heap total: ${heapTotal} | Heap used: ${heapUsed} | External: ${external}`);
64
+ // The duration goes into the message text itself: as a `{uptime}`
65
+ // placeholder, text formatters would render the string quoted. It is
66
+ // safe to embed because "en" durations never contain `{` or `}`.
67
+ __logger.info(`Process uptime: ${formattedUptime}`, {
68
+ uptime: formattedUptime,
69
+ uptimeMs,
70
+ });
71
+ __logger.info("Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}", { rss, heapTotal, heapUsed, external });
37
72
  }, delay);
73
+ // Monitoring alone must not keep the process alive.
74
+ timer.unref();
75
+ return () => clearInterval(timer);
38
76
  }
39
77
  //# sourceMappingURL=monitorMemory.js.map