@helpers4/node 3.1.4 → 3.1.5
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 +6 -0
- package/lib/index.d.ts +9 -2
- package/lib/index.js.map +1 -1
- package/llms.txt +5 -5
- package/meta/api.json +6 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,12 +22,15 @@ A set of helpers for working with URLs.
|
|
|
22
22
|
## See
|
|
23
23
|
|
|
24
24
|
<!-- AUTOMATIC-SIBLINGS -->
|
|
25
|
+
- [animation](../animation)
|
|
25
26
|
- [array](../array)
|
|
27
|
+
- [browser](../browser)
|
|
26
28
|
- [ci](../ci)
|
|
27
29
|
- [color](../color)
|
|
28
30
|
- [commit](../commit)
|
|
29
31
|
- [date](../date)
|
|
30
32
|
- [function](../function)
|
|
33
|
+
- [geometry](../geometry)
|
|
31
34
|
- [guard](../guard)
|
|
32
35
|
- [id](../id)
|
|
33
36
|
- [json](../json)
|
|
@@ -51,12 +54,15 @@ A set of helpers for working with URLs.
|
|
|
51
54
|
<!-- AUTOMATIC-CATEGORIES-TABLE -->
|
|
52
55
|
| Name | Package | Source Code | Description |
|
|
53
56
|
|------|---------|-------------|-------------|
|
|
57
|
+
| animation | [@helpers4/animation](https://www.npmjs.com/package/@helpers4/animation) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/animation) | Timing and interpolation for animations |
|
|
54
58
|
| array | [@helpers4/array](https://www.npmjs.com/package/@helpers4/array) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/array) | Array manipulation utilities |
|
|
59
|
+
| browser | [@helpers4/browser](https://www.npmjs.com/package/@helpers4/browser) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/browser) | Browser-specific utilities |
|
|
55
60
|
| ci | [@helpers4/ci](https://www.npmjs.com/package/@helpers4/ci) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/ci) | CI/CD workflow status utilities |
|
|
56
61
|
| color | [@helpers4/color](https://www.npmjs.com/package/@helpers4/color) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/color) | Color conversion and validation utilities |
|
|
57
62
|
| commit | [@helpers4/commit](https://www.npmjs.com/package/@helpers4/commit) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/commit) | Conventional Commits parsing and analysis |
|
|
58
63
|
| date | [@helpers4/date](https://www.npmjs.com/package/@helpers4/date) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/date) | Date and time utility functions |
|
|
59
64
|
| function | [@helpers4/function](https://www.npmjs.com/package/@helpers4/function) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/function) | Function utilities and type guards |
|
|
65
|
+
| geometry | [@helpers4/geometry](https://www.npmjs.com/package/@helpers4/geometry) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/geometry) | 2D points, rectangles and affine matrices |
|
|
60
66
|
| guard | [@helpers4/guard](https://www.npmjs.com/package/@helpers4/guard) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/guard) | Runtime type guard utilities |
|
|
61
67
|
| id | [@helpers4/id](https://www.npmjs.com/package/@helpers4/id) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/id) | Unique identifier generation utilities |
|
|
62
68
|
| json | [@helpers4/json](https://www.npmjs.com/package/@helpers4/json) | [Source](https://github.com/helpers4/helpers4/tree/main/helpers/json) | JSON parsing and serialization, with its common variants |
|
package/lib/index.d.ts
CHANGED
|
@@ -88,8 +88,7 @@ declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer
|
|
|
88
88
|
* Unlike `readFileSync` + `JSON.parse`, this never throws.
|
|
89
89
|
*
|
|
90
90
|
* @param filePath - Path to the JSON (or JSONC) file to read.
|
|
91
|
-
* @
|
|
92
|
-
* @returns The parsed value typed as `T`, or `fallback` on failure.
|
|
91
|
+
* @returns The parsed value typed as `T`, or `null` on failure (pass a `fallback` to get it instead)
|
|
93
92
|
* @example
|
|
94
93
|
* safeReadJsonFile<{ name: string }>('./package.json') // => { name: 'helpers4', ... }
|
|
95
94
|
* safeReadJsonFile('./missing.json') // => null
|
|
@@ -100,6 +99,14 @@ declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer
|
|
|
100
99
|
* @since 3.0.6
|
|
101
100
|
*/
|
|
102
101
|
declare function safeReadJsonFile<T>(filePath: string): T | null;
|
|
102
|
+
/**
|
|
103
|
+
* Overload taking a `fallback`: returns it instead of `null` on invalid input.
|
|
104
|
+
*
|
|
105
|
+
* @param filePath - Path to the JSON (or JSONC) file to read
|
|
106
|
+
* @param fallback - Value returned on failure
|
|
107
|
+
* @returns The parsed value typed as `T`, or `fallback` on failure
|
|
108
|
+
* @since 3.0.6
|
|
109
|
+
*/
|
|
103
110
|
declare function safeReadJsonFile<T>(filePath: string, fallback: T): T;
|
|
104
111
|
|
|
105
112
|
/**
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../helpers/node/isBuffer.ts","../../../helpers/node/isNodeStream.ts","../../../helpers/node/isSharedArrayBuffer.ts","../../../helpers/_shared/_stripJsonComments.ts","../../../helpers/node/safeReadJsonFile.ts","../../../helpers/node/withTempDir.ts"],"sourcesContent":["/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a Node.js Buffer instance.\n *\n * `Buffer` extends `Uint8Array` and is specific to Node.js, Bun, and Deno.\n * In browser-only environments where `Buffer` is not defined, this function\n * always returns `false`.\n *\n * Useful for filtering or type-narrowing in a functional pipeline:\n * `values.filter(isBuffer)`\n *\n * @param value - The value to check\n * @returns True if value is a Buffer\n * @example\n * isBuffer(Buffer.from('hello')) // => true\n * isBuffer(new Uint8Array(8)) // => false\n * isBuffer('hello') // => false\n * @since 2.0.0\n */\nexport function isBuffer(value: unknown): value is Buffer {\n return typeof Buffer !== 'undefined' && value instanceof Buffer;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a Node.js stream (has a `.pipe()` method).\n *\n * Uses duck-typing: any object with a `pipe` function qualifies, covering\n * `Readable`, `Writable`, `Duplex`, `Transform`, and custom stream-compatible\n * objects without importing from `node:stream`.\n *\n * @param value - The value to check\n * @returns `true` if value is a Node.js stream\n * @example\n * import { Readable } from 'node:stream';\n * isNodeStream(new Readable()) // => true\n * isNodeStream({}) // => false\n * isNodeStream(null) // => false\n * @since 2.0.3\n */\nexport function isNodeStream(value: unknown): value is { pipe: (...args: unknown[]) => unknown } {\n return (\n // Intentionally `object`-only, unlike `isPromiseLike` (see type/isPromiseLike.ts):\n // a callable function exposing `.pipe()` would be an unusual, contrived stream shape.\n value !== null &&\n typeof value === 'object' &&\n typeof (value as Record<string, unknown>)['pipe'] === 'function'\n );\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a `SharedArrayBuffer` instance.\n *\n * `SharedArrayBuffer` enables shared memory between the main thread and worker\n * threads. In browsers without COOP/COEP headers, `SharedArrayBuffer` may be\n * unavailable; this function returns `false` in that case.\n *\n * @param value - The value to check\n * @returns `true` if value is a SharedArrayBuffer\n * @example\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // => true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // => false\n * isSharedArrayBuffer(null) // => false\n * @since 2.0.3\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n return typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n *\n * Internal helper used by `node/safeReadJsonFile` and `json/parse` to support JSONC (JSON with\n * line and block comments, plus trailing commas) — the dialect used by tsconfig.json, VS Code's\n * settings.json, etc. Not exported from any package barrel — tests live in\n * _stripJsonComments.test.ts.\n */\n\n/**\n * Blanks out line comments (starting with two slashes), block comments (slash-star ... star-slash),\n * and trailing commas (before `}` or `]`) in a JSONC string, so the result can be passed to\n * `JSON.parse`. String literals are tracked so a comment-like or comma character occurring\n * *inside* a JSON string (e.g. a URL) is left untouched — this is a string-boundary-aware pass,\n * not a naive regex strip.\n *\n * Everything removed is replaced by spaces (line breaks inside a block comment are kept), so the\n * output has exactly the same length and line layout as the input: a position `JSON.parse`\n * reports in an error on the output points at the same place in the original JSONC text.\n * @ignore\n */\nexport function stripJsonComments(input: string): string {\n let output = '';\n let inString = false;\n // A comma seen outside a string is held back instead of emitted immediately:\n // if the next significant token turns out to be `}`/`]`, it was a trailing\n // comma and gets blanked; otherwise it (and any whitespace/comments held\n // alongside it) is flushed once a real token confirms it wasn't trailing.\n let pendingComma = '';\n const flushPendingComma = () => {\n output += pendingComma;\n pendingComma = '';\n };\n // Whitespace and blanked-out comments don't resolve a pending comma either way, so they're\n // buffered alongside it to keep the output in the original order.\n const emitFiller = (text: string) => {\n if (pendingComma) {\n pendingComma += text;\n } else {\n output += text;\n }\n };\n\n let i = 0;\n while (i < input.length) {\n const char = input[i];\n\n if (inString) {\n output += char;\n if (char === '\\\\') {\n // Copy the escaped character as-is (whatever it is) so an escaped\n // quote (`\\\"`) doesn't get mistaken for the string's end.\n i++;\n if (i < input.length) output += input[i];\n } else if (char === '\"') {\n inString = false;\n }\n i++;\n continue;\n }\n\n if (char === '\"') {\n flushPendingComma();\n inString = true;\n output += char;\n i++;\n continue;\n }\n\n if (char === '/' && input[i + 1] === '/') {\n const start = i;\n i += 2;\n // Stop at any line-ending character, not just \\n — a bare \\r (classic\n // Mac line endings, or a lone \\r before a later \\n) also ends the line,\n // otherwise everything up to the next \\n (or EOF) gets silently eaten.\n while (i < input.length && input[i] !== '\\n' && input[i] !== '\\r') i++;\n emitFiller(' '.repeat(i - start));\n continue;\n }\n\n if (char === '/' && input[i + 1] === '*') {\n const start = i;\n i += 2;\n while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i++;\n // An unterminated block comment runs to the end of the input.\n i = Math.min(i + 2, input.length);\n emitFiller(input.slice(start, i).replace(/[^\\r\\n]/g, ' '));\n continue;\n }\n\n if (char === ',') {\n flushPendingComma();\n pendingComma = char;\n i++;\n continue;\n }\n\n if (char === '}' || char === ']') {\n // Blank the comma — it was trailing — but keep what was buffered after it.\n output += pendingComma.replace(',', ' ');\n pendingComma = '';\n output += char;\n i++;\n continue;\n }\n\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n emitFiller(char);\n i++;\n continue;\n }\n\n flushPendingComma();\n output += char;\n i++;\n }\n\n flushPendingComma();\n return output;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\nimport { readFileSync } from 'node:fs';\nimport { stripJsonComments } from '../_shared/_stripJsonComments';\n\n/**\n * Reads a file and parses its contents as JSON, returning `null` (or a\n * fallback) on any failure — a missing/unreadable file and invalid content\n * are both treated the same way.\n *\n * Also tolerates JSONC (line/block comments and trailing commas — the\n * dialect used by `tsconfig.json`, VS Code's `settings.json`, etc.): strict\n * `JSON.parse` is tried first, and only on failure is the content re-parsed\n * with comments/trailing commas stripped, so plain JSON pays no extra cost.\n *\n * Unlike `readFileSync` + `JSON.parse`, this never throws.\n *\n * @param filePath - Path to the JSON (or JSONC) file to read.\n * @param fallback - Value returned on failure. Defaults to `null` when omitted.\n * @returns The parsed value typed as `T`, or `fallback` on failure.\n * @example\n * safeReadJsonFile<{ name: string }>('./package.json') // => { name: 'helpers4', ... }\n * safeReadJsonFile('./missing.json') // => null\n * safeReadJsonFile('./missing.json', {}) // => {}\n * @example\n * // tsconfig.json-style JSONC (comments + trailing comma) also parses:\n * safeReadJsonFile('./tsconfig.json') // => { compilerOptions: { strict: true }, ... }\n * @since 3.0.6\n */\nexport function safeReadJsonFile<T>(filePath: string): T | null;\nexport function safeReadJsonFile<T>(filePath: string, fallback: T): T;\nexport function safeReadJsonFile<T>(filePath: string, fallback?: T): T | null {\n try {\n const content = readFileSync(filePath, 'utf-8');\n try {\n return JSON.parse(content) as T;\n } catch {\n // Not strict JSON — retry tolerating JSONC comments/trailing commas\n // before giving up.\n return JSON.parse(stripJsonComments(content)) as T;\n }\n } catch {\n // Distinguish \"no fallback provided\" (→ null) from \"fallback is undefined\"\n // (→ undefined as T) to keep runtime behaviour aligned with the overloads.\n return arguments.length < 2 ? null : (fallback as T);\n }\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and\n * always removes it (recursively) afterward — including when `fn` throws.\n * @param prefix - Prepended to the generated directory name, to make it identifiable\n * @param fn - Receives the temp directory's absolute path; its (possibly synchronous) return\n * value is returned\n * @returns Whatever `fn` returns or resolves to\n * @example\n * await withTempDir('my-tool', async (dir) => {\n * await writeFile(`${dir}/output.txt`, 'data');\n * return readFile(`${dir}/output.txt`, 'utf-8');\n * });\n * // => 'data' (the directory no longer exists once this resolves)\n * @since 3.1.1\n */\nexport async function withTempDir<T>(prefix: string, fn: (dir: string) => T | Promise<T>): Promise<T> {\n const dir = await mkdtemp(join(tmpdir(), `${prefix}-`));\n try {\n return await fn(dir);\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,OAAiC;CACxD,OAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;ACJA,SAAgB,aAAa,OAAoE;CAC/F,OAGE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAAkC,YAAY;AAE1D;;;;;;;;;;;;;;;;;;;;;;;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AG;GACvC,eAAe;GACf,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;GACnE,WAAW,IAAI;GACf;GACA;EACF;EAEA,kBAAkB;EAClB,UAAU;EACV;CACF;CAEA,kBAAkB;CAClB,OAAO;AACT;;;;;;;;ACtFA,SAAgB,iBAAoB,UAAkB,UAAwB;CAC5E,IAAI;EACF,MAAM,UAAU,aAAa,UAAU,OAAO;EAC9C,IAAI;GACF,OAAO,KAAK,MAAM,OAAO;EAC3B,QAAQ;GAGN,OAAO,KAAK,MAAM,kBAAkB,OAAO,CAAC;EAC9C;CACF,QAAQ;EAGN,OAAO,UAAU,SAAS,IAAI,OAAQ;CACxC;AACF;;;;;;;;;;;;;;;;;;;;;;;ACzBA,eAAsB,YAAe,QAAgB,IAAiD;CACpG,MAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,GAAG,GAAG,OAAO,EAAE,CAAC;CACtD,IAAI;EACF,OAAO,MAAM,GAAG,GAAG;CACrB,UAAU;EACR,MAAM,GAAG,KAAK;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAChD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../helpers/node/isBuffer.ts","../../../helpers/node/isNodeStream.ts","../../../helpers/node/isSharedArrayBuffer.ts","../../../helpers/_shared/_stripJsonComments.ts","../../../helpers/node/safeReadJsonFile.ts","../../../helpers/node/withTempDir.ts"],"sourcesContent":["/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a Node.js Buffer instance.\n *\n * `Buffer` extends `Uint8Array` and is specific to Node.js, Bun, and Deno.\n * In browser-only environments where `Buffer` is not defined, this function\n * always returns `false`.\n *\n * Useful for filtering or type-narrowing in a functional pipeline:\n * `values.filter(isBuffer)`\n *\n * @param value - The value to check\n * @returns True if value is a Buffer\n * @example\n * isBuffer(Buffer.from('hello')) // => true\n * isBuffer(new Uint8Array(8)) // => false\n * isBuffer('hello') // => false\n * @since 2.0.0\n */\nexport function isBuffer(value: unknown): value is Buffer {\n return typeof Buffer !== 'undefined' && value instanceof Buffer;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a Node.js stream (has a `.pipe()` method).\n *\n * Uses duck-typing: any object with a `pipe` function qualifies, covering\n * `Readable`, `Writable`, `Duplex`, `Transform`, and custom stream-compatible\n * objects without importing from `node:stream`.\n *\n * @param value - The value to check\n * @returns `true` if value is a Node.js stream\n * @example\n * import { Readable } from 'node:stream';\n * isNodeStream(new Readable()) // => true\n * isNodeStream({}) // => false\n * isNodeStream(null) // => false\n * @since 2.0.3\n */\nexport function isNodeStream(value: unknown): value is { pipe: (...args: unknown[]) => unknown } {\n return (\n // Intentionally `object`-only, unlike `isPromiseLike` (see type/isPromiseLike.ts):\n // a callable function exposing `.pipe()` would be an unusual, contrived stream shape.\n value !== null &&\n typeof value === 'object' &&\n typeof (value as Record<string, unknown>)['pipe'] === 'function'\n );\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\n/**\n * Checks if a value is a `SharedArrayBuffer` instance.\n *\n * `SharedArrayBuffer` enables shared memory between the main thread and worker\n * threads. In browsers without COOP/COEP headers, `SharedArrayBuffer` may be\n * unavailable; this function returns `false` in that case.\n *\n * @param value - The value to check\n * @returns `true` if value is a SharedArrayBuffer\n * @example\n * isSharedArrayBuffer(new SharedArrayBuffer(8)) // => true\n * isSharedArrayBuffer(new ArrayBuffer(8)) // => false\n * isSharedArrayBuffer(null) // => false\n * @since 2.0.3\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n return typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n *\n * Internal helper used by `node/safeReadJsonFile` and `json/parse` to support JSONC (JSON with\n * line and block comments, plus trailing commas) — the dialect used by tsconfig.json, VS Code's\n * settings.json, etc. Not exported from any package barrel — tests live in\n * _stripJsonComments.test.ts.\n */\n\n/**\n * Blanks out line comments (starting with two slashes), block comments (slash-star ... star-slash),\n * and trailing commas (before `}` or `]`) in a JSONC string, so the result can be passed to\n * `JSON.parse`. String literals are tracked so a comment-like or comma character occurring\n * *inside* a JSON string (e.g. a URL) is left untouched — this is a string-boundary-aware pass,\n * not a naive regex strip.\n *\n * Everything removed is replaced by spaces (line breaks inside a block comment are kept), so the\n * output has exactly the same length and line layout as the input: a position `JSON.parse`\n * reports in an error on the output points at the same place in the original JSONC text.\n * @ignore\n */\nexport function stripJsonComments(input: string): string {\n let output = '';\n let inString = false;\n // A comma seen outside a string is held back instead of emitted immediately:\n // if the next significant token turns out to be `}`/`]`, it was a trailing\n // comma and gets blanked; otherwise it (and any whitespace/comments held\n // alongside it) is flushed once a real token confirms it wasn't trailing.\n let pendingComma = '';\n const flushPendingComma = () => {\n output += pendingComma;\n pendingComma = '';\n };\n // Whitespace and blanked-out comments don't resolve a pending comma either way, so they're\n // buffered alongside it to keep the output in the original order.\n const emitFiller = (text: string) => {\n if (pendingComma) {\n pendingComma += text;\n } else {\n output += text;\n }\n };\n\n let i = 0;\n while (i < input.length) {\n const char = input[i];\n\n if (inString) {\n output += char;\n if (char === '\\\\') {\n // Copy the escaped character as-is (whatever it is) so an escaped\n // quote (`\\\"`) doesn't get mistaken for the string's end.\n i++;\n if (i < input.length) output += input[i];\n } else if (char === '\"') {\n inString = false;\n }\n i++;\n continue;\n }\n\n if (char === '\"') {\n flushPendingComma();\n inString = true;\n output += char;\n i++;\n continue;\n }\n\n if (char === '/' && input[i + 1] === '/') {\n const start = i;\n i += 2;\n // Stop at any line-ending character, not just \\n — a bare \\r (classic\n // Mac line endings, or a lone \\r before a later \\n) also ends the line,\n // otherwise everything up to the next \\n (or EOF) gets silently eaten.\n while (i < input.length && input[i] !== '\\n' && input[i] !== '\\r') i++;\n emitFiller(' '.repeat(i - start));\n continue;\n }\n\n if (char === '/' && input[i + 1] === '*') {\n const start = i;\n i += 2;\n while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i++;\n // An unterminated block comment runs to the end of the input.\n i = Math.min(i + 2, input.length);\n emitFiller(input.slice(start, i).replace(/[^\\r\\n]/g, ' '));\n continue;\n }\n\n if (char === ',') {\n flushPendingComma();\n pendingComma = char;\n i++;\n continue;\n }\n\n if (char === '}' || char === ']') {\n // Blank the comma — it was trailing — but keep what was buffered after it.\n output += pendingComma.replace(',', ' ');\n pendingComma = '';\n output += char;\n i++;\n continue;\n }\n\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n emitFiller(char);\n i++;\n continue;\n }\n\n flushPendingComma();\n output += char;\n i++;\n }\n\n flushPendingComma();\n return output;\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\nimport { readFileSync } from 'node:fs';\nimport { stripJsonComments } from '../_shared/_stripJsonComments';\n\n/**\n * Reads a file and parses its contents as JSON, returning `null` (or a\n * fallback) on any failure — a missing/unreadable file and invalid content\n * are both treated the same way.\n *\n * Also tolerates JSONC (line/block comments and trailing commas — the\n * dialect used by `tsconfig.json`, VS Code's `settings.json`, etc.): strict\n * `JSON.parse` is tried first, and only on failure is the content re-parsed\n * with comments/trailing commas stripped, so plain JSON pays no extra cost.\n *\n * Unlike `readFileSync` + `JSON.parse`, this never throws.\n *\n * @param filePath - Path to the JSON (or JSONC) file to read.\n * @returns The parsed value typed as `T`, or `null` on failure (pass a `fallback` to get it instead)\n * @example\n * safeReadJsonFile<{ name: string }>('./package.json') // => { name: 'helpers4', ... }\n * safeReadJsonFile('./missing.json') // => null\n * safeReadJsonFile('./missing.json', {}) // => {}\n * @example\n * // tsconfig.json-style JSONC (comments + trailing comma) also parses:\n * safeReadJsonFile('./tsconfig.json') // => { compilerOptions: { strict: true }, ... }\n * @since 3.0.6\n */\nexport function safeReadJsonFile<T>(filePath: string): T | null;\n/**\n * Overload taking a `fallback`: returns it instead of `null` on invalid input.\n *\n * @param filePath - Path to the JSON (or JSONC) file to read\n * @param fallback - Value returned on failure\n * @returns The parsed value typed as `T`, or `fallback` on failure\n * @since 3.0.6\n */\nexport function safeReadJsonFile<T>(filePath: string, fallback: T): T;\nexport function safeReadJsonFile<T>(filePath: string, fallback?: T): T | null {\n try {\n const content = readFileSync(filePath, 'utf-8');\n try {\n return JSON.parse(content) as T;\n } catch {\n // Not strict JSON — retry tolerating JSONC comments/trailing commas\n // before giving up.\n return JSON.parse(stripJsonComments(content)) as T;\n }\n } catch {\n // Distinguish \"no fallback provided\" (→ null) from \"fallback is undefined\"\n // (→ undefined as T) to keep runtime behaviour aligned with the overloads.\n return arguments.length < 2 ? null : (fallback as T);\n }\n}\n","/**\n * This file is part of helpers4.\n * Copyright (C) 2025 baxyz\n * SPDX-License-Identifier: LGPL-3.0-or-later\n */\n\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and\n * always removes it (recursively) afterward — including when `fn` throws.\n * @param prefix - Prepended to the generated directory name, to make it identifiable\n * @param fn - Receives the temp directory's absolute path; its (possibly synchronous) return\n * value is returned\n * @returns Whatever `fn` returns or resolves to\n * @example\n * await withTempDir('my-tool', async (dir) => {\n * await writeFile(`${dir}/output.txt`, 'data');\n * return readFile(`${dir}/output.txt`, 'utf-8');\n * });\n * // => 'data' (the directory no longer exists once this resolves)\n * @since 3.1.1\n */\nexport async function withTempDir<T>(prefix: string, fn: (dir: string) => T | Promise<T>): Promise<T> {\n const dir = await mkdtemp(join(tmpdir(), `${prefix}-`));\n try {\n return await fn(dir);\n } finally {\n await r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AO,MAAM,IAAI,OAAO,MAAM;GAExE,IAAI,KAAK,IAAI,IAAI,GAAG,MAAM,MAAM;GAChC,WAAW,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,QAAQ,YAAY,GAAG,CAAC;GACzD;EACF;EAEA,IAAI,SAAS,KAAK;GAChB,kBAAkB;GAClB,eAAe;GACf;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,KAAK;GAEhC,UAAU,aAAa,QAAQ,KAAK,GAAG;GACvC,eAAe;GACf,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;GACnE,WAAW,IAAI;GACf;GACA;EACF;EAEA,kBAAkB;EAClB,UAAU;EACV;CACF;CAEA,kBAAkB;CAClB,OAAO;AACT;;;;;;;;AC/EA,SAAgB,iBAAoB,UAAkB,UAAwB;CAC5E,IAAI;EACF,MAAM,UAAU,aAAa,UAAU,OAAO;EAC9C,IAAI;GACF,OAAO,KAAK,MAAM,OAAO;EAC3B,QAAQ;GAGN,OAAO,KAAK,MAAM,kBAAkB,OAAO,CAAC;EAC9C;CACF,QAAQ;EAGN,OAAO,UAAU,SAAS,IAAI,OAAQ;CACxC;AACF;;;;;;;;;;;;;;;;;;;;;;;AChCA,eAAsB,YAAe,QAAgB,IAAiD;CACpG,MAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,GAAG,GAAG,OAAO,EAAE,CAAC;CACtD,IAAI;EACF,OAAO,MAAM,GAAG,GAAG;CACrB,UAAU;EACR,MAAM,GAAG,KAAK;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAChD;AACF"}
|
package/llms.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @helpers4/node
|
|
2
2
|
|
|
3
3
|
> Tree-shakable TypeScript utility functions for the `node` domain.
|
|
4
|
-
> Package: `@helpers4/node` — Version: 3.1.
|
|
4
|
+
> Package: `@helpers4/node` — Version: 3.1.5
|
|
5
5
|
> License: LGPL-3.0-or-later
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
@@ -199,7 +199,7 @@ safeReadJsonFile<T>(filePath: string): T | null
|
|
|
199
199
|
|
|
200
200
|
- `filePath: string` — Path to the JSON (or JSONC) file to read.
|
|
201
201
|
|
|
202
|
-
**Returns:** `T | null` — The parsed value typed as `T`, or `
|
|
202
|
+
**Returns:** `T | null` — The parsed value typed as `T`, or `null` on failure (pass a `fallback` to get it instead)
|
|
203
203
|
|
|
204
204
|
```typescript
|
|
205
205
|
import { safeReadJsonFile } from '@helpers4/node';
|
|
@@ -209,10 +209,10 @@ safeReadJsonFile<T>(filePath: string, fallback: T): T
|
|
|
209
209
|
|
|
210
210
|
**Parameters:**
|
|
211
211
|
|
|
212
|
-
- `filePath: string` — Path to the JSON (or JSONC) file to read
|
|
213
|
-
- `fallback: T` — Value returned on failure
|
|
212
|
+
- `filePath: string` — Path to the JSON (or JSONC) file to read
|
|
213
|
+
- `fallback: T` — Value returned on failure
|
|
214
214
|
|
|
215
|
-
**Returns:** `T` — The parsed value typed as `T`, or `fallback` on failure
|
|
215
|
+
**Returns:** `T` — The parsed value typed as `T`, or `fallback` on failure
|
|
216
216
|
|
|
217
217
|
**Examples:**
|
|
218
218
|
|
package/meta/api.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"category": "node",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.5",
|
|
4
4
|
"functions": [
|
|
5
5
|
{
|
|
6
6
|
"name": "isBuffer",
|
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
],
|
|
129
129
|
"returns": {
|
|
130
130
|
"type": "T | null",
|
|
131
|
-
"description": "The parsed value typed as `T`, or `
|
|
131
|
+
"description": "The parsed value typed as `T`, or `null` on failure (pass a `fallback` to get it instead)"
|
|
132
132
|
},
|
|
133
133
|
"typeParameters": [
|
|
134
134
|
{
|
|
@@ -138,22 +138,22 @@
|
|
|
138
138
|
},
|
|
139
139
|
{
|
|
140
140
|
"signature": "safeReadJsonFile<T>(filePath: string, fallback: T): T",
|
|
141
|
-
"description": "
|
|
141
|
+
"description": "Overload taking a `fallback`: returns it instead of `null` on invalid input.",
|
|
142
142
|
"params": [
|
|
143
143
|
{
|
|
144
144
|
"name": "filePath",
|
|
145
145
|
"type": "string",
|
|
146
|
-
"description": "Path to the JSON (or JSONC) file to read
|
|
146
|
+
"description": "Path to the JSON (or JSONC) file to read"
|
|
147
147
|
},
|
|
148
148
|
{
|
|
149
149
|
"name": "fallback",
|
|
150
150
|
"type": "T",
|
|
151
|
-
"description": "Value returned on failure
|
|
151
|
+
"description": "Value returned on failure"
|
|
152
152
|
}
|
|
153
153
|
],
|
|
154
154
|
"returns": {
|
|
155
155
|
"type": "T",
|
|
156
|
-
"description": "The parsed value typed as `T`, or `fallback` on failure
|
|
156
|
+
"description": "The parsed value typed as `T`, or `fallback` on failure"
|
|
157
157
|
},
|
|
158
158
|
"typeParameters": [
|
|
159
159
|
{
|