@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/dist/osRelease.d.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import type { RuntimeObject } from "./types.ts";
|
|
2
|
-
/**
|
|
3
|
-
* OS release information with normalized fields and optional platform-specific extras.
|
|
4
|
-
*
|
|
5
|
-
* `name`, `version`, and `arch` are always present. On Linux, the keys read from
|
|
6
|
-
* the os-release file (`/etc/os-release`, or `/usr/lib/os-release` as a
|
|
7
|
-
* fallback; e.g. `ID`, `PRETTY_NAME`, `ID_LIKE`) are also accessible by string
|
|
8
|
-
* index.
|
|
9
|
-
*/
|
|
10
|
-
export type OsRelease = {
|
|
11
|
-
/** Human-readable OS name, e.g. `"Ubuntu"` or `"Windows 11"`. */
|
|
12
|
-
name: string;
|
|
13
|
-
/** OS version string, e.g. `"24.04"` or `"10.0.22000"`. */
|
|
14
|
-
version: string;
|
|
15
|
-
/** Processor architecture as returned by `os.arch()`, e.g. `"x64"`. */
|
|
16
|
-
arch: string;
|
|
17
|
-
} & RuntimeObject;
|
|
18
|
-
/**
|
|
19
|
-
* Returns OS release information for the current platform, or `null` on
|
|
20
|
-
* unsupported platforms or when no os-release file can be read on Linux.
|
|
21
|
-
*
|
|
22
|
-
* On Linux, the information is read from `/etc/os-release`, falling back to
|
|
23
|
-
* `/usr/lib/os-release`. `name`, `version`, and `arch` are normalized from
|
|
24
|
-
* `NAME`/`PRETTY_NAME`, `VERSION_ID`/`VERSION`, and `os.arch()` respectively.
|
|
25
|
-
* All raw keys from the file are also present on the returned object. Comment
|
|
26
|
-
* lines are ignored, single- and double-quoted values are unquoted (with
|
|
27
|
-
* backslash escapes inside double quotes), and keys that are not upper-case
|
|
28
|
-
* shell variable names are skipped.
|
|
29
|
-
*
|
|
30
|
-
* On Windows, distinguishes Windows 11 from Windows 10 by NT build number
|
|
31
|
-
* (>= 22000 → Windows 11).
|
|
32
|
-
*
|
|
33
|
-
* @returns An {@link OsRelease} object on supported platforms, or `null` when
|
|
34
|
-
* the platform is unsupported or no os-release file can be read on Linux.
|
|
35
|
-
*
|
|
36
|
-
* @example
|
|
37
|
-
* ```ts
|
|
38
|
-
* import { osRelease } from "@darthcav/ts-utils"
|
|
39
|
-
*
|
|
40
|
-
* const info = osRelease()
|
|
41
|
-
* if (info) console.log(info.name) // e.g. "Ubuntu" or "Windows 11"
|
|
42
|
-
* if (info) console.log(info.PRETTY_NAME) // e.g. "Ubuntu 24.04 LTS" (Linux only)
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
export declare function osRelease(): OsRelease | null;
|
|
46
|
-
//# sourceMappingURL=osRelease.d.ts.map
|
package/dist/osRelease.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"osRelease.d.ts","sourceRoot":"","sources":["../src/osRelease.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,GAAG;IACpB,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAA;IACZ,2DAA2D;IAC3D,OAAO,EAAE,MAAM,CAAA;IACf,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAA;CACf,GAAG,aAAa,CAAA;AAwEjB;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,SAAS,IAAI,SAAS,GAAG,IAAI,CAuD5C"}
|
package/dist/osRelease.js
DELETED
|
@@ -1,153 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
|
-
import { arch, release as kernelRelease, platform } from "node:os";
|
|
3
|
-
/**
|
|
4
|
-
* Candidate os-release files, in lookup order. Per the freedesktop.org spec,
|
|
5
|
-
* `/etc/os-release` takes precedence and `/usr/lib/os-release` is the fallback.
|
|
6
|
-
*/
|
|
7
|
-
const OS_RELEASE_FILES = ["/etc/os-release", "/usr/lib/os-release"];
|
|
8
|
-
/**
|
|
9
|
-
* Valid os-release keys: shell-compatible, upper-case variable names. This
|
|
10
|
-
* also rules out keys such as `__proto__` or `constructor`.
|
|
11
|
-
*/
|
|
12
|
-
const OS_RELEASE_KEY = /^[A-Z][A-Z0-9_]*$/;
|
|
13
|
-
/**
|
|
14
|
-
* Reads the first readable os-release file, or returns `null` when none can be
|
|
15
|
-
* read (missing, unreadable, or not a regular file).
|
|
16
|
-
*/
|
|
17
|
-
function readOsReleaseFile() {
|
|
18
|
-
for (const file of OS_RELEASE_FILES) {
|
|
19
|
-
try {
|
|
20
|
-
return readFileSync(file, "utf-8");
|
|
21
|
-
}
|
|
22
|
-
catch {
|
|
23
|
-
// Try the next candidate.
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Removes one level of shell-style quoting from an os-release value. Double
|
|
30
|
-
* quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
|
|
31
|
-
* literal.
|
|
32
|
-
*/
|
|
33
|
-
function unquote(value) {
|
|
34
|
-
if (value.length >= 2) {
|
|
35
|
-
const quote = value[0];
|
|
36
|
-
if (quote === '"' && value.endsWith('"')) {
|
|
37
|
-
return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1");
|
|
38
|
-
}
|
|
39
|
-
if (quote === "'" && value.endsWith("'")) {
|
|
40
|
-
return value.slice(1, -1);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return value;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Parses os-release content into a null-prototype record. Blank lines,
|
|
47
|
-
* comments, lines without `=`, and keys that are not valid variable names are
|
|
48
|
-
* skipped.
|
|
49
|
-
*/
|
|
50
|
-
function parseOsRelease(content) {
|
|
51
|
-
const raw = Object.create(null);
|
|
52
|
-
for (const line of content.split("\n")) {
|
|
53
|
-
const trimmed = line.trim();
|
|
54
|
-
if (trimmed === "" || trimmed.startsWith("#")) {
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
const eq = trimmed.indexOf("=");
|
|
58
|
-
if (eq === -1) {
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
const key = trimmed.substring(0, eq).trim();
|
|
62
|
-
if (!OS_RELEASE_KEY.test(key)) {
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
raw[key] = unquote(trimmed.substring(eq + 1).trim());
|
|
66
|
-
}
|
|
67
|
-
return raw;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Returns OS release information for the current platform, or `null` on
|
|
71
|
-
* unsupported platforms or when no os-release file can be read on Linux.
|
|
72
|
-
*
|
|
73
|
-
* On Linux, the information is read from `/etc/os-release`, falling back to
|
|
74
|
-
* `/usr/lib/os-release`. `name`, `version`, and `arch` are normalized from
|
|
75
|
-
* `NAME`/`PRETTY_NAME`, `VERSION_ID`/`VERSION`, and `os.arch()` respectively.
|
|
76
|
-
* All raw keys from the file are also present on the returned object. Comment
|
|
77
|
-
* lines are ignored, single- and double-quoted values are unquoted (with
|
|
78
|
-
* backslash escapes inside double quotes), and keys that are not upper-case
|
|
79
|
-
* shell variable names are skipped.
|
|
80
|
-
*
|
|
81
|
-
* On Windows, distinguishes Windows 11 from Windows 10 by NT build number
|
|
82
|
-
* (>= 22000 → Windows 11).
|
|
83
|
-
*
|
|
84
|
-
* @returns An {@link OsRelease} object on supported platforms, or `null` when
|
|
85
|
-
* the platform is unsupported or no os-release file can be read on Linux.
|
|
86
|
-
*
|
|
87
|
-
* @example
|
|
88
|
-
* ```ts
|
|
89
|
-
* import { osRelease } from "@darthcav/ts-utils"
|
|
90
|
-
*
|
|
91
|
-
* const info = osRelease()
|
|
92
|
-
* if (info) console.log(info.name) // e.g. "Ubuntu" or "Windows 11"
|
|
93
|
-
* if (info) console.log(info.PRETTY_NAME) // e.g. "Ubuntu 24.04 LTS" (Linux only)
|
|
94
|
-
* ```
|
|
95
|
-
*/
|
|
96
|
-
export function osRelease() {
|
|
97
|
-
const p = platform();
|
|
98
|
-
if (p === "linux") {
|
|
99
|
-
const content = readOsReleaseFile();
|
|
100
|
-
if (content === null) {
|
|
101
|
-
return null;
|
|
102
|
-
}
|
|
103
|
-
const raw = parseOsRelease(content);
|
|
104
|
-
return {
|
|
105
|
-
...raw,
|
|
106
|
-
name: raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
|
|
107
|
-
version: raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
|
|
108
|
-
arch: arch(),
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
if (p === "win32") {
|
|
112
|
-
const version = kernelRelease();
|
|
113
|
-
const [major, , build] = version.split(".").map(Number);
|
|
114
|
-
let name = "Windows ";
|
|
115
|
-
if (major === 10 && (build ?? 0) >= 22000) {
|
|
116
|
-
name += "11";
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
switch (version.substring(0, 3)) {
|
|
120
|
-
case "10.":
|
|
121
|
-
name += "10";
|
|
122
|
-
break;
|
|
123
|
-
case "6.3":
|
|
124
|
-
name += "8.1";
|
|
125
|
-
break;
|
|
126
|
-
case "6.2":
|
|
127
|
-
name += "8";
|
|
128
|
-
break;
|
|
129
|
-
case "6.1":
|
|
130
|
-
name += "7";
|
|
131
|
-
break;
|
|
132
|
-
case "6.0":
|
|
133
|
-
name += "Vista";
|
|
134
|
-
break;
|
|
135
|
-
case "5.2":
|
|
136
|
-
name += "XP 64-Bit Edition";
|
|
137
|
-
break;
|
|
138
|
-
case "5.1":
|
|
139
|
-
name += "XP";
|
|
140
|
-
break;
|
|
141
|
-
case "5.0":
|
|
142
|
-
name += "2000";
|
|
143
|
-
break;
|
|
144
|
-
default:
|
|
145
|
-
name += "unknown version";
|
|
146
|
-
break;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
return { name, version, arch: arch() };
|
|
150
|
-
}
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
//# sourceMappingURL=osRelease.js.map
|
package/dist/osRelease.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"osRelease.js","sourceRoot":"","sources":["../src/osRelease.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,aAAa,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAoBlE;;;GAGG;AACH,MAAM,gBAAgB,GAAG,CAAC,iBAAiB,EAAE,qBAAqB,CAAU,CAAA;AAE5E;;;GAGG;AACH,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAE1C;;;GAGG;AACH,SAAS,iBAAiB;IACtB,KAAK,MAAM,IAAI,IAAI,gBAAgB,EAAE,CAAC;QAClC,IAAI,CAAC;YACD,OAAO,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QACtC,CAAC;QAAC,MAAM,CAAC;YACL,0BAA0B;QAC9B,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAA;AACf,CAAC;AAED;;;;GAIG;AACH,SAAS,OAAO,CAAC,KAAa;IAC1B,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;QACtB,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC,CAAA;QAC3D,CAAC;QACD,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QAC7B,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAA;AAChB,CAAC;AAED;;;;GAIG;AACH,SAAS,cAAc,CAAC,OAAe;IACnC,MAAM,GAAG,GAA2B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvD,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACrC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;QAC3B,IAAI,OAAO,KAAK,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YAC5C,SAAQ;QACZ,CAAC;QACD,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;QAC/B,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;YACZ,SAAQ;QACZ,CAAC;QACD,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAA;QAC3C,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAC5B,SAAQ;QACZ,CAAC;QACD,GAAG,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IACxD,CAAC;IACD,OAAO,GAAG,CAAA;AACd,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,SAAS;IACrB,MAAM,CAAC,GAAG,QAAQ,EAAE,CAAA;IACpB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,iBAAiB,EAAE,CAAA;QACnC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YACnB,OAAO,IAAI,CAAA;QACf,CAAC;QACD,MAAM,GAAG,GAAG,cAAc,CAAC,OAAO,CAAC,CAAA;QACnC,OAAO;YACH,GAAG,GAAG;YACN,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE;YAC7C,OAAO,EAAE,GAAG,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;YAClD,IAAI,EAAE,IAAI,EAAE;SACf,CAAA;IACL,CAAC;IACD,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAA;QAC/B,MAAM,CAAC,KAAK,EAAE,AAAD,EAAG,KAAK,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACvD,IAAI,IAAI,GAAG,UAAU,CAAA;QACrB,IAAI,KAAK,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC;YACxC,IAAI,IAAI,IAAI,CAAA;QAChB,CAAC;aAAM,CAAC;YACJ,QAAQ,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;gBAC9B,KAAK,KAAK;oBACN,IAAI,IAAI,IAAI,CAAA;oBACZ,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,KAAK,CAAA;oBACb,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,GAAG,CAAA;oBACX,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,GAAG,CAAA;oBACX,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,OAAO,CAAA;oBACf,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,mBAAmB,CAAA;oBAC3B,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,IAAI,CAAA;oBACZ,MAAK;gBACT,KAAK,KAAK;oBACN,IAAI,IAAI,MAAM,CAAA;oBACd,MAAK;gBACT;oBACI,IAAI,IAAI,iBAAiB,CAAA;oBACzB,MAAK;YACb,CAAC;QACL,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAA;IAC1C,CAAC;IACD,OAAO,IAAI,CAAA;AACf,CAAC"}
|
package/dist/types.d.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
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 that can be treated as a runtime
|
|
38
|
-
* JSON object, as decided by {@link isRuntimeObject} (see there for what counts
|
|
39
|
-
* as a plain object and the caveats about unsanitized keys).
|
|
40
|
-
*
|
|
41
|
-
* @param value - Value to narrow.
|
|
42
|
-
* @returns The same value as a {@link RuntimeObject}, or `undefined` when the
|
|
43
|
-
* value is not a plain object.
|
|
44
|
-
*/
|
|
45
|
-
export declare function asRuntimeObject(value: unknown): RuntimeObject | undefined;
|
|
46
|
-
/**
|
|
47
|
-
* Type guard that checks whether a value is a string.
|
|
48
|
-
*
|
|
49
|
-
* @param value - Value to check.
|
|
50
|
-
* @returns `true` when the value is a string, narrowing it to `string`.
|
|
51
|
-
*/
|
|
52
|
-
export declare function isString(value: unknown): value is string;
|
|
53
|
-
/**
|
|
54
|
-
* Returns the input when it is a string.
|
|
55
|
-
*
|
|
56
|
-
* @param value - Value to narrow.
|
|
57
|
-
* @returns The same value as a string, or `undefined` when the value is not a string.
|
|
58
|
-
*/
|
|
59
|
-
export declare function asString(value: unknown): string | undefined;
|
|
60
|
-
/**
|
|
61
|
-
* Filters an unknown value down to an array of runtime JSON objects.
|
|
62
|
-
*
|
|
63
|
-
* Elements are kept when {@link isRuntimeObject} accepts them, i.e. only plain
|
|
64
|
-
* objects; the same caveats about unsanitized keys apply.
|
|
65
|
-
*
|
|
66
|
-
* @param value - Value that may contain runtime objects.
|
|
67
|
-
* @returns Only the elements that can be treated as {@link RuntimeObject} values.
|
|
68
|
-
*/
|
|
69
|
-
export declare function toRuntimeObjectArray(value: unknown): RuntimeObject[];
|
|
70
|
-
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.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;;;;;;;;GAQG;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;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,EAAE,CAEpE"}
|
package/dist/types.js
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Type guard that checks whether a value is a plain object that can be treated
|
|
3
|
-
* as a runtime JSON object.
|
|
4
|
-
*
|
|
5
|
-
* Plain objects are object literals, `JSON.parse` results, and
|
|
6
|
-
* `Object.create(null)` objects, including those from another realm (e.g. a
|
|
7
|
-
* `node:vm` context). Arrays, class instances, and built-ins such as `Date`,
|
|
8
|
-
* `Map`, `Set`, `RegExp`, or module namespace objects are rejected.
|
|
9
|
-
*
|
|
10
|
-
* The check is shallow and keys are not sanitized: an own `__proto__` or
|
|
11
|
-
* `constructor` key (as `JSON.parse` can produce from untrusted input) is kept.
|
|
12
|
-
* Do not merge the value into other objects key by key without guarding
|
|
13
|
-
* against those keys, or prototype pollution becomes possible.
|
|
14
|
-
*
|
|
15
|
-
* @param value - Value to check.
|
|
16
|
-
* @returns `true` when the value is a plain object, narrowing it to
|
|
17
|
-
* {@link RuntimeObject}.
|
|
18
|
-
*
|
|
19
|
-
* @example
|
|
20
|
-
* ```ts
|
|
21
|
-
* const body: unknown = JSON.parse(input)
|
|
22
|
-
* if (isRuntimeObject(body)) {
|
|
23
|
-
* console.log(Object.keys(body)) // body: RuntimeObject
|
|
24
|
-
* }
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
export function isRuntimeObject(value) {
|
|
28
|
-
if (typeof value !== "object" || value === null) {
|
|
29
|
-
return false;
|
|
30
|
-
}
|
|
31
|
-
const prototype = Object.getPrototypeOf(value);
|
|
32
|
-
// A null prototype, or a realm's root `Object.prototype` (whose own
|
|
33
|
-
// prototype is null), marks a plain object.
|
|
34
|
-
if (prototype !== null &&
|
|
35
|
-
prototype !== Object.prototype &&
|
|
36
|
-
Object.getPrototypeOf(prototype) !== null) {
|
|
37
|
-
return false;
|
|
38
|
-
}
|
|
39
|
-
// Exclude null-prototype exotics such as module namespace objects.
|
|
40
|
-
return !(Symbol.toStringTag in value || Symbol.iterator in value);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Returns the input when it is a plain object that can be treated as a runtime
|
|
44
|
-
* JSON object, as decided by {@link isRuntimeObject} (see there for what counts
|
|
45
|
-
* as a plain object and the caveats about unsanitized keys).
|
|
46
|
-
*
|
|
47
|
-
* @param value - Value to narrow.
|
|
48
|
-
* @returns The same value as a {@link RuntimeObject}, or `undefined` when the
|
|
49
|
-
* value is not a plain object.
|
|
50
|
-
*/
|
|
51
|
-
export function asRuntimeObject(value) {
|
|
52
|
-
return isRuntimeObject(value) ? value : undefined;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Type guard that checks whether a value is a string.
|
|
56
|
-
*
|
|
57
|
-
* @param value - Value to check.
|
|
58
|
-
* @returns `true` when the value is a string, narrowing it to `string`.
|
|
59
|
-
*/
|
|
60
|
-
export function isString(value) {
|
|
61
|
-
return typeof value === "string";
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Returns the input when it is a string.
|
|
65
|
-
*
|
|
66
|
-
* @param value - Value to narrow.
|
|
67
|
-
* @returns The same value as a string, or `undefined` when the value is not a string.
|
|
68
|
-
*/
|
|
69
|
-
export function asString(value) {
|
|
70
|
-
return isString(value) ? value : undefined;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Filters an unknown value down to an array of runtime JSON objects.
|
|
74
|
-
*
|
|
75
|
-
* Elements are kept when {@link isRuntimeObject} accepts them, i.e. only plain
|
|
76
|
-
* objects; the same caveats about unsanitized keys apply.
|
|
77
|
-
*
|
|
78
|
-
* @param value - Value that may contain runtime objects.
|
|
79
|
-
* @returns Only the elements that can be treated as {@link RuntimeObject} values.
|
|
80
|
-
*/
|
|
81
|
-
export function toRuntimeObjectArray(value) {
|
|
82
|
-
return Array.isArray(value) ? value.filter(isRuntimeObject) : [];
|
|
83
|
-
}
|
|
84
|
-
//# sourceMappingURL=types.js.map
|
package/dist/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAA;IAChB,CAAC;IACD,MAAM,SAAS,GAAY,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAA;IACvD,oEAAoE;IACpE,4CAA4C;IAC5C,IACI,SAAS,KAAK,IAAI;QAClB,SAAS,KAAK,MAAM,CAAC,SAAS;QAC9B,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,IAAI,EAC3C,CAAC;QACC,OAAO,KAAK,CAAA;IAChB,CAAC;IACD,mEAAmE;IACnE,OAAO,CAAC,CAAC,MAAM,CAAC,WAAW,IAAI,KAAK,IAAI,MAAM,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAA;AACrE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC1C,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;AACrD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAA;AACpC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAc;IACnC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;AAC9C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAc;IAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;AACpE,CAAC"}
|
package/src/main.ts
DELETED
|
@@ -1,302 +0,0 @@
|
|
|
1
|
-
import { constants } from "node:os"
|
|
2
|
-
import process, { env, execArgv, pid, title } from "node:process"
|
|
3
|
-
import { dispose, type Logger } from "@logtape/logtape"
|
|
4
|
-
import { monitorMemory } from "./monitorMemory.ts"
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Default upper bound for flushing log sinks before the process exits, so a
|
|
8
|
-
* hanging sink cannot block shutdown.
|
|
9
|
-
*/
|
|
10
|
-
const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Longest delay `setTimeout` supports (2³¹ − 1 ms). Node.js silently replaces
|
|
14
|
-
* larger delays with 1 ms.
|
|
15
|
-
*/
|
|
16
|
-
const MAX_FLUSH_TIMEOUT_MS = 2_147_483_647
|
|
17
|
-
|
|
18
|
-
/** Whether a {@link main} call is active, i.e. not yet torn down. */
|
|
19
|
-
let active = false
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Flushes and disposes the configured logtape sinks, giving up after
|
|
23
|
-
* `timeoutMs`. Never rejects: logging is best effort while the process is
|
|
24
|
-
* shutting down.
|
|
25
|
-
*/
|
|
26
|
-
async function flushLogs(timeoutMs: number): Promise<void> {
|
|
27
|
-
let timer: ReturnType<typeof setTimeout> | undefined
|
|
28
|
-
try {
|
|
29
|
-
await Promise.race([
|
|
30
|
-
dispose(),
|
|
31
|
-
new Promise<void>((resolve) => {
|
|
32
|
-
timer = setTimeout(resolve, timeoutMs)
|
|
33
|
-
}),
|
|
34
|
-
])
|
|
35
|
-
} catch {
|
|
36
|
-
// Ignore sink errors: the process is exiting anyway.
|
|
37
|
-
} finally {
|
|
38
|
-
clearTimeout(timer)
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Renders an error (with its stack when available) or any other value. */
|
|
43
|
-
function describe(value: unknown): string {
|
|
44
|
-
return value instanceof Error
|
|
45
|
-
? (value.stack ?? String(value))
|
|
46
|
-
: String(value)
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* A function that performs the actual application launch after process
|
|
51
|
-
* lifecycle handlers have been set up by {@link main}. Use a closure to
|
|
52
|
-
* capture any context needed (e.g. a logger).
|
|
53
|
-
*
|
|
54
|
-
* It may be asynchronous: if it throws or its promise rejects, {@link main}
|
|
55
|
-
* logs the failure and exits the process with status `1`.
|
|
56
|
-
*/
|
|
57
|
-
export type LauncherFunction = () => void | Promise<void>
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Options for {@link main}. All of them are optional.
|
|
61
|
-
*/
|
|
62
|
-
export type MainOptions = {
|
|
63
|
-
/**
|
|
64
|
-
* Function invoked after all process handlers are registered. Use a
|
|
65
|
-
* closure to capture any context needed (e.g. a logger).
|
|
66
|
-
*/
|
|
67
|
-
launcher?: LauncherFunction
|
|
68
|
-
/**
|
|
69
|
-
* When greater than `0`, starts periodic memory logging every
|
|
70
|
-
* `monitorMemoryHours` hours via {@link monitorMemory} (which validates
|
|
71
|
-
* the value). Must be `0` or a positive finite number; negative values
|
|
72
|
-
* and `NaN` throw. Defaults to `0` (disabled).
|
|
73
|
-
*/
|
|
74
|
-
monitorMemoryHours?: number
|
|
75
|
-
/**
|
|
76
|
-
* When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
|
|
77
|
-
* log, flush the logs, and stop the process. Set to `false` when the
|
|
78
|
-
* application manages its own graceful shutdown (e.g. closing servers or
|
|
79
|
-
* database connections).
|
|
80
|
-
*/
|
|
81
|
-
defaultInterruptionHandler?: boolean
|
|
82
|
-
/**
|
|
83
|
-
* Maximum time in milliseconds to wait for the logtape sinks to flush
|
|
84
|
-
* before the process exits. Must be between `0` and 2³¹ − 1. Defaults to
|
|
85
|
-
* `3000`.
|
|
86
|
-
*/
|
|
87
|
-
flushTimeoutMs?: number
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Bootstraps an application process: logs startup information, optionally
|
|
92
|
-
* registers handlers for `SIGINT` and `SIGTERM` (see
|
|
93
|
-
* {@link MainOptions.defaultInterruptionHandler}), always registers handlers
|
|
94
|
-
* for `uncaughtException` and `unhandledRejection`, optionally starts memory
|
|
95
|
-
* monitoring, then runs the optional launcher function.
|
|
96
|
-
*
|
|
97
|
-
* The process title, PID, name, and `NODE_ENV` are logged at `info` level.
|
|
98
|
-
* The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
|
|
99
|
-
* `debug` level only, since they can reveal sensitive flags such as
|
|
100
|
-
* `--inspect=0.0.0.0` or `--require` paths.
|
|
101
|
-
*
|
|
102
|
-
* Before the process exits, the configured logtape sinks are flushed and
|
|
103
|
-
* disposed (for at most `flushTimeoutMs`, 3 seconds by default), so buffered
|
|
104
|
-
* or asynchronous sinks do not lose the final messages. On `SIGINT`/`SIGTERM`
|
|
105
|
-
* the signal is logged at `info` level and then re-raised, so the process ends
|
|
106
|
-
* as killed by that signal (exit status 130/143), which shells and
|
|
107
|
-
* supervisors such as systemd treat as a clean stop. If another listener for
|
|
108
|
-
* that signal is registered, the process exits with status
|
|
109
|
-
* `128 + signal number` instead. Uncaught exceptions, unhandled rejections,
|
|
110
|
-
* and launcher failures exit with status `1`. A second signal or error during
|
|
111
|
-
* the flush exits immediately.
|
|
112
|
-
*
|
|
113
|
-
* Only one `main` call can be active at a time: calling it again before
|
|
114
|
-
* running the returned teardown function throws, instead of registering a
|
|
115
|
-
* second set of handlers.
|
|
116
|
-
*
|
|
117
|
-
* @param name - Human-readable application name used in log output.
|
|
118
|
-
* @param logger - Logger instance used for all startup and lifecycle messages.
|
|
119
|
-
* @param options - Optional {@link MainOptions}.
|
|
120
|
-
* @returns A teardown function that removes the process handlers registered
|
|
121
|
-
* by this call and stops the memory monitoring, allowing `main` to be called
|
|
122
|
-
* again (e.g. in tests). It does not exit the process; calling it more than
|
|
123
|
-
* once is harmless.
|
|
124
|
-
* @throws {TypeError} If `options` is not an object.
|
|
125
|
-
* @throws {Error} If another `main` call is still active.
|
|
126
|
-
* @throws {RangeError} If `monitorMemoryHours` or `flushTimeoutMs` is out of
|
|
127
|
-
* range. Nothing is registered in that case.
|
|
128
|
-
*
|
|
129
|
-
* @example Without options:
|
|
130
|
-
* ```ts
|
|
131
|
-
* main("my-app", logger)
|
|
132
|
-
* ```
|
|
133
|
-
*
|
|
134
|
-
* @example With an async launcher and memory monitoring every 2 hours:
|
|
135
|
-
* ```ts
|
|
136
|
-
* main("my-app", logger, {
|
|
137
|
-
* launcher: async () => {
|
|
138
|
-
* await connectToDatabase()
|
|
139
|
-
* startServer()
|
|
140
|
-
* },
|
|
141
|
-
* monitorMemoryHours: 2,
|
|
142
|
-
* })
|
|
143
|
-
* ```
|
|
144
|
-
*
|
|
145
|
-
* @example Managing graceful shutdown in the application:
|
|
146
|
-
* ```ts
|
|
147
|
-
* let server: Server | undefined
|
|
148
|
-
* const teardown = main("my-app", logger, {
|
|
149
|
-
* launcher: () => {
|
|
150
|
-
* server = startServer()
|
|
151
|
-
* },
|
|
152
|
-
* defaultInterruptionHandler: false,
|
|
153
|
-
* })
|
|
154
|
-
* process.once("SIGTERM", async () => {
|
|
155
|
-
* await server?.close()
|
|
156
|
-
* teardown()
|
|
157
|
-
* })
|
|
158
|
-
* ```
|
|
159
|
-
*/
|
|
160
|
-
export function main(
|
|
161
|
-
name: string,
|
|
162
|
-
logger: Logger,
|
|
163
|
-
options?: MainOptions,
|
|
164
|
-
): () => void {
|
|
165
|
-
// Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
|
|
166
|
-
// function) from untyped callers, instead of silently ignoring them.
|
|
167
|
-
if (
|
|
168
|
-
options !== undefined &&
|
|
169
|
-
(typeof options !== "object" || options === null)
|
|
170
|
-
) {
|
|
171
|
-
throw new TypeError(
|
|
172
|
-
`main: "options" must be a MainOptions object, received ${options === null ? "null" : typeof options}`,
|
|
173
|
-
)
|
|
174
|
-
}
|
|
175
|
-
const {
|
|
176
|
-
launcher,
|
|
177
|
-
monitorMemoryHours = 0,
|
|
178
|
-
defaultInterruptionHandler = true,
|
|
179
|
-
flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
|
|
180
|
-
} = options ?? {}
|
|
181
|
-
|
|
182
|
-
// Positive values are validated further by `monitorMemory`.
|
|
183
|
-
if (!Number.isFinite(monitorMemoryHours) || monitorMemoryHours < 0) {
|
|
184
|
-
throw new RangeError(
|
|
185
|
-
`main: "monitorMemoryHours" must be 0 (disabled) or a positive finite number, received ${monitorMemoryHours}`,
|
|
186
|
-
)
|
|
187
|
-
}
|
|
188
|
-
if (
|
|
189
|
-
!Number.isFinite(flushTimeoutMs) ||
|
|
190
|
-
flushTimeoutMs < 0 ||
|
|
191
|
-
flushTimeoutMs > MAX_FLUSH_TIMEOUT_MS
|
|
192
|
-
) {
|
|
193
|
-
throw new RangeError(
|
|
194
|
-
`main: "flushTimeoutMs" must be a finite number between 0 and ${MAX_FLUSH_TIMEOUT_MS}, received ${flushTimeoutMs}`,
|
|
195
|
-
)
|
|
196
|
-
}
|
|
197
|
-
if (active) {
|
|
198
|
-
throw new Error(
|
|
199
|
-
"main: already active; call the teardown function returned by the previous main() call first",
|
|
200
|
-
)
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const __logger = logger.getChild(["main"])
|
|
204
|
-
|
|
205
|
-
__logger.info`Main process launched [${title} :: ${pid}]`
|
|
206
|
-
__logger.info`Process name: ${name}`
|
|
207
|
-
__logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
|
|
208
|
-
// Process options can reveal sensitive flags (e.g. `--inspect=0.0.0.0`
|
|
209
|
-
// or `--require` paths), so they are only logged at debug level.
|
|
210
|
-
__logger.debug`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
|
|
211
|
-
|
|
212
|
-
// Started before any handler is registered: it throws on invalid hours.
|
|
213
|
-
const stopMonitoring =
|
|
214
|
-
monitorMemoryHours > 0
|
|
215
|
-
? monitorMemory(__logger, monitorMemoryHours)
|
|
216
|
-
: undefined
|
|
217
|
-
|
|
218
|
-
// Set once a shutdown starts: a second signal or error while the logs are
|
|
219
|
-
// being flushed exits immediately instead of waiting again.
|
|
220
|
-
let shuttingDown = false
|
|
221
|
-
const exitAfterFlush = async (exit: () => void): Promise<void> => {
|
|
222
|
-
if (!shuttingDown) {
|
|
223
|
-
shuttingDown = true
|
|
224
|
-
await flushLogs(flushTimeoutMs)
|
|
225
|
-
}
|
|
226
|
-
exit()
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
const removeListeners: (() => void)[] = []
|
|
230
|
-
|
|
231
|
-
if (defaultInterruptionHandler) {
|
|
232
|
-
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
233
|
-
const onSignal = (): Promise<void> => {
|
|
234
|
-
__logger.info`Process interrupted. Received signal: ${signal}`
|
|
235
|
-
return exitAfterFlush(() => {
|
|
236
|
-
// Re-raise the signal with its default disposition so the
|
|
237
|
-
// process ends as killed by it. Exit with the conventional
|
|
238
|
-
// status instead if another listener would intercept it.
|
|
239
|
-
process.off(signal, onSignal)
|
|
240
|
-
if (process.listenerCount(signal) === 0) {
|
|
241
|
-
process.kill(pid, signal)
|
|
242
|
-
} else {
|
|
243
|
-
process.exit(128 + constants.signals[signal])
|
|
244
|
-
}
|
|
245
|
-
})
|
|
246
|
-
}
|
|
247
|
-
process.on(signal, onSignal)
|
|
248
|
-
removeListeners.push(() => process.off(signal, onSignal))
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
const onUncaughtException = (
|
|
253
|
-
error: Error,
|
|
254
|
-
origin: NodeJS.UncaughtExceptionOrigin,
|
|
255
|
-
): Promise<void> => {
|
|
256
|
-
__logger.error`Uncaught exception: ${describe(error)}`
|
|
257
|
-
__logger.error`Exception origin: ${origin}`
|
|
258
|
-
return exitAfterFlush(() => process.exit(1))
|
|
259
|
-
}
|
|
260
|
-
process.on("uncaughtException", onUncaughtException)
|
|
261
|
-
removeListeners.push(() =>
|
|
262
|
-
process.off("uncaughtException", onUncaughtException),
|
|
263
|
-
)
|
|
264
|
-
|
|
265
|
-
const onUnhandledRejection = (reason: unknown): Promise<void> => {
|
|
266
|
-
__logger.error`Unhandled promise rejection. Reason:\n${describe(reason)}`
|
|
267
|
-
return exitAfterFlush(() => process.exit(1))
|
|
268
|
-
}
|
|
269
|
-
process.on("unhandledRejection", onUnhandledRejection)
|
|
270
|
-
removeListeners.push(() =>
|
|
271
|
-
process.off("unhandledRejection", onUnhandledRejection),
|
|
272
|
-
)
|
|
273
|
-
|
|
274
|
-
active = true
|
|
275
|
-
let tornDown = false
|
|
276
|
-
const teardown = (): void => {
|
|
277
|
-
if (tornDown) {
|
|
278
|
-
return
|
|
279
|
-
}
|
|
280
|
-
tornDown = true
|
|
281
|
-
stopMonitoring?.()
|
|
282
|
-
for (const remove of removeListeners) {
|
|
283
|
-
remove()
|
|
284
|
-
}
|
|
285
|
-
active = false
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const onLauncherFailure = (error: unknown): Promise<void> => {
|
|
289
|
-
__logger.error`Launcher failed: ${describe(error)}`
|
|
290
|
-
return exitAfterFlush(() => process.exit(1))
|
|
291
|
-
}
|
|
292
|
-
try {
|
|
293
|
-
const result = launcher?.()
|
|
294
|
-
if (result !== undefined) {
|
|
295
|
-
Promise.resolve(result).catch(onLauncherFailure)
|
|
296
|
-
}
|
|
297
|
-
} catch (error) {
|
|
298
|
-
void onLauncherFailure(error)
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
return teardown
|
|
302
|
-
}
|