Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544/// <reference lib="dom" />import type { FileSystemFileHandle as TypeFileSystemFileHandle, FileSystemFileHandleWithPath, FileSystemDirectoryHandle as IFileSystemDirectoryHandle} from "./types.ts";import { decode, encode } from "@bundle/utils/encode-decode";import { dirname, basename, resolve, posix } from "@bundle/utils/path";import { LOGGER_WARN, dispatchEvent } from "../configs/events.ts";
export const ROOT_DIR = "root";
export interface IFileSystem<T, Content = Uint8Array> { /** Direct Access to Virtual Filesystem Storage, if requred for some specific use case */ files: () => Promise<Map<string, T>>,
/** * Retrevies file from virtual file system storage in either string or uint8array buffer format * * @param path path of file in virtual file system storage * @returns file from file system storage as a Uint8Array buffer */ get: (path: string) => Promise<Content | null | undefined>,
/** * Determine if file from virtual file system storage exists * * @param path path of file in virtual file system storage * @returns file from file system storage as a Uint8Array buffer */ has: (path: string) => Promise<boolean>,
/** * Writes file to filesystem in either string or uint8array buffer format * * @param path path of file in virtual file system storage * @param content contents of file to store as a Uint8Array buffer, if no Uint8Array is given, a new folder is created */ set: (path: string, content?: Content | null, type?: "file" | "folder") => Promise<void>,
/** * Deletes files and directories at specific paths in the virtual file system storage * * @param path the relative or absolute path to resolve to * @returns promise indicating delete was successful */ delete: (path: string) => Promise<boolean | void>,
/** * Clears all files and directories at specific paths in the virtual file system storage * * @returns promise indicating clear was successful */ clear?: () => Promise<void>,}
export function isValid(file: unknown) { return file !== undefined && file !== null && !Number.isNaN(file);}
/** * Resolves path to a file in the virtual file system storage * * @param path the relative or absolute path to resolve to * @param importer an absolute path to use to determine relative file paths * @returns resolved final path */export function getResolvedPath(path: string, importer?: string) { let resolvedPath = path; if (importer && path.startsWith(".")) resolvedPath = resolve(dirname(importer), path);
return resolvedPath; // throw `File "${resolvedPath}" does not exist`;};
/** * Retrieves file from virtual file system storage in either string or uint8array buffer format * * If `getFile` returns these * - `undefined` means file doesn't exist * - `null` means content is an intentionally empty file * * @param fs virtual file system * @param path path of file in virtual file system storage * @param type format to retrieve file in, buffer and string are the 2 options available * @param importer an absolute path to use to determine a relative file path * @returns file from file system storage in either string format or as a Uint8Array buffer */export async function getFile<T, F extends IFileSystem<T, Content>, Content = Uint8Array>(fs: F, path: string, type: "string", importer?: string): Promise<string | null>;export async function getFile<T, F extends IFileSystem<T, Content>, Content = Uint8Array>(fs: F, path: string, type: "buffer", importer?: string): Promise<Awaited<Content> | null>;export async function getFile<T, F extends IFileSystem<T, Content>, Content = Uint8Array>(fs: F, path: string, type?: string, importer?: string): Promise<string | Awaited<Content> | null>export async function getFile<T, F extends IFileSystem<T, Content>, Content = Uint8Array>(fs: F, path: string, type: string = "buffer", importer?: string): Promise<string | Awaited<Content> | null> { const resolvedPath = getResolvedPath(path, importer); try { const file = await fs.get(resolvedPath); if (file === undefined) return null; if (!isValid(file)) return null;
if (type === "string" && ArrayBuffer.isView(file)) return decode(file as BufferSource); return file; // deno-lint-ignore no-empty } catch (_) { } return null;}
/** * Determines if entity from virtual file system storage in either string or uint8array exists, * this technically also includes directories * * @param fs virtual file system * @param path path of file in virtual file system storage * @param importer an absolute path to use to determine a relative file path * @returns file from file system storage in either string format or as a Uint8Array buffer */export async function hasFile<T, F extends IFileSystem<T, Content>, Content = Uint8Array>(fs: F, path: string, importer?: string): Promise<boolean> { const resolvedPath = getResolvedPath(path, importer); try { return await fs.has(resolvedPath); // deno-lint-ignore no-empty } catch (_) { } return false;}
/** * Similar to {@link hasFile} except it doesn't just check if the file is in the file system, * it also validates that the file contains valid content, avoiding directories. * * > Note: still treats empty files as existing (Uint8Array length can be 0). * > Note: has slightly higher overhead than `hasFile` * * @param fs virtual file system * @param path path of file in virtual file system storage * @param importer an absolute path to use to determine a relative file path * @returns boolean of if file from file system storage in either string format or as a Uint8Array buffer */export async function fileExists<T>(fs: IFileSystem<T>, path: string, importer?: string): Promise<boolean> { // This treats empty files as existing (Uint8Array length can be 0). // It also avoids counting directories as “existing modules”. const content = await getFile(fs, path, "buffer", importer); return content !== null;}
/** * Writes file to filesystem in either string or uint8array buffer format * * @param fs virtual file system * @param path path of file in virtual file system storage * @param content contents of file to store, you can store buffers and/or strings * @param importer an absolute path to use to determine a relative file path */export async function setFile<T, F extends IFileSystem<T>>(fs: F, path: string, content?: Uint8Array | string, importer?: string) { const resolvedPath = getResolvedPath(path, importer); try { if (!isValid(content)) { // return await fs.set(resolvedPath, null, 'folder'); return; }
return await fs.set(resolvedPath, content instanceof Uint8Array ? content : encode(content!), 'file'); } catch (e) { throw new Error(`Error occurred while writing to "${resolvedPath}": ${e}`, { cause: e }); }};
/** * Deletes file in the filesystem * * @param fs virtual file system * @param path path of file in virtual file system storage * @param importer an absolute path to use to determine a relative file path * @returns true if a file or folder existed and has been removed, or false if file/folder doesn't exist. */export async function deleteFile<T, F extends IFileSystem<T>>(fs: F, path: string, importer?: string) { const resolvedPath = getResolvedPath(path, importer); try { const exists = await fs.has(resolvedPath); if (!exists) return false;
return await fs.delete(resolvedPath); } catch (e) { throw new Error(`Error occurred while deleting "${resolvedPath}": ${e}`, { cause: e }); }};
/** Virtual Filesystem Storage */export function createDefaultFileSystem<T = Uint8Array, Content = Uint8Array>(FileSystem = new Map<string, Content | undefined | null>()) { const fs: IFileSystem<T, Content> = { files: () => Promise.resolve(FileSystem as unknown as Map<string, T>), get: (path: string) => Promise.resolve(FileSystem.get(resolve(path))), set(path: string, content?: Content | null) { const resolvedPath = resolve(path); const dir = dirname(resolvedPath);
const parentDirs = dir.split(posix.SEPARATOR).filter(x => x.length > 0); const len = parentDirs.length; FileSystem.set("/", null);
// Generate all the subdirectories in b/w let accPath = parentDirs[0] !== posix.SEPARATOR ? "/" : ""; for (let i = 0; i < len; i++) { accPath += parentDirs[i]; if (!FileSystem.has(accPath)) FileSystem.set(accPath, null); accPath += "/"; }
FileSystem.set(resolvedPath, content); return Promise.resolve(); }, has(path: string) { return Promise.resolve(FileSystem.has(path)); }, delete(path: string) { return Promise.resolve(FileSystem.delete(resolve(path))) }, clear() { return Promise.resolve(FileSystem.clear()); } };
return fs;}
/** * Write File Contents the Origin Private File System (OPFS) file handles */async function writeFile(fileHandle: FileSystemFileHandle | TypeFileSystemFileHandle, contents: Uint8Array | string) { // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createSyncAccessHandle if ("createSyncAccessHandle" in fileHandle && fileHandle.createSyncAccessHandle) { // Get sync access handle const accessHandle = await fileHandle.createSyncAccessHandle();
try { // Write the message to the begining of the file. const encodedMessage = contents instanceof Uint8Array ? contents : encode(contents); accessHandle.write(encodedMessage as BufferSource, { at: 0 });
// Persist changes to disk. accessHandle.flush(); } finally { // Always close FileSystemSyncAccessHandle if done. accessHandle.close(); } }
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createWritable // Create a FileSystemWritableFileStream to write to. const writable = await fileHandle.createWritable!();
// Write the contents of the file to the stream. await writable.write(contents as BufferSource);
// Close the file and write the contents to disk. await writable.close();}
/** * Read File Contents of Origin Private File System (OPFS) file handles as Uint8Arrays */async function readFile(fileHandle: FileSystemFileHandle | TypeFileSystemFileHandle) { // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createSyncAccessHandle if ("createSyncAccessHandle" in fileHandle && fileHandle.createSyncAccessHandle) { // Get sync access handle const accessHandle = await fileHandle.createSyncAccessHandle();
try { // Get size of the file. const fileSize = accessHandle.getSize();
// Read file content to a buffer. const buffer = new Uint8Array(new ArrayBuffer(fileSize)); accessHandle.read(buffer, { at: 0 });
return buffer; } finally { // Always close FileSystemSyncAccessHandle if done. accessHandle.close(); } }
// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/getFile // Get file contents const fileData = await fileHandle.getFile(); const arrbuf = await fileData.arrayBuffer();
// Return file contents as ArrayBuffer. return new Uint8Array(arrbuf);}
async function traverseFileSystem(root: FileSystemDirectoryHandle, path: string, files?: Map<string, FileSystemHandle | FileSystemFileHandle | FileSystemDirectoryHandle> | null, { create = true } = {}) { files ??= new Map<string, FileSystemHandle | FileSystemFileHandle | FileSystemDirectoryHandle>();
const resPath = path.replace(/[:,]/g, "_"); const resolvedPath = resolve(resPath); const dir = dirname(resolvedPath);
const parentDirs = dir.split(posix.SEPARATOR).filter(x => x.length > 0); const len = parentDirs.length;
// Generate all the subdirectories in between let accPath = parentDirs[0] !== posix.SEPARATOR ? "/" : ""; let parentDirHandle = root; files.set(posix.SEPARATOR, root);
for (let i = 0; i < len; i++) { const parentDir = parentDirs[i]; accPath += parentDir;
if (!files.has(accPath)) { parentDirHandle = await parentDirHandle.getDirectoryHandle(parentDir, { "create": create }); files.set(accPath, parentDirHandle); }
accPath += posix.SEPARATOR; }
return { resolvedPath, parentDirs, dir, files, parentDirHandle }}
async function getRelativePath(root: FileSystemDirectoryHandle, entry: FileSystemFileHandle) { // Check if handle exists inside our directory handle const relativePaths = await root.resolve(entry);
// relativePath is an array of names, giving the relative path if (Array.isArray(relativePaths) && relativePaths.length > 0) { return relativePaths.join(posix.SEPARATOR) }
return null}
export const enum ListFilter { File = "file", Directory = "directory", Both = "both",}
// Define the overloads with the correct return typesfunction listFilesRecursively( root: FileSystemDirectoryHandle, entry?: FileSystemHandle | null, opts?: { filter?: ListFilter.File, recursive?: boolean }): AsyncGenerator<FileSystemFileHandleWithPath>;function listFilesRecursively( root: FileSystemDirectoryHandle, entry?: FileSystemHandle | null, opts?: { filter: ListFilter.Both, recursive?: boolean }): AsyncGenerator<FileSystemFileHandleWithPath | FileSystemHandle>;function listFilesRecursively( root: FileSystemDirectoryHandle, entry?: FileSystemHandle | null, opts?: { filter: ListFilter.Directory, recursive?: boolean }): AsyncGenerator<FileSystemHandle>;function listFilesRecursively( root: FileSystemDirectoryHandle, entry?: FileSystemHandle | null, opts?: { filter?: ListFilter, recursive?: boolean }): AsyncGenerator<FileSystemFileHandleWithPath>;async function* listFilesRecursively( root: FileSystemDirectoryHandle, entry?: FileSystemHandle | null, opts: { filter?: ListFilter, recursive?: boolean } = {}): AsyncGenerator<FileSystemFileHandleWithPath> | AsyncGenerator<FileSystemHandle> | AsyncGenerator<FileSystemFileHandleWithPath | FileSystemHandle> { const { filter = ListFilter.File, recursive = true } = opts; const allowFiles = filter === ListFilter.File || filter === ListFilter.Both; const allowDirectories = filter === ListFilter.Directory || filter === ListFilter.Both; entry ??= root;
if (entry.kind === "file" && allowFiles) { const fileHandle = entry as FileSystemFileHandleWithPath; if (fileHandle) { const absolutePath = posix.SEPARATOR + await getRelativePath(root, entry as FileSystemFileHandle); if (absolutePath) fileHandle.absolutePath = absolutePath; yield fileHandle; } } else if (entry.kind === "directory") { for await (const handle of (entry as IFileSystemDirectoryHandle).values()) { if (allowDirectories) { yield handle; }
if (recursive) { yield* listFilesRecursively(root, handle, opts); } } }}
/** Origin Private File System - Virtual Filesystem Storage */export async function createOPFSFileSystem() { try { if (!( "navigator" in globalThis && "storage" in globalThis.navigator && typeof globalThis?.navigator?.storage?.getDirectory === 'function' )) { throw new Error("OPFS not supported by the current browser"); }
const INTERNAL_FS = createDefaultFileSystem<FileSystemFileHandleWithPath>(); const initRoot = await navigator.storage.getDirectory(); const root = await initRoot.getDirectoryHandle(ROOT_DIR, { "create": true });
const fs: IFileSystem<FileSystemFileHandleWithPath> = { async files() { const files = await INTERNAL_FS.files(); files.clear();
for await (const fileHandle of listFilesRecursively(root)) { const file = await fileHandle.getFile(); INTERNAL_FS.set( fileHandle.absolutePath, new Uint8Array(await file.arrayBuffer()) ); }
return files; }, async get(path: string) { const { parentDirHandle, resolvedPath } = await traverseFileSystem(root, path); const _basename = basename(resolvedPath); const isRootDir = _basename === posix.SEPARATOR || _basename.length < 1;
let fileHandle: FileSystemDirectoryHandle | FileSystemFileHandle = parentDirHandle; if (!isRootDir) { try { fileHandle = await parentDirHandle.getFileHandle(_basename); } catch (e) { } }
if (fileHandle.kind === "file") { return await readFile(fileHandle); } else { return null; } }, async has(path: string) { const { parentDirHandle, resolvedPath } = await traverseFileSystem(root, path); const _basename = basename(resolvedPath); const isRootDir = _basename === posix.SEPARATOR || _basename.length < 1;
if (!isRootDir) { try { await parentDirHandle.getFileHandle(_basename); return true; } catch (e) { }
try { await parentDirHandle.getDirectoryHandle(_basename); return true; } catch (e) { }
return false; }
return true; }, async set(path: string, content?: Uint8Array | string | null, type?: string) { const { parentDirHandle, resolvedPath } = await traverseFileSystem(root, path); const _basename = basename(resolvedPath); const isRootDir = _basename === posix.SEPARATOR || _basename.length < 1;
let fileHandle: FileSystemDirectoryHandle | FileSystemFileHandle = parentDirHandle; if (!isRootDir) { try { fileHandle = await parentDirHandle.getFileHandle(_basename, { "create": true }); } catch (e) { } }
if (content && fileHandle.kind === "file") await writeFile(fileHandle, content); }, async delete(path: string) { try { const { parentDirHandle, resolvedPath } = await traverseFileSystem(root, path, null, { create: false }); const _basename = basename(resolvedPath); const isRootDir = _basename === posix.SEPARATOR || _basename.length < 1;
let fileHandle: FileSystemDirectoryHandle | FileSystemFileHandle = parentDirHandle; if (!isRootDir) { try { fileHandle = await parentDirHandle.getFileHandle(_basename); } catch (e) { } }
if (!isRootDir) { await parentDirHandle.removeEntry(_basename, { recursive: true }); }
// If you reach the root folder delete all the child entries, // we need the root folder to always exist else if (fileHandle.kind === "directory" && isRootDir) { const list = listFilesRecursively(root, fileHandle, { filter: ListFilter.Both, recursive: false });
for await (const entry of list) { await parentDirHandle.removeEntry(entry.name, { recursive: true }); } } } catch (error) { console.error(`Error occurred while deleting "${path}":`, error); throw error; } return true; } }
return fs; } catch (e) { throw new Error(`Cannot create OPFS Virtual File System: ${e}`, { cause: e }) }}
/** * Selects the OPFS File System if possible, otherwise fallback to the default Map based Virtual File System * @param type Virtual File System to use */export async function useFileSystem(type?: "DEFAULT"): Promise<IFileSystem<Uint8Array>>;export async function useFileSystem(type?: "OPFS"): Promise<IFileSystem<FileSystemFileHandleWithPath>>;export async function useFileSystem(type: string = "DEFAULT") {
try { switch (type) { case "DEFAULT": return createDefaultFileSystem(); case "OPFS": return await createOPFSFileSystem(); } } catch (e) { dispatchEvent(LOGGER_WARN, e); }
return createDefaultFileSystem();}