@darthcav/ts-utils 0.12.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +162 -84
  2. package/dist/core/guards.d.ts +176 -0
  3. package/dist/core/guards.d.ts.map +1 -0
  4. package/dist/core/guards.js +201 -0
  5. package/dist/core/guards.js.map +1 -0
  6. package/dist/core/index.d.ts +17 -0
  7. package/dist/core/index.d.ts.map +1 -0
  8. package/dist/core/index.js +17 -0
  9. package/dist/core/index.js.map +1 -0
  10. package/dist/core/millisecondsToString.d.ts.map +1 -0
  11. package/dist/{millisecondsToString.js → core/millisecondsToString.js} +9 -14
  12. package/dist/core/millisecondsToString.js.map +1 -0
  13. package/dist/core/noop.d.ts +3 -0
  14. package/dist/core/noop.d.ts.map +1 -0
  15. package/dist/core/noop.js +3 -0
  16. package/dist/core/noop.js.map +1 -0
  17. package/dist/index.d.ts +13 -17
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +12 -10
  20. package/dist/index.js.map +1 -1
  21. package/dist/loggers/getConsoleLogger.d.ts +11 -12
  22. package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
  23. package/dist/loggers/getConsoleLogger.js +14 -19
  24. package/dist/loggers/getConsoleLogger.js.map +1 -1
  25. package/dist/loggers/index.d.ts +14 -0
  26. package/dist/loggers/index.d.ts.map +1 -0
  27. package/dist/loggers/index.js +14 -0
  28. package/dist/loggers/index.js.map +1 -0
  29. package/dist/node/delays.d.ts +11 -0
  30. package/dist/node/delays.d.ts.map +1 -0
  31. package/dist/node/delays.js +14 -0
  32. package/dist/node/delays.js.map +1 -0
  33. package/dist/node/index.d.ts +15 -0
  34. package/dist/node/index.d.ts.map +1 -0
  35. package/dist/node/index.js +15 -0
  36. package/dist/node/index.js.map +1 -0
  37. package/dist/node/main.d.ts +158 -0
  38. package/dist/node/main.d.ts.map +1 -0
  39. package/dist/node/main.js +255 -0
  40. package/dist/node/main.js.map +1 -0
  41. package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +14 -5
  42. package/dist/node/monitorMemory.d.ts.map +1 -0
  43. package/dist/{monitorMemory.js → node/monitorMemory.js} +22 -16
  44. package/dist/node/monitorMemory.js.map +1 -0
  45. package/dist/node/osRelease.d.ts +58 -0
  46. package/dist/node/osRelease.d.ts.map +1 -0
  47. package/dist/node/osRelease.js +111 -0
  48. package/dist/node/osRelease.js.map +1 -0
  49. package/dist/node/releaseParsers.d.ts +11 -0
  50. package/dist/node/releaseParsers.d.ts.map +1 -0
  51. package/dist/node/releaseParsers.js +92 -0
  52. package/dist/node/releaseParsers.js.map +1 -0
  53. package/dist/type-testing/index.d.ts +18 -0
  54. package/dist/type-testing/index.d.ts.map +1 -0
  55. package/dist/type-testing/index.js +12 -0
  56. package/dist/type-testing/index.js.map +1 -0
  57. package/package.json +22 -7
  58. package/src/core/guards.ts +239 -0
  59. package/src/core/index.ts +32 -0
  60. package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +9 -16
  61. package/src/core/noop.ts +2 -0
  62. package/src/index.ts +13 -49
  63. package/src/loggers/getConsoleLogger.ts +14 -19
  64. package/src/loggers/index.ts +14 -0
  65. package/src/node/delays.ts +15 -0
  66. package/src/node/index.ts +21 -0
  67. package/src/node/main.ts +419 -0
  68. package/src/{monitorMemory.ts → node/monitorMemory.ts} +24 -18
  69. package/src/node/osRelease.ts +152 -0
  70. package/src/node/releaseParsers.ts +109 -0
  71. package/src/type-testing/index.ts +18 -0
  72. package/dist/main.d.ts +0 -112
  73. package/dist/main.d.ts.map +0 -1
  74. package/dist/main.js +0 -219
  75. package/dist/main.js.map +0 -1
  76. package/dist/millisecondsToString.d.ts.map +0 -1
  77. package/dist/millisecondsToString.js.map +0 -1
  78. package/dist/monitorMemory.d.ts.map +0 -1
  79. package/dist/monitorMemory.js.map +0 -1
  80. package/dist/noop.d.ts +0 -7
  81. package/dist/noop.d.ts.map +0 -1
  82. package/dist/noop.js +0 -7
  83. package/dist/noop.js.map +0 -1
  84. package/dist/osRelease.d.ts +0 -46
  85. package/dist/osRelease.d.ts.map +0 -1
  86. package/dist/osRelease.js +0 -153
  87. package/dist/osRelease.js.map +0 -1
  88. package/dist/types.d.ts +0 -70
  89. package/dist/types.d.ts.map +0 -1
  90. package/dist/types.js +0 -84
  91. package/dist/types.js.map +0 -1
  92. package/src/main.ts +0 -302
  93. package/src/noop.ts +0 -6
  94. package/src/osRelease.ts +0 -174
  95. package/src/types.ts +0 -98
  96. /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
@@ -0,0 +1,111 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { arch, release as kernelRelease, platform } from "node:os";
3
+ import { parseOsRelease, parsePlistStrings } from "./releaseParsers.js";
4
+ /** The platforms whose release information comes from a file. */
5
+ const RELEASE_FILES = {
6
+ linux: {
7
+ // Per the freedesktop.org spec, `/etc/os-release` takes precedence and
8
+ // `/usr/lib/os-release` is the fallback.
9
+ files: ["/etc/os-release", "/usr/lib/os-release"],
10
+ parse: parseOsRelease,
11
+ name: (raw) => raw["NAME"] ?? raw["PRETTY_NAME"] ?? "",
12
+ version: (raw) => raw["VERSION_ID"] ?? raw["VERSION"] ?? "",
13
+ },
14
+ darwin: {
15
+ files: ["/System/Library/CoreServices/SystemVersion.plist"],
16
+ parse: parsePlistStrings,
17
+ name: (raw) => raw["ProductName"] || "macOS",
18
+ version: (raw) => raw["ProductVersion"] ?? "",
19
+ },
20
+ };
21
+ /**
22
+ * Windows names by the first three characters of the kernel version. Windows
23
+ * 11 also reports `10.`, so it is told apart by build number.
24
+ */
25
+ const WINDOWS_NAMES = new Map([
26
+ ["10.", "10"],
27
+ ["6.3", "8.1"],
28
+ ["6.2", "8"],
29
+ ["6.1", "7"],
30
+ ["6.0", "Vista"],
31
+ ["5.2", "XP 64-Bit Edition"],
32
+ ["5.1", "XP"],
33
+ ["5.0", "2000"],
34
+ ]);
35
+ /** First Windows 11 build number. */
36
+ const WINDOWS_11_BUILD = 22000;
37
+ /** Reads the first readable file of `files`, or returns `null` if none is. */
38
+ function readFirstFile(files) {
39
+ for (const file of files) {
40
+ try {
41
+ return readFileSync(file, "utf-8");
42
+ }
43
+ catch {
44
+ // Try the next candidate.
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+ /** Maps a Windows kernel version (e.g. `"10.0.22000"`) to a product name. */
50
+ function windowsName(version) {
51
+ const [major, , build = 0] = version.split(".").map(Number);
52
+ if (major === 10 && build >= WINDOWS_11_BUILD) {
53
+ return "Windows 11";
54
+ }
55
+ return `Windows ${WINDOWS_NAMES.get(version.substring(0, 3)) ?? "unknown version"}`;
56
+ }
57
+ /**
58
+ * Returns OS release information for the current platform (Linux, macOS, or
59
+ * Windows). `arch` always comes from `os.arch()`.
60
+ *
61
+ * - On Linux, it reads `/etc/os-release`, falling back to
62
+ * `/usr/lib/os-release`. `name` comes from `NAME` (or `PRETTY_NAME`) and
63
+ * `version` from `VERSION_ID` (or `VERSION`). Values are unquoted as in a
64
+ * shell; comments and keys that are not upper-case variable names are
65
+ * skipped.
66
+ * - On macOS, it reads `/System/Library/CoreServices/SystemVersion.plist`.
67
+ * `name` is `ProductName` (or `"macOS"`) and `version` is
68
+ * `ProductVersion` (e.g. `"15.1"`), never the Darwin kernel version.
69
+ * - On Windows, `version` is the kernel version, and Windows 11 is told
70
+ * apart from Windows 10 by NT build number (>= 22000).
71
+ *
72
+ * On Linux and macOS, the raw keys of the file are also present.
73
+ *
74
+ * @returns An {@link OsRelease}, or `null` on unsupported platforms or when
75
+ * the release file cannot be read.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import { asString, osRelease } from "@darthcav/ts-utils"
80
+ *
81
+ * const info = osRelease()
82
+ * if (info) {
83
+ * console.log(info.name) // e.g. "Ubuntu", "macOS", or "Windows 11"
84
+ * // Raw keys are `unknown`; narrow them before use.
85
+ * const prettyName = asString(info["PRETTY_NAME"]) // e.g. "Ubuntu 24.04 LTS" (Linux only)
86
+ * }
87
+ * ```
88
+ */
89
+ export function osRelease() {
90
+ const p = platform();
91
+ if (p === "win32") {
92
+ const version = kernelRelease();
93
+ return { name: windowsName(version), version, arch: arch() };
94
+ }
95
+ const source = RELEASE_FILES[p];
96
+ if (source === undefined) {
97
+ return null;
98
+ }
99
+ const content = readFirstFile(source.files);
100
+ if (content === null) {
101
+ return null;
102
+ }
103
+ const raw = source.parse(content);
104
+ return {
105
+ ...raw,
106
+ name: source.name(raw),
107
+ version: source.version(raw),
108
+ arch: arch(),
109
+ };
110
+ }
111
+ //# sourceMappingURL=osRelease.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"osRelease.js","sourceRoot":"","sources":["../../src/node/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;AAElE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAsCvE,iEAAiE;AACjE,MAAM,aAAa,GAA4D;IAC3E,KAAK,EAAE;QACH,uEAAuE;QACvE,yCAAyC;QACzC,KAAK,EAAE,CAAC,iBAAiB,EAAE,qBAAqB,CAAC;QACjD,KAAK,EAAE,cAAc;QACrB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE;QACtD,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;KAC9D;IACD,MAAM,EAAE;QACJ,KAAK,EAAE,CAAC,kDAAkD,CAAC;QAC3D,KAAK,EAAE,iBAAiB;QACxB,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,OAAO;QAC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;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,SAAS;IACrB,MAAM,CAAC,GAAG,QAAQ,EAAE,CAAA;IACpB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAA;QAC/B,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAA;IAChE,CAAC;IACD,MAAM,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC,CAAA;IAC/B,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,IAAI,CAAA;IACf,CAAC;IACD,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAC3C,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAA;IACf,CAAC;IACD,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO;QACH,GAAG,GAAG;QACN,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;QACtB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC;QAC5B,IAAI,EAAE,IAAI,EAAE;KACf,CAAA;AACL,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Parses os-release content into a null-prototype record, skipping blank
3
+ * lines, comments, lines without `=`, and invalid keys.
4
+ */
5
+ export declare function parseOsRelease(content: string): Record<string, string>;
6
+ /**
7
+ * Parses the `<string>` entries of an XML property list into a
8
+ * null-prototype record, skipping other value types and invalid keys.
9
+ */
10
+ export declare function parsePlistStrings(content: string): Record<string, string>;
11
+ //# sourceMappingURL=releaseParsers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"releaseParsers.d.ts","sourceRoot":"","sources":["../../src/node/releaseParsers.ts"],"names":[],"mappings":"AAqEA;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBtE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAWzE"}
@@ -0,0 +1,92 @@
1
+ // Parsers for the OS release files read by `osRelease()`. Internal: the `node`
2
+ // entry point does not re-export them, so they are tested directly.
3
+ /**
4
+ * Valid os-release keys: shell-compatible, upper-case variable names. This
5
+ * also rules out keys such as `__proto__` or `constructor`.
6
+ */
7
+ const OS_RELEASE_KEY = /^[A-Z][A-Z0-9_]*$/;
8
+ /** A `<key>…</key>` followed by a `<string>…</string>` value in a plist. */
9
+ const PLIST_STRING_ENTRY = /<key>([^<]*)<\/key>\s*<string>([^<]*)<\/string>/g;
10
+ /** Valid plist keys to copy; this also rules out keys such as `__proto__`. */
11
+ const PLIST_KEY = /^[A-Za-z][A-Za-z0-9_]*$/;
12
+ /** The predefined XML entities. */
13
+ const XML_ENTITIES = new Map([
14
+ ["amp", "&"],
15
+ ["apos", "'"],
16
+ ["gt", ">"],
17
+ ["lt", "<"],
18
+ ["quot", '"'],
19
+ ]);
20
+ /** Decodes the predefined and numeric character references of XML text. */
21
+ function decodeXml(text) {
22
+ return text.replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([a-z]+));/g, (match, hex, decimal,
23
+ // Set when neither `hex` nor `decimal` is: one group always matches.
24
+ name) => {
25
+ const codePoint = hex !== undefined
26
+ ? Number.parseInt(hex, 16)
27
+ : decimal !== undefined
28
+ ? Number.parseInt(decimal, 10)
29
+ : undefined;
30
+ if (codePoint === undefined) {
31
+ return XML_ENTITIES.get(name) ?? match;
32
+ }
33
+ return codePoint <= 0x10ffff
34
+ ? String.fromCodePoint(codePoint)
35
+ : match;
36
+ });
37
+ }
38
+ /**
39
+ * Removes one level of shell-style quoting from an os-release value. Double
40
+ * quotes allow the `\\`, `\"`, `` \` `` and `\$` escapes; single quotes are
41
+ * literal.
42
+ */
43
+ function unquote(value) {
44
+ if (value.length >= 2) {
45
+ const quote = value[0];
46
+ if (quote === '"' && value.endsWith('"')) {
47
+ return value.slice(1, -1).replace(/\\([\\"`$])/g, "$1");
48
+ }
49
+ if (quote === "'" && value.endsWith("'")) {
50
+ return value.slice(1, -1);
51
+ }
52
+ }
53
+ return value;
54
+ }
55
+ /**
56
+ * Parses os-release content into a null-prototype record, skipping blank
57
+ * lines, comments, lines without `=`, and invalid keys.
58
+ */
59
+ export function parseOsRelease(content) {
60
+ const raw = Object.create(null);
61
+ for (const line of content.split("\n")) {
62
+ const trimmed = line.trim();
63
+ if (trimmed === "" || trimmed.startsWith("#")) {
64
+ continue;
65
+ }
66
+ const eq = trimmed.indexOf("=");
67
+ if (eq === -1) {
68
+ continue;
69
+ }
70
+ const key = trimmed.substring(0, eq).trim();
71
+ if (!OS_RELEASE_KEY.test(key)) {
72
+ continue;
73
+ }
74
+ raw[key] = unquote(trimmed.substring(eq + 1).trim());
75
+ }
76
+ return raw;
77
+ }
78
+ /**
79
+ * Parses the `<string>` entries of an XML property list into a
80
+ * null-prototype record, skipping other value types and invalid keys.
81
+ */
82
+ export function parsePlistStrings(content) {
83
+ const raw = Object.create(null);
84
+ for (const [, rawKey = "", value = ""] of content.matchAll(PLIST_STRING_ENTRY)) {
85
+ const key = decodeXml(rawKey.trim());
86
+ if (PLIST_KEY.test(key)) {
87
+ raw[key] = decodeXml(value.trim());
88
+ }
89
+ }
90
+ return raw;
91
+ }
92
+ //# sourceMappingURL=releaseParsers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"releaseParsers.js","sourceRoot":"","sources":["../../src/node/releaseParsers.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,oEAAoE;AAEpE;;;GAGG;AACH,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAE1C,4EAA4E;AAC5E,MAAM,kBAAkB,GAAG,kDAAkD,CAAA;AAE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iBAAiB,CAAC,OAAe;IAC7C,MAAM,GAAG,GAA2B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvD,KAAK,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,EAAE,CAAC,IAAI,OAAO,CAAC,QAAQ,CACtD,kBAAkB,CACrB,EAAE,CAAC;QACA,MAAM,GAAG,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;QACpC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;QACtC,CAAC;IACL,CAAC;IACD,OAAO,GAAG,CAAA;AACd,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Type-level testing helpers. They are types only and add no code at runtime.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import type { Assert, Equal } from "@darthcav/ts-utils/type-testing"
7
+ * ```
8
+ *
9
+ * @module type-testing
10
+ */
11
+ export type { Assert } from "./Assert.ts";
12
+ export type { Equal } from "./Equal.ts";
13
+ export type { Extends } from "./Extends.ts";
14
+ export type { IsAny } from "./IsAny.ts";
15
+ export type { IsNever } from "./IsNever.ts";
16
+ export type { IsUnknown } from "./IsUnknown.ts";
17
+ export type { Not } from "./Not.ts";
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/type-testing/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACzC,YAAY,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AACvC,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,YAAY,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AACvC,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAC3C,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/C,YAAY,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Type-level testing helpers. They are types only and add no code at runtime.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import type { Assert, Equal } from "@darthcav/ts-utils/type-testing"
7
+ * ```
8
+ *
9
+ * @module type-testing
10
+ */
11
+ export {};
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/type-testing/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@darthcav/ts-utils",
3
3
  "description": "A collection of utility functions for TypeScript applications and modules",
4
- "version": "0.12.3",
4
+ "version": "1.0.1",
5
5
  "author": {
6
6
  "name": "darthcav",
7
7
  "url": "https://github.com/darthcav"
@@ -15,19 +15,34 @@
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "default": "./dist/index.js"
18
+ },
19
+ "./core": {
20
+ "types": "./dist/core/index.d.ts",
21
+ "default": "./dist/core/index.js"
22
+ },
23
+ "./node": {
24
+ "types": "./dist/node/index.d.ts",
25
+ "default": "./dist/node/index.js"
26
+ },
27
+ "./loggers": {
28
+ "types": "./dist/loggers/index.d.ts",
29
+ "default": "./dist/loggers/index.js"
30
+ },
31
+ "./type-testing": {
32
+ "types": "./dist/type-testing/index.d.ts",
33
+ "default": "./dist/type-testing/index.js"
18
34
  }
19
35
  },
20
36
  "files": [
21
37
  "src",
22
38
  "!src/__tests__",
23
- "dist",
24
- "!dist/__tests__"
39
+ "dist"
25
40
  ],
26
41
  "dependencies": {
27
42
  "@logtape/logtape": "2.4.2"
28
43
  },
29
44
  "devDependencies": {
30
- "@biomejs/biome": "2.6.7",
45
+ "@biomejs/biome": "2.6.8",
31
46
  "@types/node": "26.6.6",
32
47
  "prettier": "3.10.1",
33
48
  "typedoc": "0.28.20"
@@ -42,14 +57,14 @@
42
57
  "scripts": {
43
58
  "\n===== Build =====": "",
44
59
  "clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
45
- "build": "npm run clean && tsc",
60
+ "build": "npm run clean && tsc -p tsconfig.build.json",
46
61
  "prepare": "npm run build",
47
62
  "\n===== Typecheck =====": "",
48
63
  "typecheck": "tsc --noEmit",
49
64
  "\n===== Test =====": "",
50
65
  "test": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --test --test-reporter=spec \"src/**/*.test.ts\"",
51
- "test:coverage": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test \"src/**/*.test.ts\"",
52
- "test:coverage:lcov": "node -e \"fs.mkdirSync('coverage', { recursive: true })\" && node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-reporter=spec --test-reporter-destination=stdout --test \"src/**/*.test.ts\"",
66
+ "test:coverage": "node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 --test-coverage-exclude=\"src/__tests__/**\" --test \"src/**/*.test.ts\"",
67
+ "test:coverage:lcov": "node -e \"fs.mkdirSync('coverage', { recursive: true })\" && node --env-file-if-exists=.env.local --experimental-test-module-mocks --experimental-test-coverage --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 --test-coverage-exclude=\"src/__tests__/**\" --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-reporter=spec --test-reporter-destination=stdout --test \"src/**/*.test.ts\"",
53
68
  "\n===== Linter =====": "",
54
69
  "lint": "biome check . && prettier --check \"**/*.md\" --ignore-path .gitignore",
55
70
  "lint:fix": "biome check --write . && prettier --write \"**/*.md\" --ignore-path .gitignore",
@@ -0,0 +1,239 @@
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
+ /**
11
+ * Type guard that checks whether a value is a plain object that can be treated
12
+ * as a runtime JSON object.
13
+ *
14
+ * Plain objects are object literals, `JSON.parse` results, and
15
+ * `Object.create(null)` objects, including those from another realm (e.g. a
16
+ * `node:vm` context). Arrays, class instances, and built-ins such as `Date`,
17
+ * `Map`, `Set`, `RegExp`, or module namespace objects are rejected.
18
+ *
19
+ * The check is shallow and keys are not sanitized: an own `__proto__` or
20
+ * `constructor` key (as `JSON.parse` can produce from untrusted input) is kept.
21
+ * Do not merge the value into other objects key by key without guarding
22
+ * against those keys, or prototype pollution becomes possible.
23
+ *
24
+ * @param value - Value to check.
25
+ * @returns `true` when the value is a plain object, narrowing it to
26
+ * {@link RuntimeObject}.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const body: unknown = JSON.parse(input)
31
+ * if (isRuntimeObject(body)) {
32
+ * console.log(Object.keys(body)) // body: RuntimeObject
33
+ * }
34
+ * ```
35
+ */
36
+ export function isRuntimeObject(value: unknown): value is RuntimeObject {
37
+ if (typeof value !== "object" || value === null) {
38
+ return false
39
+ }
40
+ const prototype: unknown = Object.getPrototypeOf(value)
41
+ // A null prototype, or a realm's root `Object.prototype` (whose own
42
+ // prototype is null), marks a plain object.
43
+ if (
44
+ prototype !== null &&
45
+ prototype !== Object.prototype &&
46
+ Object.getPrototypeOf(prototype) !== null
47
+ ) {
48
+ return false
49
+ }
50
+ // Exclude null-prototype exotics such as module namespace objects.
51
+ return !(Symbol.toStringTag in value || Symbol.iterator in value)
52
+ }
53
+
54
+ /**
55
+ * Returns the input when it is a plain object, as decided by
56
+ * {@link isRuntimeObject} (see there for the caveats about unsanitized keys).
57
+ *
58
+ * @param value - Value to narrow.
59
+ * @returns The same value as a {@link RuntimeObject}, or `undefined` when the
60
+ * value is not a plain object.
61
+ */
62
+ export function asRuntimeObject(value: unknown): RuntimeObject | undefined {
63
+ return isRuntimeObject(value) ? value : undefined
64
+ }
65
+
66
+ /**
67
+ * Type guard that checks whether a value is a string.
68
+ *
69
+ * @param value - Value to check.
70
+ * @returns `true` when the value is a string, narrowing it to `string`.
71
+ */
72
+ export function isString(value: unknown): value is string {
73
+ return typeof value === "string"
74
+ }
75
+
76
+ /**
77
+ * Returns the input when it is a string.
78
+ *
79
+ * @param value - Value to narrow.
80
+ * @returns The same value as a string, or `undefined` when the value is not a string.
81
+ */
82
+ export function asString(value: unknown): string | undefined {
83
+ return isString(value) ? value : undefined
84
+ }
85
+
86
+ /**
87
+ * Type guard that checks whether a value is a boolean primitive (`true` or
88
+ * `false`). Boxed `Boolean` objects are rejected.
89
+ *
90
+ * @param value - Value to check.
91
+ * @returns `true` when the value is a boolean, narrowing it to `boolean`.
92
+ */
93
+ export function isBoolean(value: unknown): value is boolean {
94
+ return typeof value === "boolean"
95
+ }
96
+
97
+ /**
98
+ * Returns the input when it is a boolean primitive, as decided by
99
+ * {@link isBoolean}.
100
+ *
101
+ * @param value - Value to narrow.
102
+ * @returns The same value as a boolean, or `undefined` when the value is not
103
+ * a boolean.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * const enabled = asBoolean(config["enabled"]) ?? false
108
+ * ```
109
+ */
110
+ export function asBoolean(value: unknown): boolean | undefined {
111
+ return isBoolean(value) ? value : undefined
112
+ }
113
+
114
+ /**
115
+ * Type guard that checks whether a value is a finite number primitive. `NaN`,
116
+ * `Infinity`, `-Infinity`, boxed `Number` objects, bigints, and numeric
117
+ * strings are rejected.
118
+ *
119
+ * @param value - Value to check.
120
+ * @returns `true` when the value is a finite number, narrowing it to
121
+ * `number`.
122
+ */
123
+ export function isFiniteNumber(value: unknown): value is number {
124
+ return Number.isFinite(value)
125
+ }
126
+
127
+ /**
128
+ * Returns the input when it is a finite number primitive, as decided by
129
+ * {@link isFiniteNumber}.
130
+ *
131
+ * @param value - Value to narrow.
132
+ * @returns The same value as a number, or `undefined` when the value is not a
133
+ * finite number.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const port = asFiniteNumber(config["port"]) ?? 3000
138
+ * ```
139
+ */
140
+ export function asFiniteNumber(value: unknown): number | undefined {
141
+ return isFiniteNumber(value) ? value : undefined
142
+ }
143
+
144
+ /**
145
+ * A predicate that narrows an `unknown` value to `T`, such as
146
+ * {@link isString}. Used by {@link isArrayOf}, {@link asArrayOf}, and
147
+ * {@link filterByGuard}.
148
+ *
149
+ * @typeParam T - The type the guard narrows to.
150
+ */
151
+ export type TypeGuard<T> = (value: unknown) => value is T
152
+
153
+ /**
154
+ * Type guard that checks whether a value is an array whose elements all pass
155
+ * `guard`. A single invalid element makes it fail (use {@link filterByGuard}
156
+ * to keep only the valid ones); an empty array passes. Holes in sparse arrays
157
+ * are checked as `undefined`.
158
+ *
159
+ * @typeParam T - The element type the guard narrows to.
160
+ * @param value - Value to check.
161
+ * @param guard - Type guard every element must pass.
162
+ * @returns `true` when the value is an array of `T`, narrowing it to `T[]`.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const body: unknown = JSON.parse(input)
167
+ * if (isArrayOf(body, isString)) {
168
+ * body.map((tag) => tag.toUpperCase()) // body: string[]
169
+ * }
170
+ * ```
171
+ */
172
+ export function isArrayOf<T>(
173
+ value: unknown,
174
+ guard: TypeGuard<T>,
175
+ ): value is T[] {
176
+ // An array iterator, unlike `Array#every`, visits the holes of sparse
177
+ // arrays, as `undefined`.
178
+ return (
179
+ Array.isArray(value) &&
180
+ value.values().every((element: unknown) => guard(element))
181
+ )
182
+ }
183
+
184
+ /**
185
+ * Returns the input when it is an array whose elements all pass `guard`, as
186
+ * decided by {@link isArrayOf}.
187
+ *
188
+ * @typeParam T - The element type the guard narrows to.
189
+ * @param value - Value to narrow.
190
+ * @param guard - Type guard every element must pass.
191
+ * @returns The same array as `T[]`, or `undefined` when the value is not an
192
+ * array or any element fails the guard.
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * const tags = asArrayOf(asRuntimeObject(body)?.["tags"], isString) ?? []
197
+ * ```
198
+ */
199
+ export function asArrayOf<T>(
200
+ value: unknown,
201
+ guard: TypeGuard<T>,
202
+ ): T[] | undefined {
203
+ return isArrayOf(value, guard) ? value : undefined
204
+ }
205
+
206
+ /**
207
+ * Keeps the elements of an array that pass `guard` and silently drops the
208
+ * others, unlike {@link isArrayOf}, which rejects the whole array. A value
209
+ * that is not an array yields an empty array, and holes in sparse arrays are
210
+ * skipped.
211
+ *
212
+ * @typeParam T - The element type the guard narrows to.
213
+ * @param value - Value that may be an array.
214
+ * @param guard - Type guard deciding which elements to keep.
215
+ * @returns A new array with the elements that pass the guard.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * filterByGuard(["a", 1, "b", null], isString) // ["a", "b"]
220
+ * filterByGuard("not an array", isString) // []
221
+ * ```
222
+ */
223
+ export function filterByGuard<T>(value: unknown, guard: TypeGuard<T>): T[] {
224
+ return Array.isArray(value)
225
+ ? value.filter((element: unknown): element is T => guard(element))
226
+ : []
227
+ }
228
+
229
+ /**
230
+ * Keeps the plain objects of an array: {@link filterByGuard} with
231
+ * {@link isRuntimeObject}, whose caveats about unsanitized keys apply. A value
232
+ * that is not an array yields an empty array.
233
+ *
234
+ * @param value - Value that may contain runtime objects.
235
+ * @returns Only the elements that can be treated as {@link RuntimeObject} values.
236
+ */
237
+ export function toRuntimeObjectArray(value: unknown): RuntimeObject[] {
238
+ return filterByGuard(value, isRuntimeObject)
239
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Portable helpers: type guards and narrowing helpers, duration formatting,
3
+ * and `noop`. They import no Node.js built-ins or packages, so they run in any
4
+ * ES2025 runtime (`millisecondsToString` also needs `Intl.DurationFormat` and
5
+ * `Temporal`).
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { asString, millisecondsToString } from "@darthcav/ts-utils/core"
10
+ * ```
11
+ *
12
+ * @module core
13
+ */
14
+
15
+ export {
16
+ asArrayOf,
17
+ asBoolean,
18
+ asFiniteNumber,
19
+ asRuntimeObject,
20
+ asString,
21
+ filterByGuard,
22
+ isArrayOf,
23
+ isBoolean,
24
+ isFiniteNumber,
25
+ isRuntimeObject,
26
+ isString,
27
+ type RuntimeObject,
28
+ type TypeGuard,
29
+ toRuntimeObjectArray,
30
+ } from "./guards.ts"
31
+ export { millisecondsToString } from "./millisecondsToString.ts"
32
+ export { noop } from "./noop.ts"
@@ -1,8 +1,7 @@
1
1
  /**
2
- * Maximum number of {@link Intl.DurationFormat} instances retained in the
3
- * cache. Bounds memory growth when many distinct locales are requested (e.g.
4
- * a locale derived from untrusted input). When the limit is reached, the
5
- * least-recently-inserted entry is evicted.
2
+ * Maximum number of cached formatters, so many distinct locales (e.g. from
3
+ * untrusted input) cannot grow memory without bound. The oldest entry is
4
+ * evicted first.
6
5
  */
7
6
  const MAX_CACHED_FORMATTERS = 64
8
7
 
@@ -67,16 +66,10 @@ export function millisecondsToString(ms: number, locale = "en"): string {
67
66
  )
68
67
  }
69
68
 
70
- const totalMilliseconds = Math.round(ms)
71
- const magnitude = Math.abs(totalMilliseconds)
72
-
73
- const formatted = getDurationFormatter(locale).format({
74
- days: Math.floor(magnitude / 86_400_000),
75
- hours: Math.floor((magnitude % 86_400_000) / 3_600_000),
76
- minutes: Math.floor((magnitude % 3_600_000) / 60_000),
77
- seconds: Math.floor((magnitude % 60_000) / 1000),
78
- milliseconds: magnitude % 1000,
79
- })
80
-
81
- return totalMilliseconds < 0 && formatted ? `-${formatted}` : formatted
69
+ // Balances the milliseconds into days (of 24 hours) down to milliseconds.
70
+ // `Intl.DurationFormat` puts the sign of a negative duration in front.
71
+ const duration = Temporal.Duration.from({
72
+ milliseconds: Math.round(ms),
73
+ }).round({ largestUnit: "days" })
74
+ return getDurationFormatter(locale).format(duration)
82
75
  }
@@ -0,0 +1,2 @@
1
+ /** Does nothing. Useful as a placeholder callback, default handler, or in tests. */
2
+ export const noop = (): void => {}