All files / src/fsa CoreFileSystemWritableFileStream.ts

38.66% Statements 29/75
20.45% Branches 9/44
72.72% Functions 8/11
38.66% Lines 29/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170    4x   4x 4x         4x   5x 5x             5x     5x 5x 5x                       4x 4x 4x                     5x 5x 5x             1x     1x                                                       5x       5x       5x       5x 5x                                                         5x 5x 5x                     5x       5x 5x                                      
import type { IFileSystemWritableFileStream, FileSystemWritableFileStreamParams, Data } from './types';
import type { Superblock } from '../core/Superblock';
import { Buffer } from '../internal/buffer';
import { ERROR_CODE } from '../core/constants';
import { newNotAllowedError } from './util';
import { FLAGS, MODE } from '../node/constants';
 
/**
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream
 */
export class CoreFileSystemWritableFileStream extends WritableStream implements IFileSystemWritableFileStream {
  private _fd: number | undefined;
  private _position: number = 0;
  private _closed = false;
  private readonly _core: Superblock;
  private readonly _path: string;
 
  constructor(core: Superblock, path: string, keepExistingData: boolean = false) {
    let fd: number | undefined;
 
    super({
      start: controller => {
        // Open file for writing
        const flags = keepExistingData ? FLAGS['r+'] : FLAGS.w;
        try {
          fd = core.open(path, flags, MODE.FILE);
        } catch (error) {
          Iif (error && typeof error === 'object' && error.code === ERROR_CODE.EACCES) {
            throw newNotAllowedError();
          }
          throw error;
        }
      },
      write: async (chunk: Data | FileSystemWritableFileStreamParams) => {
        await this._write(chunk);
      },
      close: async () => {
        if (!this._closed && this._fd !== undefined) {
          core.close(this._fd);
          this._closed = true;
        }
      },
      abort: async () => {
        Iif (!this._closed && this._fd !== undefined) {
          core.close(this._fd);
          this._closed = true;
        }
      },
    });
 
    this._core = core;
    this._path = path;
    this._fd = fd;
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/seek
   */
  public async seek(position: number): Promise<void> {
    Iif (this._closed) {
      throw new DOMException('The stream is closed.', 'InvalidStateError');
    }
    this._position = position;
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/truncate
   */
  public async truncate(size: number): Promise<void> {
    Iif (this._closed) {
      throw new DOMException('The stream is closed.', 'InvalidStateError');
    }
    try {
      const link = this._core.getResolvedLinkOrThrow(this._path);
      const node = link.getNode();
      node.truncate(size);
    } catch (error) {
      Iif (error && typeof error === 'object' && error.code === ERROR_CODE.EACCES) {
        throw newNotAllowedError();
      }
      throw error;
    }
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write
   */
  public async write(chunk: Data): Promise<void>;
  public async write(params: FileSystemWritableFileStreamParams): Promise<void>;
  public async write(chunkOrParams: Data | FileSystemWritableFileStreamParams): Promise<void> {
    await this._write(chunkOrParams);
  }
 
  private async _write(chunkOrParams: Data | FileSystemWritableFileStreamParams): Promise<void> {
    Iif (this._closed) {
      throw new DOMException('The stream is closed.', 'InvalidStateError');
    }
 
    Iif (this._fd === undefined) {
      throw new DOMException('The stream is not ready.', 'InvalidStateError');
    }
 
    try {
      Iif (this._isParams(chunkOrParams)) {
        const params = chunkOrParams;
        switch (params.type) {
          case 'write': {
            Iif (params.data !== undefined) {
              const buffer = this._dataToBuffer(params.data);
              const position = params.position !== undefined ? params.position : this._position;
              const written = this._core.write(this._fd, buffer, 0, buffer.length, position);
              Iif (params.position === undefined) {
                this._position += written;
              }
            }
            break;
          }
          case 'seek': {
            Iif (params.position !== undefined) {
              this._position = params.position;
            }
            break;
          }
          case 'truncate': {
            Iif (params.size !== undefined) {
              await this.truncate(params.size);
            }
            break;
          }
        }
      } else {
        // Direct data write
        const buffer = this._dataToBuffer(chunkOrParams);
        const written = this._core.write(this._fd, buffer, 0, buffer.length, this._position);
        this._position += written;
      }
    } catch (error) {
      Iif (error && typeof error === 'object' && error.code === ERROR_CODE.EACCES) {
        throw newNotAllowedError();
      }
      throw error;
    }
  }
 
  private _isParams(chunk: Data | FileSystemWritableFileStreamParams): chunk is FileSystemWritableFileStreamParams {
    return !!(chunk && typeof chunk === 'object' && 'type' in chunk);
  }
 
  private _dataToBuffer(data: Data): Buffer {
    if (typeof data === 'string') {
      return Buffer.from(data, 'utf8');
    }
    Iif (data instanceof Buffer) {
      return data;
    }
    Iif (data instanceof ArrayBuffer) {
      return Buffer.from(data);
    }
    Iif (ArrayBuffer.isView(data)) {
      return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
    }
    Iif (data instanceof Blob) {
      // For Blob, we would need to read it asynchronously
      // This is a simplified implementation
      throw new Error('Blob data type not fully supported in this implementation');
    }
    throw new Error('Unsupported data type');
  }
}