@darthcav/ts-utils 0.12.3 → 1.0.1

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 (96) hide show
  1. package/README.md +162 -84
  2. package/dist/core/guards.d.ts +176 -0
  3. package/dist/core/guards.d.ts.map +1 -0
  4. package/dist/core/guards.js +201 -0
  5. package/dist/core/guards.js.map +1 -0
  6. package/dist/core/index.d.ts +17 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/index.js +17 -0
  9. package/dist/core/index.js.map +1 -0
  10. package/dist/core/millisecondsToString.d.ts.map +1 -0
  11. package/dist/{millisecondsToString.js → core/millisecondsToString.js} +9 -14
  12. package/dist/core/millisecondsToString.js.map +1 -0
  13. package/dist/core/noop.d.ts +3 -0
  14. package/dist/core/noop.d.ts.map +1 -0
  15. package/dist/core/noop.js +3 -0
  16. package/dist/core/noop.js.map +1 -0
  17. package/dist/index.d.ts +13 -17
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +12 -10
  20. package/dist/index.js.map +1 -1
  21. package/dist/loggers/getConsoleLogger.d.ts +11 -12
  22. package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
  23. package/dist/loggers/getConsoleLogger.js +14 -19
  24. package/dist/loggers/getConsoleLogger.js.map +1 -1
  25. package/dist/loggers/index.d.ts +14 -0
  26. package/dist/loggers/index.d.ts.map +1 -0
  27. package/dist/loggers/index.js +14 -0
  28. package/dist/loggers/index.js.map +1 -0
  29. package/dist/node/delays.d.ts +11 -0
  30. package/dist/node/delays.d.ts.map +1 -0
  31. package/dist/node/delays.js +14 -0
  32. package/dist/node/delays.js.map +1 -0
  33. package/dist/node/index.d.ts +15 -0
  34. package/dist/node/index.d.ts.map +1 -0
  35. package/dist/node/index.js +15 -0
  36. package/dist/node/index.js.map +1 -0
  37. package/dist/node/main.d.ts +158 -0
  38. package/dist/node/main.d.ts.map +1 -0
  39. package/dist/node/main.js +255 -0
  40. package/dist/node/main.js.map +1 -0
  41. package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +14 -5
  42. package/dist/node/monitorMemory.d.ts.map +1 -0
  43. package/dist/{monitorMemory.js → node/monitorMemory.js} +22 -16
  44. package/dist/node/monitorMemory.js.map +1 -0
  45. package/dist/node/osRelease.d.ts +58 -0
  46. package/dist/node/osRelease.d.ts.map +1 -0
  47. package/dist/node/osRelease.js +111 -0
  48. package/dist/node/osRelease.js.map +1 -0
  49. package/dist/node/releaseParsers.d.ts +11 -0
  50. package/dist/node/releaseParsers.d.ts.map +1 -0
  51. package/dist/node/releaseParsers.js +92 -0
  52. package/dist/node/releaseParsers.js.map +1 -0
  53. package/dist/type-testing/index.d.ts +18 -0
  54. package/dist/type-testing/index.d.ts.map +1 -0
  55. package/dist/type-testing/index.js +12 -0
  56. package/dist/type-testing/index.js.map +1 -0
  57. package/package.json +22 -7
  58. package/src/core/guards.ts +239 -0
  59. package/src/core/index.ts +32 -0
  60. package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +9 -16
  61. package/src/core/noop.ts +2 -0
  62. package/src/index.ts +13 -49
  63. package/src/loggers/getConsoleLogger.ts +14 -19
  64. package/src/loggers/index.ts +14 -0
  65. package/src/node/delays.ts +15 -0
  66. package/src/node/index.ts +21 -0
  67. package/src/node/main.ts +419 -0
  68. package/src/{monitorMemory.ts → node/monitorMemory.ts} +24 -18
  69. package/src/node/osRelease.ts +152 -0
  70. package/src/node/releaseParsers.ts +109 -0
  71. package/src/type-testing/index.ts +18 -0
  72. package/dist/main.d.ts +0 -112
  73. package/dist/main.d.ts.map +0 -1
  74. package/dist/main.js +0 -219
  75. package/dist/main.js.map +0 -1
  76. package/dist/millisecondsToString.d.ts.map +0 -1
  77. package/dist/millisecondsToString.js.map +0 -1
  78. package/dist/monitorMemory.d.ts.map +0 -1
  79. package/dist/monitorMemory.js.map +0 -1
  80. package/dist/noop.d.ts +0 -7
  81. package/dist/noop.d.ts.map +0 -1
  82. package/dist/noop.js +0 -7
  83. package/dist/noop.js.map +0 -1
  84. package/dist/osRelease.d.ts +0 -46
  85. package/dist/osRelease.d.ts.map +0 -1
  86. package/dist/osRelease.js +0 -153
  87. package/dist/osRelease.js.map +0 -1
  88. package/dist/types.d.ts +0 -70
  89. package/dist/types.d.ts.map +0 -1
  90. package/dist/types.js +0 -84
  91. package/dist/types.js.map +0 -1
  92. package/src/main.ts +0 -302
  93. package/src/noop.ts +0 -6
  94. package/src/osRelease.ts +0 -174
  95. package/src/types.ts +0 -98
  96. /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
@@ -0,0 +1,158 @@
1
+ import { type Logger } from "@logtape/logtape";
2
+ /**
3
+ * Starts the application once {@link main} has registered the process
4
+ * handlers. Use a closure to capture any context needed (e.g. a logger). It
5
+ * may be asynchronous; if it throws or rejects, {@link main} logs the failure
6
+ * and shuts down with exit status `1`.
7
+ */
8
+ export type LauncherFunction = () => void | Promise<void>;
9
+ /**
10
+ * Why {@link main} is shutting down, passed to the {@link ShutdownFunction}.
11
+ *
12
+ * - `reason: "signal"`: a normal stop requested with `SIGINT` or `SIGTERM`.
13
+ * - `reason: "error"`: a fatal failure; `source` says where it came from and
14
+ * `error` holds the thrown value or rejection reason. The application may
15
+ * be in an inconsistent state, so only clean up (e.g. close connections).
16
+ */
17
+ export type ShutdownContext = {
18
+ readonly reason: "signal";
19
+ readonly signal: "SIGINT" | "SIGTERM";
20
+ } | {
21
+ readonly reason: "error";
22
+ readonly source: "uncaughtException" | "unhandledRejection" | "launcher";
23
+ readonly error: unknown;
24
+ };
25
+ /**
26
+ * Application cleanup (e.g. closing servers and database connections), run
27
+ * once by {@link main} before the logs are flushed and the process exits. It
28
+ * may be asynchronous; {@link main} waits at most
29
+ * {@link MainOptions.shutdownTimeoutMs} for it.
30
+ *
31
+ * @param context - Why the process is shutting down.
32
+ */
33
+ export type ShutdownFunction = (context: ShutdownContext) => void | Promise<void>;
34
+ /** Options for {@link main}, all optional. */
35
+ export type MainOptions = {
36
+ /** Starts the application (see {@link LauncherFunction}). */
37
+ launcher?: LauncherFunction;
38
+ /**
39
+ * Application cleanup, run once on shutdown (see {@link ShutdownFunction}).
40
+ * If it throws, rejects, or exceeds {@link MainOptions.shutdownTimeoutMs},
41
+ * the failure is logged and the process exits with status `1`.
42
+ */
43
+ shutdown?: ShutdownFunction;
44
+ /**
45
+ * Maximum wait in milliseconds for {@link MainOptions.shutdown}, between
46
+ * `0` and 2³¹ − 1. Defaults to `10000`.
47
+ */
48
+ shutdownTimeoutMs?: number;
49
+ /**
50
+ * When greater than `0`, logs the memory usage every `monitorMemoryHours`
51
+ * hours via {@link monitorMemory}. Must be `0` or an interval that
52
+ * {@link monitorMemory} accepts (one minute to 2³¹ − 1 ms). Defaults to
53
+ * `0` (disabled).
54
+ */
55
+ monitorMemoryHours?: number;
56
+ /**
57
+ * When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
58
+ * run the shutdown sequence and stop the process. Set to `false` when the
59
+ * application handles these signals itself.
60
+ */
61
+ defaultInterruptionHandler?: boolean;
62
+ /**
63
+ * Flushes the log sinks before the process exits; errors are ignored.
64
+ * Defaults to LogTape's `dispose`, which flushes the sinks configured
65
+ * through the `@logtape/logtape` copy this package uses. Pass another
66
+ * function (e.g. the `dispose` of the application's own LogTape copy), or
67
+ * `noop` to skip flushing.
68
+ */
69
+ flushLogs?: () => void | Promise<void>;
70
+ /**
71
+ * Maximum wait in milliseconds for {@link MainOptions.flushLogs}, between
72
+ * `0` and 2³¹ − 1. Defaults to `3000`.
73
+ */
74
+ flushTimeoutMs?: number;
75
+ };
76
+ /**
77
+ * Bootstraps an application process: logs startup information, optionally
78
+ * registers handlers for `SIGINT` and `SIGTERM` (see
79
+ * {@link MainOptions.defaultInterruptionHandler}), always registers handlers
80
+ * for `uncaughtException` and `unhandledRejection`, optionally starts memory
81
+ * monitoring, then runs the optional launcher function.
82
+ *
83
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
84
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
85
+ * `debug` level only, since they can reveal sensitive flags such as
86
+ * `--inspect=0.0.0.0` or `--require` paths.
87
+ *
88
+ * On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
89
+ * launcher failure, `main` runs a shutdown sequence once:
90
+ *
91
+ * 1. The cause is logged (signals at `info`, failures at `error` level) and
92
+ * the memory monitoring stops.
93
+ * 2. The {@link MainOptions.shutdown} function, if any, runs for at most
94
+ * `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
95
+ * logged at `error` level.
96
+ * 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
97
+ * `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
98
+ * final messages.
99
+ * 4. The process exits. A signal is re-raised, so the process ends as killed
100
+ * by it (exit status 130/143), which shells and supervisors such as
101
+ * systemd treat as a clean stop; if another listener for that signal
102
+ * exists, it exits with status `128 + signal number` instead. Fatal
103
+ * failures, and a failed or timed-out shutdown function, exit with
104
+ * status `1`.
105
+ *
106
+ * A second signal or fatal failure during the sequence exits immediately.
107
+ *
108
+ * Only one `main` call can be active at a time: calling it again before
109
+ * running the returned teardown function throws.
110
+ *
111
+ * @param name - Human-readable application name used in log output.
112
+ * @param logger - Logger instance used for all startup and lifecycle messages.
113
+ * @param options - Optional {@link MainOptions}.
114
+ * @returns A teardown function that removes the process handlers registered
115
+ * by this call and stops the memory monitoring, allowing `main` to be called
116
+ * again (e.g. in tests). It neither runs the shutdown function nor exits
117
+ * the process; calling it more than once is harmless.
118
+ * @throws {TypeError} If `options` is not an object, or `launcher`,
119
+ * `shutdown`, or `flushLogs` is not a function.
120
+ * @throws {Error} If another `main` call is still active.
121
+ * @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
122
+ * `flushTimeoutMs` is out of range. Nothing is logged or registered in that
123
+ * case.
124
+ *
125
+ * @example Without options:
126
+ * ```ts
127
+ * main("my-app", logger)
128
+ * ```
129
+ *
130
+ * @example With an async launcher and memory monitoring every 2 hours:
131
+ * ```ts
132
+ * main("my-app", logger, {
133
+ * launcher: async () => {
134
+ * await connectToDatabase()
135
+ * startServer()
136
+ * },
137
+ * monitorMemoryHours: 2,
138
+ * })
139
+ * ```
140
+ *
141
+ * @example With graceful shutdown of the application's resources:
142
+ * ```ts
143
+ * let server: Server | undefined
144
+ * main("my-app", logger, {
145
+ * launcher: async () => {
146
+ * await connectToDatabase()
147
+ * server = startServer()
148
+ * },
149
+ * shutdown: async () => {
150
+ * await server?.close()
151
+ * await disconnectFromDatabase()
152
+ * },
153
+ * shutdownTimeoutMs: 15_000,
154
+ * })
155
+ * ```
156
+ */
157
+ export declare function main(name: string, logger: Logger, options?: MainOptions): () => void;
158
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/node/main.ts"],"names":[],"mappings":"AAGA,OAAO,EAAW,KAAK,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAmFvD;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AAEzD;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GACrB;IACI,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAA;IACzB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAA;CACxC,GACD;IACI,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;IACxB,QAAQ,CAAC,MAAM,EACT,mBAAmB,GACnB,oBAAoB,GACpB,UAAU,CAAA;IAChB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAC1B,CAAA;AAEP;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC3B,OAAO,EAAE,eAAe,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AAEzB,8CAA8C;AAC9C,MAAM,MAAM,WAAW,GAAG;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,gBAAgB,CAAA;IAC3B;;;;OAIG;IACH,QAAQ,CAAC,EAAE,gBAAgB,CAAA;IAC3B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;;;;OAIG;IACH,0BAA0B,CAAC,EAAE,OAAO,CAAA;IACpC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACtC;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgFG;AACH,wBAAgB,IAAI,CAChB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,WAAW,GACtB,MAAM,IAAI,CAkKZ"}
@@ -0,0 +1,255 @@
1
+ import { constants } from "node:os";
2
+ import process, { env, execArgv, pid, title } from "node:process";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { dispose } from "@logtape/logtape";
5
+ import { isValidDelay, MAX_DELAY_MS } from "./delays.js";
6
+ import { HOURS_RANGE, isValidHours, monitorMemory } from "./monitorMemory.js";
7
+ /** Default for {@link MainOptions.flushTimeoutMs}. */
8
+ const DEFAULT_FLUSH_TIMEOUT_MS = 3_000;
9
+ /** Default for {@link MainOptions.shutdownTimeoutMs}. */
10
+ const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_000;
11
+ /** Whether a {@link main} call has not been torn down yet. */
12
+ let active = false;
13
+ /**
14
+ * Runs a possibly asynchronous task and waits for it for at most `timeoutMs`.
15
+ * Never rejects: a throwing or rejecting task is reported as `"rejected"`.
16
+ * The timer stays referenced, so the process keeps running while it waits.
17
+ */
18
+ async function runBounded(task, timeoutMs) {
19
+ const timeout = new AbortController();
20
+ try {
21
+ return await Promise.race([
22
+ Promise.try(task).then(() => ({ status: "fulfilled" }), (reason) => ({
23
+ status: "rejected",
24
+ reason,
25
+ })),
26
+ delay(timeoutMs, { status: "timeout" }, { signal: timeout.signal }),
27
+ ]);
28
+ }
29
+ finally {
30
+ // Cancels the timer. The pending delay then rejects, but the race has
31
+ // already handled that.
32
+ timeout.abort();
33
+ }
34
+ }
35
+ /**
36
+ * Renders an error (with its stack when available) or any other value.
37
+ * `Error.isError`, unlike `instanceof`, also recognizes errors from another
38
+ * realm (e.g. a `node:vm` context).
39
+ */
40
+ function describe(value) {
41
+ return Error.isError(value) ? (value.stack ?? String(value)) : String(value);
42
+ }
43
+ /** Names the type of `value`, telling `null` apart from objects. */
44
+ function typeName(value) {
45
+ return value === null ? "null" : typeof value;
46
+ }
47
+ /** Throws a `RangeError` unless `value` is a valid timer delay. */
48
+ function assertTimeout(option, value) {
49
+ if (!isValidDelay(value)) {
50
+ throw new RangeError(`main: "${option}" must be a finite number between 0 and ${MAX_DELAY_MS}, received ${value}`);
51
+ }
52
+ }
53
+ /** Throws a `TypeError` unless `value` is a function or `undefined`. */
54
+ function assertOptionalFunction(option, value) {
55
+ if (value !== undefined && typeof value !== "function") {
56
+ throw new TypeError(`main: "${option}" must be a function, received ${typeName(value)}`);
57
+ }
58
+ }
59
+ /**
60
+ * Bootstraps an application process: logs startup information, optionally
61
+ * registers handlers for `SIGINT` and `SIGTERM` (see
62
+ * {@link MainOptions.defaultInterruptionHandler}), always registers handlers
63
+ * for `uncaughtException` and `unhandledRejection`, optionally starts memory
64
+ * monitoring, then runs the optional launcher function.
65
+ *
66
+ * The process title, PID, name, and `NODE_ENV` are logged at `info` level.
67
+ * The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
68
+ * `debug` level only, since they can reveal sensitive flags such as
69
+ * `--inspect=0.0.0.0` or `--require` paths.
70
+ *
71
+ * On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
72
+ * launcher failure, `main` runs a shutdown sequence once:
73
+ *
74
+ * 1. The cause is logged (signals at `info`, failures at `error` level) and
75
+ * the memory monitoring stops.
76
+ * 2. The {@link MainOptions.shutdown} function, if any, runs for at most
77
+ * `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
78
+ * logged at `error` level.
79
+ * 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
80
+ * `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
81
+ * final messages.
82
+ * 4. The process exits. A signal is re-raised, so the process ends as killed
83
+ * by it (exit status 130/143), which shells and supervisors such as
84
+ * systemd treat as a clean stop; if another listener for that signal
85
+ * exists, it exits with status `128 + signal number` instead. Fatal
86
+ * failures, and a failed or timed-out shutdown function, exit with
87
+ * status `1`.
88
+ *
89
+ * A second signal or fatal failure during the sequence exits immediately.
90
+ *
91
+ * Only one `main` call can be active at a time: calling it again before
92
+ * running the returned teardown function throws.
93
+ *
94
+ * @param name - Human-readable application name used in log output.
95
+ * @param logger - Logger instance used for all startup and lifecycle messages.
96
+ * @param options - Optional {@link MainOptions}.
97
+ * @returns A teardown function that removes the process handlers registered
98
+ * by this call and stops the memory monitoring, allowing `main` to be called
99
+ * again (e.g. in tests). It neither runs the shutdown function nor exits
100
+ * the process; calling it more than once is harmless.
101
+ * @throws {TypeError} If `options` is not an object, or `launcher`,
102
+ * `shutdown`, or `flushLogs` is not a function.
103
+ * @throws {Error} If another `main` call is still active.
104
+ * @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
105
+ * `flushTimeoutMs` is out of range. Nothing is logged or registered in that
106
+ * case.
107
+ *
108
+ * @example Without options:
109
+ * ```ts
110
+ * main("my-app", logger)
111
+ * ```
112
+ *
113
+ * @example With an async launcher and memory monitoring every 2 hours:
114
+ * ```ts
115
+ * main("my-app", logger, {
116
+ * launcher: async () => {
117
+ * await connectToDatabase()
118
+ * startServer()
119
+ * },
120
+ * monitorMemoryHours: 2,
121
+ * })
122
+ * ```
123
+ *
124
+ * @example With graceful shutdown of the application's resources:
125
+ * ```ts
126
+ * let server: Server | undefined
127
+ * main("my-app", logger, {
128
+ * launcher: async () => {
129
+ * await connectToDatabase()
130
+ * server = startServer()
131
+ * },
132
+ * shutdown: async () => {
133
+ * await server?.close()
134
+ * await disconnectFromDatabase()
135
+ * },
136
+ * shutdownTimeoutMs: 15_000,
137
+ * })
138
+ * ```
139
+ */
140
+ export function main(name, logger, options) {
141
+ // Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
142
+ // function) from untyped callers, instead of silently ignoring them.
143
+ if (options !== undefined &&
144
+ (typeof options !== "object" || options === null)) {
145
+ throw new TypeError(`main: "options" must be a MainOptions object, received ${typeName(options)}`);
146
+ }
147
+ const { launcher, shutdown, shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS, monitorMemoryHours = 0, defaultInterruptionHandler = true, flushLogs = dispose, flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS, } = options ?? {};
148
+ assertOptionalFunction("launcher", launcher);
149
+ assertOptionalFunction("shutdown", shutdown);
150
+ assertOptionalFunction("flushLogs", flushLogs);
151
+ if (monitorMemoryHours !== 0 && !isValidHours(monitorMemoryHours)) {
152
+ throw new RangeError(`main: "monitorMemoryHours" must be 0 (disabled) or a finite number ${HOURS_RANGE}, received ${monitorMemoryHours}`);
153
+ }
154
+ assertTimeout("shutdownTimeoutMs", shutdownTimeoutMs);
155
+ assertTimeout("flushTimeoutMs", flushTimeoutMs);
156
+ if (active) {
157
+ throw new Error("main: already active; call the teardown function returned by the previous main() call first");
158
+ }
159
+ const __logger = logger.getChild(["main"]);
160
+ __logger.info `Main process launched [${title} :: ${pid}]`;
161
+ __logger.info `Process name: ${name}`;
162
+ __logger.info `Node.js environment: ${env["NODE_ENV"] ?? ""}`;
163
+ __logger.debug `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`;
164
+ const stopMonitoring = monitorMemoryHours > 0
165
+ ? monitorMemory(__logger, monitorMemoryHours)
166
+ : undefined;
167
+ // A second signal or failure during the shutdown sequence exits at once.
168
+ let shuttingDown = false;
169
+ /** Runs the shutdown sequence, then `exit` (or status `1` on failure). */
170
+ const shutDown = async (context, exit) => {
171
+ if (shuttingDown) {
172
+ exit();
173
+ return;
174
+ }
175
+ shuttingDown = true;
176
+ stopMonitoring?.();
177
+ let cleanupFailed = false;
178
+ if (shutdown !== undefined) {
179
+ const outcome = await runBounded(() => shutdown(context), shutdownTimeoutMs);
180
+ cleanupFailed = outcome.status !== "fulfilled";
181
+ if (outcome.status === "rejected") {
182
+ __logger.error `Shutdown function failed: ${describe(outcome.reason)}`;
183
+ }
184
+ else if (outcome.status === "timeout") {
185
+ __logger.error `Shutdown function timed out after ${shutdownTimeoutMs} ms`;
186
+ }
187
+ }
188
+ // Best effort: flush failures and timeouts are ignored.
189
+ await runBounded(flushLogs, flushTimeoutMs);
190
+ if (cleanupFailed) {
191
+ process.exit(1);
192
+ }
193
+ else {
194
+ exit();
195
+ }
196
+ };
197
+ const removeListeners = [];
198
+ if (defaultInterruptionHandler) {
199
+ for (const signal of ["SIGINT", "SIGTERM"]) {
200
+ const onSignal = () => {
201
+ __logger.info `Process interrupted. Received signal: ${signal}`;
202
+ return shutDown({ reason: "signal", signal }, () => {
203
+ // Re-raise the signal so the process ends as killed by it,
204
+ // unless another listener would intercept it.
205
+ process.off(signal, onSignal);
206
+ if (process.listenerCount(signal) === 0) {
207
+ process.kill(pid, signal);
208
+ }
209
+ else {
210
+ process.exit(128 + constants.signals[signal]);
211
+ }
212
+ });
213
+ };
214
+ process.on(signal, onSignal);
215
+ removeListeners.push(() => process.off(signal, onSignal));
216
+ }
217
+ }
218
+ /** Runs the shutdown sequence for a fatal failure, then exits with `1`. */
219
+ const fail = (source, error) => shutDown({ reason: "error", source, error }, () => process.exit(1));
220
+ const onUncaughtException = (error, origin) => {
221
+ __logger.error `Uncaught exception: ${describe(error)}`;
222
+ __logger.error `Exception origin: ${origin}`;
223
+ return fail("uncaughtException", error);
224
+ };
225
+ process.on("uncaughtException", onUncaughtException);
226
+ removeListeners.push(() => process.off("uncaughtException", onUncaughtException));
227
+ const onUnhandledRejection = (reason) => {
228
+ __logger.error `Unhandled promise rejection. Reason:\n${describe(reason)}`;
229
+ return fail("unhandledRejection", reason);
230
+ };
231
+ process.on("unhandledRejection", onUnhandledRejection);
232
+ removeListeners.push(() => process.off("unhandledRejection", onUnhandledRejection));
233
+ active = true;
234
+ let tornDown = false;
235
+ const teardown = () => {
236
+ if (tornDown) {
237
+ return;
238
+ }
239
+ tornDown = true;
240
+ stopMonitoring?.();
241
+ for (const remove of removeListeners) {
242
+ remove();
243
+ }
244
+ active = false;
245
+ };
246
+ const onLauncherFailure = (error) => {
247
+ __logger.error `Launcher failed: ${describe(error)}`;
248
+ return fail("launcher", error);
249
+ };
250
+ if (launcher !== undefined) {
251
+ Promise.try(launcher).catch(onLauncherFailure);
252
+ }
253
+ return teardown;
254
+ }
255
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../../src/node/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACnC,OAAO,OAAO,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AACjE,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,EAAE,OAAO,EAAe,MAAM,kBAAkB,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AACxD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAE7E,sDAAsD;AACtD,MAAM,wBAAwB,GAAG,KAAK,CAAA;AAEtC,yDAAyD;AACzD,MAAM,2BAA2B,GAAG,MAAM,CAAA;AAE1C,8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C,GAAG,EAAE,CACtB,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAC1D,CAAA;IAED,MAAM,GAAG,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,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;IAClC,CAAC,CAAA;IACD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAA;IAClD,CAAC;IAED,OAAO,QAAQ,CAAA;AACnB,CAAC"}
@@ -1,4 +1,15 @@
1
1
  import type { Logger } from "@logtape/logtape";
2
+ /**
3
+ * The valid range of a reporting interval in hours, for error messages.
4
+ * Internal, like {@link isValidHours}.
5
+ */
6
+ export declare const HOURS_RANGE: string;
7
+ /**
8
+ * Whether `hours` is a valid reporting interval ({@link HOURS_RANGE}).
9
+ * Internal: {@link main} uses it too, but the `node` entry point does not
10
+ * re-export it.
11
+ */
12
+ export declare function isValidHours(hours: unknown): hours is number;
2
13
  /**
3
14
  * Starts a periodic interval that logs process uptime and memory usage, and
4
15
  * returns a function that stops it.
@@ -21,13 +32,11 @@ import type { Logger } from "@logtape/logtape";
21
32
  *
22
33
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
23
34
  * reports.
24
- * @param hours - Interval between reports in hours. Must be a finite number
25
- * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
26
- * delay `setInterval` supports). Defaults to `24`.
35
+ * @param hours - Interval between reports in hours, from `1 / 60` (one
36
+ * minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
27
37
  * @returns A function that stops the monitoring. Calling it more than once is
28
38
  * 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.
39
+ * @throws {RangeError} If `hours` is not finite or out of that range.
31
40
  *
32
41
  * @example
33
42
  * ```ts
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitorMemory.d.ts","sourceRoot":"","sources":["../../src/node/monitorMemory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAW9C;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE,MAAoG,CAAA;AAE9H;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE5D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,GAAE,MAAW,GAAG,MAAM,IAAI,CA2B5E"}
@@ -1,12 +1,24 @@
1
1
  import { memoryUsage, uptime } from "node:process";
2
- import { millisecondsToString } from "./millisecondsToString.js";
2
+ import { isFiniteNumber } from "../core/guards.js";
3
+ import { millisecondsToString } from "../core/millisecondsToString.js";
4
+ import { isValidDelay, MAX_DELAY_MS } from "./delays.js";
3
5
  /** Shortest allowed reporting interval: one minute. */
4
6
  const MIN_DELAY_MS = 60 * 1_000;
7
+ /** One hour in milliseconds. */
8
+ const HOUR_MS = 60 * 60 * 1_000;
5
9
  /**
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.
10
+ * The valid range of a reporting interval in hours, for error messages.
11
+ * Internal, like {@link isValidHours}.
8
12
  */
9
- const MAX_DELAY_MS = 2_147_483_647;
13
+ export const HOURS_RANGE = `between ${MIN_DELAY_MS / HOUR_MS} and ${MAX_DELAY_MS / HOUR_MS} (1 minute to 2^31 - 1 ms)`;
14
+ /**
15
+ * Whether `hours` is a valid reporting interval ({@link HOURS_RANGE}).
16
+ * Internal: {@link main} uses it too, but the `node` entry point does not
17
+ * re-export it.
18
+ */
19
+ export function isValidHours(hours) {
20
+ return isFiniteNumber(hours) && isValidDelay(hours * HOUR_MS, MIN_DELAY_MS);
21
+ }
10
22
  /**
11
23
  * Starts a periodic interval that logs process uptime and memory usage, and
12
24
  * returns a function that stops it.
@@ -29,13 +41,11 @@ const MAX_DELAY_MS = 2_147_483_647;
29
41
  *
30
42
  * @param logger - Logger whose `"monitorMemory"` child emits the memory
31
43
  * reports.
32
- * @param hours - Interval between reports in hours. Must be a finite number
33
- * between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
34
- * delay `setInterval` supports). Defaults to `24`.
44
+ * @param hours - Interval between reports in hours, from `1 / 60` (one
45
+ * minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
35
46
  * @returns A function that stops the monitoring. Calling it more than once is
36
47
  * 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.
48
+ * @throws {RangeError} If `hours` is not finite or out of that range.
39
49
  *
40
50
  * @example
41
51
  * ```ts
@@ -50,11 +60,8 @@ const MAX_DELAY_MS = 2_147_483_647;
50
60
  * ```
51
61
  */
52
62
  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}`);
63
+ if (!isValidHours(hours)) {
64
+ throw new RangeError(`monitorMemory: "hours" must be a finite number ${HOURS_RANGE}, received ${hours}`);
58
65
  }
59
66
  const __logger = logger.getChild(["monitorMemory"]);
60
67
  const timer = setInterval(() => {
@@ -69,8 +76,7 @@ export function monitorMemory(logger, hours = 24) {
69
76
  uptimeMs,
70
77
  });
71
78
  __logger.info("Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}", { rss, heapTotal, heapUsed, external });
72
- }, delay);
73
- // Monitoring alone must not keep the process alive.
79
+ }, hours * HOUR_MS);
74
80
  timer.unref();
75
81
  return () => clearInterval(timer);
76
82
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitorMemory.js","sourceRoot":"","sources":["../../src/node/monitorMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAA;AACtE,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAExD,uDAAuD;AACvD,MAAM,YAAY,GAAG,EAAE,GAAG,KAAK,CAAA;AAE/B,gCAAgC;AAChC,MAAM,OAAO,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,CAAA;AAE/B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAW,WAAW,YAAY,GAAG,OAAO,QAAQ,YAAY,GAAG,OAAO,4BAA4B,CAAA;AAE9H;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACvC,OAAO,cAAc,CAAC,KAAK,CAAC,IAAI,YAAY,CAAC,KAAK,GAAG,OAAO,EAAE,YAAY,CAAC,CAAA;AAC/E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,QAAgB,EAAE;IAC5D,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,UAAU,CAChB,kDAAkD,WAAW,cAAc,KAAK,EAAE,CACrF,CAAA;IACL,CAAC;IACD,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,eAAe,CAAC,CAAC,CAAA;IAEnD,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC3B,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAA;QAC7C,MAAM,eAAe,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAA;QACtD,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,WAAW,EAAE,CAAA;QAC5D,kEAAkE;QAClE,qEAAqE;QACrE,iEAAiE;QACjE,QAAQ,CAAC,IAAI,CAAC,mBAAmB,eAAe,EAAE,EAAE;YAChD,MAAM,EAAE,eAAe;YACvB,QAAQ;SACX,CAAC,CAAA;QACF,QAAQ,CAAC,IAAI,CACT,oHAAoH,EACpH,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,CACzC,CAAA;IACL,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,CAAA;IACnB,KAAK,CAAC,KAAK,EAAE,CAAA;IAEb,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;AACrC,CAAC"}
@@ -0,0 +1,58 @@
1
+ import type { RuntimeObject } from "../core/guards.ts";
2
+ /**
3
+ * OS release information: the normalized `name`, `version`, and `arch`, plus
4
+ * the platform's raw keys by string index:
5
+ *
6
+ * - On Linux, the keys read from the os-release file (`/etc/os-release`, or
7
+ * `/usr/lib/os-release` as a fallback; e.g. `ID`, `PRETTY_NAME`,
8
+ * `ID_LIKE`).
9
+ * - On macOS, the string keys of
10
+ * `/System/Library/CoreServices/SystemVersion.plist` (e.g. `ProductName`,
11
+ * `ProductVersion`, `ProductBuildVersion`).
12
+ */
13
+ export type OsRelease = {
14
+ /** Human-readable OS name, e.g. `"Ubuntu"`, `"macOS"`, or `"Windows 11"`. */
15
+ name: string;
16
+ /**
17
+ * OS version string, e.g. `"24.04"`, `"15.1"`, or `"10.0.22000"`. On
18
+ * macOS it is the product version, not the Darwin kernel version (which
19
+ * `os.release()` returns).
20
+ */
21
+ version: string;
22
+ /** Processor architecture as returned by `os.arch()`, e.g. `"x64"`. */
23
+ arch: string;
24
+ } & RuntimeObject;
25
+ /**
26
+ * Returns OS release information for the current platform (Linux, macOS, or
27
+ * Windows). `arch` always comes from `os.arch()`.
28
+ *
29
+ * - On Linux, it reads `/etc/os-release`, falling back to
30
+ * `/usr/lib/os-release`. `name` comes from `NAME` (or `PRETTY_NAME`) and
31
+ * `version` from `VERSION_ID` (or `VERSION`). Values are unquoted as in a
32
+ * shell; comments and keys that are not upper-case variable names are
33
+ * skipped.
34
+ * - On macOS, it reads `/System/Library/CoreServices/SystemVersion.plist`.
35
+ * `name` is `ProductName` (or `"macOS"`) and `version` is
36
+ * `ProductVersion` (e.g. `"15.1"`), never the Darwin kernel version.
37
+ * - On Windows, `version` is the kernel version, and Windows 11 is told
38
+ * apart from Windows 10 by NT build number (>= 22000).
39
+ *
40
+ * On Linux and macOS, the raw keys of the file are also present.
41
+ *
42
+ * @returns An {@link OsRelease}, or `null` on unsupported platforms or when
43
+ * the release file cannot be read.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * import { asString, osRelease } from "@darthcav/ts-utils"
48
+ *
49
+ * const info = osRelease()
50
+ * if (info) {
51
+ * console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
52
+ * // Raw keys are `unknown`; narrow them before use.
53
+ * const prettyName = asString(info["PRETTY_NAME"]) // e.g. "Ubuntu 24.04 LTS" (Linux only)
54
+ * }
55
+ * ```
56
+ */
57
+ export declare function osRelease(): OsRelease | null;
58
+ //# sourceMappingURL=osRelease.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"osRelease.d.ts","sourceRoot":"","sources":["../../src/node/osRelease.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAGtD;;;;;;;;;;GAUG;AACH,MAAM,MAAM,SAAS,GAAG;IACpB,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAA;IACf,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAA;CACf,GAAG,aAAa,CAAA;AAuEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,SAAS,IAAI,SAAS,GAAG,IAAI,CAqB5C"}