@darthcav/ts-utils 0.12.2 → 1.0.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 (85) hide show
  1. package/README.md +152 -81
  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 +207 -0
  5. package/dist/core/guards.js.map +1 -0
  6. package/dist/core/index.d.ts +16 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/index.js +16 -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} +3 -4
  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/index.d.ts +15 -0
  30. package/dist/node/index.d.ts.map +1 -0
  31. package/dist/node/index.js +15 -0
  32. package/dist/node/index.js.map +1 -0
  33. package/dist/node/main.d.ts +156 -0
  34. package/dist/node/main.d.ts.map +1 -0
  35. package/dist/node/main.js +261 -0
  36. package/dist/node/main.js.map +1 -0
  37. package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +3 -5
  38. package/dist/node/monitorMemory.d.ts.map +1 -0
  39. package/dist/{monitorMemory.js → node/monitorMemory.js} +4 -7
  40. package/dist/node/monitorMemory.js.map +1 -0
  41. package/dist/node/osRelease.d.ts +55 -0
  42. package/dist/node/osRelease.d.ts.map +1 -0
  43. package/dist/{osRelease.js → node/osRelease.js} +77 -24
  44. package/dist/node/osRelease.js.map +1 -0
  45. package/dist/type-testing/index.d.ts +18 -0
  46. package/dist/type-testing/index.d.ts.map +1 -0
  47. package/dist/type-testing/index.js +12 -0
  48. package/dist/type-testing/index.js.map +1 -0
  49. package/package.json +23 -8
  50. package/src/core/guards.ts +243 -0
  51. package/src/core/index.ts +31 -0
  52. package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +3 -4
  53. package/src/core/noop.ts +2 -0
  54. package/src/index.ts +13 -49
  55. package/src/loggers/getConsoleLogger.ts +14 -19
  56. package/src/loggers/index.ts +14 -0
  57. package/src/node/index.ts +21 -0
  58. package/src/node/main.ts +427 -0
  59. package/src/{monitorMemory.ts → node/monitorMemory.ts} +4 -7
  60. package/src/node/osRelease.ts +251 -0
  61. package/src/type-testing/index.ts +18 -0
  62. package/dist/main.d.ts +0 -112
  63. package/dist/main.d.ts.map +0 -1
  64. package/dist/main.js +0 -219
  65. package/dist/main.js.map +0 -1
  66. package/dist/millisecondsToString.d.ts.map +0 -1
  67. package/dist/millisecondsToString.js.map +0 -1
  68. package/dist/monitorMemory.d.ts.map +0 -1
  69. package/dist/monitorMemory.js.map +0 -1
  70. package/dist/noop.d.ts +0 -7
  71. package/dist/noop.d.ts.map +0 -1
  72. package/dist/noop.js +0 -7
  73. package/dist/noop.js.map +0 -1
  74. package/dist/osRelease.d.ts +0 -46
  75. package/dist/osRelease.d.ts.map +0 -1
  76. package/dist/osRelease.js.map +0 -1
  77. package/dist/types.d.ts +0 -70
  78. package/dist/types.d.ts.map +0 -1
  79. package/dist/types.js +0 -84
  80. package/dist/types.js.map +0 -1
  81. package/src/main.ts +0 -302
  82. package/src/noop.ts +0 -6
  83. package/src/osRelease.ts +0 -174
  84. package/src/types.ts +0 -98
  85. /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
package/README.md CHANGED
@@ -11,15 +11,17 @@ A collection of utility functions for TypeScript applications and modules.
11
11
 
12
12
  ## Features
13
13
 
14
- - `main`: bootstraps a Node.js process with startup logging, signal and error handlers, log flushing
15
- on exit, and optional memory monitoring.
14
+ - `main`: bootstraps a Node.js process with startup logging, signal and error handlers, graceful
15
+ shutdown of application resources, log flushing on exit, and optional memory monitoring.
16
16
  - `getConsoleLogger` and `getDummyLogger`: a configured LogTape console logger, and a no-op logger
17
17
  for tests.
18
18
  - `monitorMemory`: periodic uptime and memory usage reports.
19
19
  - `millisecondsToString`: human-readable, localized durations.
20
- - `osRelease`: OS name, version, and architecture on Linux and Windows.
21
- - `RuntimeObject` with `isRuntimeObject`, `isString`, `asRuntimeObject`, `asString`, and
22
- `toRuntimeObjectArray`: narrow `unknown` values such as parsed JSON without type assertions.
20
+ - `osRelease`: OS name, version, and architecture on Linux, macOS, and Windows.
21
+ - Type guards and narrowing helpers (`isString`/`asString`, `isBoolean`/`asBoolean`,
22
+ `isFiniteNumber`/`asFiniteNumber`, `isRuntimeObject`/`asRuntimeObject`, `isArrayOf`/`asArrayOf`,
23
+ `filterByGuard`, `toRuntimeObjectArray`): narrow `unknown` values such as parsed JSON without type
24
+ assertions.
23
25
  - `Assert`, `Equal`, `Extends`, `Not`, `IsAny`, `IsNever`, and `IsUnknown`: type-level assertions
24
26
  for tests.
25
27
  - `noop`: a function that does nothing.
@@ -32,14 +34,39 @@ ESM only, with TypeScript declarations included; requires Node.js 26 or later.
32
34
  npm install @darthcav/ts-utils
33
35
  ```
34
36
 
37
+ ## Entry points
38
+
39
+ The root entry point re-exports everything. Subpath entry points load only one domain:
40
+
41
+ | Import | Contents |
42
+ | --------------------------------- | ---------------------------------------------------------------------------------- |
43
+ | `@darthcav/ts-utils` | Everything below. |
44
+ | `@darthcav/ts-utils/core` | Type guards and narrowing helpers, `millisecondsToString`, `noop`. Portable. |
45
+ | `@darthcav/ts-utils/node` | `main`, `monitorMemory`, `osRelease`. |
46
+ | `@darthcav/ts-utils/loggers` | `getConsoleLogger`, `getDummyLogger` (LogTape). |
47
+ | `@darthcav/ts-utils/type-testing` | `Assert`, `Equal`, `Extends`, `Not`, `IsAny`, `IsNever`, `IsUnknown` (types only). |
48
+
49
+ ```ts
50
+ import { asString } from "@darthcav/ts-utils/core"
51
+ import { main } from "@darthcav/ts-utils/node"
52
+ import { getConsoleLogger } from "@darthcav/ts-utils/loggers"
53
+ import type { Assert, Equal } from "@darthcav/ts-utils/type-testing"
54
+ ```
55
+
56
+ The `core` entry point imports no Node.js built-ins and no packages, so its helpers run in any
57
+ runtime that supports ES2025 (`millisecondsToString` needs `Intl.DurationFormat`).
58
+
35
59
  ## Usage
36
60
 
37
61
  ### `getConsoleLogger`
38
62
 
39
- Configures logging and resolves to a `Logger` for the given category name. Records at or above
40
- `lowestLevel` are written to the console with RFC 3339 timestamps. The internal `logtape/meta`
41
- logger is silenced. The function is safe to call more than once — each call reconfigures logtape
42
- from scratch (the most recent call wins).
63
+ Configures LogTape globally and resolves to a `Logger` for the given category name. Records at or
64
+ above `lowestLevel` are written to the console with RFC 3339 timestamps, and the internal
65
+ `logtape/meta` logger is silenced.
66
+
67
+ Each call replaces the whole global LogTape configuration, including one made by the application, so
68
+ the latest call wins. Applications that configure LogTape themselves should not call it; they get
69
+ their loggers from LogTape's `getLogger` and can pass them to `main` (see its `flushLogs` option).
43
70
 
44
71
  ANSI colors are used only when both stdout and stderr are terminals that support them (respecting
45
72
  `NO_COLOR`, `NODE_DISABLE_COLORS`, and `TERM=dumb`), so logs redirected to files or pipes stay free
@@ -73,23 +100,19 @@ must be between one minute (`1 / 60`) and about 596.5 hours (2³¹ − 1 ms, the
73
100
  `setInterval` supports); anything outside that range throws a `RangeError`.
74
101
 
75
102
  It returns a function that stops the monitoring. The timer is unreferenced, so monitoring alone does
76
- not keep the process alive. Besides the human-readable message, each report attaches its figures as
77
- structured properties (`uptime` and `uptimeMs`; `rss`, `heapTotal`, `heapUsed`, and `external`), so
78
- sinks that keep properties, such as JSON Lines, can query them.
103
+ not keep the process alive. Each report also attaches its figures as structured properties (`uptime`
104
+ and `uptimeMs`; `rss`, `heapTotal`, `heapUsed`, and `external`), so sinks that keep properties, such
105
+ as JSON Lines, can query them. With `main`, use its `monitorMemoryHours` option instead.
79
106
 
80
107
  ```ts
81
- import { getConsoleLogger, main, monitorMemory } from "@darthcav/ts-utils"
108
+ import { getConsoleLogger, monitorMemory } from "@darthcav/ts-utils"
82
109
 
83
110
  const logger = await getConsoleLogger("my-app")
84
111
 
85
- main("my-app", logger, {
86
- launcher: () => {
87
- monitorMemory(logger) // every 24 hours
88
- const stop = monitorMemory(logger, 1) // every hour
89
- // later, e.g. during shutdown:
90
- stop()
91
- },
92
- })
112
+ monitorMemory(logger) // every 24 hours
113
+ const stop = monitorMemory(logger, 1) // every hour
114
+ // later:
115
+ stop()
93
116
  ```
94
117
 
95
118
  ### `millisecondsToString`
@@ -114,8 +137,7 @@ millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
114
137
 
115
138
  ### `noop`
116
139
 
117
- A no-op function that does nothing and returns `void`. Useful as a placeholder callback or default
118
- handler.
140
+ Does nothing. Useful as a placeholder callback or default handler.
119
141
 
120
142
  ```ts
121
143
  import { noop } from "@darthcav/ts-utils"
@@ -142,10 +164,18 @@ const payload: RuntimeObject = {
142
164
 
143
165
  Narrow `unknown` values (e.g. parsed JSON) without type assertions:
144
166
 
145
- - `isRuntimeObject` / `isString` are type guards for use in conditions.
146
- - `asRuntimeObject` / `asString` return the value, or `undefined` when it does not match, for use
147
- with `?.` and `??`.
148
- - `toRuntimeObjectArray` keeps only the plain-object elements of an array.
167
+ - `isRuntimeObject`, `isString`, `isBoolean`, and `isFiniteNumber` are type guards for use in
168
+ conditions. `isBoolean` and `isFiniteNumber` accept primitives only; `isFiniteNumber` rejects
169
+ `NaN`, `Infinity`, and `-Infinity`.
170
+ - `asRuntimeObject`, `asString`, `asBoolean`, and `asFiniteNumber` return the value, or `undefined`
171
+ when it does not match, for use with `?.` and `??`.
172
+ - `isArrayOf(value, guard)` checks that a value is an array whose elements **all** pass a guard; one
173
+ invalid element makes it fail, and an empty array passes. `asArrayOf` is its narrowing helper.
174
+ - `filterByGuard(value, guard)` keeps the elements that pass a guard and silently drops the others;
175
+ a value that is not an array yields `[]`. Use it to filter, and `isArrayOf` to validate.
176
+ - `toRuntimeObjectArray` keeps only the plain-object elements of an array (`filterByGuard` with
177
+ `isRuntimeObject`).
178
+ - `TypeGuard<T>` is the type of a guard (`(value: unknown) => value is T`), for writing your own.
149
179
 
150
180
  A runtime object is a plain object (an object literal, a `JSON.parse` result, or an
151
181
  `Object.create(null)` object); arrays, class instances, and built-ins such as `Date` or `Map` are
@@ -154,12 +184,15 @@ kept, so guard against those keys before merging the value into other objects.
154
184
 
155
185
  ```ts
156
186
  import {
187
+ asArrayOf,
188
+ asFiniteNumber,
157
189
  asRuntimeObject,
158
190
  asString,
191
+ filterByGuard,
159
192
  isRuntimeObject,
160
193
  isString,
161
194
  toRuntimeObjectArray,
162
- } from "@darthcav/ts-utils"
195
+ } from "@darthcav/ts-utils/core"
163
196
 
164
197
  const body: unknown = JSON.parse(input)
165
198
 
@@ -167,29 +200,38 @@ if (isRuntimeObject(body) && isString(body["name"])) {
167
200
  console.log(body["name"].toUpperCase()) // narrowed to string
168
201
  }
169
202
 
170
- const name = asString(asRuntimeObject(body)?.["name"]) ?? "anonymous"
171
- const items = toRuntimeObjectArray(asRuntimeObject(body)?.["items"])
203
+ const config = asRuntimeObject(body)
204
+ const name = asString(config?.["name"]) ?? "anonymous"
205
+ const port = asFiniteNumber(config?.["port"]) ?? 3000
206
+ const tags = asArrayOf(config?.["tags"], isString) // string[] | undefined (all or nothing)
207
+ const someTags = filterByGuard(config?.["tags"], isString) // string[] (invalid ones dropped)
208
+ const items = toRuntimeObjectArray(config?.["items"])
172
209
  ```
173
210
 
174
211
  ### `osRelease`
175
212
 
176
213
  Returns OS release information for the current platform as an `OsRelease` object, or `null` on
177
- unsupported platforms or when no os-release file can be read on Linux (it never throws for a missing
178
- or unreadable file).
179
-
180
- The `OsRelease` type exposes three normalized fields — `name`, `version`, and `arch` — present on
181
- all platforms. On Linux, the data comes from `/etc/os-release`, falling back to
182
- `/usr/lib/os-release`, and all raw key-value pairs (e.g. `PRETTY_NAME`, `ID`, `ID_LIKE`) are also
183
- accessible by string index. Comment lines are ignored, single- and double-quoted values are
184
- unquoted, and keys that are not upper-case shell variable names (such as `__proto__`) are skipped.
214
+ unsupported platforms or when the release file cannot be read. The normalized fields `name`,
215
+ `version`, and `arch` are present on every platform.
216
+
217
+ - On Linux, the data comes from `/etc/os-release`, falling back to `/usr/lib/os-release`, and all
218
+ raw key-value pairs (e.g. `PRETTY_NAME`, `ID`, `ID_LIKE`) are also accessible by string index.
219
+ Values are unquoted as in a shell; comments and keys that are not upper-case variable names (such
220
+ as `__proto__`) are skipped.
221
+ - On macOS, the data comes from `/System/Library/CoreServices/SystemVersion.plist`: `name` is the
222
+ product name (`"macOS"`) and `version` the product version (e.g. `"15.1"`) — never the Darwin
223
+ kernel version, which `os.release()` returns. The string keys of the file (e.g.
224
+ `ProductBuildVersion`) are also accessible by string index.
225
+ - On Windows, `version` is the kernel version and `name` tells Windows 11 from Windows 10 by build
226
+ number.
185
227
 
186
228
  ```ts
187
229
  import { osRelease } from "@darthcav/ts-utils"
188
230
 
189
231
  const info = osRelease()
190
232
  if (info) {
191
- console.log(info.name) // e.g. "Ubuntu" or "Windows 11"
192
- console.log(info.version) // e.g. "24.04" or "10.0.22000"
233
+ console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
234
+ console.log(info.version) // e.g. "24.04", "15.1", or "10.0.22000"
193
235
  console.log(info.arch) // e.g. "x64"
194
236
  console.log(info.PRETTY_NAME) // e.g. "Ubuntu 24.04 LTS" (Linux only)
195
237
  }
@@ -218,33 +260,53 @@ The process title, PID, name, and `NODE_ENV` are logged at `info` level. The Nod
218
260
  (`execArgv` and `NODE_OPTIONS`) are logged at `debug` level only, since they can reveal sensitive
219
261
  flags such as `--inspect=0.0.0.0`.
220
262
 
221
- Before exiting, `main` flushes and disposes the configured logtape sinks (for at most
222
- `flushTimeoutMs`, 3 seconds by default), so buffered or asynchronous sinks keep the final messages.
223
- On `SIGINT`/`SIGTERM` it logs the signal at `info` level and then re-raises it, so the process ends
224
- as killed by that signal (exit status 130/143), which shells and supervisors such as systemd treat
225
- as a clean stop. If another listener for that signal is registered, the process exits with status
226
- `128 + signal number` instead. Uncaught exceptions, unhandled rejections, and launcher failures exit
227
- with status `1`. A second signal or error during the flush exits immediately.
263
+ On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a launcher failure, `main`
264
+ runs a shutdown sequence once:
265
+
266
+ 1. It logs the cause (signals at `info`, failures at `error` level) and stops the memory monitoring.
267
+ 2. It runs your `shutdown` function, if any, for at most `shutdownTimeoutMs` (10 seconds by
268
+ default). The function receives a `ShutdownContext`: `{ reason: "signal", signal }` for a normal
269
+ stop, or `{ reason: "error", source, error }` for a fatal failure, where `source` is
270
+ `"uncaughtException"`, `"unhandledRejection"`, or `"launcher"`. A rejection, exception, or
271
+ timeout is logged at `error` level.
272
+ 3. It flushes the logs with `flushLogs` (LogTape's `dispose` by default) for at most
273
+ `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the final messages.
274
+ 4. It exits. A signal is re-raised, so the process ends as killed by it (exit status 130/143), which
275
+ shells and supervisors such as systemd treat as a clean stop; if another listener for that signal
276
+ exists, it exits with status `128 + signal number` instead. Fatal failures, and a failed or
277
+ timed-out `shutdown` function, exit with status `1`, so supervisors notice the failed cleanup.
278
+
279
+ A second signal or fatal failure during the sequence exits immediately. After a fatal failure the
280
+ application may be in an inconsistent state, so check `context.reason` and only clean up, e.g. close
281
+ connections.
228
282
 
229
283
  Optional settings are passed as a `MainOptions` object:
230
284
 
231
- | Option | Type | Default | Description |
232
- | ---------------------------- | ----------------------------- | ------- | ---------------------------------------------------------- |
233
- | `launcher` | `() => void \| Promise<void>` | — | Runs after the handlers are registered; may be async. |
234
- | `monitorMemoryHours` | `number` | `0` | Logs memory usage every N hours; `0` disables it. |
235
- | `defaultInterruptionHandler` | `boolean` | `true` | Register the `SIGINT`/`SIGTERM` handlers. |
236
- | `flushTimeoutMs` | `number` | `3000` | Longest wait for the log sinks to flush (0 to 2³¹ − 1 ms). |
237
-
238
- An out-of-range `monitorMemoryHours` (negative, `NaN`, or outside `monitorMemory`'s range) or
239
- `flushTimeoutMs` throws a `RangeError` before any handler is registered. If the launcher throws or
240
- its promise rejects, the failure is logged and the process exits with status `1`.
285
+ | Option | Type | Default | Description |
286
+ | ---------------------------- | ------------------------------------ | ----------------- | --------------------------------------------------------------- |
287
+ | `launcher` | `() => void \| Promise<void>` | — | Runs after the handlers are registered; may be async. |
288
+ | `shutdown` | `(context) => void \| Promise<void>` | — | Cleans up application resources once, before the process exits. |
289
+ | `shutdownTimeoutMs` | `number` | `10000` | Longest wait for `shutdown` (0 to 2³¹ − 1 ms). |
290
+ | `monitorMemoryHours` | `number` | `0` | Logs memory usage every N hours; `0` disables it. |
291
+ | `defaultInterruptionHandler` | `boolean` | `true` | Register the `SIGINT`/`SIGTERM` handlers. |
292
+ | `flushLogs` | `() => void \| Promise<void>` | LogTape `dispose` | Flushes the log sinks before exiting; `noop` skips flushing. |
293
+ | `flushTimeoutMs` | `number` | `3000` | Longest wait for `flushLogs` (0 to 2³¹ − 1 ms). |
294
+
295
+ An out-of-range `monitorMemoryHours` (negative, `NaN`, or outside `monitorMemory`'s range),
296
+ `shutdownTimeoutMs`, or `flushTimeoutMs` throws a `RangeError`, and a `launcher`, `shutdown`, or
297
+ `flushLogs` that is not a function throws a `TypeError`, before any handler is registered. If the
298
+ launcher throws or its promise rejects, the failure is logged and the shutdown sequence runs.
299
+
300
+ The default `flushLogs` disposes the sinks configured through the `@logtape/logtape` copy this
301
+ package uses. If the application configures another copy (e.g. a different LogTape version, whose
302
+ configuration this package cannot reach), pass that copy's `dispose` instead.
241
303
 
242
304
  `main` returns a teardown function that removes the handlers it registered and stops the memory
243
- monitoring (it does not exit the process). Only one `main` call can be active at a time: calling it
244
- again before the teardown throws, instead of registering a second set of handlers.
305
+ monitoring (it neither runs `shutdown` nor exits the process). Only one `main` call can be active at
306
+ a time: calling it again before the teardown throws.
245
307
 
246
308
  ```ts
247
- import { getLogger } from "@logtape/logtape"
309
+ import { dispose, getLogger } from "@logtape/logtape"
248
310
  import { main } from "@darthcav/ts-utils"
249
311
 
250
312
  const logger = getLogger(["my-app"])
@@ -263,18 +325,25 @@ main("my-app", logger, {
263
325
  monitorMemoryHours: 2,
264
326
  })
265
327
 
266
- // 3. Manage graceful shutdown in the application instead:
328
+ // 3. Graceful shutdown of the application's resources:
267
329
  let server: Server | undefined
268
- const teardown = main("my-app", logger, {
269
- launcher: () => {
330
+ main("my-app", logger, {
331
+ launcher: async () => {
332
+ await connectToDatabase()
270
333
  server = startServer()
271
334
  },
272
- defaultInterruptionHandler: false,
273
- })
274
- process.once("SIGTERM", async () => {
275
- await server?.close()
276
- teardown()
335
+ shutdown: async (context) => {
336
+ if (context.reason === "error") {
337
+ logger.warn`Shutting down after a failure in ${context.source}`
338
+ }
339
+ await server?.close()
340
+ await disconnectFromDatabase()
341
+ },
342
+ shutdownTimeoutMs: 15_000,
277
343
  })
344
+
345
+ // 4. Keep your own LogTape setup (e.g. another LogTape version) and flush it yourself:
346
+ main("my-app", logger, { flushLogs: dispose })
278
347
  ```
279
348
 
280
349
  The positional forms of earlier versions (e.g. `main("my-app", logger, () => startServer(), 2)`)
@@ -341,18 +410,20 @@ npm run doc
341
410
 
342
411
  ```
343
412
  src/
344
- index.ts # Public API entry point
345
- main.ts # Process bootstrap (main)
346
- millisecondsToString.ts # Duration formatting
347
- monitorMemory.ts # Periodic memory reporting
348
- noop.ts # No-op function
349
- osRelease.ts # OS release utilities
350
- types.ts # RuntimeObject type and type guards
351
- loggers/ # Logger utilities
352
- type-testing/ # Type-level assertion helpers
353
- __tests__/ # Test files
354
- dist/ # Compiled output (generated)
355
- public/ # Documentation output (generated)
413
+ index.ts # Root entry point (re-exports every domain)
414
+ core/ # @darthcav/ts-utils/core (portable)
415
+ guards.ts # RuntimeObject, TypeGuard, type guards and narrowing helpers
416
+ millisecondsToString.ts # Duration formatting
417
+ noop.ts # No-op function
418
+ node/ # @darthcav/ts-utils/node
419
+ main.ts # Process bootstrap and shutdown (main)
420
+ monitorMemory.ts # Periodic memory reporting
421
+ osRelease.ts # OS release information
422
+ loggers/ # @darthcav/ts-utils/loggers (LogTape helpers)
423
+ type-testing/ # @darthcav/ts-utils/type-testing (type-level assertions)
424
+ __tests__/ # Test files (and child-process fixtures)
425
+ dist/ # Compiled output (generated)
426
+ public/ # Documentation output (generated)
356
427
  ```
357
428
 
358
429
  ## License
@@ -361,7 +432,7 @@ public/ # Documentation output (generated)
361
432
 
362
433
  [node-version]: https://img.shields.io/badge/node-%3E%3D26-orange.svg?style=flat-square
363
434
  [node-url]: https://nodejs.org
364
- [version-image]: https://img.shields.io/badge/version-0.12.2-blue.svg?style=flat-square
435
+ [version-image]: https://img.shields.io/badge/version-1.0.0-blue.svg?style=flat-square
365
436
  [ci-badge]: https://github.com/darthcav/ts-utils/actions/workflows/tests.yml/badge.svg
366
437
  [coverage-badge]:
367
438
  https://codecov.io/github/darthcav/ts-utils/branch/dev/graph/badge.svg?token=RNEPER4KEI
@@ -0,0 +1,176 @@
1
+ /**
2
+ * A generic runtime object with property names and values that are not known at
3
+ * compile time.
4
+ *
5
+ * Uses `unknown` instead of `any` so callers must narrow values before using
6
+ * them in a type-safe way.
7
+ */
8
+ export type RuntimeObject = Record<string, unknown>;
9
+ /**
10
+ * Type guard that checks whether a value is a plain object that can be treated
11
+ * as a runtime JSON object.
12
+ *
13
+ * Plain objects are object literals, `JSON.parse` results, and
14
+ * `Object.create(null)` objects, including those from another realm (e.g. a
15
+ * `node:vm` context). Arrays, class instances, and built-ins such as `Date`,
16
+ * `Map`, `Set`, `RegExp`, or module namespace objects are rejected.
17
+ *
18
+ * The check is shallow and keys are not sanitized: an own `__proto__` or
19
+ * `constructor` key (as `JSON.parse` can produce from untrusted input) is kept.
20
+ * Do not merge the value into other objects key by key without guarding
21
+ * against those keys, or prototype pollution becomes possible.
22
+ *
23
+ * @param value - Value to check.
24
+ * @returns `true` when the value is a plain object, narrowing it to
25
+ * {@link RuntimeObject}.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const body: unknown = JSON.parse(input)
30
+ * if (isRuntimeObject(body)) {
31
+ * console.log(Object.keys(body)) // body: RuntimeObject
32
+ * }
33
+ * ```
34
+ */
35
+ export declare function isRuntimeObject(value: unknown): value is RuntimeObject;
36
+ /**
37
+ * Returns the input when it is a plain object, as decided by
38
+ * {@link isRuntimeObject} (see there for the caveats about unsanitized keys).
39
+ *
40
+ * @param value - Value to narrow.
41
+ * @returns The same value as a {@link RuntimeObject}, or `undefined` when the
42
+ * value is not a plain object.
43
+ */
44
+ export declare function asRuntimeObject(value: unknown): RuntimeObject | undefined;
45
+ /**
46
+ * Type guard that checks whether a value is a string.
47
+ *
48
+ * @param value - Value to check.
49
+ * @returns `true` when the value is a string, narrowing it to `string`.
50
+ */
51
+ export declare function isString(value: unknown): value is string;
52
+ /**
53
+ * Returns the input when it is a string.
54
+ *
55
+ * @param value - Value to narrow.
56
+ * @returns The same value as a string, or `undefined` when the value is not a string.
57
+ */
58
+ export declare function asString(value: unknown): string | undefined;
59
+ /**
60
+ * Type guard that checks whether a value is a boolean primitive (`true` or
61
+ * `false`). Boxed `Boolean` objects are rejected.
62
+ *
63
+ * @param value - Value to check.
64
+ * @returns `true` when the value is a boolean, narrowing it to `boolean`.
65
+ */
66
+ export declare function isBoolean(value: unknown): value is boolean;
67
+ /**
68
+ * Returns the input when it is a boolean primitive, as decided by
69
+ * {@link isBoolean}.
70
+ *
71
+ * @param value - Value to narrow.
72
+ * @returns The same value as a boolean, or `undefined` when the value is not
73
+ * a boolean.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * const enabled = asBoolean(config["enabled"]) ?? false
78
+ * ```
79
+ */
80
+ export declare function asBoolean(value: unknown): boolean | undefined;
81
+ /**
82
+ * Type guard that checks whether a value is a finite number primitive. `NaN`,
83
+ * `Infinity`, `-Infinity`, boxed `Number` objects, bigints, and numeric
84
+ * strings are rejected.
85
+ *
86
+ * @param value - Value to check.
87
+ * @returns `true` when the value is a finite number, narrowing it to
88
+ * `number`.
89
+ */
90
+ export declare function isFiniteNumber(value: unknown): value is number;
91
+ /**
92
+ * Returns the input when it is a finite number primitive, as decided by
93
+ * {@link isFiniteNumber}.
94
+ *
95
+ * @param value - Value to narrow.
96
+ * @returns The same value as a number, or `undefined` when the value is not a
97
+ * finite number.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const port = asFiniteNumber(config["port"]) ?? 3000
102
+ * ```
103
+ */
104
+ export declare function asFiniteNumber(value: unknown): number | undefined;
105
+ /**
106
+ * A predicate that narrows an `unknown` value to `T`, such as
107
+ * {@link isString}. Used by {@link isArrayOf}, {@link asArrayOf}, and
108
+ * {@link filterByGuard}.
109
+ *
110
+ * @typeParam T - The type the guard narrows to.
111
+ */
112
+ export type TypeGuard<T> = (value: unknown) => value is T;
113
+ /**
114
+ * Type guard that checks whether a value is an array whose elements all pass
115
+ * `guard`. A single invalid element makes it fail (use {@link filterByGuard}
116
+ * to keep only the valid ones); an empty array passes. Holes in sparse arrays
117
+ * are checked as `undefined`.
118
+ *
119
+ * @typeParam T - The element type the guard narrows to.
120
+ * @param value - Value to check.
121
+ * @param guard - Type guard every element must pass.
122
+ * @returns `true` when the value is an array of `T`, narrowing it to `T[]`.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * const body: unknown = JSON.parse(input)
127
+ * if (isArrayOf(body, isString)) {
128
+ * body.map((tag) => tag.toUpperCase()) // body: string[]
129
+ * }
130
+ * ```
131
+ */
132
+ export declare function isArrayOf<T>(value: unknown, guard: TypeGuard<T>): value is T[];
133
+ /**
134
+ * Returns the input when it is an array whose elements all pass `guard`, as
135
+ * decided by {@link isArrayOf}.
136
+ *
137
+ * @typeParam T - The element type the guard narrows to.
138
+ * @param value - Value to narrow.
139
+ * @param guard - Type guard every element must pass.
140
+ * @returns The same array as `T[]`, or `undefined` when the value is not an
141
+ * array or any element fails the guard.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const tags = asArrayOf(asRuntimeObject(body)?.["tags"], isString) ?? []
146
+ * ```
147
+ */
148
+ export declare function asArrayOf<T>(value: unknown, guard: TypeGuard<T>): T[] | undefined;
149
+ /**
150
+ * Keeps the elements of an array that pass `guard` and silently drops the
151
+ * others, unlike {@link isArrayOf}, which rejects the whole array. A value
152
+ * that is not an array yields an empty array, and holes in sparse arrays are
153
+ * skipped.
154
+ *
155
+ * @typeParam T - The element type the guard narrows to.
156
+ * @param value - Value that may be an array.
157
+ * @param guard - Type guard deciding which elements to keep.
158
+ * @returns A new array with the elements that pass the guard.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * filterByGuard(["a", 1, "b", null], isString) // ["a", "b"]
163
+ * filterByGuard("not an array", isString) // []
164
+ * ```
165
+ */
166
+ export declare function filterByGuard<T>(value: unknown, guard: TypeGuard<T>): T[];
167
+ /**
168
+ * Keeps the plain objects of an array: {@link filterByGuard} with
169
+ * {@link isRuntimeObject}, whose caveats about unsanitized keys apply. A value
170
+ * that is not an array yields an empty array.
171
+ *
172
+ * @param value - Value that may contain runtime objects.
173
+ * @returns Only the elements that can be treated as {@link RuntimeObject} values.
174
+ */
175
+ export declare function toRuntimeObjectArray(value: unknown): RuntimeObject[];
176
+ //# sourceMappingURL=guards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/core/guards.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAgBtE;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,GAAG,SAAS,CAEzE;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAExD;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAE3D;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,OAAO,CAE1D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,GAAG,SAAS,CAE7D;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE9D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAEjE;AAED;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,IAAI,CAAC,CAAA;AAEzD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CAAC,CAAC,EACvB,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GACpB,KAAK,IAAI,CAAC,EAAE,CAWd;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,CAAC,EACvB,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GACpB,CAAC,EAAE,GAAG,SAAS,CAEjB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAIzE;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,EAAE,CAEpE"}