@helpers4/node 3.0.9 → 3.1.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 +1 -0
- package/lib/index.d.ts +23 -1
- package/lib/index.js +34 -1
- package/lib/index.js.map +1 -1
- package/llms.txt +37 -1
- package/meta/api.json +42 -1
- package/meta/examples.json +10 -0
- package/package.json +3 -2
package/README.md
CHANGED
package/lib/index.d.ts
CHANGED
|
@@ -102,4 +102,26 @@ declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer
|
|
|
102
102
|
declare function safeReadJsonFile<T>(filePath: string): T | null;
|
|
103
103
|
declare function safeReadJsonFile<T>(filePath: string, fallback: T): T;
|
|
104
104
|
|
|
105
|
-
|
|
105
|
+
/**
|
|
106
|
+
* This file is part of helpers4.
|
|
107
|
+
* Copyright (C) 2025 baxyz
|
|
108
|
+
* SPDX-License-Identifier: LGPL-3.0-or-later
|
|
109
|
+
*/
|
|
110
|
+
/**
|
|
111
|
+
* Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and
|
|
112
|
+
* always removes it (recursively) afterward — including when `fn` throws.
|
|
113
|
+
* @param prefix - Prepended to the generated directory name, to make it identifiable
|
|
114
|
+
* @param fn - Receives the temp directory's absolute path; its (possibly synchronous) return
|
|
115
|
+
* value is returned
|
|
116
|
+
* @returns Whatever `fn` returns or resolves to
|
|
117
|
+
* @example
|
|
118
|
+
* await withTempDir('my-tool', async (dir) => {
|
|
119
|
+
* await writeFile(`${dir}/output.txt`, 'data');
|
|
120
|
+
* return readFile(`${dir}/output.txt`, 'utf-8');
|
|
121
|
+
* });
|
|
122
|
+
* // => 'data' (the directory no longer exists once this resolves)
|
|
123
|
+
* @since 3.1.1
|
|
124
|
+
*/
|
|
125
|
+
declare function withTempDir<T>(prefix: string, fn: (dir: string) => T | Promise<T>): Promise<T>;
|
|
126
|
+
|
|
127
|
+
export { isBuffer, isNodeStream, isSharedArrayBuffer, safeReadJsonFile, withTempDir };
|
package/lib/index.js
CHANGED
|
@@ -188,6 +188,39 @@ function safeReadJsonFile(filePath, fallback) {
|
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
190
|
//#endregion
|
|
191
|
-
|
|
191
|
+
//#region helpers/node/withTempDir.ts
|
|
192
|
+
/**
|
|
193
|
+
* This file is part of helpers4.
|
|
194
|
+
* Copyright (C) 2025 baxyz
|
|
195
|
+
* SPDX-License-Identifier: LGPL-3.0-or-later
|
|
196
|
+
*/
|
|
197
|
+
/**
|
|
198
|
+
* Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and
|
|
199
|
+
* always removes it (recursively) afterward — including when `fn` throws.
|
|
200
|
+
* @param prefix - Prepended to the generated directory name, to make it identifiable
|
|
201
|
+
* @param fn - Receives the temp directory's absolute path; its (possibly synchronous) return
|
|
202
|
+
* value is returned
|
|
203
|
+
* @returns Whatever `fn` returns or resolves to
|
|
204
|
+
* @example
|
|
205
|
+
* await withTempDir('my-tool', async (dir) => {
|
|
206
|
+
* await writeFile(`${dir}/output.txt`, 'data');
|
|
207
|
+
* return readFile(`${dir}/output.txt`, 'utf-8');
|
|
208
|
+
* });
|
|
209
|
+
* // => 'data' (the directory no longer exists once this resolves)
|
|
210
|
+
* @since 3.1.1
|
|
211
|
+
*/
|
|
212
|
+
async function withTempDir(prefix, fn) {
|
|
213
|
+
const dir = await (0, import___vite_browser_external.mkdtemp)((0, import___vite_browser_external.join)((0, import___vite_browser_external.tmpdir)(), `${prefix}-`));
|
|
214
|
+
try {
|
|
215
|
+
return await fn(dir);
|
|
216
|
+
} finally {
|
|
217
|
+
await (0, import___vite_browser_external.rm)(dir, {
|
|
218
|
+
recursive: true,
|
|
219
|
+
force: true
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
//#endregion
|
|
224
|
+
export { isBuffer, isNodeStream, isSharedArrayBuffer, safeReadJsonFile, withTempDir };
|
|
192
225
|
|
|
193
226
|
//# sourceMappingURL=index.js.map
|
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","../../../__vite-browser-external","../../../helpers/node/_stripJsonComments.ts","../../../helpers/node/safeReadJsonFile.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","module.exports = {}","/**\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 safeReadJsonFile.ts to support JSONC (JSON with\n * line and block comments, plus trailing commas) — the dialect used by\n * tsconfig.json, VS Code's settings.json, etc. Not exported from the package\n * barrel — tests live in _stripJsonComments.test.ts.\n */\n\n/**\n * Strips line comments (starting with two slashes), block comments (slash-star\n * ... star-slash), and trailing commas (before `}` or `]`) from a JSONC\n * string, so the result can be safely passed to `JSON.parse`. String literals\n * are tracked so a comment-like or comma character occurring *inside* a JSON\n * string (e.g. a URL) is left untouched — this is a string-boundary-aware\n * pass, not a naive regex strip.\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 dropped; 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 if (pendingComma) {\n output += pendingComma;\n pendingComma = '';\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 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 continue;\n }\n\n if (char === '/' && input[i + 1] === '*') {\n i += 2;\n while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i++;\n i += 2;\n continue;\n }\n\n if (char === ',') {\n flushPendingComma();\n pendingComma = char;\n i++;\n continue;\n }\n\n if (char === '}' || char === ']') {\n pendingComma = ''; // drop — it was trailing\n output += char;\n i++;\n continue;\n }\n\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n // Whitespace doesn't resolve a pending comma either way — buffer it\n // alongside so it's dropped too if the comma turns out to be trailing.\n if (pendingComma) {\n pendingComma += char;\n } else {\n output += char;\n }\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 './_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"],"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;;;;;;;;;;;;;;;;;;;;;;;ACTA,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,sBAAsB,eAAe,iBAAiB;AACtE;;;;CCvBA,OAAO,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;ACoBlB,SAAgB,kBAAkB,OAAuB;CACvD,IAAI,SAAS;CACb,IAAI,WAAW;CAKf,IAAI,eAAe;CACnB,MAAM,0BAA0B;EAC9B,IAAI,cAAc;GAChB,UAAU;GACV,eAAe;EACjB;CACF;CAEA,IAAI,IAAI;CACR,OAAO,IAAI,MAAM,QAAQ;EACvB,MAAM,OAAO,MAAM;EAEnB,IAAI,UAAU;GACZ,UAAU;GACV,IAAI,SAAS,MAAM;IAGjB;IACA,IAAI,IAAI,MAAM,QAAQ,UAAU,MAAM;GACxC,OAAO,IAAI,SAAS,MAClB,WAAW;GAEb;GACA;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,kBAAkB;GAClB,WAAW;GACX,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,MAAM,IAAI,OAAO,KAAK;GACxC,KAAK;GAIL,OAAO,IAAI,MAAM,UAAU,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAM;GACnE;EACF;EAEA,IAAI,SAAS,OAAO,MAAM,IAAI,OAAO,KAAK;GACxC,KAAK;GACL,OAAO,IAAI,MAAM,UAAU,EAAE,MAAM,OAAO,OAAO,MAAM,IAAI,OAAO,MAAM;GACxE,KAAK;GACL;EACF;EAEA,IAAI,SAAS,KAAK;GAChB,kBAAkB;GAClB,eAAe;GACf;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,KAAK;GAChC,eAAe;GACf,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;GAGnE,IAAI,cACF,gBAAgB;QAEhB,UAAU;GAEZ;GACA;EACF;EAEA,kBAAkB;EAClB,UAAU;EACV;CACF;CAEA,kBAAkB;CAClB,OAAO;AACT;;;;;;;;AC3EA,SAAgB,iBAAoB,UAAkB,UAAwB;CAC5E,IAAI;EACF,MAAM,WAAA,GAAU,+BAAA,aAAA,CAAa,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"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../helpers/node/isBuffer.ts","../../../helpers/node/isNodeStream.ts","../../../helpers/node/isSharedArrayBuffer.ts","../../../__vite-browser-external","../../../helpers/node/_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","module.exports = {}","/**\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 safeReadJsonFile.ts to support JSONC (JSON with\n * line and block comments, plus trailing commas) — the dialect used by\n * tsconfig.json, VS Code's settings.json, etc. Not exported from the package\n * barrel — tests live in _stripJsonComments.test.ts.\n */\n\n/**\n * Strips line comments (starting with two slashes), block comments (slash-star\n * ... star-slash), and trailing commas (before `}` or `]`) from a JSONC\n * string, so the result can be safely passed to `JSON.parse`. String literals\n * are tracked so a comment-like or comma character occurring *inside* a JSON\n * string (e.g. a URL) is left untouched — this is a string-boundary-aware\n * pass, not a naive regex strip.\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 dropped; 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 if (pendingComma) {\n output += pendingComma;\n pendingComma = '';\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 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 continue;\n }\n\n if (char === '/' && input[i + 1] === '*') {\n i += 2;\n while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i++;\n i += 2;\n continue;\n }\n\n if (char === ',') {\n flushPendingComma();\n pendingComma = char;\n i++;\n continue;\n }\n\n if (char === '}' || char === ']') {\n pendingComma = ''; // drop — it was trailing\n output += char;\n i++;\n continue;\n }\n\n if (char === ' ' || char === '\\t' || char === '\\n' || char === '\\r') {\n // Whitespace doesn't resolve a pending comma either way — buffer it\n // alongside so it's dropped too if the comma turns out to be trailing.\n if (pendingComma) {\n pendingComma += char;\n } else {\n output += char;\n }\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 './_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;;;;;;;;;;;;;;;;;;;;;;;ACTA,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,sBAAsB,eAAe,iBAAiB;AACtE;;;;CCvBA,OAAO,UAAU,CAAC;;;;;;;;;;;;;;;;;;;;;ACoBlB,SAAgB,kBAAkB,OAAuB;CACvD,IAAI,SAAS;CACb,IAAI,WAAW;CAKf,IAAI,eAAe;CACnB,MAAM,0BAA0B;EAC9B,IAAI,cAAc;GAChB,UAAU;GACV,eAAe;EACjB;CACF;CAEA,IAAI,IAAI;CACR,OAAO,IAAI,MAAM,QAAQ;EACvB,MAAM,OAAO,MAAM;EAEnB,IAAI,UAAU;GACZ,UAAU;GACV,IAAI,SAAS,MAAM;IAGjB;IACA,IAAI,IAAI,MAAM,QAAQ,UAAU,MAAM;GACxC,OAAO,IAAI,SAAS,MAClB,WAAW;GAEb;GACA;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,kBAAkB;GAClB,WAAW;GACX,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,MAAM,IAAI,OAAO,KAAK;GACxC,KAAK;GAIL,OAAO,IAAI,MAAM,UAAU,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAM;GACnE;EACF;EAEA,IAAI,SAAS,OAAO,MAAM,IAAI,OAAO,KAAK;GACxC,KAAK;GACL,OAAO,IAAI,MAAM,UAAU,EAAE,MAAM,OAAO,OAAO,MAAM,IAAI,OAAO,MAAM;GACxE,KAAK;GACL;EACF;EAEA,IAAI,SAAS,KAAK;GAChB,kBAAkB;GAClB,eAAe;GACf;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,KAAK;GAChC,eAAe;GACf,UAAU;GACV;GACA;EACF;EAEA,IAAI,SAAS,OAAO,SAAS,OAAQ,SAAS,QAAQ,SAAS,MAAM;GAGnE,IAAI,cACF,gBAAgB;QAEhB,UAAU;GAEZ;GACA;EACF;EAEA,kBAAkB;EAClB,UAAU;EACV;CACF;CAEA,kBAAkB;CAClB,OAAO;AACT;;;;;;;;AC3EA,SAAgB,iBAAoB,UAAkB,UAAwB;CAC5E,IAAI;EACF,MAAM,WAAA,GAAU,+BAAA,aAAA,CAAa,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,OAAA,GAAM,+BAAA,QAAA,EAAA,GAAQ,+BAAA,KAAA,EAAA,GAAK,+BAAA,OAAA,CAAO,GAAG,GAAG,OAAO,EAAE,CAAC;CACtD,IAAI;EACF,OAAO,MAAM,GAAG,GAAG;CACrB,UAAU;EACR,OAAA,GAAM,+BAAA,GAAA,CAAG,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.
|
|
4
|
+
> Package: `@helpers4/node` — Version: 3.1.1
|
|
5
5
|
> License: LGPL-3.0-or-later
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
@@ -26,6 +26,7 @@ import { isBuffer, isNodeStream, isSharedArrayBuffer, ... } from '@helpers4/node
|
|
|
26
26
|
| `isNodeStream` | Checks if a value is a Node.js stream (has a `.pipe()` method). Uses duck-typing: any object with a |
|
|
27
27
|
| `isSharedArrayBuffer` | Checks if a value is a `SharedArrayBuffer` instance. `SharedArrayBuffer` enables shared memory betw |
|
|
28
28
|
| `safeReadJsonFile` | Reads a file and parses its contents as JSON, returning `null` (or a fallback) on any failure — a mi |
|
|
29
|
+
| `withTempDir` | Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and always remo |
|
|
29
30
|
|
|
30
31
|
---
|
|
31
32
|
|
|
@@ -256,3 +257,38 @@ safeReadJsonFile('./tsconfig.json')
|
|
|
256
257
|
```
|
|
257
258
|
|
|
258
259
|
---
|
|
260
|
+
|
|
261
|
+
### `withTempDir`
|
|
262
|
+
|
|
263
|
+
Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and
|
|
264
|
+
always removes it (recursively) afterward — including when `fn` throws.
|
|
265
|
+
|
|
266
|
+
```typescript
|
|
267
|
+
import { withTempDir } from '@helpers4/node';
|
|
268
|
+
|
|
269
|
+
withTempDir<T>(prefix: string, fn: function): Promise<T>
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
**Parameters:**
|
|
273
|
+
|
|
274
|
+
- `prefix: string` — Prepended to the generated directory name, to make it identifiable
|
|
275
|
+
- `fn: function` — Receives the temp directory's absolute path; its (possibly synchronous) return
|
|
276
|
+
value is returned
|
|
277
|
+
|
|
278
|
+
**Returns:** `Promise<T>` — Whatever `fn` returns or resolves to
|
|
279
|
+
|
|
280
|
+
**Examples:**
|
|
281
|
+
|
|
282
|
+
*Do work in a scratch directory that always gets cleaned up*
|
|
283
|
+
|
|
284
|
+
The directory is removed once fn resolves, even if fn throws.
|
|
285
|
+
|
|
286
|
+
```typescript
|
|
287
|
+
await withTempDir('my-tool', async (dir) => {
|
|
288
|
+
await writeFile(`${dir}/output.txt`, 'data');
|
|
289
|
+
return readFile(`${dir}/output.txt`, 'utf-8');
|
|
290
|
+
});
|
|
291
|
+
// => 'data' (the directory no longer exists once this resolves)
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
---
|
package/meta/api.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"category": "node",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"functions": [
|
|
5
5
|
{
|
|
6
6
|
"name": "isBuffer",
|
|
@@ -185,6 +185,47 @@
|
|
|
185
185
|
}
|
|
186
186
|
],
|
|
187
187
|
"sourceFile": "safeReadJsonFile.ts"
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
"name": "withTempDir",
|
|
191
|
+
"kind": "function",
|
|
192
|
+
"description": "Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and\nalways removes it (recursively) afterward — including when `fn` throws.",
|
|
193
|
+
"since": "3.1.1",
|
|
194
|
+
"signatures": [
|
|
195
|
+
{
|
|
196
|
+
"signature": "withTempDir<T>(prefix: string, fn: function): Promise<T>",
|
|
197
|
+
"description": "Creates a fresh temporary directory under the OS temp root, runs `fn` with its path, and\nalways removes it (recursively) afterward — including when `fn` throws.",
|
|
198
|
+
"params": [
|
|
199
|
+
{
|
|
200
|
+
"name": "prefix",
|
|
201
|
+
"type": "string",
|
|
202
|
+
"description": "Prepended to the generated directory name, to make it identifiable"
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
"name": "fn",
|
|
206
|
+
"type": "function",
|
|
207
|
+
"description": "Receives the temp directory's absolute path; its (possibly synchronous) return\nvalue is returned"
|
|
208
|
+
}
|
|
209
|
+
],
|
|
210
|
+
"returns": {
|
|
211
|
+
"type": "Promise<T>",
|
|
212
|
+
"description": "Whatever `fn` returns or resolves to"
|
|
213
|
+
},
|
|
214
|
+
"typeParameters": [
|
|
215
|
+
{
|
|
216
|
+
"name": "T"
|
|
217
|
+
}
|
|
218
|
+
]
|
|
219
|
+
}
|
|
220
|
+
],
|
|
221
|
+
"examples": [
|
|
222
|
+
{
|
|
223
|
+
"title": "Do work in a scratch directory that always gets cleaned up",
|
|
224
|
+
"description": "The directory is removed once fn resolves, even if fn throws.",
|
|
225
|
+
"code": "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)"
|
|
226
|
+
}
|
|
227
|
+
],
|
|
228
|
+
"sourceFile": "withTempDir.ts"
|
|
188
229
|
}
|
|
189
230
|
]
|
|
190
231
|
}
|
package/meta/examples.json
CHANGED
|
@@ -70,6 +70,16 @@
|
|
|
70
70
|
"code": "safeReadJsonFile('./tsconfig.json')\n// {\n// // enable strict type-checking\n// \"compilerOptions\": { \"strict\": true },\n// }\n// => { compilerOptions: { strict: true } }"
|
|
71
71
|
}
|
|
72
72
|
]
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"name": "withTempDir",
|
|
76
|
+
"examples": [
|
|
77
|
+
{
|
|
78
|
+
"title": "Do work in a scratch directory that always gets cleaned up",
|
|
79
|
+
"description": "The directory is removed once fn resolves, even if fn throws.",
|
|
80
|
+
"code": "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)"
|
|
81
|
+
}
|
|
82
|
+
]
|
|
73
83
|
}
|
|
74
84
|
]
|
|
75
85
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@helpers4/node",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"description": "A set of helpers in TS/JS, compatible with tree-shaking, for node.",
|
|
5
5
|
"author": "baxyz <craft@baxyz.dev>",
|
|
6
6
|
"license": "LGPL-3.0",
|
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
"isBuffer",
|
|
31
31
|
"isNodeStream",
|
|
32
32
|
"isSharedArrayBuffer",
|
|
33
|
-
"safeReadJsonFile"
|
|
33
|
+
"safeReadJsonFile",
|
|
34
|
+
"withTempDir"
|
|
34
35
|
],
|
|
35
36
|
"files": [
|
|
36
37
|
"lib/index.js",
|