@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.
- package/README.md +162 -84
- package/dist/core/guards.d.ts +176 -0
- package/dist/core/guards.d.ts.map +1 -0
- package/dist/core/guards.js +201 -0
- package/dist/core/guards.js.map +1 -0
- package/dist/core/index.d.ts +17 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +17 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/millisecondsToString.d.ts.map +1 -0
- package/dist/{millisecondsToString.js → core/millisecondsToString.js} +9 -14
- package/dist/core/millisecondsToString.js.map +1 -0
- package/dist/core/noop.d.ts +3 -0
- package/dist/core/noop.d.ts.map +1 -0
- package/dist/core/noop.js +3 -0
- package/dist/core/noop.js.map +1 -0
- package/dist/index.d.ts +13 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/loggers/getConsoleLogger.d.ts +11 -12
- package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
- package/dist/loggers/getConsoleLogger.js +14 -19
- package/dist/loggers/getConsoleLogger.js.map +1 -1
- package/dist/loggers/index.d.ts +14 -0
- package/dist/loggers/index.d.ts.map +1 -0
- package/dist/loggers/index.js +14 -0
- package/dist/loggers/index.js.map +1 -0
- package/dist/node/delays.d.ts +11 -0
- package/dist/node/delays.d.ts.map +1 -0
- package/dist/node/delays.js +14 -0
- package/dist/node/delays.js.map +1 -0
- package/dist/node/index.d.ts +15 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +15 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/main.d.ts +158 -0
- package/dist/node/main.d.ts.map +1 -0
- package/dist/node/main.js +255 -0
- package/dist/node/main.js.map +1 -0
- package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +14 -5
- package/dist/node/monitorMemory.d.ts.map +1 -0
- package/dist/{monitorMemory.js → node/monitorMemory.js} +22 -16
- package/dist/node/monitorMemory.js.map +1 -0
- package/dist/node/osRelease.d.ts +58 -0
- package/dist/node/osRelease.d.ts.map +1 -0
- package/dist/node/osRelease.js +111 -0
- package/dist/node/osRelease.js.map +1 -0
- package/dist/node/releaseParsers.d.ts +11 -0
- package/dist/node/releaseParsers.d.ts.map +1 -0
- package/dist/node/releaseParsers.js +92 -0
- package/dist/node/releaseParsers.js.map +1 -0
- package/dist/type-testing/index.d.ts +18 -0
- package/dist/type-testing/index.d.ts.map +1 -0
- package/dist/type-testing/index.js +12 -0
- package/dist/type-testing/index.js.map +1 -0
- package/package.json +22 -7
- package/src/core/guards.ts +239 -0
- package/src/core/index.ts +32 -0
- package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +9 -16
- package/src/core/noop.ts +2 -0
- package/src/index.ts +13 -49
- package/src/loggers/getConsoleLogger.ts +14 -19
- package/src/loggers/index.ts +14 -0
- package/src/node/delays.ts +15 -0
- package/src/node/index.ts +21 -0
- package/src/node/main.ts +419 -0
- package/src/{monitorMemory.ts → node/monitorMemory.ts} +24 -18
- package/src/node/osRelease.ts +152 -0
- package/src/node/releaseParsers.ts +109 -0
- package/src/type-testing/index.ts +18 -0
- package/dist/main.d.ts +0 -112
- package/dist/main.d.ts.map +0 -1
- package/dist/main.js +0 -219
- package/dist/main.js.map +0 -1
- package/dist/millisecondsToString.d.ts.map +0 -1
- package/dist/millisecondsToString.js.map +0 -1
- package/dist/monitorMemory.d.ts.map +0 -1
- package/dist/monitorMemory.js.map +0 -1
- package/dist/noop.d.ts +0 -7
- package/dist/noop.d.ts.map +0 -1
- package/dist/noop.js +0 -7
- package/dist/noop.js.map +0 -1
- package/dist/osRelease.d.ts +0 -46
- package/dist/osRelease.d.ts.map +0 -1
- package/dist/osRelease.js +0 -153
- package/dist/osRelease.js.map +0 -1
- package/dist/types.d.ts +0 -70
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -84
- package/dist/types.js.map +0 -1
- package/src/main.ts +0 -302
- package/src/noop.ts +0 -6
- package/src/osRelease.ts +0 -174
- package/src/types.ts +0 -98
- /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,
|
|
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
|
-
-
|
|
22
|
-
`
|
|
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,40 @@ 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` also needs `Intl.DurationFormat` and
|
|
58
|
+
`Temporal`).
|
|
59
|
+
|
|
35
60
|
## Usage
|
|
36
61
|
|
|
37
62
|
### `getConsoleLogger`
|
|
38
63
|
|
|
39
|
-
Configures
|
|
40
|
-
`lowestLevel` are written to the console with RFC 3339 timestamps
|
|
41
|
-
logger is silenced.
|
|
42
|
-
|
|
64
|
+
Configures LogTape globally and resolves to a `Logger` for the given category name. Records at or
|
|
65
|
+
above `lowestLevel` are written to the console with RFC 3339 timestamps, and the internal
|
|
66
|
+
`logtape/meta` logger is silenced.
|
|
67
|
+
|
|
68
|
+
Each call replaces the whole global LogTape configuration, including one made by the application, so
|
|
69
|
+
the latest call wins. Applications that configure LogTape themselves should not call it; they get
|
|
70
|
+
their loggers from LogTape's `getLogger` and can pass them to `main` (see its `flushLogs` option).
|
|
43
71
|
|
|
44
72
|
ANSI colors are used only when both stdout and stderr are terminals that support them (respecting
|
|
45
73
|
`NO_COLOR`, `NODE_DISABLE_COLORS`, and `TERM=dumb`), so logs redirected to files or pipes stay free
|
|
@@ -73,23 +101,19 @@ must be between one minute (`1 / 60`) and about 596.5 hours (2³¹ − 1 ms, the
|
|
|
73
101
|
`setInterval` supports); anything outside that range throws a `RangeError`.
|
|
74
102
|
|
|
75
103
|
It returns a function that stops the monitoring. The timer is unreferenced, so monitoring alone does
|
|
76
|
-
not keep the process alive.
|
|
77
|
-
|
|
78
|
-
|
|
104
|
+
not keep the process alive. Each report also attaches its figures as structured properties (`uptime`
|
|
105
|
+
and `uptimeMs`; `rss`, `heapTotal`, `heapUsed`, and `external`), so sinks that keep properties, such
|
|
106
|
+
as JSON Lines, can query them. With `main`, use its `monitorMemoryHours` option instead.
|
|
79
107
|
|
|
80
108
|
```ts
|
|
81
|
-
import { getConsoleLogger,
|
|
109
|
+
import { getConsoleLogger, monitorMemory } from "@darthcav/ts-utils"
|
|
82
110
|
|
|
83
111
|
const logger = await getConsoleLogger("my-app")
|
|
84
112
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
// later, e.g. during shutdown:
|
|
90
|
-
stop()
|
|
91
|
-
},
|
|
92
|
-
})
|
|
113
|
+
monitorMemory(logger) // every 24 hours
|
|
114
|
+
const stop = monitorMemory(logger, 1) // every hour
|
|
115
|
+
// later:
|
|
116
|
+
stop()
|
|
93
117
|
```
|
|
94
118
|
|
|
95
119
|
### `millisecondsToString`
|
|
@@ -114,8 +138,7 @@ millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
|
|
|
114
138
|
|
|
115
139
|
### `noop`
|
|
116
140
|
|
|
117
|
-
|
|
118
|
-
handler.
|
|
141
|
+
Does nothing. Useful as a placeholder callback or default handler.
|
|
119
142
|
|
|
120
143
|
```ts
|
|
121
144
|
import { noop } from "@darthcav/ts-utils"
|
|
@@ -142,10 +165,18 @@ const payload: RuntimeObject = {
|
|
|
142
165
|
|
|
143
166
|
Narrow `unknown` values (e.g. parsed JSON) without type assertions:
|
|
144
167
|
|
|
145
|
-
- `isRuntimeObject`
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
- `
|
|
168
|
+
- `isRuntimeObject`, `isString`, `isBoolean`, and `isFiniteNumber` are type guards for use in
|
|
169
|
+
conditions. `isBoolean` and `isFiniteNumber` accept primitives only; `isFiniteNumber` rejects
|
|
170
|
+
`NaN`, `Infinity`, and `-Infinity`.
|
|
171
|
+
- `asRuntimeObject`, `asString`, `asBoolean`, and `asFiniteNumber` return the value, or `undefined`
|
|
172
|
+
when it does not match, for use with `?.` and `??`.
|
|
173
|
+
- `isArrayOf(value, guard)` checks that a value is an array whose elements **all** pass a guard; one
|
|
174
|
+
invalid element makes it fail, and an empty array passes. `asArrayOf` is its narrowing helper.
|
|
175
|
+
- `filterByGuard(value, guard)` keeps the elements that pass a guard and silently drops the others;
|
|
176
|
+
a value that is not an array yields `[]`. Use it to filter, and `isArrayOf` to validate.
|
|
177
|
+
- `toRuntimeObjectArray` keeps only the plain-object elements of an array (`filterByGuard` with
|
|
178
|
+
`isRuntimeObject`).
|
|
179
|
+
- `TypeGuard<T>` is the type of a guard (`(value: unknown) => value is T`), for writing your own.
|
|
149
180
|
|
|
150
181
|
A runtime object is a plain object (an object literal, a `JSON.parse` result, or an
|
|
151
182
|
`Object.create(null)` object); arrays, class instances, and built-ins such as `Date` or `Map` are
|
|
@@ -154,12 +185,15 @@ kept, so guard against those keys before merging the value into other objects.
|
|
|
154
185
|
|
|
155
186
|
```ts
|
|
156
187
|
import {
|
|
188
|
+
asArrayOf,
|
|
189
|
+
asFiniteNumber,
|
|
157
190
|
asRuntimeObject,
|
|
158
191
|
asString,
|
|
192
|
+
filterByGuard,
|
|
159
193
|
isRuntimeObject,
|
|
160
194
|
isString,
|
|
161
195
|
toRuntimeObjectArray,
|
|
162
|
-
} from "@darthcav/ts-utils"
|
|
196
|
+
} from "@darthcav/ts-utils/core"
|
|
163
197
|
|
|
164
198
|
const body: unknown = JSON.parse(input)
|
|
165
199
|
|
|
@@ -167,31 +201,41 @@ if (isRuntimeObject(body) && isString(body["name"])) {
|
|
|
167
201
|
console.log(body["name"].toUpperCase()) // narrowed to string
|
|
168
202
|
}
|
|
169
203
|
|
|
170
|
-
const
|
|
171
|
-
const
|
|
204
|
+
const config = asRuntimeObject(body)
|
|
205
|
+
const name = asString(config?.["name"]) ?? "anonymous"
|
|
206
|
+
const port = asFiniteNumber(config?.["port"]) ?? 3000
|
|
207
|
+
const tags = asArrayOf(config?.["tags"], isString) // string[] | undefined (all or nothing)
|
|
208
|
+
const someTags = filterByGuard(config?.["tags"], isString) // string[] (invalid ones dropped)
|
|
209
|
+
const items = toRuntimeObjectArray(config?.["items"])
|
|
172
210
|
```
|
|
173
211
|
|
|
174
212
|
### `osRelease`
|
|
175
213
|
|
|
176
214
|
Returns OS release information for the current platform as an `OsRelease` object, or `null` on
|
|
177
|
-
unsupported platforms or when
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
215
|
+
unsupported platforms or when the release file cannot be read. The normalized fields `name`,
|
|
216
|
+
`version`, and `arch` are present on every platform.
|
|
217
|
+
|
|
218
|
+
- On Linux, the data comes from `/etc/os-release`, falling back to `/usr/lib/os-release`, and all
|
|
219
|
+
raw key-value pairs (e.g. `PRETTY_NAME`, `ID`, `ID_LIKE`) are also accessible by string index.
|
|
220
|
+
Values are unquoted as in a shell; comments and keys that are not upper-case variable names (such
|
|
221
|
+
as `__proto__`) are skipped.
|
|
222
|
+
- On macOS, the data comes from `/System/Library/CoreServices/SystemVersion.plist`: `name` is the
|
|
223
|
+
product name (`"macOS"`) and `version` the product version (e.g. `"15.1"`) — never the Darwin
|
|
224
|
+
kernel version, which `os.release()` returns. The string keys of the file (e.g.
|
|
225
|
+
`ProductBuildVersion`) are also accessible by string index.
|
|
226
|
+
- On Windows, `version` is the kernel version and `name` tells Windows 11 from Windows 10 by build
|
|
227
|
+
number.
|
|
185
228
|
|
|
186
229
|
```ts
|
|
187
|
-
import { osRelease } from "@darthcav/ts-utils"
|
|
230
|
+
import { asString, osRelease } from "@darthcav/ts-utils"
|
|
188
231
|
|
|
189
232
|
const info = osRelease()
|
|
190
233
|
if (info) {
|
|
191
|
-
console.log(info.name)
|
|
192
|
-
console.log(info.version)
|
|
193
|
-
console.log(info.arch)
|
|
194
|
-
|
|
234
|
+
console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
|
|
235
|
+
console.log(info.version) // e.g. "24.04", "15.1", or "10.0.22000"
|
|
236
|
+
console.log(info.arch) // e.g. "x64"
|
|
237
|
+
// Raw keys are `unknown`; narrow them before use.
|
|
238
|
+
const prettyName = asString(info["PRETTY_NAME"]) // e.g. "Ubuntu 24.04 LTS" (Linux only)
|
|
195
239
|
}
|
|
196
240
|
```
|
|
197
241
|
|
|
@@ -218,33 +262,53 @@ The process title, PID, name, and `NODE_ENV` are logged at `info` level. The Nod
|
|
|
218
262
|
(`execArgv` and `NODE_OPTIONS`) are logged at `debug` level only, since they can reveal sensitive
|
|
219
263
|
flags such as `--inspect=0.0.0.0`.
|
|
220
264
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
265
|
+
On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a launcher failure, `main`
|
|
266
|
+
runs a shutdown sequence once:
|
|
267
|
+
|
|
268
|
+
1. It logs the cause (signals at `info`, failures at `error` level) and stops the memory monitoring.
|
|
269
|
+
2. It runs your `shutdown` function, if any, for at most `shutdownTimeoutMs` (10 seconds by
|
|
270
|
+
default). The function receives a `ShutdownContext`: `{ reason: "signal", signal }` for a normal
|
|
271
|
+
stop, or `{ reason: "error", source, error }` for a fatal failure, where `source` is
|
|
272
|
+
`"uncaughtException"`, `"unhandledRejection"`, or `"launcher"`. A rejection, exception, or
|
|
273
|
+
timeout is logged at `error` level.
|
|
274
|
+
3. It flushes the logs with `flushLogs` (LogTape's `dispose` by default) for at most
|
|
275
|
+
`flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the final messages.
|
|
276
|
+
4. It exits. A signal is re-raised, so the process ends as killed by it (exit status 130/143), which
|
|
277
|
+
shells and supervisors such as systemd treat as a clean stop; if another listener for that signal
|
|
278
|
+
exists, it exits with status `128 + signal number` instead. Fatal failures, and a failed or
|
|
279
|
+
timed-out `shutdown` function, exit with status `1`, so supervisors notice the failed cleanup.
|
|
280
|
+
|
|
281
|
+
A second signal or fatal failure during the sequence exits immediately. After a fatal failure the
|
|
282
|
+
application may be in an inconsistent state, so check `context.reason` and only clean up, e.g. close
|
|
283
|
+
connections.
|
|
228
284
|
|
|
229
285
|
Optional settings are passed as a `MainOptions` object:
|
|
230
286
|
|
|
231
|
-
| Option | Type
|
|
232
|
-
| ---------------------------- |
|
|
233
|
-
| `launcher` | `() => void \| Promise<void>`
|
|
234
|
-
| `
|
|
235
|
-
| `
|
|
236
|
-
| `
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
`flushTimeoutMs`
|
|
240
|
-
|
|
287
|
+
| Option | Type | Default | Description |
|
|
288
|
+
| ---------------------------- | ------------------------------------ | ----------------- | --------------------------------------------------------------- |
|
|
289
|
+
| `launcher` | `() => void \| Promise<void>` | — | Runs after the handlers are registered; may be async. |
|
|
290
|
+
| `shutdown` | `(context) => void \| Promise<void>` | — | Cleans up application resources once, before the process exits. |
|
|
291
|
+
| `shutdownTimeoutMs` | `number` | `10000` | Longest wait for `shutdown` (0 to 2³¹ − 1 ms). |
|
|
292
|
+
| `monitorMemoryHours` | `number` | `0` | Logs memory usage every N hours; `0` disables it. |
|
|
293
|
+
| `defaultInterruptionHandler` | `boolean` | `true` | Register the `SIGINT`/`SIGTERM` handlers. |
|
|
294
|
+
| `flushLogs` | `() => void \| Promise<void>` | LogTape `dispose` | Flushes the log sinks before exiting; `noop` skips flushing. |
|
|
295
|
+
| `flushTimeoutMs` | `number` | `3000` | Longest wait for `flushLogs` (0 to 2³¹ − 1 ms). |
|
|
296
|
+
|
|
297
|
+
An out-of-range `monitorMemoryHours` (negative, `NaN`, or outside `monitorMemory`'s range),
|
|
298
|
+
`shutdownTimeoutMs`, or `flushTimeoutMs` throws a `RangeError`, and a `launcher`, `shutdown`, or
|
|
299
|
+
`flushLogs` that is not a function throws a `TypeError`, before anything is logged or registered. If
|
|
300
|
+
the launcher throws or its promise rejects, the failure is logged and the shutdown sequence runs.
|
|
301
|
+
|
|
302
|
+
The default `flushLogs` disposes the sinks configured through the `@logtape/logtape` copy this
|
|
303
|
+
package uses. If the application configures another copy (e.g. a different LogTape version, whose
|
|
304
|
+
configuration this package cannot reach), pass that copy's `dispose` instead.
|
|
241
305
|
|
|
242
306
|
`main` returns a teardown function that removes the handlers it registered and stops the memory
|
|
243
|
-
monitoring (it
|
|
244
|
-
again before the teardown throws
|
|
307
|
+
monitoring (it neither runs `shutdown` nor exits the process). Only one `main` call can be active at
|
|
308
|
+
a time: calling it again before the teardown throws.
|
|
245
309
|
|
|
246
310
|
```ts
|
|
247
|
-
import { getLogger } from "@logtape/logtape"
|
|
311
|
+
import { dispose, getLogger } from "@logtape/logtape"
|
|
248
312
|
import { main } from "@darthcav/ts-utils"
|
|
249
313
|
|
|
250
314
|
const logger = getLogger(["my-app"])
|
|
@@ -263,18 +327,25 @@ main("my-app", logger, {
|
|
|
263
327
|
monitorMemoryHours: 2,
|
|
264
328
|
})
|
|
265
329
|
|
|
266
|
-
// 3.
|
|
330
|
+
// 3. Graceful shutdown of the application's resources:
|
|
267
331
|
let server: Server | undefined
|
|
268
|
-
|
|
269
|
-
launcher: () => {
|
|
332
|
+
main("my-app", logger, {
|
|
333
|
+
launcher: async () => {
|
|
334
|
+
await connectToDatabase()
|
|
270
335
|
server = startServer()
|
|
271
336
|
},
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
337
|
+
shutdown: async (context) => {
|
|
338
|
+
if (context.reason === "error") {
|
|
339
|
+
logger.warn`Shutting down after a failure in ${context.source}`
|
|
340
|
+
}
|
|
341
|
+
await server?.close()
|
|
342
|
+
await disconnectFromDatabase()
|
|
343
|
+
},
|
|
344
|
+
shutdownTimeoutMs: 15_000,
|
|
277
345
|
})
|
|
346
|
+
|
|
347
|
+
// 4. Keep your own LogTape setup (e.g. another LogTape version) and flush it yourself:
|
|
348
|
+
main("my-app", logger, { flushLogs: dispose })
|
|
278
349
|
```
|
|
279
350
|
|
|
280
351
|
The positional forms of earlier versions (e.g. `main("my-app", logger, () => startServer(), 2)`)
|
|
@@ -329,6 +400,9 @@ npm run build
|
|
|
329
400
|
# Run tests
|
|
330
401
|
npm test
|
|
331
402
|
|
|
403
|
+
# Run tests with coverage (fails below 100%)
|
|
404
|
+
npm run test:coverage
|
|
405
|
+
|
|
332
406
|
# Lint and format
|
|
333
407
|
npm run lint
|
|
334
408
|
npm run lint:fix
|
|
@@ -341,18 +415,22 @@ npm run doc
|
|
|
341
415
|
|
|
342
416
|
```
|
|
343
417
|
src/
|
|
344
|
-
index.ts
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
418
|
+
index.ts # Root entry point (re-exports every domain)
|
|
419
|
+
core/ # @darthcav/ts-utils/core (portable)
|
|
420
|
+
guards.ts # RuntimeObject, TypeGuard, type guards and narrowing helpers
|
|
421
|
+
millisecondsToString.ts # Duration formatting
|
|
422
|
+
noop.ts # No-op function
|
|
423
|
+
node/ # @darthcav/ts-utils/node
|
|
424
|
+
main.ts # Process bootstrap and shutdown (main)
|
|
425
|
+
monitorMemory.ts # Periodic memory reporting
|
|
426
|
+
osRelease.ts # OS release information
|
|
427
|
+
releaseParsers.ts # os-release and plist parsers (internal)
|
|
428
|
+
delays.ts # Timer delay limit and range check (internal)
|
|
429
|
+
loggers/ # @darthcav/ts-utils/loggers (LogTape helpers)
|
|
430
|
+
type-testing/ # @darthcav/ts-utils/type-testing (type-level assertions)
|
|
431
|
+
__tests__/ # Test files, shared helpers, and child-process fixtures
|
|
432
|
+
dist/ # Compiled output (generated)
|
|
433
|
+
public/ # Documentation output (generated)
|
|
356
434
|
```
|
|
357
435
|
|
|
358
436
|
## License
|
|
@@ -361,7 +439,7 @@ public/ # Documentation output (generated)
|
|
|
361
439
|
|
|
362
440
|
[node-version]: https://img.shields.io/badge/node-%3E%3D26-orange.svg?style=flat-square
|
|
363
441
|
[node-url]: https://nodejs.org
|
|
364
|
-
[version-image]: https://img.shields.io/badge/version-0.
|
|
442
|
+
[version-image]: https://img.shields.io/badge/version-1.0.1-blue.svg?style=flat-square
|
|
365
443
|
[ci-badge]: https://github.com/darthcav/ts-utils/actions/workflows/tests.yml/badge.svg
|
|
366
444
|
[coverage-badge]:
|
|
367
445
|
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,CAOd;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"}
|