All files / src/packlets/file-system real-fs.ts

0% Statements 0/22
0% Branches 0/7
0% Functions 0/6
0% Lines 0/21

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                                                                                             
import type { FileEntry, ProjectFileSystem } from "./types";
 
export function createFileSystemFromHandle(handle: FileSystemDirectoryHandle): ProjectFileSystem {
  async function getEntries(dir: FileSystemDirectoryHandle, prefix = ""): Promise<FileEntry[]> {
    const entries: FileEntry[] = [];
    for await (const entry of dir.values()) {
      const path = prefix ? `${prefix}/${entry.name}` : entry.name;
      if (entry.kind === "file") {
        const file = await entry.getFile();
        entries.push({
          name: entry.name,
          path,
          size: file.size,
          lastModified: new Date(file.lastModified),
        });
      } else if (entry.kind === "directory") {
        entries.push(...(await getEntries(entry, path)));
      }
    }
    return entries;
  }
 
  async function getFileHandle(path: string): Promise<FileSystemFileHandle> {
    const parts = path.split("/");
    let dir = handle;
    for (let i = 0; i < parts.length - 1; i++) {
      dir = await dir.getDirectoryHandle(parts[i]);
    }
    return dir.getFileHandle(parts[parts.length - 1]);
  }
 
  return {
    async listFiles() {
      return getEntries(handle);
    },
    async readFile(path: string) {
      const fileHandle = await getFileHandle(path);
      const file = await fileHandle.getFile();
      return file.arrayBuffer();
    },
    async readText(path: string) {
      const buffer = await this.readFile(path);
      return new TextDecoder().decode(buffer);
    },
  };
}