@zenfs/core 2.5.5 → 2.5.7

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.
@@ -2,7 +2,7 @@
2
2
  import { withErrno } from 'kerium';
3
3
  import { err, warn } from 'kerium/log';
4
4
  import { decodeUTF8 } from 'utilium';
5
- import * as requests from 'utilium/requests.js';
5
+ import * as requests from 'utilium/requests';
6
6
  import { Index } from '../internal/file_index.js';
7
7
  import { IndexFS } from '../internal/index_fs.js';
8
8
  import { normalizePath } from '../utils.js';
@@ -1,6 +1,6 @@
1
1
  import type { ArrayOf } from 'memium';
2
2
  import type { UUID } from 'node:crypto';
3
- import { BufferView } from 'utilium/buffer.js';
3
+ import { BufferView } from 'utilium/buffer';
4
4
  import type { UsageInfo } from '../internal/filesystem.js';
5
5
  import { StoreFS } from './store/fs.js';
6
6
  import { SyncMapTransaction, type SyncMapStore } from './store/map.js';
@@ -89,9 +89,9 @@ import { withErrno } from 'kerium';
89
89
  import { alert, crit, debug, err, warn } from 'kerium/log';
90
90
  import { array, offsetof, sizeof } from 'memium';
91
91
  import { $from, field, struct, types as t } from 'memium/decorators';
92
- import { BufferView } from 'utilium/buffer.js';
93
- import { crc32c } from 'utilium/checksum.js';
94
- import { decodeUUID, encodeUUID } from 'utilium/string.js';
92
+ import { BufferView } from 'utilium/buffer';
93
+ import { crc32c } from 'utilium/checksum';
94
+ import { decodeUUID, encodeUUID } from 'utilium/string';
95
95
  import { _inode_version, Inode } from '../internal/inode.js';
96
96
  import { StoreFS } from './store/fs.js';
97
97
  import { SyncMapTransaction } from './store/map.js';
@@ -55,7 +55,7 @@ import { withErrno } from 'kerium';
55
55
  import { crit, debug, err, notice, warn } from 'kerium/log';
56
56
  import { sizeof } from 'memium';
57
57
  import { _throw, canary, encodeUTF8 } from 'utilium';
58
- import { extendBuffer } from 'utilium/buffer.js';
58
+ import { extendBuffer } from 'utilium/buffer';
59
59
  import { Index } from '../../internal/file_index.js';
60
60
  import { FileSystem } from '../../internal/filesystem.js';
61
61
  import { Inode, isDirectory, isFile, rootIno } from '../../internal/inode.js';
@@ -1,5 +1,5 @@
1
1
  import type { UUID } from 'node:crypto';
2
- import { Resource } from 'utilium/cache.js';
2
+ import { Resource } from 'utilium/cache';
3
3
  import type { UsageInfo } from '../../internal/filesystem.js';
4
4
  import '../../polyfills.js';
5
5
  import type { StoreFS } from './fs.js';
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: LGPL-3.0-or-later
2
2
  import { withErrno } from 'kerium';
3
3
  import { warn } from 'kerium/log';
4
- import { Resource } from 'utilium/cache.js';
4
+ import { Resource } from 'utilium/cache';
5
5
  import '../../polyfills.js';
6
6
  /**
7
7
  * A transaction for a store.
package/dist/index.js CHANGED
@@ -16,5 +16,4 @@ export { fs };
16
16
  export default fs;
17
17
  export * from './node/compat.js';
18
18
  export * as vfs from './vfs/index.js';
19
- import $pkg from '../package.json' with { type: 'json' };
20
- globalThis.__zenfs__ = Object.assign(Object.create(fs), { _version: $pkg.version });
19
+ globalThis.__zenfs__ = Object.create(fs);
@@ -1,4 +1,4 @@
1
- import { BufferView } from 'utilium/buffer.js';
1
+ import { BufferView } from 'utilium/buffer';
2
2
  import { Stats } from '../node/stats.js';
3
3
  import { type V_Context } from './contexts.js';
4
4
  /**
@@ -38,7 +38,7 @@ import { crit, warn } from 'kerium/log';
38
38
  import { sizeof } from 'memium';
39
39
  import { $from, field, struct, types as t } from 'memium/decorators';
40
40
  import { decodeUTF8, encodeUTF8, pick } from 'utilium';
41
- import { BufferView } from 'utilium/buffer.js';
41
+ import { BufferView } from 'utilium/buffer';
42
42
  import * as c from '../constants.js';
43
43
  import { Stats } from '../node/stats.js';
44
44
  import { contextOf } from './contexts.js';
@@ -2,3 +2,4 @@ export * from '../vfs/ioctl.js';
2
2
  export { chroot, mount, umount } from '../vfs/shared.js';
3
3
  export * as xattr from '../vfs/xattr.js';
4
4
  export * from './index.js';
5
+ export declare const _version: string;
@@ -4,3 +4,5 @@ export * from '../vfs/ioctl.js';
4
4
  export { chroot, mount, umount } from '../vfs/shared.js';
5
5
  export * as xattr from '../vfs/xattr.js';
6
6
  export * from './index.js';
7
+ import $pkg from '../../package.json' with { type: 'json' };
8
+ export const _version = $pkg.version;
@@ -2,6 +2,7 @@ import type { Abortable } from 'node:events';
2
2
  import type * as fs from 'node:fs';
3
3
  import type * as promises from 'node:fs/promises';
4
4
  import type { Stream } from 'node:stream';
5
+ import type { ByteReadableStream, Transform, Writer } from 'node:stream/iter';
5
6
  import type { ReadableStream as NodeReadableStream } from 'node:stream/web';
6
7
  import type { V_Context } from '../context.js';
7
8
  import type { StreamOptions } from '../internal/filesystem.js';
@@ -157,6 +158,20 @@ export declare class FileHandle implements promises.FileHandle {
157
158
  * @param options Options for the writeable stream.
158
159
  */
159
160
  createWriteStream(options?: promises.CreateWriteStreamOptions): WriteStream;
161
+ /**
162
+ * Return the file contents as an async iterable using the `node:stream/iter` pull model.
163
+ * Reads are performed in `chunkSize`-byte chunks (default 128 KiB).
164
+ * If transforms are provided, they are applied via `stream/iter`'s `pull()`.
165
+ * The handle is closed when iteration completes if `autoClose` is set.
166
+ * @experimental
167
+ */
168
+ pull(...transforms: Transform[]): ByteReadableStream;
169
+ pull(...args: [...transforms: Transform[], options: promises.PullOptions]): ByteReadableStream;
170
+ /**
171
+ * Return a `node:stream/iter` writer backed by this file handle.
172
+ * @experimental
173
+ */
174
+ writer(options?: promises.WriterOptions): Writer;
160
175
  }
161
176
  export declare function rename(this: V_Context, oldPath: fs.PathLike, newPath: fs.PathLike): Promise<void>;
162
177
  /**
@@ -69,6 +69,68 @@ import { createInterface } from './readline.js';
69
69
  import { BigIntStats, Stats } from './stats.js';
70
70
  import { ReadStream, WriteStream } from './streams.js';
71
71
  export * as constants from '../constants.js';
72
+ /** Coerce a `stream/iter` transform result into a flat array of `Uint8Array` chunks. */
73
+ async function* normalizeTransformResult(result) {
74
+ if (result == null)
75
+ return;
76
+ if (typeof result == 'string') {
77
+ yield encodeUTF8(result);
78
+ return;
79
+ }
80
+ if (result instanceof Uint8Array) {
81
+ yield result;
82
+ return;
83
+ }
84
+ if (ArrayBuffer.isView(result)) {
85
+ yield new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
86
+ return;
87
+ }
88
+ if (result instanceof ArrayBuffer || (typeof SharedArrayBuffer != 'undefined' && result instanceof SharedArrayBuffer)) {
89
+ yield new Uint8Array(result);
90
+ return;
91
+ }
92
+ if (typeof result[Symbol.asyncIterator] == 'function'
93
+ || typeof result[Symbol.iterator] == 'function') {
94
+ for await (const part of result)
95
+ yield* normalizeTransformResult(part);
96
+ return;
97
+ }
98
+ throw new TypeError('Invalid transform result');
99
+ }
100
+ /** Ponyfill for `node:stream/iter`'s `pull()` transform application */
101
+ async function* applyTransform(source, transform, signal) {
102
+ const options = { signal: signal };
103
+ if (typeof transform == 'function') {
104
+ for await (const chunks of source) {
105
+ signal?.throwIfAborted();
106
+ const out = [];
107
+ for await (const chunk of normalizeTransformResult(await transform(chunks, options)))
108
+ out.push(chunk);
109
+ if (out.length)
110
+ yield out;
111
+ }
112
+ const out = [];
113
+ for await (const chunk of normalizeTransformResult(await transform(null, options)))
114
+ out.push(chunk);
115
+ if (out.length)
116
+ yield out;
117
+ return;
118
+ }
119
+ // Stateful transform: feed it the source (with a trailing `null` to signal EOF).
120
+ async function* withFlush() {
121
+ for await (const chunks of source)
122
+ yield chunks;
123
+ yield null;
124
+ }
125
+ for await (const result of transform.transform(withFlush(), options)) {
126
+ signal?.throwIfAborted();
127
+ const out = [];
128
+ for await (const chunk of normalizeTransformResult(result))
129
+ out.push(chunk);
130
+ if (out.length)
131
+ yield out;
132
+ }
133
+ }
72
134
  export class FileHandle {
73
135
  context;
74
136
  fd;
@@ -332,6 +394,122 @@ export class FileHandle {
332
394
  throw UV('EROFS', 'createWriteStream', this.vfs.path);
333
395
  return new WriteStream(options, this);
334
396
  }
397
+ pull(...args) {
398
+ if (this.vfs.isClosed || this.vfs.flag & constants.O_WRONLY)
399
+ throw UV('EBADF', 'read', this.vfs.path);
400
+ // A trailing plain object that is neither a transform function nor a stateful transform is the options bag.
401
+ const last = args.at(-1);
402
+ const hasOptions = last != null && typeof last == 'object' && typeof last.transform != 'function';
403
+ const options = hasOptions ? args.pop() : {};
404
+ const transforms = args;
405
+ const { autoClose, start, limit, chunkSize = 131072, signal } = options;
406
+ const handle = this;
407
+ async function* source() {
408
+ let position = typeof start == 'number' ? start : 0;
409
+ let remaining = typeof limit == 'number' ? limit : Infinity;
410
+ try {
411
+ while (remaining > 0) {
412
+ signal?.throwIfAborted();
413
+ const size = Math.min(chunkSize, remaining);
414
+ const buffer = new Uint8Array(size);
415
+ const bytesRead = await handle.vfs.read(buffer, 0, size, position);
416
+ if (bytesRead <= 0)
417
+ break;
418
+ position += bytesRead;
419
+ remaining -= bytesRead;
420
+ yield [buffer.subarray(0, bytesRead)];
421
+ }
422
+ }
423
+ finally {
424
+ if (autoClose)
425
+ await handle.close();
426
+ }
427
+ }
428
+ let stream = source();
429
+ for (const transform of transforms)
430
+ stream = applyTransform(stream, transform, signal);
431
+ return stream;
432
+ }
433
+ /**
434
+ * Return a `node:stream/iter` writer backed by this file handle.
435
+ * @experimental
436
+ */
437
+ writer(options = {}) {
438
+ if (this.vfs.isClosed)
439
+ throw UV('EBADF', 'write', this.vfs.path);
440
+ if (this.vfs.inode.flags & InodeFlags.Immutable)
441
+ throw UV('EPERM', 'write', this.vfs.path);
442
+ if (this.vfs.fs.attributes.has('readonly'))
443
+ throw UV('EROFS', 'write', this.vfs.path);
444
+ const { autoClose, start, limit, chunkSize = 131072 } = options;
445
+ const handle = this;
446
+ let position = typeof start == 'number' ? start : handle.vfs.position;
447
+ let written = 0;
448
+ let failed = false;
449
+ // Tracks whether the writer has been ended or failed, so disposal and `autoClose` don't double-close.
450
+ let done = false;
451
+ async function finish() {
452
+ if (done)
453
+ return;
454
+ done = true;
455
+ if (autoClose)
456
+ await handle.close();
457
+ }
458
+ const toBuffer = (chunk) => typeof chunk == 'string' ? Buffer.from(chunk, 'utf8') : new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
459
+ async function writeChunk(chunk) {
460
+ const buffer = toBuffer(chunk);
461
+ if (typeof limit == 'number' && written + buffer.byteLength > limit) {
462
+ throw new RangeError(`Writer limit of ${limit} bytes exceeded`);
463
+ }
464
+ const bytesWritten = await handle.vfs.write(buffer, 0, buffer.byteLength, position);
465
+ position += bytesWritten;
466
+ written += bytesWritten;
467
+ handle._emitChange();
468
+ }
469
+ return {
470
+ get desiredSize() {
471
+ if (failed)
472
+ return null;
473
+ return typeof limit == 'number' ? Math.max(0, limit - written) : chunkSize;
474
+ },
475
+ async write(chunk, opts) {
476
+ opts?.signal?.throwIfAborted();
477
+ await writeChunk(chunk);
478
+ },
479
+ async writev(chunks, opts) {
480
+ opts?.signal?.throwIfAborted();
481
+ for (const chunk of chunks)
482
+ await writeChunk(chunk);
483
+ },
484
+ writeSync() {
485
+ // Synchronous writes are not supported by the async handle.
486
+ throw UV('ENOSYS', 'writeSync', handle.vfs.path);
487
+ },
488
+ writevSync() {
489
+ throw UV('ENOSYS', 'writevSync', handle.vfs.path);
490
+ },
491
+ async end() {
492
+ await finish();
493
+ return written;
494
+ },
495
+ endSync() {
496
+ throw UV('ENOSYS', 'endSync', handle.vfs.path);
497
+ },
498
+ fail() {
499
+ failed = true;
500
+ void finish();
501
+ },
502
+ [Symbol.dispose]() {
503
+ // `using w = fh.writer()` fails the writer unconditionally.
504
+ failed = true;
505
+ void finish();
506
+ },
507
+ async [Symbol.asyncDispose]() {
508
+ // `await using w = fh.writer()` only finishes if still open.
509
+ await finish();
510
+ },
511
+ };
512
+ }
335
513
  }
336
514
  export async function rename(oldPath, newPath) {
337
515
  await _async.rename.call(this, oldPath, newPath);
@@ -131,5 +131,5 @@ export declare function moveCursor(stream: NodeJS.WritableStream, dx: number, dy
131
131
  *
132
132
  * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop the `input` from emitting `'keypress'` events.
133
133
  */
134
- export declare function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface | readline.Interface): void;
134
+ export declare function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: readline.Interface): void;
135
135
  export {};
package/dist/vfs/acl.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BufferView } from 'utilium/buffer.js';
1
+ import { BufferView } from 'utilium/buffer';
2
2
  import { type V_Context } from '../internal/contexts.js';
3
3
  import { type InodeLike } from '../internal/inode.js';
4
4
  export declare const enum Type {
package/dist/vfs/acl.js CHANGED
@@ -43,7 +43,7 @@ import { withErrno } from 'kerium';
43
43
  import { err } from 'kerium/log';
44
44
  import { sizeof } from 'memium';
45
45
  import { $from, struct, types as t } from 'memium/decorators';
46
- import { BufferView } from 'utilium/buffer.js';
46
+ import { BufferView } from 'utilium/buffer';
47
47
  import { R_OK, S_IRWXG, S_IRWXO, S_IRWXU, W_OK, X_OK } from '../constants.js';
48
48
  import { contextOf } from '../internal/contexts.js';
49
49
  import { Attributes } from '../internal/inode.js';
@@ -1,4 +1,4 @@
1
- import { BufferView } from 'utilium/buffer.js';
1
+ import { BufferView } from 'utilium/buffer';
2
2
  import type { V_Context } from '../context.js';
3
3
  import { Inode } from '../internal/inode.js';
4
4
  declare const fsxattr_base: import("memium").StructConstructor<BufferView<any>>;
package/dist/vfs/ioctl.js CHANGED
@@ -43,7 +43,7 @@ import { Errno, Exception, setUVMessage, UV } from 'kerium';
43
43
  import { sizeof } from 'memium';
44
44
  import { $from, struct, types as t } from 'memium/decorators';
45
45
  import { _throw } from 'utilium';
46
- import { BufferView } from 'utilium/buffer.js';
46
+ import { BufferView } from 'utilium/buffer';
47
47
  import { Inode, InodeFlags } from '../internal/inode.js';
48
48
  import { normalizePath } from '../utils.js';
49
49
  import { resolveMount } from './shared.js';
@@ -150,13 +150,15 @@ export function emitChange(context, eventType, filename) {
150
150
  if ($)
151
151
  filename = join($.root ?? '/', filename);
152
152
  filename = normalizePath(filename);
153
- // Notify watchers, including ones on parent directories if they are watching recursively
154
- for (let path = filename; path != '/'; path = dirname(path)) {
153
+ // Notify watchers, including ones on parent directories if they are watching recursively.
154
+ for (let path = filename;; path = dirname(path)) {
155
155
  const watchersForPath = watchers.get(path);
156
- if (!watchersForPath)
157
- continue;
158
- for (const watcher of watchersForPath) {
159
- watcher.emit('change', eventType, relative.call(watcher._context, path, filename) || basename(filename));
156
+ if (watchersForPath) {
157
+ for (const watcher of watchersForPath) {
158
+ watcher.emit('change', eventType, relative.call(watcher._context, path, filename) || basename(filename));
159
+ }
160
160
  }
161
+ if (path === '/')
162
+ break;
161
163
  }
162
164
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenfs/core",
3
- "version": "2.5.5",
3
+ "version": "2.5.7",
4
4
  "description": "A filesystem, anywhere",
5
5
  "funding": {
6
6
  "type": "individual",
@@ -77,12 +77,13 @@
77
77
  "kerium": "^1.3.4",
78
78
  "memium": "^0.4.0",
79
79
  "readable-stream": "^4.5.2",
80
- "utilium": "^2.5.0"
80
+ "utilium": "^3.0.0"
81
81
  },
82
82
  "devDependencies": {
83
+ "@eslint/js": "^10.0.1",
83
84
  "@octokit/action": "^8.0.4",
84
- "c8": "^10.1.3",
85
- "eslint": "^9.15.0",
85
+ "c8": "^11.0.0",
86
+ "eslint": "^10.1.0",
86
87
  "globals": "^17.3.0",
87
88
  "prettier": "^3.2.5",
88
89
  "tsx": "^4.19.1",
package/scripts/test.js CHANGED
File without changes
@@ -0,0 +1,86 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import { promises } from '@zenfs/core';
3
+ import assert from 'node:assert/strict';
4
+ import type { FileHandle } from 'node:fs/promises';
5
+ import { suite, test } from 'node:test';
6
+
7
+ const content = 'hello';
8
+
9
+ /** Decode a `ByteReadableStream` (`AsyncIterable<Uint8Array[]>`) into a string. */
10
+ async function text(source: AsyncIterable<Uint8Array[]>): Promise<string> {
11
+ const decoder = new TextDecoder();
12
+ let out = '';
13
+ for await (const chunks of source) {
14
+ for (const chunk of chunks) out += decoder.decode(chunk, { stream: true });
15
+ }
16
+ return out + decoder.decode();
17
+ }
18
+
19
+ // The `asciiUpper` transform from the Node.js `node:stream/iter` docs.
20
+ const asciiUpper = (chunks: Uint8Array[] | null): Uint8Array[] | null => {
21
+ if (chunks === null) return null;
22
+ return chunks.map(c => {
23
+ for (let i = 0; i < c.length; i++) {
24
+ c[i] -= (c[i] >= 97 && c[i] <= 122 ? 1 : 0) * 32;
25
+ }
26
+ return c;
27
+ });
28
+ };
29
+
30
+ const handle: FileHandle = await promises.open('./pull.txt', 'w+');
31
+ await handle.writeFile(content);
32
+
33
+ suite('FileHandle.pull', () => {
34
+ test('reads file contents', async () => {
35
+ assert.equal(await text(handle.pull()), content);
36
+ });
37
+
38
+ test('reads a range with start and limit', async () => {
39
+ assert.equal(await text(handle.pull({ start: 1, limit: 3 })), content.slice(1, 4));
40
+ });
41
+
42
+ test('respects a small chunkSize', async () => {
43
+ const chunks: number[] = [];
44
+ for await (const part of handle.pull({ chunkSize: 2 })) {
45
+ for (const c of part) chunks.push(c.length);
46
+ }
47
+ assert.deepEqual(chunks, [2, 2, 1]);
48
+ });
49
+
50
+ test('applies the asciiUpper transform from the Node.js docs', async () => {
51
+ assert.equal(await text(handle.pull(asciiUpper)), content.toUpperCase()); // 'HELLO'
52
+ });
53
+
54
+ test('autoClose closes the handle', async () => {
55
+ const fh = await promises.open('./pull-autoclose.txt', 'w+');
56
+ await fh.writeFile(content);
57
+ assert.equal(await text(fh.pull({ autoClose: true })), content);
58
+ await assert.rejects(fh.readFile('utf8'));
59
+ });
60
+ });
61
+
62
+ suite('FileHandle.writer', () => {
63
+ test('writes data backed by the handle', async () => {
64
+ const fh = await promises.open('./writer.txt', 'w+');
65
+ const w = fh.writer();
66
+ await w.write('Hello!');
67
+ assert.equal(await w.end(), 6);
68
+ assert.equal(await fh.readFile('utf8'), 'Hello!');
69
+ await fh.close();
70
+ });
71
+
72
+ test('limit rejects oversized writes', async () => {
73
+ const fh = await promises.open('./writer-limit.txt', 'w+');
74
+ const w = fh.writer({ limit: 4 });
75
+ await assert.rejects(w.write('too long'), RangeError);
76
+ await fh.close();
77
+ });
78
+
79
+ test('autoClose closes the handle on end', async () => {
80
+ const fh = await promises.open('./writer-autoclose.txt', 'w+');
81
+ using w = fh.writer({ autoClose: true });
82
+ await w.write('bye');
83
+ await w.end();
84
+ await assert.rejects(fh.readFile('utf8'));
85
+ });
86
+ });
@@ -156,4 +156,23 @@ suite('Watch', () => {
156
156
  await watcher.return!();
157
157
  await promise;
158
158
  });
159
+
160
+ test('watch("/") receives events for files under root #293', async () => {
161
+ // Regression: emitChange previously exited its parent-walk before
162
+ // checking watchers.get('/'), so a watcher registered on '/' never fired.
163
+ const { promise, resolve } = Promise.withResolvers<[string, string]>();
164
+
165
+ using watcher = fs.watch('/', (eventType, filename) => {
166
+ resolve([eventType, filename]);
167
+ });
168
+
169
+ await fs.promises.writeFile('/watch-root-file.txt', 'x');
170
+
171
+ const [eventType, filename] = await Promise.race([
172
+ promise,
173
+ new Promise<[string, string]>((_, reject) => setTimeout(() => reject(new Error('watch("/") timed out')), 1000)),
174
+ ]);
175
+ assert.equal(eventType, 'change');
176
+ assert.equal(filename, 'watch-root-file.txt');
177
+ });
159
178
  });