]> git.ardis.lu - csvio/commitdiff
Support path of type `SharedArrayBuffer`
authorArdis Lu <ardisglu@gmail.com>
Wed, 2 Jul 2025 06:02:29 +0000 (23:02 -0700)
committerArdis Lu <ardisglu@gmail.com>
Wed, 2 Jul 2025 06:02:29 +0000 (23:02 -0700)
src/core.js
test/core.test.js

index cce5ca4fd19c7d1acb1d54be5d4b8767138e8633..c76004fbb88fb8eb8862072025fb1d6d3c9e590f 100644 (file)
@@ -8,7 +8,7 @@ import { ReadableStream, WritableStream, TransformStream } from 'node:stream/web
 /**
  * Parse and normalize a `PathLike` object into a string.
  * 
- * @param {PathLike|ArrayBufferView|ArrayBuffer} path A `string`, `Buffer`, or `URL` representing a path to a local file.
+ * @param {PathLike|ArrayBufferView|ArrayBufferLike} path A `string`, `Buffer`, or `URL` representing a path to a local file.
  * @returns {string} The normalized file path in string form.
  * @throws {TypeError} If `path` is not a `string`, `Buffer`, or `URL`, or it is a `URL` that is not using the `file` schema.
  */
@@ -19,6 +19,14 @@ export function parsePathLike(path) {
   else if (ArrayBuffer.isView(path) || path instanceof ArrayBuffer) {
     return normalize(new TextDecoder().decode(path));
   }
+  // Although Node.js supports directly passing SharedArrayBuffer to TextDecoder().decode(), this capability is not yet
+  // supported by all JS runtimes. For compatibility with other runtimes, the below code will copy the SAB into a non-shared
+  // buffer and then decode it. Reference: https://github.com/whatwg/encoding/pull/182
+  else if (path instanceof SharedArrayBuffer) {
+    const copy = new Uint8Array(path.byteLength);
+    copy.set(new Uint8Array(path));
+    return normalize(new TextDecoder().decode(copy));
+  }
   else if (path instanceof URL) {
     return fileURLToPath(path);
   }
index c709a793fd07d5e39ded2b16a7c49ce64e587493..1c4918eb504665494cdb8ff3122196615092b7f6 100644 (file)
@@ -55,6 +55,20 @@ suite('parsePathLike', { concurrency: true }, () => {
       }
     });
   }
+  test('parses SharedArrayBuffer relative path', { concurrency: true }, () => {
+    const str = './folder/example.txt';
+    const view = new Uint8Array(new SharedArrayBuffer(str.length));
+    new TextEncoder().encodeInto(str, view);
+    ok(view.buffer instanceof SharedArrayBuffer);
+    deepStrictEqual(parsePathLike(view.buffer), normalize(str));
+  })
+  test('parses SharedArrayBuffer absolute path', { concurrency: true }, () => {
+    const str = '/absolute/path/to/file.txt';
+    const view = new Uint8Array(new SharedArrayBuffer(str.length));
+    new TextEncoder().encodeInto(str, view);
+    ok(view.buffer instanceof SharedArrayBuffer);
+    deepStrictEqual(parsePathLike(view.buffer), normalize(str));
+  })
 });
 
 suite('createFileStream', { concurrency: true }, () => {
This page took 0.040091 seconds and 4 git commands to generate.