@darthcav/ts-utils 0.7.0 → 0.8.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 (40) hide show
  1. package/README.md +58 -13
  2. package/dist/__tests__/main.test.js +43 -26
  3. package/dist/__tests__/main.test.js.map +1 -1
  4. package/dist/__tests__/millisecondsToString.test.d.ts +2 -0
  5. package/dist/__tests__/millisecondsToString.test.d.ts.map +1 -0
  6. package/dist/__tests__/millisecondsToString.test.js +31 -0
  7. package/dist/__tests__/millisecondsToString.test.js.map +1 -0
  8. package/dist/__tests__/monitorMemory.test.d.ts +2 -0
  9. package/dist/__tests__/monitorMemory.test.d.ts.map +1 -0
  10. package/dist/__tests__/monitorMemory.test.js +36 -0
  11. package/dist/__tests__/monitorMemory.test.js.map +1 -0
  12. package/dist/index.d.ts +4 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +4 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/loggers/getDummyLogger.d.ts +12 -0
  17. package/dist/loggers/getDummyLogger.d.ts.map +1 -0
  18. package/dist/loggers/getDummyLogger.js +29 -0
  19. package/dist/loggers/getDummyLogger.js.map +1 -0
  20. package/dist/main.d.ts +44 -25
  21. package/dist/main.d.ts.map +1 -1
  22. package/dist/main.js +27 -12
  23. package/dist/main.js.map +1 -1
  24. package/dist/millisecondsToString.d.ts +19 -0
  25. package/dist/millisecondsToString.d.ts.map +1 -0
  26. package/dist/millisecondsToString.js +37 -0
  27. package/dist/millisecondsToString.js.map +1 -0
  28. package/dist/monitorMemory.d.ts +20 -0
  29. package/dist/monitorMemory.d.ts.map +1 -0
  30. package/dist/monitorMemory.js +28 -0
  31. package/dist/monitorMemory.js.map +1 -0
  32. package/package.json +3 -3
  33. package/src/__tests__/main.test.ts +76 -48
  34. package/src/__tests__/millisecondsToString.test.ts +37 -0
  35. package/src/__tests__/monitorMemory.test.ts +47 -0
  36. package/src/index.ts +11 -1
  37. package/src/loggers/getDummyLogger.ts +31 -0
  38. package/src/main.ts +96 -39
  39. package/src/millisecondsToString.ts +37 -0
  40. package/src/monitorMemory.ts +34 -0
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;AAqEjE,MAAM,UAAU,IAAI,CAChB,IAAY,EACZ,MAAc,EACd,oCAAiE,EACjE,QAA2B;IAE3B,IAAI,0BAA0B,GAAG,IAAI,CAAA;IACrC,IAAI,GAAiC,CAAA;IAErC,IAAI,OAAO,oCAAoC,KAAK,SAAS,EAAE,CAAC;QAC5D,0BAA0B,GAAG,oCAAoC,CAAA;QACjE,GAAG,GAAG,QAAQ,CAAA;IAClB,CAAC;SAAM,CAAC;QACJ,GAAG,GAAG,oCAAoC,CAAA;IAC9C,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;IAE1C,QAAQ,CAAC,IAAI,CAAC,0BAA0B,KAAK,OAAO,GAAG,GAAG,CAAC,CAAA;IAC3D,QAAQ,CAAC,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAA;IACtC,QAAQ,CAAC,IAAI,CAAC,wBAAwB,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,CAAA;IAC9D,QAAQ,CAAC,IAAI,CACT,4BAA4B,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CACvF,CAAA;IAED,IAAI,0BAA0B,EAAE,CAAC;QAC7B,KAAK,MAAM,MAAM,IAAI,CAAC,QAAQ,EAAE,SAAS,CAAU,EAAE,CAAC;YAClD,OAAO,CAAC,EAAE,CAAC,MAAM,EAA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,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CACzH,CAAA;QACD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACnB,CAAC,CAAC,CAAA;IAEF,QAAQ,EAAE,EAAE,CAAA;AAChB,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Converts a duration in milliseconds to a human-readable string such as
3
+ * `"1d 4h 32m 10s"`.
4
+ *
5
+ * Sub-second values are rounded to the nearest second. Leading zero components
6
+ * are omitted except for seconds, which are always included.
7
+ *
8
+ * @param ms - Duration in milliseconds.
9
+ * @returns A formatted duration string.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * millisecondsToString(3_661_000) // "1h 1m 1s"
14
+ * millisecondsToString(90_000) // "1m 30s"
15
+ * millisecondsToString(5_000) // "5s"
16
+ * ```
17
+ */
18
+ export default function millisecondsToString(ms: number): string;
19
+ //# sourceMappingURL=millisecondsToString.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"millisecondsToString.d.ts","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAmB/D"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Converts a duration in milliseconds to a human-readable string such as
3
+ * `"1d 4h 32m 10s"`.
4
+ *
5
+ * Sub-second values are rounded to the nearest second. Leading zero components
6
+ * are omitted except for seconds, which are always included.
7
+ *
8
+ * @param ms - Duration in milliseconds.
9
+ * @returns A formatted duration string.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * millisecondsToString(3_661_000) // "1h 1m 1s"
14
+ * millisecondsToString(90_000) // "1m 30s"
15
+ * millisecondsToString(5_000) // "5s"
16
+ * ```
17
+ */
18
+ export default function millisecondsToString(ms) {
19
+ const totalSeconds = Math.round(ms / 1000);
20
+ const days = Math.floor(totalSeconds / 86400);
21
+ const hours = Math.floor((totalSeconds % 86400) / 3600);
22
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
23
+ const seconds = totalSeconds % 60;
24
+ const parts = [];
25
+ if (days > 0) {
26
+ parts.push(`${days}d`);
27
+ }
28
+ if (hours > 0) {
29
+ parts.push(`${hours}h`);
30
+ }
31
+ if (minutes > 0) {
32
+ parts.push(`${minutes}m`);
33
+ }
34
+ parts.push(`${seconds}s`);
35
+ return parts.join(" ");
36
+ }
37
+ //# sourceMappingURL=millisecondsToString.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"millisecondsToString.js","sourceRoot":"","sources":["../src/millisecondsToString.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAAC,EAAU;IACnD,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,IAAI,CAAC,CAAA;IAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,CAAA;IAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,YAAY,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA;IACvD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,YAAY,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;IACtD,MAAM,OAAO,GAAG,YAAY,GAAG,EAAE,CAAA;IAEjC,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;QACX,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,CAAA;IAC1B,CAAC;IACD,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QACZ,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,CAAA;IAC3B,CAAC;IACD,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QACd,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,GAAG,CAAC,CAAA;IAC7B,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,GAAG,OAAO,GAAG,CAAC,CAAA;IACzB,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { Logger } from "@logtape/logtape";
2
+ /**
3
+ * Starts a periodic interval that logs process uptime and memory usage.
4
+ *
5
+ * Memory figures are reported in bytes as returned by Node.js
6
+ * {@link https://nodejs.org/api/process.html#processmemoryusage | process.memoryUsage()}.
7
+ *
8
+ * @param logger - Logger instance used to emit the memory reports.
9
+ * @param hours - Interval between reports in hours. Defaults to `24`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { getConsoleLogger, monitorMemory } from "@darthcav/ts-utils"
14
+ *
15
+ * monitorMemory(getConsoleLogger()) // every 24 hours
16
+ * monitorMemory(getConsoleLogger(), 1) // every hour
17
+ * ```
18
+ */
19
+ export default function monitorMemory(logger: Logger, hours?: number): void;
20
+ //# sourceMappingURL=monitorMemory.d.ts.map
@@ -0,0 +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;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,KAAK,GAAE,MAAW,GACnB,IAAI,CASN"}
@@ -0,0 +1,28 @@
1
+ import { memoryUsage, uptime } from "node:process";
2
+ import millisecondsToString from "./millisecondsToString.js";
3
+ /**
4
+ * Starts a periodic interval that logs process uptime and memory usage.
5
+ *
6
+ * Memory figures are reported in bytes as returned by Node.js
7
+ * {@link https://nodejs.org/api/process.html#processmemoryusage | process.memoryUsage()}.
8
+ *
9
+ * @param logger - Logger instance used to emit the memory reports.
10
+ * @param hours - Interval between reports in hours. Defaults to `24`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { getConsoleLogger, monitorMemory } from "@darthcav/ts-utils"
15
+ *
16
+ * monitorMemory(getConsoleLogger()) // every 24 hours
17
+ * monitorMemory(getConsoleLogger(), 1) // every hour
18
+ * ```
19
+ */
20
+ export default function monitorMemory(logger, hours = 24) {
21
+ const delay = 60 * 60 * 1_000 * hours;
22
+ setInterval(() => {
23
+ const { rss, heapTotal, heapUsed, external } = memoryUsage();
24
+ logger.info(`Process uptime: ${millisecondsToString(uptime() * 1_000)}`);
25
+ logger.info(`Process memory - Resident set size: ${rss} | Heap total: ${heapTotal} | Heap used: ${heapUsed} | External: ${external}`);
26
+ }, delay);
27
+ }
28
+ //# sourceMappingURL=monitorMemory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"monitorMemory.js","sourceRoot":"","sources":["../src/monitorMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAElD,OAAO,oBAAoB,MAAM,2BAA2B,CAAA;AAE5D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACjC,MAAc,EACd,QAAgB,EAAE;IAElB,MAAM,KAAK,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,GAAG,KAAK,CAAA;IACrC,WAAW,CAAC,GAAG,EAAE;QACb,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,WAAW,EAAE,CAAA;QAC5D,MAAM,CAAC,IAAI,CAAC,mBAAmB,oBAAoB,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,CAAC,CAAA;QACxE,MAAM,CAAC,IAAI,CACP,uCAAuC,GAAG,kBAAkB,SAAS,iBAAiB,QAAQ,gBAAgB,QAAQ,EAAE,CAC3H,CAAA;IACL,CAAC,EAAE,KAAK,CAAC,CAAA;AACb,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@darthcav/ts-utils",
3
3
  "description": "A collection of utility functions for TypeScript applications and modules",
4
- "version": "0.7.0",
4
+ "version": "0.8.1",
5
5
  "author": {
6
6
  "name": "darthcav"
7
7
  },
@@ -31,8 +31,8 @@
31
31
  "@logtape/logtape": "2.0.4"
32
32
  },
33
33
  "devDependencies": {
34
- "@biomejs/biome": "2.4.6",
35
- "@types/node": "25.4.0",
34
+ "@biomejs/biome": "2.4.7",
35
+ "@types/node": "25.5.0",
36
36
  "asserttt": "1.0.1",
37
37
  "shx": "0.4.0",
38
38
  "typedoc": "0.28.17"
@@ -9,6 +9,7 @@ await suite("main", () => {
9
9
  const onMock = mock.fn()
10
10
  const onceMock = mock.fn()
11
11
  const exitMock = mock.fn()
12
+ const setIntervalMock = mock.fn()
12
13
 
13
14
  const childLogger = { info: logMock, error: logMock } as unknown as Logger
14
15
  const logger = { getChild: () => childLogger } as unknown as Logger
@@ -18,9 +19,11 @@ await suite("main", () => {
18
19
  onMock.mock.resetCalls()
19
20
  onceMock.mock.resetCalls()
20
21
  exitMock.mock.resetCalls()
22
+ setIntervalMock.mock.resetCalls()
21
23
  mock.method(process, "on", onMock)
22
24
  mock.method(process, "once", onceMock)
23
25
  mock.method(process, "exit", exitMock)
26
+ mock.method(globalThis, "setInterval", setIntervalMock)
24
27
  })
25
28
 
26
29
  afterEach(() => {
@@ -96,47 +99,6 @@ await suite("main", () => {
96
99
  )
97
100
  })
98
101
 
99
- test("should register SIGKILL handler", () => {
100
- main("test-app", logger)
101
-
102
- const sigkillCall = onMock.mock.calls.find(
103
- (c) => c.arguments[0] === "SIGKILL",
104
- )
105
- assert.ok(sigkillCall, "SIGKILL handler not registered")
106
- })
107
-
108
- test("should not register SIGKILL handler when defaultInterruptionHandler is false", () => {
109
- main("test-app", logger, false)
110
-
111
- const sigkillCall = onMock.mock.calls.find(
112
- (c) => c.arguments[0] === "SIGKILL",
113
- )
114
- assert.equal(
115
- sigkillCall,
116
- undefined,
117
- "SIGKILL handler should not be registered",
118
- )
119
- })
120
-
121
- test("should exit on SIGKILL", () => {
122
- main("test-app", logger)
123
-
124
- const sigkillCall = onMock.mock.calls.find(
125
- (c) => c.arguments[0] === "SIGKILL",
126
- )
127
- assert.ok(sigkillCall)
128
- const handler = sigkillCall.arguments[1]
129
- handler("SIGKILL")
130
-
131
- assert.ok(
132
- logMock.mock.calls.some((c) =>
133
- /Received signal: SIGKILL/.test(c.arguments[0]),
134
- ),
135
- )
136
- assert.equal(exitMock.mock.callCount(), 1)
137
- assert.equal(exitMock.mock.calls[0]?.arguments[0], 1)
138
- })
139
-
140
102
  test("should register uncaughtException handler", () => {
141
103
  main("test-app", logger)
142
104
 
@@ -267,13 +229,6 @@ await suite("main", () => {
267
229
  assert.equal(launcher.mock.calls[0]?.arguments.length, 0)
268
230
  })
269
231
 
270
- test("should invoke the launcher function when provided with explicit defaultInterruptionHandler", () => {
271
- const launcher = mock.fn()
272
- main("test-app", logger, true, launcher)
273
- assert.equal(launcher.mock.callCount(), 1)
274
- assert.equal(launcher.mock.calls[0]?.arguments.length, 0)
275
- })
276
-
277
232
  test("should exit on unhandledRejection with an Error reason and no stack", () => {
278
233
  main("test-app", logger)
279
234
 
@@ -338,4 +293,77 @@ await suite("main", () => {
338
293
  assert.equal(exitMock.mock.callCount(), 1)
339
294
  assert.equal(exitMock.mock.calls[0]?.arguments[0], 1)
340
295
  })
296
+
297
+ // monitorMemoryHours overload combinations
298
+
299
+ test("should not start memory monitoring when monitorMemoryHours is 0 (default)", () => {
300
+ main("test-app", logger)
301
+ assert.equal(setIntervalMock.mock.callCount(), 0)
302
+ })
303
+
304
+ test("should start memory monitoring with only monitorMemoryHours", () => {
305
+ main("test-app", logger, 2)
306
+ assert.equal(setIntervalMock.mock.callCount(), 1)
307
+ assert.equal(
308
+ setIntervalMock.mock.calls[0]?.arguments[1],
309
+ 2 * 60 * 60 * 1_000,
310
+ )
311
+ })
312
+
313
+ test("should start memory monitoring with launcher and monitorMemoryHours", () => {
314
+ main("test-app", logger, mock.fn(), 2)
315
+ assert.equal(setIntervalMock.mock.callCount(), 1)
316
+ assert.equal(
317
+ setIntervalMock.mock.calls[0]?.arguments[1],
318
+ 2 * 60 * 60 * 1_000,
319
+ )
320
+ })
321
+
322
+ test("should start memory monitoring with monitorMemoryHours and defaultInterruptionHandler", () => {
323
+ main("test-app", logger, 3, false)
324
+ assert.equal(setIntervalMock.mock.callCount(), 1)
325
+ assert.equal(
326
+ setIntervalMock.mock.calls[0]?.arguments[1],
327
+ 3 * 60 * 60 * 1_000,
328
+ )
329
+ assert.equal(
330
+ onMock.mock.calls.find((c) => c.arguments[0] === "SIGINT"),
331
+ undefined,
332
+ )
333
+ })
334
+
335
+ test("should start memory monitoring with all three optional parameters", () => {
336
+ const launcher = mock.fn()
337
+ main("test-app", logger, launcher, 4, true)
338
+ assert.equal(setIntervalMock.mock.callCount(), 1)
339
+ assert.equal(
340
+ setIntervalMock.mock.calls[0]?.arguments[1],
341
+ 4 * 60 * 60 * 1_000,
342
+ )
343
+ assert.equal(launcher.mock.callCount(), 1)
344
+ })
345
+
346
+ // defaultInterruptionHandler overload combinations
347
+
348
+ test("should disable interruption handler with only defaultInterruptionHandler=false", () => {
349
+ main("test-app", logger, false)
350
+ assert.equal(
351
+ onMock.mock.calls.find((c) => c.arguments[0] === "SIGINT"),
352
+ undefined,
353
+ )
354
+ assert.equal(
355
+ onMock.mock.calls.find((c) => c.arguments[0] === "SIGTERM"),
356
+ undefined,
357
+ )
358
+ })
359
+
360
+ test("should disable interruption handler with launcher and defaultInterruptionHandler=false", () => {
361
+ const launcher = mock.fn()
362
+ main("test-app", logger, launcher, false)
363
+ assert.equal(
364
+ onMock.mock.calls.find((c) => c.arguments[0] === "SIGINT"),
365
+ undefined,
366
+ )
367
+ assert.equal(launcher.mock.callCount(), 1)
368
+ })
341
369
  })
@@ -0,0 +1,37 @@
1
+ import assert from "node:assert/strict"
2
+ import { suite, test } from "node:test"
3
+ import millisecondsToString from "../millisecondsToString.ts"
4
+
5
+ await suite("millisecondsToString", () => {
6
+ test("seconds only", () => {
7
+ assert.equal(millisecondsToString(5_000), "5s")
8
+ })
9
+
10
+ test("zero milliseconds", () => {
11
+ assert.equal(millisecondsToString(0), "0s")
12
+ })
13
+
14
+ test("sub-second values are rounded to nearest second", () => {
15
+ assert.equal(millisecondsToString(499), "0s")
16
+ assert.equal(millisecondsToString(500), "1s")
17
+ assert.equal(millisecondsToString(1_499), "1s")
18
+ assert.equal(millisecondsToString(1_500), "2s")
19
+ })
20
+
21
+ test("minutes and seconds", () => {
22
+ assert.equal(millisecondsToString(90_000), "1m 30s")
23
+ })
24
+
25
+ test("hours, minutes, and seconds", () => {
26
+ assert.equal(millisecondsToString(3_661_000), "1h 1m 1s")
27
+ })
28
+
29
+ test("days, hours, minutes, and seconds", () => {
30
+ assert.equal(millisecondsToString(90_061_000), "1d 1h 1m 1s")
31
+ })
32
+
33
+ test("leading zero components are omitted", () => {
34
+ assert.equal(millisecondsToString(3_600_000), "1h 0s")
35
+ assert.equal(millisecondsToString(86_400_000), "1d 0s")
36
+ })
37
+ })
@@ -0,0 +1,47 @@
1
+ import assert from "node:assert/strict"
2
+ import { afterEach, beforeEach, mock, suite, test } from "node:test"
3
+ import type { Logger } from "@logtape/logtape"
4
+ import monitorMemory from "../monitorMemory.ts"
5
+
6
+ await suite("monitorMemory", () => {
7
+ const logMock = mock.fn()
8
+ const logger = { info: logMock } as unknown as Logger
9
+
10
+ let setIntervalMock: ReturnType<typeof mock.method>
11
+
12
+ beforeEach(() => {
13
+ logMock.mock.resetCalls()
14
+ setIntervalMock = mock.method(
15
+ globalThis,
16
+ "setInterval",
17
+ (fn: () => void, _delay: number) => {
18
+ fn()
19
+ return 0
20
+ },
21
+ )
22
+ })
23
+
24
+ afterEach(() => {
25
+ mock.restoreAll()
26
+ })
27
+
28
+ test("defaults to 24-hour interval", () => {
29
+ monitorMemory(logger)
30
+ const delay = setIntervalMock.mock.calls[0]?.arguments[1]
31
+ assert.equal(delay, 24 * 60 * 60 * 1_000)
32
+ })
33
+
34
+ test("uses the provided hours parameter", () => {
35
+ monitorMemory(logger, 1)
36
+ const delay = setIntervalMock.mock.calls[0]?.arguments[1]
37
+ assert.equal(delay, 1 * 60 * 60 * 1_000)
38
+ })
39
+
40
+ test("logs uptime and memory info on each tick", () => {
41
+ monitorMemory(logger)
42
+ assert.equal(logMock.mock.calls.length, 2)
43
+ const messages = logMock.mock.calls.map((c) => String(c.arguments[0]))
44
+ assert.match(messages[0] ?? "", /Process uptime:/)
45
+ assert.match(messages[1] ?? "", /Process memory/)
46
+ })
47
+ })
package/src/index.ts CHANGED
@@ -5,6 +5,16 @@
5
5
  */
6
6
 
7
7
  import getConsoleLogger from "./loggers/getConsoleLogger.ts"
8
+ import getDummyLogger from "./loggers/getDummyLogger.ts"
8
9
  import { type LauncherFunction, main } from "./main.ts"
10
+ import millisecondsToString from "./millisecondsToString.ts"
11
+ import monitorMemory from "./monitorMemory.ts"
9
12
 
10
- export { getConsoleLogger, main, type LauncherFunction }
13
+ export {
14
+ getConsoleLogger,
15
+ getDummyLogger,
16
+ type LauncherFunction,
17
+ main,
18
+ millisecondsToString,
19
+ monitorMemory,
20
+ }
@@ -0,0 +1,31 @@
1
+ import type { Logger, LogLevel, LogRecord } from "@logtape/logtape"
2
+
3
+ const noop = (): void => {}
4
+
5
+ /**
6
+ * Returns a no-op {@link Logger} useful as a placeholder in tests.
7
+ *
8
+ * All logging methods (`trace`, `debug`, `info`, `warn`, `warning`, `error`,
9
+ * `fatal`) are no-ops. `getChild` and `with` return the same dummy logger
10
+ * instance.
11
+ *
12
+ * @returns A logger whose methods are all no-ops.
13
+ */
14
+ export default function getDummyLogger(): Logger {
15
+ const logger: Logger = {
16
+ category: [],
17
+ parent: null,
18
+ trace: noop as unknown as Logger["trace"],
19
+ debug: noop as unknown as Logger["debug"],
20
+ info: noop as unknown as Logger["info"],
21
+ warn: noop as unknown as Logger["warn"],
22
+ warning: noop as unknown as Logger["warning"],
23
+ error: noop as unknown as Logger["error"],
24
+ fatal: noop as unknown as Logger["fatal"],
25
+ emit: (_record: Omit<LogRecord, "category">): void => {},
26
+ getChild: () => logger,
27
+ isEnabledFor: (_level: LogLevel): boolean => false,
28
+ with: () => logger,
29
+ }
30
+ return logger
31
+ }
package/src/main.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import process, { env, execArgv, pid, title } from "node:process"
2
2
  import type { Logger } from "@logtape/logtape"
3
+ import monitorMemory from "./monitorMemory.ts"
3
4
 
4
5
  /**
5
6
  * A function that performs the actual application launch after process
@@ -10,77 +11,133 @@ export type LauncherFunction = () => void
10
11
 
11
12
  /**
12
13
  * Bootstraps an application process: logs startup information, registers
13
- * handlers for `SIGINT`, `SIGTERM`, `SIGKILL`, `uncaughtException`, and
14
+ * handlers for `SIGINT`, `SIGTERM`, `uncaughtException`, and
14
15
  * `unhandledRejection`, then delegates to the optional launcher function.
15
16
  *
17
+ * The three optional parameters — `launcher`, `monitorMemoryHours`, and
18
+ * `defaultInterruptionHandler` — have distinct types and can be supplied in
19
+ * any subset and in that order, omitting whichever are not needed:
20
+ *
21
+ * | Call | launcher | monitorMemoryHours | defaultInterruptionHandler |
22
+ * |------|----------|--------------------|---------------------------|
23
+ * | `main(name, logger)` | — | 0 | true |
24
+ * | `main(name, logger, fn)` | fn | 0 | true |
25
+ * | `main(name, logger, 2)` | — | 2 | true |
26
+ * | `main(name, logger, false)` | — | 0 | false |
27
+ * | `main(name, logger, fn, 2)` | fn | 2 | true |
28
+ * | `main(name, logger, fn, false)` | fn | 0 | false |
29
+ * | `main(name, logger, 2, false)` | — | 2 | false |
30
+ * | `main(name, logger, fn, 2, false)` | fn | 2 | false |
31
+ *
16
32
  * @param name - Human-readable application name used in log output.
17
33
  * @param logger - Logger instance used for all startup and lifecycle messages.
18
- * @param launcher - Optional function invoked after all process handlers are
19
- * registered. Use a closure to capture any context needed (e.g. a logger).
20
34
  *
21
- * @example Without a launcher:
35
+ * @example Without optional parameters:
22
36
  * ```ts
23
- * import { getLogger } from "@logtape/logtape"
24
- * import { main } from "@darthcav/ts-utils"
25
- *
26
- * main("my-app", getLogger(["my-app"]))
37
+ * main("my-app", logger)
27
38
  * ```
28
39
  *
29
40
  * @example With a launcher:
30
41
  * ```ts
31
- * const logger = getLogger(["my-app"])
32
- * main("my-app", logger, () => {
33
- * logger.info(`Application is running`)
34
- * // start servers, connect to databases, etc.
35
- * })
42
+ * main("my-app", logger, () => startServer())
36
43
  * ```
37
44
  *
38
- * @example Disable the built-in interruption handler to manage shutdown yourself:
45
+ * @example With memory monitoring every 2 hours:
39
46
  * ```ts
40
- * const logger = getLogger(["my-app"])
41
- * main("my-app", logger, false, () => {
42
- * const server = createServer(...)
43
- * process.on("SIGTERM", () => server.close(() => process.exit(0)))
44
- * })
47
+ * main("my-app", logger, 2)
48
+ * main("my-app", logger, () => startServer(), 2)
49
+ * ```
50
+ *
51
+ * @example Disable the built-in interruption handler:
52
+ * ```ts
53
+ * main("my-app", logger, false)
54
+ * main("my-app", logger, () => startServer(), false)
55
+ * main("my-app", logger, 2, false)
56
+ * main("my-app", logger, () => startServer(), 2, false)
45
57
  * ```
46
58
  */
59
+ export function main(name: string, logger: Logger): void
47
60
  export function main(
48
61
  name: string,
49
62
  logger: Logger,
50
- launcher?: LauncherFunction,
63
+ launcher: LauncherFunction,
64
+ ): void
65
+ export function main(
66
+ name: string,
67
+ logger: Logger,
68
+ monitorMemoryHours: number,
69
+ ): void
70
+ export function main(
71
+ name: string,
72
+ logger: Logger,
73
+ defaultInterruptionHandler: boolean,
74
+ ): void
75
+ export function main(
76
+ name: string,
77
+ logger: Logger,
78
+ launcher: LauncherFunction,
79
+ monitorMemoryHours: number,
80
+ ): void
81
+ export function main(
82
+ name: string,
83
+ logger: Logger,
84
+ launcher: LauncherFunction,
85
+ defaultInterruptionHandler: boolean,
86
+ ): void
87
+ export function main(
88
+ name: string,
89
+ logger: Logger,
90
+ monitorMemoryHours: number,
91
+ defaultInterruptionHandler: boolean,
51
92
  ): void
52
-
53
93
  /**
54
94
  * @param name - Human-readable application name used in log output.
55
95
  * @param logger - Logger instance used for all startup and lifecycle messages.
96
+ * @param launcher - Optional function invoked after all process handlers are
97
+ * registered. Use a closure to capture any context needed (e.g. a logger).
98
+ * @param monitorMemoryHours - When greater than `0`, starts periodic memory
99
+ * logging every `monitorMemoryHours` hours via {@link monitorMemory}.
100
+ * Defaults to `0` (disabled).
56
101
  * @param defaultInterruptionHandler - When `true` (default), registers `SIGINT`
57
102
  * and `SIGTERM` handlers that log and exit cleanly. Set to `false` when the
58
103
  * application manages its own graceful shutdown (e.g. closing servers or
59
- * database connections). Can be omitted entirely — pass the launcher directly
60
- * as the third argument to use the default (`true`).
61
- * @param launcher - Optional function invoked after all process handlers are
62
- * registered. Use a closure to capture any context needed (e.g. a logger).
104
+ * database connections).
63
105
  */
64
106
  export function main(
65
107
  name: string,
66
108
  logger: Logger,
109
+ launcher: LauncherFunction,
110
+ monitorMemoryHours: number,
67
111
  defaultInterruptionHandler: boolean,
68
- launcher?: LauncherFunction,
69
112
  ): void
70
113
  export function main(
71
114
  name: string,
72
115
  logger: Logger,
73
- defaultInterruptionHandlerOrLauncher?: boolean | LauncherFunction,
74
- launcher?: LauncherFunction,
116
+ arg3?: LauncherFunction | number | boolean,
117
+ arg4?: number | boolean,
118
+ arg5?: boolean,
75
119
  ): void {
120
+ let launcher: LauncherFunction | undefined
121
+ let monitorMemoryHours = 0
76
122
  let defaultInterruptionHandler = true
77
- let __f: LauncherFunction | undefined
78
123
 
79
- if (typeof defaultInterruptionHandlerOrLauncher === "boolean") {
80
- defaultInterruptionHandler = defaultInterruptionHandlerOrLauncher
81
- __f = launcher
82
- } else {
83
- __f = defaultInterruptionHandlerOrLauncher
124
+ if (typeof arg3 === "function") {
125
+ launcher = arg3
126
+ if (typeof arg4 === "number") {
127
+ monitorMemoryHours = arg4
128
+ if (typeof arg5 === "boolean") {
129
+ defaultInterruptionHandler = arg5
130
+ }
131
+ } else if (typeof arg4 === "boolean") {
132
+ defaultInterruptionHandler = arg4
133
+ }
134
+ } else if (typeof arg3 === "number") {
135
+ monitorMemoryHours = arg3
136
+ if (typeof arg4 === "boolean") {
137
+ defaultInterruptionHandler = arg4
138
+ }
139
+ } else if (typeof arg3 === "boolean") {
140
+ defaultInterruptionHandler = arg3
84
141
  }
85
142
 
86
143
  const __logger = logger.getChild(["main"])
@@ -92,6 +149,10 @@ export function main(
92
149
  `Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`,
93
150
  )
94
151
 
152
+ if (monitorMemoryHours > 0) {
153
+ monitorMemory(__logger, monitorMemoryHours)
154
+ }
155
+
95
156
  if (defaultInterruptionHandler) {
96
157
  for (const signal of ["SIGINT", "SIGTERM"] as const) {
97
158
  process.on(signal, (signal) => {
@@ -101,10 +162,6 @@ export function main(
101
162
  process.exit(0)
102
163
  })
103
164
  }
104
- process.on("SIGKILL", (signal) => {
105
- __logger.error(`Process killed. Received signal: ${signal}`)
106
- process.exit(1)
107
- })
108
165
  }
109
166
 
110
167
  process.on("uncaughtException", (error, origin) => {
@@ -122,5 +179,5 @@ export function main(
122
179
  process.exit(1)
123
180
  })
124
181
 
125
- __f?.()
182
+ launcher?.()
126
183
  }