@fgv/ts-web-extras 5.1.0-26 → 5.1.0-28
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.
- package/dist/packlets/crypto-utils/browserCryptoProvider.js +82 -0
- package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +12 -0
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -1
- package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
- package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/httpTreeAccessors.js +2 -2
- package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/dist/packlets/helpers/fileTreeHelpers.js +1 -1
- package/dist/packlets/helpers/fileTreeHelpers.js.map +1 -1
- package/dist/ts-web-extras.d.ts +61 -3
- package/dist/tsdoc-metadata.json +1 -1
- package/eslint.config.js +32 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +42 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.js +82 -0
- package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +13 -0
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +13 -0
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/file-tree/directoryHandleStore.d.ts +2 -2
- package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -1
- package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +2 -2
- package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.js +2 -2
- package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.d.ts +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.d.ts.map +1 -1
- package/lib/packlets/helpers/fileTreeHelpers.js +6 -6
- package/lib/packlets/helpers/fileTreeHelpers.js.map +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileApiTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileApiTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;AAEH,0EAA0E;AAC1E,4CAAsD;AACtD,oDAA6C;AAC7C,sDAK2B;AAC3B,mFAA6G;AAC7G,2DAAyE;AACzE,2EAAiG;AAWjG;;;GAGG;AACH,SAAS,mBAAmB,CAAC,IAAU;IACrC,OAAQ,IAAuC,CAAC,kBAAkB,IAAI,IAAI,CAAC,IAAI,CAAC;AAClF,CAAC;AAkDD;;;;GAIG;AACH,MAAa,oBAAoB;IAC/B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAClC,SAAoC,EACpC,MAAyC;QAEzC,MAAM,eAAe,GAAG,MAAM,6DAA6B,CAAC,mBAAmB,CAAM,SAAS,EAAE,MAAM,CAAC,CAAC;QACxG,IAAI,eAAe,CAAC,SAAS,EAAE,EAAE,CAAC;YAChC,OAAO,IAAA,eAAI,EAAC,eAAe,CAAC,OAAO,CAAC,CAA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C;4BAC7B,OAAO,YAAY,CAAC;wBACtB,CAAC;wBACD,KAAK,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;oBACpC,CAAC;gBACH,CAAC;;;;;;;;;YAED,OAAO,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,yCAAyC;YACzC,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAA,eAAI,EAAC,+BAA+B,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,MAAc,EAAE,IAAY;QACxD,wEAAwE;QACxE,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/D,oFAAoF;QACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACpE,kEAAkE;QAClE,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC;IACpE,CAAC;CACF;AAtaD,oDAsaC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// File System Access API types are imported via the file-api-types module\nimport { Result, succeed, fail } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport {\n isFileHandle,\n isDirectoryHandle,\n FileSystemFileHandle,\n FileSystemDirectoryHandle\n} from '../file-api-types';\nimport { FileSystemAccessTreeAccessors, IFileSystemAccessTreeParams } from './fileSystemAccessTreeAccessors';\nimport { HttpTreeAccessors, IHttpTreeParams } from './httpTreeAccessors';\nimport { LocalStorageTreeAccessors, ILocalStorageTreeParams } from './localStorageTreeAccessors';\n\n/**\n * Interface for File objects that may have the webkitRelativePath property.\n * This property is added by browsers when using directory upload (webkitdirectory).\n * @internal\n */\ninterface IFileWithWebkitPath {\n readonly webkitRelativePath?: string;\n}\n\n/**\n * Helper function to safely get webkitRelativePath from a File object.\n * @internal\n */\nfunction getFileRelativePath(file: File): string {\n return (file as unknown as IFileWithWebkitPath).webkitRelativePath || file.name;\n}\n\n/**\n * Tree initializer for FileList objects (from File API).\n * @public\n */\nexport interface IFileListTreeInitializer {\n readonly fileList: FileList;\n}\n\n/**\n * Tree initializer for File System Access API file handles.\n * @public\n */\nexport interface IFileHandleTreeInitializer {\n readonly prefix?: string;\n readonly fileHandles: FileSystemFileHandle[];\n}\n\n/**\n * Tree initializer for File System Access API directory handles.\n * @public\n */\nexport interface IDirectoryHandleTreeInitializer {\n readonly prefix?: string;\n readonly dirHandles: FileSystemDirectoryHandle[];\n readonly nonRecursive?: boolean; // Default: false (recursive by default)\n}\n\n/**\n * Union type for all supported tree initializers.\n * @public\n */\nexport type TreeInitializer =\n | IFileListTreeInitializer\n | IFileHandleTreeInitializer\n | IDirectoryHandleTreeInitializer;\n\n/**\n * Interface for file metadata.\n * @public\n */\nexport interface IFileMetadata {\n path: string;\n name: string;\n size: number;\n type: string;\n lastModified: number;\n}\n\n/**\n * Helper class to create FileTree instances from various file sources.\n * Supports File API (FileList) and File System Access API handles.\n * @public\n */\nexport class FileApiTreeAccessors<TCT extends string = string> {\n /**\n * Create a persistent FileTree from a File System Access API directory handle.\n * Changes to files can be synced back to disk.\n *\n * @param dirHandle - FileSystemDirectoryHandle to load files from\n * @param params - Optional parameters including autoSync and permission settings\n * @returns Promise resolving to a FileTree with persistence capability\n *\n * @remarks\n * - Only works in browsers supporting File System Access API (Chrome, Edge, Opera)\n * - Requires 'readwrite' permission on the directory handle\n * - Falls back to read-only mode if permissions unavailable (unless requireWritePermission is true)\n *\n * @public\n */\n public static async createPersistent<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await FileSystemAccessTreeAccessors.fromDirectoryHandle<TCT>(dirHandle, params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from an HTTP storage service.\n *\n * @param params - Configuration including API base URL, namespace, and optional autoSync\n * @returns Promise resolving to a FileTree with persistence capability\n * @public\n */\n public static async createFromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await HttpTreeAccessors.fromHttp<TCT>(params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from a single File System Access API file handle.\n * The tree contains exactly one file at `/<filename>`.\n * Changes can be synced back to the original file via `syncToDisk()`.\n *\n * @param fileHandle - FileSystemFileHandle to load\n * @param params - Optional parameters including autoSync and permission settings\n * @returns Promise resolving to a FileTree with persistence capability\n * @public\n */\n public static async createPersistentFromFile<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await FileSystemAccessTreeAccessors.fromFileHandle<TCT>(fileHandle, params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from browser localStorage.\n * Changes to files can be synced back to localStorage.\n *\n * @param params - Configuration including path-to-key mappings and optional autoSync\n * @returns Result containing a FileTree with persistence capability\n *\n * @remarks\n * - Works in all browsers with localStorage support\n * - Maps directory paths to localStorage keys\n * - Each key stores multiple collections as JSON\n * - Files are automatically discovered from storage\n *\n * @example\n * ```typescript\n * const tree = FileApiTreeAccessors.createFromLocalStorage({\n * pathToKeyMap: {\n * '/data/ingredients': 'myapp:ingredients:v1',\n * '/data/fillings': 'myapp:fillings:v1'\n * },\n * mutable: true,\n * autoSync: false\n * });\n * ```\n *\n * @public\n */\n public static createFromLocalStorage<TCT extends string = string>(\n params: ILocalStorageTreeParams<TCT>\n ): Result<FileTree.FileTree<TCT>> {\n const accessorsResult = LocalStorageTreeAccessors.fromStorage<TCT>(params);\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create FileTree from various file sources using TreeInitializer array.\n * @param initializers - Array of TreeInitializer objects specifying file sources\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async create<TCT extends string = string>(\n initializers: TreeInitializer[],\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n try {\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const initializer of initializers) {\n const filesResult = await this._processInitializer<TCT>(initializer, params);\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n allFiles.push(...filesResult.value);\n }\n\n return FileTree.inMemory<TCT>(allFiles, params);\n /* c8 ignore next 5 - defense in depth */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to process initializers: ${message}`);\n }\n }\n\n /**\n * Create FileTree from FileList (e.g., from input[type=\"file\"]).\n * @param fileList - FileList from a file input element\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async fromFileList<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const path = this._normalizePath(params?.prefix || '', file.name);\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, file.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${file.name}: ${message}`);\n }\n }\n\n return FileTree.inMemory<TCT>(files, params);\n }\n\n /**\n * Create FileTree from directory upload with webkitRelativePath.\n * @param fileList - FileList from a directory upload (input with webkitdirectory)\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async fromDirectoryUpload<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const relativePath = getFileRelativePath(file);\n const path = this._normalizePath(params?.prefix || '', relativePath);\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, file.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${relativePath}: ${message}`);\n }\n }\n\n return FileTree.inMemory<TCT>(files, params);\n }\n\n /**\n * Get the File object for a specific path from the original FileList.\n * This is useful for accessing the original File API object for operations\n * like getting file metadata, MIME type, etc.\n * @param fileList - The original FileList\n * @param targetPath - The path to find\n * @returns Result containing the File object if found\n */\n public static getOriginalFile(fileList: FileList, targetPath: string): Result<File> {\n for (const file of Array.from(fileList)) {\n const filePath = getFileRelativePath(file);\n if (filePath === targetPath) {\n return succeed(file);\n }\n }\n return fail(`File not found: ${targetPath}`);\n }\n\n /**\n * Extract file metadata from a File.\n * @param file - The File to extract metadata from\n * @returns The {@link IFileMetadata | file metadata}\n */\n public static extractFileMetadata(file: File): IFileMetadata {\n return {\n path: getFileRelativePath(file),\n name: file.name,\n size: file.size,\n type: file.type,\n lastModified: file.lastModified\n };\n }\n\n /**\n * Process a single TreeInitializer and return the resulting files.\n * @param initializer - The TreeInitializer to process\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processInitializer<TCT extends string = string>(\n initializer: TreeInitializer,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n if ('fileList' in initializer) {\n return this._processFileList<TCT>(initializer.fileList, params);\n } else if ('fileHandles' in initializer) {\n return this._processFileHandles<TCT>(initializer.fileHandles, params);\n } else if ('dirHandles' in initializer) {\n return this._processDirectoryHandles<TCT>(\n initializer.dirHandles,\n initializer.prefix ?? params?.prefix,\n !initializer.nonRecursive,\n params\n );\n } else {\n return fail('Unknown initializer type');\n }\n }\n\n /**\n * Process a FileList and return IInMemoryFile array.\n * @param fileList - The FileList to process\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processFileList<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const metadata = this.extractFileMetadata(file);\n const relativePath = metadata.path;\n const path = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, metadata.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${relativePath}: ${message}`);\n }\n }\n\n return succeed(files);\n }\n\n /**\n * Process FileSystemFileHandles and return IInMemoryFile array.\n * @internal\n */\n private static async _processFileHandles<TCT extends string = string>(\n handles: FileSystemFileHandle[],\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const handle of handles) {\n try {\n const file = await handle.getFile();\n const contents = await file.text();\n const metadata = this.extractFileMetadata(file);\n /* c8 ignore next 1 - defense in depth */\n const path = this._normalizePath(params?.prefix ?? '', handle.name);\n const contentType = params?.inferContentType?.(path, metadata.type).orDefault();\n\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file handle ${handle.name}: ${message}`);\n }\n }\n\n return succeed(files);\n }\n\n /**\n * Process FileSystemDirectoryHandles and return IInMemoryFile array.\n * @param handles - The FileSystemDirectoryHandle[] to process\n * @param prefix - The prefix to use for the file paths\n * @param recursive - Whether to process the directory recursively\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processDirectoryHandles<TCT extends string = string>(\n handles: FileSystemDirectoryHandle[],\n prefix?: string,\n recursive: boolean = true,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n prefix = prefix ?? params?.prefix;\n\n for (const handle of handles) {\n const dirPrefix = this._normalizePath(prefix ?? '', handle.name);\n const filesResult = await this._processDirectoryHandle<TCT>(handle, dirPrefix, recursive, params);\n if (filesResult.isFailure()) {\n return filesResult;\n }\n allFiles.push(...filesResult.value);\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Process a single FileSystemDirectoryHandle recursively.\n * @param handle - The FileSystemDirectoryHandle to process\n * @param basePath - The base path to use for the file paths\n * @param recursive - Whether to process the directory recursively\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processDirectoryHandle<TCT extends string = string>(\n handle: FileSystemDirectoryHandle,\n basePath: string,\n recursive: boolean,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n try {\n for await (const entry of handle.values()) {\n if (isFileHandle(entry)) {\n const file = await entry.getFile();\n const contents = await file.text();\n const path = this._normalizePath(basePath, entry.name);\n const contentType = params?.inferContentType?.(path).orDefault();\n\n files.push({\n path,\n contents,\n contentType\n });\n } else if (isDirectoryHandle(entry) && recursive) {\n const subDirPath = this._normalizePath(basePath, entry.name);\n const subdirResult = await this._processDirectoryHandle<TCT>(entry, subDirPath, recursive, params);\n if (subdirResult.isFailure()) {\n return subdirResult;\n }\n files.push(...subdirResult.value);\n }\n }\n\n return succeed(files);\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to process directory ${handle.name}: ${message}`);\n }\n }\n\n private static _normalizePath(prefix: string, path: string): string {\n // Remove leading slash from prefix if it exists to avoid double slashes\n const cleanPrefix = prefix ? prefix.replace(/^\\/+/, '') : '';\n const combined = cleanPrefix ? `${cleanPrefix}/${path}` : path;\n // Normalize multiple slashes and ensure it starts with / for FileTree compatibility\n const normalized = combined.replace(/\\/+/g, '/').replace(/\\/$/, '');\n /* c8 ignore next 1 - tested but coverage intermittently missed */\n return normalized.startsWith('/') ? normalized : `/${normalized}`;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileApiTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileApiTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;AAEH,0EAA0E;AAC1E,4CAAsD;AACtD,oDAA6C;AAC7C,sDAK2B;AAC3B,mFAA6G;AAC7G,2DAAyE;AACzE,2EAAiG;AAWjG;;;GAGG;AACH,SAAS,mBAAmB,CAAC,IAAU;IACrC,OAAQ,IAAuC,CAAC,kBAAkB,IAAI,IAAI,CAAC,IAAI,CAAC;AAClF,CAAC;AAkDD;;;;GAIG;AACH,MAAa,oBAAoB;IAC/B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAClC,SAAoC,EACpC,MAAyC;QAEzC,MAAM,eAAe,GAAG,MAAM,6DAA6B,CAAC,mBAAmB,CAAM,SAAS,EAAE,MAAM,CAAC,CAAC;QACxG,IAAI,eAAe,CAAC,SAAS,EAAE,EAAE,CAAC;YAChC,OAAO,IAAA,eAAI,EAAC,e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AAC,SAAS,EAAE,EAAE,CAAC;4BAC7B,OAAO,YAAY,CAAC;wBACtB,CAAC;wBACD,KAAK,CAAC,IAAI,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;oBACpC,CAAC;gBACH,CAAC;;;;;;;;;YAED,OAAO,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,yCAAyC;YACzC,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAA,eAAI,EAAC,+BAA+B,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,MAAc,EAAE,IAAY;QACxD,wEAAwE;QACxE,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/D,oFAAoF;QACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACpE,kEAAkE;QAClE,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC;IACpE,CAAC;CACF;AAtaD,oDAsaC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// File System Access API types are imported via the file-api-types module\nimport { Result, succeed, fail } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport {\n isFileHandle,\n isDirectoryHandle,\n FileSystemFileHandle,\n FileSystemDirectoryHandle\n} from '../file-api-types';\nimport { FileSystemAccessTreeAccessors, IFileSystemAccessTreeParams } from './fileSystemAccessTreeAccessors';\nimport { HttpTreeAccessors, IHttpTreeParams } from './httpTreeAccessors';\nimport { LocalStorageTreeAccessors, ILocalStorageTreeParams } from './localStorageTreeAccessors';\n\n/**\n * Interface for File objects that may have the webkitRelativePath property.\n * This property is added by browsers when using directory upload (webkitdirectory).\n * @internal\n */\ninterface IFileWithWebkitPath {\n readonly webkitRelativePath?: string;\n}\n\n/**\n * Helper function to safely get webkitRelativePath from a File object.\n * @internal\n */\nfunction getFileRelativePath(file: File): string {\n return (file as unknown as IFileWithWebkitPath).webkitRelativePath || file.name;\n}\n\n/**\n * Tree initializer for FileList objects (from File API).\n * @public\n */\nexport interface IFileListTreeInitializer {\n readonly fileList: FileList;\n}\n\n/**\n * Tree initializer for File System Access API file handles.\n * @public\n */\nexport interface IFileHandleTreeInitializer {\n readonly prefix?: string;\n readonly fileHandles: FileSystemFileHandle[];\n}\n\n/**\n * Tree initializer for File System Access API directory handles.\n * @public\n */\nexport interface IDirectoryHandleTreeInitializer {\n readonly prefix?: string;\n readonly dirHandles: FileSystemDirectoryHandle[];\n readonly nonRecursive?: boolean; // Default: false (recursive by default)\n}\n\n/**\n * Union type for all supported tree initializers.\n * @public\n */\nexport type TreeInitializer =\n | IFileListTreeInitializer\n | IFileHandleTreeInitializer\n | IDirectoryHandleTreeInitializer;\n\n/**\n * Interface for file metadata.\n * @public\n */\nexport interface IFileMetadata {\n path: string;\n name: string;\n size: number;\n type: string;\n lastModified: number;\n}\n\n/**\n * Helper class to create FileTree instances from various file sources.\n * Supports File API (FileList) and File System Access API handles.\n * @public\n */\nexport class FileApiTreeAccessors {\n /**\n * Create a persistent FileTree from a File System Access API directory handle.\n * Changes to files can be synced back to disk.\n *\n * @param dirHandle - FileSystemDirectoryHandle to load files from\n * @param params - Optional parameters including autoSync and permission settings\n * @returns Promise resolving to a FileTree with persistence capability\n *\n * @remarks\n * - Only works in browsers supporting File System Access API (Chrome, Edge, Opera)\n * - Requires 'readwrite' permission on the directory handle\n * - Falls back to read-only mode if permissions unavailable (unless requireWritePermission is true)\n *\n * @public\n */\n public static async createPersistent<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await FileSystemAccessTreeAccessors.fromDirectoryHandle<TCT>(dirHandle, params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from an HTTP storage service.\n *\n * @param params - Configuration including API base URL, namespace, and optional autoSync\n * @returns Promise resolving to a FileTree with persistence capability\n * @public\n */\n public static async createFromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await HttpTreeAccessors.fromHttp<TCT>(params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from a single File System Access API file handle.\n * The tree contains exactly one file at `/<filename>`.\n * Changes can be synced back to the original file via `syncToDisk()`.\n *\n * @param fileHandle - FileSystemFileHandle to load\n * @param params - Optional parameters including autoSync and permission settings\n * @returns Promise resolving to a FileTree with persistence capability\n * @public\n */\n public static async createPersistentFromFile<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const accessorsResult = await FileSystemAccessTreeAccessors.fromFileHandle<TCT>(fileHandle, params);\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create a persistent FileTree from browser localStorage.\n * Changes to files can be synced back to localStorage.\n *\n * @param params - Configuration including path-to-key mappings and optional autoSync\n * @returns Result containing a FileTree with persistence capability\n *\n * @remarks\n * - Works in all browsers with localStorage support\n * - Maps directory paths to localStorage keys\n * - Each key stores multiple collections as JSON\n * - Files are automatically discovered from storage\n *\n * @example\n * ```typescript\n * const tree = FileApiTreeAccessors.createFromLocalStorage({\n * pathToKeyMap: {\n * '/data/ingredients': 'myapp:ingredients:v1',\n * '/data/fillings': 'myapp:fillings:v1'\n * },\n * mutable: true,\n * autoSync: false\n * });\n * ```\n *\n * @public\n */\n public static createFromLocalStorage<TCT extends string = string>(\n params: ILocalStorageTreeParams<TCT>\n ): Result<FileTree.FileTree<TCT>> {\n const accessorsResult = LocalStorageTreeAccessors.fromStorage<TCT>(params);\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (accessorsResult.isFailure()) {\n return fail(accessorsResult.message);\n }\n\n return FileTree.FileTree.create<TCT>(accessorsResult.value);\n }\n\n /**\n * Create FileTree from various file sources using TreeInitializer array.\n * @param initializers - Array of TreeInitializer objects specifying file sources\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async create<TCT extends string = string>(\n initializers: TreeInitializer[],\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n try {\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const initializer of initializers) {\n const filesResult = await this._processInitializer<TCT>(initializer, params);\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n allFiles.push(...filesResult.value);\n }\n\n return FileTree.inMemory<TCT>(allFiles, params);\n /* c8 ignore next 5 - defense in depth */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to process initializers: ${message}`);\n }\n }\n\n /**\n * Create FileTree from FileList (e.g., from input[type=\"file\"]).\n * @param fileList - FileList from a file input element\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async fromFileList<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const path = this._normalizePath(params?.prefix || '', file.name);\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, file.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${file.name}: ${message}`);\n }\n }\n\n return FileTree.inMemory<TCT>(files, params);\n }\n\n /**\n * Create FileTree from directory upload with webkitRelativePath.\n * @param fileList - FileList from a directory upload (input with webkitdirectory)\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to a FileTree with all content pre-loaded\n */\n public static async fromDirectoryUpload<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.FileTree<TCT>>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const relativePath = getFileRelativePath(file);\n const path = this._normalizePath(params?.prefix || '', relativePath);\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, file.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${relativePath}: ${message}`);\n }\n }\n\n return FileTree.inMemory<TCT>(files, params);\n }\n\n /**\n * Get the File object for a specific path from the original FileList.\n * This is useful for accessing the original File API object for operations\n * like getting file metadata, MIME type, etc.\n * @param fileList - The original FileList\n * @param targetPath - The path to find\n * @returns Result containing the File object if found\n */\n public static getOriginalFile(fileList: FileList, targetPath: string): Result<File> {\n for (const file of Array.from(fileList)) {\n const filePath = getFileRelativePath(file);\n if (filePath === targetPath) {\n return succeed(file);\n }\n }\n return fail(`File not found: ${targetPath}`);\n }\n\n /**\n * Extract file metadata from a File.\n * @param file - The File to extract metadata from\n * @returns The {@link IFileMetadata | file metadata}\n */\n public static extractFileMetadata(file: File): IFileMetadata {\n return {\n path: getFileRelativePath(file),\n name: file.name,\n size: file.size,\n type: file.type,\n lastModified: file.lastModified\n };\n }\n\n /**\n * Process a single TreeInitializer and return the resulting files.\n * @param initializer - The TreeInitializer to process\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processInitializer<TCT extends string = string>(\n initializer: TreeInitializer,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n if ('fileList' in initializer) {\n return this._processFileList<TCT>(initializer.fileList, params);\n } else if ('fileHandles' in initializer) {\n return this._processFileHandles<TCT>(initializer.fileHandles, params);\n } else if ('dirHandles' in initializer) {\n return this._processDirectoryHandles<TCT>(\n initializer.dirHandles,\n initializer.prefix ?? params?.prefix,\n !initializer.nonRecursive,\n params\n );\n } else {\n return fail('Unknown initializer type');\n }\n }\n\n /**\n * Process a FileList and return IInMemoryFile array.\n * @param fileList - The FileList to process\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processFileList<TCT extends string = string>(\n fileList: FileList,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (let i = 0; i < fileList.length; i++) {\n const file = fileList[i];\n const metadata = this.extractFileMetadata(file);\n const relativePath = metadata.path;\n const path = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;\n\n try {\n const contents = await file.text();\n const contentType = params?.inferContentType?.(path, metadata.type).orDefault();\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file ${relativePath}: ${message}`);\n }\n }\n\n return succeed(files);\n }\n\n /**\n * Process FileSystemFileHandles and return IInMemoryFile array.\n * @internal\n */\n private static async _processFileHandles<TCT extends string = string>(\n handles: FileSystemFileHandle[],\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const handle of handles) {\n try {\n const file = await handle.getFile();\n const contents = await file.text();\n const metadata = this.extractFileMetadata(file);\n /* c8 ignore next 1 - defense in depth */\n const path = this._normalizePath(params?.prefix ?? '', handle.name);\n const contentType = params?.inferContentType?.(path, metadata.type).orDefault();\n\n files.push({\n path,\n contents,\n contentType\n });\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to read file handle ${handle.name}: ${message}`);\n }\n }\n\n return succeed(files);\n }\n\n /**\n * Process FileSystemDirectoryHandles and return IInMemoryFile array.\n * @param handles - The FileSystemDirectoryHandle[] to process\n * @param prefix - The prefix to use for the file paths\n * @param recursive - Whether to process the directory recursively\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processDirectoryHandles<TCT extends string = string>(\n handles: FileSystemDirectoryHandle[],\n prefix?: string,\n recursive: boolean = true,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n prefix = prefix ?? params?.prefix;\n\n for (const handle of handles) {\n const dirPrefix = this._normalizePath(prefix ?? '', handle.name);\n const filesResult = await this._processDirectoryHandle<TCT>(handle, dirPrefix, recursive, params);\n if (filesResult.isFailure()) {\n return filesResult;\n }\n allFiles.push(...filesResult.value);\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Process a single FileSystemDirectoryHandle recursively.\n * @param handle - The FileSystemDirectoryHandle to process\n * @param basePath - The base path to use for the file paths\n * @param recursive - Whether to process the directory recursively\n * @param params - Optional `IFileTreeInitParams` for the file tree.\n * @returns Promise resolving to an array of `IInMemoryFile` objects\n * @internal\n */\n private static async _processDirectoryHandle<TCT extends string = string>(\n handle: FileSystemDirectoryHandle,\n basePath: string,\n recursive: boolean,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n try {\n for await (const entry of handle.values()) {\n if (isFileHandle(entry)) {\n const file = await entry.getFile();\n const contents = await file.text();\n const path = this._normalizePath(basePath, entry.name);\n const contentType = params?.inferContentType?.(path).orDefault();\n\n files.push({\n path,\n contents,\n contentType\n });\n } else if (isDirectoryHandle(entry) && recursive) {\n const subDirPath = this._normalizePath(basePath, entry.name);\n const subdirResult = await this._processDirectoryHandle<TCT>(entry, subDirPath, recursive, params);\n if (subdirResult.isFailure()) {\n return subdirResult;\n }\n files.push(...subdirResult.value);\n }\n }\n\n return succeed(files);\n } catch (error) {\n /* c8 ignore next 1 - defense in depth */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to process directory ${handle.name}: ${message}`);\n }\n }\n\n private static _normalizePath(prefix: string, path: string): string {\n // Remove leading slash from prefix if it exists to avoid double slashes\n const cleanPrefix = prefix ? prefix.replace(/^\\/+/, '') : '';\n const combined = cleanPrefix ? `${cleanPrefix}/${path}` : path;\n // Normalize multiple slashes and ensure it starts with / for FileTree compatibility\n const normalized = combined.replace(/\\/+/g, '/').replace(/\\/$/, '');\n /* c8 ignore next 1 - tested but coverage intermittently missed */\n return normalized.startsWith('/') ? normalized : `/${normalized}`;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemAccessTreeAccessors.d.ts","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":"AAsBA,OAAO,
|
|
1
|
+
{"version":3,"file":"fileSystemAccessTreeAccessors.d.ts","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAiB,cAAc,EAAqB,OAAO,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,yBAAyB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEpF;;;GAGG;AACH,MAAM,WAAW,2BAA2B,CAAC,GAAG,SAAS,MAAM,GAAG,MAAM,CACtE,SAAQ,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC;IACzC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;;;OA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,EAC5D,UAAU,EAAE,oBAAoB,EAChC,MAAM,CAAC,EAAE,2BAA2B,CAAC,GAAG,CAAC,GACxC,OAAO,CAAC,MAAM,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC,CAAC;IAqCtD;;;;;OAKG;mBACkB,qBAAqB;IAoB1C;;;;;OAKG;mBACkB,yBAAyB;IAmB9C;;;;;;;OAOG;mBACkB,cAAc;IAmCnC;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;IAKxB;;OAEG;IACU,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IA+BhD;;OAEG;IACI,OAAO,IAAI,OAAO;IAIzB;;OAEG;IACI,aAAa,IAAI,MAAM,EAAE;IAIhC;;OAEG;IACI,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC;IAiBhD;;OAEG;IACI,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAiBvE;;OAEG;IACI,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,UAAU,CAAC;IAWhF;;;;;OAKG;YACW,SAAS;IAuBvB;;;;;OAKG;YACW,mBAAmB;IAyBjC;;;;;OAKG;YACW,mBAAmB;CA6BlC"}
|
|
@@ -293,7 +293,7 @@ class FileSystemAccessTreeAccessors extends ts_json_base_1.FileTree.InMemoryTree
|
|
|
293
293
|
if (this._hasWritePermission) {
|
|
294
294
|
this._pendingDeletions.add(path);
|
|
295
295
|
if (this._autoSync) {
|
|
296
|
-
|
|
296
|
+
this._runAutoSyncTask(path, 'delete', () => this._deleteFileFromDisk(path)).catch(() => undefined);
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
299
|
}
|
|
@@ -310,7 +310,7 @@ class FileSystemAccessTreeAccessors extends ts_json_base_1.FileTree.InMemoryTree
|
|
|
310
310
|
// Auto-sync if enabled
|
|
311
311
|
if (this._autoSync) {
|
|
312
312
|
// Fire and log-on-failure; don't block the save path.
|
|
313
|
-
|
|
313
|
+
this._runAutoSyncTask(path, 'save', () => this._syncFile(path)).catch(() => undefined);
|
|
314
314
|
}
|
|
315
315
|
}
|
|
316
316
|
return result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemAccessTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;AAEH,4CAQuB;AACvB,oDAA6C;AAmC7C;;;;GAIG;AACH,MAAa,6BACX,SAAQ,uBAAQ,CAAC,qBAA0B;IAW3C;;;;;;;OAOG;IACH,YACE,KAAoC,EACpC,OAAkC,EAClC,OAA0C,EAC1C,MAAoD,EACpD,kBAA2B;;QAE3B,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAC;QACnC,0FAA0F;QAC1F,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,mCAAI,KAAK,CAAC;QAC3C,IAAI,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;QAC9C,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,mCAAI,IAAI,kBAAO,CAAC,WAAW,EAAW,CAAC;IACtE,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,IAAY,EACZ,SAA4B,EAC5B,MAAmC;QAEnC,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,MAA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AI,EAAC,yBAAyB,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF;AA/bD,sEA+bC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n Result,\n succeed,\n fail,\n captureResult,\n DetailedResult,\n succeedWithDetail,\n Logging\n} from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { FileSystemDirectoryHandle, FileSystemFileHandle } from '../file-api-types';\n\n/**\n * Options for creating persistent file trees.\n * @public\n */\nexport interface IFileSystemAccessTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Automatically sync changes to disk immediately after each save.\n * If false, changes are batched and written on explicit syncToDisk() call.\n * @defaultValue false\n */\n autoSync?: boolean;\n\n /**\n * Require write permission on the directory handle.\n * If true, fails if write permission cannot be obtained.\n * If false, falls back to read-only mode.\n * @defaultValue true\n */\n requireWritePermission?: boolean;\n\n /**\n * Override the path at which the file is stored in the tree (for fromFileHandle).\n * Must be an absolute path (e.g., '/data/confections/common.yaml').\n * If omitted, defaults to `/<filename>`.\n */\n filePath?: string;\n\n /** Optional logger for auto-sync and persistence failures. */\n logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * Implementation of `FileTree.IPersistentFileTreeAccessors` that uses the File System Access API\n * to provide persistent file editing in browsers.\n * @public\n */\nexport class FileSystemAccessTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _handles: Map<string, FileSystemFileHandle>;\n private readonly _rootDir: FileSystemDirectoryHandle;\n private readonly _dirtyFiles: Set<string>;\n private readonly _pendingDeletions: Set<string>;\n private readonly _autoSync: boolean;\n private readonly _hasWritePermission: boolean;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /**\n * Protected constructor for FileSystemAccessTreeAccessors.\n * @param files - An array of in-memory files to include in the tree.\n * @param rootDir - The root directory handle.\n * @param handles - Map of file paths to their handles.\n * @param params - Optional params for the tree.\n * @param hasWritePermission - Whether write permission was granted.\n */\n protected constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n rootDir: FileSystemDirectoryHandle,\n handles: Map<string, FileSystemFileHandle>,\n params: IFileSystemAccessTreeParams<TCT> | undefined,\n hasWritePermission: boolean\n ) {\n super(files, params);\n this._rootDir = rootDir;\n this._handles = handles;\n this._dirtyFiles = new Set();\n this._pendingDeletions = new Set();\n /* c8 ignore next 3 - intermittent branch coverage: ?? fallback branches in constructor */\n this._autoSync = params?.autoSync ?? false;\n this._hasWritePermission = hasWritePermission;\n this._logger = params?.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(\n path: string,\n operation: 'save' | 'delete',\n action: () => Promise<Result<void>>\n ): Promise<void> {\n try {\n const result = await action();\n if (result.isFailure()) {\n this._logger.error(`Auto-${operation} failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-${operation} threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a directory handle.\n * @param dirHandle - The FileSystemDirectoryHandle to load files from.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromDirectoryHandle<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n // Check write permission\n const hasWritePermission = await this._checkWritePermission(dirHandle);\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n // Load all files from the directory (always use '/' as base, prefix is handled by parent)\n const { files, handles } = await this._loadDirectory<TCT>(dirHandle, '/', params);\n\n // Enable tree mutability when write permission is granted and caller didn't explicitly set mutable\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n mutable: params?.mutable ?? (hasWritePermission ? true : false)\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dirHandle, handles, effectiveParams, hasWritePermission)\n );\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a single file handle.\n *\n * The resulting tree contains exactly one file at `/<filename>`.\n * `syncToDisk()` writes changes back to the original file via the File System Access API.\n * New file creation is not supported on this tree (no parent directory handle).\n *\n * @param fileHandle - The FileSystemFileHandle to load.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromFileHandle<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n const hasWritePermission = await this._checkFileWritePermission(fileHandle);\n\n /* c8 ignore next 1 - intermittent branch coverage: ?? true fallback */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = params?.filePath ?? `/${fileHandle.name}`;\n /* c8 ignore next 3 - intermittent branch coverage: ternary for inferContentType */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n const files: FileTree.IInMemoryFile<TCT>[] = [{ path, contents, contentType }];\n const handles = new Map<string, FileSystemFileHandle>([[path, fileHandle]]);\n\n const dummyRoot = {} as FileSystemDirectoryHandle;\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n /* c8 ignore next 1 - intermittent branch coverage: ?? false fallback */\n mutable: hasWritePermission ? true : params?.mutable ?? false\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dummyRoot, handles, effectiveParams, hasWritePermission)\n );\n } catch (error) {\n /* c8 ignore next 1 - intermittent branch coverage: error instanceof Error false branch */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors from file: ${message}`);\n }\n }\n\n /**\n * Check if the directory handle has write permission.\n * @param handle - The directory handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkWritePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n // Permission API might not be available or might throw\n return false;\n }\n }\n\n /**\n * Check if the file handle has write permission.\n * @param handle - The file handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkFileWritePermission(handle: FileSystemFileHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Load all files from a directory handle recursively.\n * @param dirHandle - The directory handle to load from.\n * @param basePath - The base path for files.\n * @param params - Optional parameters.\n * @returns Promise resolving to files and handles.\n * @internal\n */\n private static async _loadDirectory<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n basePath: string,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<{ files: FileTree.IInMemoryFile<TCT>[]; handles: Map<string, FileSystemFileHandle> }> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n const handles = new Map<string, FileSystemFileHandle>();\n\n for await (const [name, handle] of dirHandle.entries()) {\n if (handle.kind === 'file') {\n const fileHandle = handle as FileSystemFileHandle;\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = this._joinPath(basePath, name);\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n files.push({ path, contents, contentType });\n handles.set(path, fileHandle);\n } else if (handle.kind === 'directory') {\n const subDirHandle = handle as FileSystemDirectoryHandle;\n const subPath = this._joinPath(basePath, name);\n const subResult = await this._loadDirectory<TCT>(subDirHandle, subPath, params);\n files.push(...subResult.files);\n for (const [path, fileHandle] of subResult.handles) {\n handles.set(path, fileHandle);\n }\n }\n }\n\n return { files, handles };\n }\n\n /**\n * Join path segments.\n * @param base - The base path.\n * @param name - The name to append.\n * @returns The joined path.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n const normalized = base.endsWith('/') ? base.slice(0, -1) : base;\n return `${normalized}/${name}`;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.syncToDisk`\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (!this._hasWritePermission) {\n return fail('Write permission not granted - cannot sync to disk');\n }\n\n const errors: string[] = [];\n\n // Process pending deletions from disk\n for (const path of this._pendingDeletions) {\n const deleteResult = await this._deleteFileFromDisk(path);\n if (deleteResult.isFailure()) {\n errors.push(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const syncResult = await this._syncFile(path);\n if (syncResult.isFailure()) {\n errors.push(`${path}: ${syncResult.message}`);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s):\\n${errors.join('\\n')}`);\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.isDirty`\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.getDirtyPaths`\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n /**\n * Override deleteFile to track pending deletions for syncToDisk.\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._handles.delete(path);\n\n if (this._hasWritePermission) {\n this._pendingDeletions.add(path);\n\n if (this._autoSync) {\n void this._runAutoSyncTask(path, 'delete', () => this._deleteFileFromDisk(path));\n }\n }\n }\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.saveFileContents`\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n // Call parent to update in-memory state\n const result = super.saveFileContents(path, contents);\n\n if (result.isSuccess() && this._hasWritePermission) {\n this._dirtyFiles.add(path);\n\n // Auto-sync if enabled\n if (this._autoSync) {\n // Fire and log-on-failure; don't block the save path.\n void this._runAutoSyncTask(path, 'save', () => this._syncFile(path));\n }\n }\n\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.fileIsMutable`\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n\n if (baseResult.isSuccess() && baseResult.detail === 'transient' && this._hasWritePermission) {\n // Upgrade to 'persistent' if we have write permission\n return succeedWithDetail(true, 'persistent');\n }\n\n return baseResult;\n }\n\n /**\n * Sync a single file to disk.\n * @param path - The path of the file to sync.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _syncFile(path: string): Promise<Result<void>> {\n const handle = this._handles.get(path);\n if (!handle) {\n return this._createAndWriteFile(path);\n }\n\n const contents = this.getFileContents(path);\n if (contents.isFailure()) {\n return fail(contents.message);\n }\n\n try {\n const writable = await handle.createWritable();\n await writable.write(contents.value);\n await writable.close();\n return succeed(undefined);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to write file: ${message}`);\n }\n }\n\n /**\n * Delete a file from disk using the File System Access API.\n * @param path - The path of the file to delete.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _deleteFileFromDisk(path: string): Promise<Result<void>> {\n try {\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - defensive: invalid path */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate to the parent directory\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part);\n }\n\n await currentDir.removeEntry(filename);\n return succeed(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to delete file ${path}: ${message}`);\n }\n }\n\n /**\n * Create a new file and write its contents.\n * @param path - The path of the file to create.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _createAndWriteFile(path: string): Promise<Result<void>> {\n try {\n // Parse path to get directory and filename\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate/create directory structure\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n\n // Create file and write contents\n const fileHandle = await currentDir.getFileHandle(filename, { create: true });\n this._handles.set(path, fileHandle);\n\n return this._syncFile(path);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create file ${path}: ${message}`);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileSystemAccessTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileSystemAccessTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;AAEH,4CAAkG;AAClG,oDAA6C;AAmC7C;;;;GAIG;AACH,MAAa,6BACX,SAAQ,uBAAQ,CAAC,qBAA0B;IAW3C;;;;;;;OAOG;IACH,YACE,KAAoC,EACpC,OAAkC,EAClC,OAA0C,EAC1C,MAAoD,EACpD,kBAA2B;;QAE3B,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAC;QACnC,0FAA0F;QAC1F,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,mCAAI,KAAK,CAAC;QAC3C,IAAI,CAAC,mBAAmB,GAAG,kBAAkB,CAAC;QAC9C,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,mCAAI,IAA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AO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;YAC5B,qEAAqE;QACvE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAA,eAAI,EAAC,yBAAyB,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;CACF;AA/bD,sEA+bC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, succeed, fail, DetailedResult, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { FileSystemDirectoryHandle, FileSystemFileHandle } from '../file-api-types';\n\n/**\n * Options for creating persistent file trees.\n * @public\n */\nexport interface IFileSystemAccessTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Automatically sync changes to disk immediately after each save.\n * If false, changes are batched and written on explicit syncToDisk() call.\n * @defaultValue false\n */\n autoSync?: boolean;\n\n /**\n * Require write permission on the directory handle.\n * If true, fails if write permission cannot be obtained.\n * If false, falls back to read-only mode.\n * @defaultValue true\n */\n requireWritePermission?: boolean;\n\n /**\n * Override the path at which the file is stored in the tree (for fromFileHandle).\n * Must be an absolute path (e.g., '/data/confections/common.yaml').\n * If omitted, defaults to `/<filename>`.\n */\n filePath?: string;\n\n /** Optional logger for auto-sync and persistence failures. */\n logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * Implementation of `FileTree.IPersistentFileTreeAccessors` that uses the File System Access API\n * to provide persistent file editing in browsers.\n * @public\n */\nexport class FileSystemAccessTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _handles: Map<string, FileSystemFileHandle>;\n private readonly _rootDir: FileSystemDirectoryHandle;\n private readonly _dirtyFiles: Set<string>;\n private readonly _pendingDeletions: Set<string>;\n private readonly _autoSync: boolean;\n private readonly _hasWritePermission: boolean;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /**\n * Protected constructor for FileSystemAccessTreeAccessors.\n * @param files - An array of in-memory files to include in the tree.\n * @param rootDir - The root directory handle.\n * @param handles - Map of file paths to their handles.\n * @param params - Optional params for the tree.\n * @param hasWritePermission - Whether write permission was granted.\n */\n protected constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n rootDir: FileSystemDirectoryHandle,\n handles: Map<string, FileSystemFileHandle>,\n params: IFileSystemAccessTreeParams<TCT> | undefined,\n hasWritePermission: boolean\n ) {\n super(files, params);\n this._rootDir = rootDir;\n this._handles = handles;\n this._dirtyFiles = new Set();\n this._pendingDeletions = new Set();\n /* c8 ignore next 3 - intermittent branch coverage: ?? fallback branches in constructor */\n this._autoSync = params?.autoSync ?? false;\n this._hasWritePermission = hasWritePermission;\n this._logger = params?.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(\n path: string,\n operation: 'save' | 'delete',\n action: () => Promise<Result<void>>\n ): Promise<void> {\n try {\n const result = await action();\n if (result.isFailure()) {\n this._logger.error(`Auto-${operation} failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-${operation} threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a directory handle.\n * @param dirHandle - The FileSystemDirectoryHandle to load files from.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromDirectoryHandle<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n // Check write permission\n const hasWritePermission = await this._checkWritePermission(dirHandle);\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n // Load all files from the directory (always use '/' as base, prefix is handled by parent)\n const { files, handles } = await this._loadDirectory<TCT>(dirHandle, '/', params);\n\n // Enable tree mutability when write permission is granted and caller didn't explicitly set mutable\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n mutable: params?.mutable ?? (hasWritePermission ? true : false)\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dirHandle, handles, effectiveParams, hasWritePermission)\n );\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Creates a new FileSystemAccessTreeAccessors instance from a single file handle.\n *\n * The resulting tree contains exactly one file at `/<filename>`.\n * `syncToDisk()` writes changes back to the original file via the File System Access API.\n * New file creation is not supported on this tree (no parent directory handle).\n *\n * @param fileHandle - The FileSystemFileHandle to load.\n * @param params - Optional parameters including autoSync and permission settings.\n * @returns Promise resolving to a FileSystemAccessTreeAccessors instance.\n * @public\n */\n public static async fromFileHandle<TCT extends string = string>(\n fileHandle: FileSystemFileHandle,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<Result<FileSystemAccessTreeAccessors<TCT>>> {\n try {\n const hasWritePermission = await this._checkFileWritePermission(fileHandle);\n\n /* c8 ignore next 1 - intermittent branch coverage: ?? true fallback */\n if (!hasWritePermission && (params?.requireWritePermission ?? true)) {\n return fail('Write permission required but not granted');\n }\n\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = params?.filePath ?? `/${fileHandle.name}`;\n /* c8 ignore next 3 - intermittent branch coverage: ternary for inferContentType */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n const files: FileTree.IInMemoryFile<TCT>[] = [{ path, contents, contentType }];\n const handles = new Map<string, FileSystemFileHandle>([[path, fileHandle]]);\n\n const dummyRoot = {} as FileSystemDirectoryHandle;\n const effectiveParams: IFileSystemAccessTreeParams<TCT> = {\n ...params,\n /* c8 ignore next 1 - intermittent branch coverage: ?? false fallback */\n mutable: hasWritePermission ? true : params?.mutable ?? false\n };\n\n return succeed(\n new FileSystemAccessTreeAccessors<TCT>(files, dummyRoot, handles, effectiveParams, hasWritePermission)\n );\n } catch (error) {\n /* c8 ignore next 1 - intermittent branch coverage: error instanceof Error false branch */\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create FileSystemAccessTreeAccessors from file: ${message}`);\n }\n }\n\n /**\n * Check if the directory handle has write permission.\n * @param handle - The directory handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkWritePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n // Permission API might not be available or might throw\n return false;\n }\n }\n\n /**\n * Check if the file handle has write permission.\n * @param handle - The file handle to check.\n * @returns Promise resolving to true if write permission is granted.\n * @internal\n */\n private static async _checkFileWritePermission(handle: FileSystemFileHandle): Promise<boolean> {\n try {\n const permission = await handle.queryPermission({ mode: 'readwrite' });\n\n if (permission === 'granted') {\n return true;\n }\n\n if (permission === 'prompt') {\n const requested = await handle.requestPermission({ mode: 'readwrite' });\n return requested === 'granted';\n }\n\n return false;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Load all files from a directory handle recursively.\n * @param dirHandle - The directory handle to load from.\n * @param basePath - The base path for files.\n * @param params - Optional parameters.\n * @returns Promise resolving to files and handles.\n * @internal\n */\n private static async _loadDirectory<TCT extends string = string>(\n dirHandle: FileSystemDirectoryHandle,\n basePath: string,\n params?: IFileSystemAccessTreeParams<TCT>\n ): Promise<{ files: FileTree.IInMemoryFile<TCT>[]; handles: Map<string, FileSystemFileHandle> }> {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n const handles = new Map<string, FileSystemFileHandle>();\n\n for await (const [name, handle] of dirHandle.entries()) {\n if (handle.kind === 'file') {\n const fileHandle = handle as FileSystemFileHandle;\n const file = await fileHandle.getFile();\n const contents = await file.text();\n const path = this._joinPath(basePath, name);\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n const contentType = params?.inferContentType\n ? params.inferContentType(path, file.type).orDefault()\n : undefined;\n\n files.push({ path, contents, contentType });\n handles.set(path, fileHandle);\n } else if (handle.kind === 'directory') {\n const subDirHandle = handle as FileSystemDirectoryHandle;\n const subPath = this._joinPath(basePath, name);\n const subResult = await this._loadDirectory<TCT>(subDirHandle, subPath, params);\n files.push(...subResult.files);\n for (const [path, fileHandle] of subResult.handles) {\n handles.set(path, fileHandle);\n }\n }\n }\n\n return { files, handles };\n }\n\n /**\n * Join path segments.\n * @param base - The base path.\n * @param name - The name to append.\n * @returns The joined path.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n const normalized = base.endsWith('/') ? base.slice(0, -1) : base;\n return `${normalized}/${name}`;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.syncToDisk`\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (!this._hasWritePermission) {\n return fail('Write permission not granted - cannot sync to disk');\n }\n\n const errors: string[] = [];\n\n // Process pending deletions from disk\n for (const path of this._pendingDeletions) {\n const deleteResult = await this._deleteFileFromDisk(path);\n if (deleteResult.isFailure()) {\n errors.push(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const syncResult = await this._syncFile(path);\n if (syncResult.isFailure()) {\n errors.push(`${path}: ${syncResult.message}`);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s):\\n${errors.join('\\n')}`);\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.isDirty`\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Implements `FileTree.IPersistentFileTreeAccessors.getDirtyPaths`\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n /**\n * Override deleteFile to track pending deletions for syncToDisk.\n */\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isSuccess()) {\n this._dirtyFiles.delete(path);\n this._handles.delete(path);\n\n if (this._hasWritePermission) {\n this._pendingDeletions.add(path);\n\n if (this._autoSync) {\n this._runAutoSyncTask(path, 'delete', () => this._deleteFileFromDisk(path)).catch(() => undefined);\n }\n }\n }\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.saveFileContents`\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n // Call parent to update in-memory state\n const result = super.saveFileContents(path, contents);\n\n if (result.isSuccess() && this._hasWritePermission) {\n this._dirtyFiles.add(path);\n\n // Auto-sync if enabled\n if (this._autoSync) {\n // Fire and log-on-failure; don't block the save path.\n this._runAutoSyncTask(path, 'save', () => this._syncFile(path)).catch(() => undefined);\n }\n }\n\n return result;\n }\n\n /**\n * Implements `FileTree.IMutableFileTreeAccessors.fileIsMutable`\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n\n if (baseResult.isSuccess() && baseResult.detail === 'transient' && this._hasWritePermission) {\n // Upgrade to 'persistent' if we have write permission\n return succeedWithDetail(true, 'persistent');\n }\n\n return baseResult;\n }\n\n /**\n * Sync a single file to disk.\n * @param path - The path of the file to sync.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _syncFile(path: string): Promise<Result<void>> {\n const handle = this._handles.get(path);\n if (!handle) {\n return this._createAndWriteFile(path);\n }\n\n const contents = this.getFileContents(path);\n if (contents.isFailure()) {\n return fail(contents.message);\n }\n\n try {\n const writable = await handle.createWritable();\n await writable.write(contents.value);\n await writable.close();\n return succeed(undefined);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to write file: ${message}`);\n }\n }\n\n /**\n * Delete a file from disk using the File System Access API.\n * @param path - The path of the file to delete.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _deleteFileFromDisk(path: string): Promise<Result<void>> {\n try {\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - defensive: invalid path */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate to the parent directory\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part);\n }\n\n await currentDir.removeEntry(filename);\n return succeed(undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to delete file ${path}: ${message}`);\n }\n }\n\n /**\n * Create a new file and write its contents.\n * @param path - The path of the file to create.\n * @returns Promise resolving to success or failure.\n * @internal\n */\n private async _createAndWriteFile(path: string): Promise<Result<void>> {\n try {\n // Parse path to get directory and filename\n const absolutePath = this.resolveAbsolutePath(path);\n const parts = absolutePath.split('/').filter((p) => p.length > 0);\n const filename = parts.pop();\n\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!filename) {\n return fail(`Invalid file path: ${path}`);\n }\n\n // Navigate/create directory structure\n let currentDir = this._rootDir;\n for (const part of parts) {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n\n // Create file and write contents\n const fileHandle = await currentDir.getFileHandle(filename, { create: true });\n this._handles.set(path, fileHandle);\n\n return this._syncFile(path);\n /* c8 ignore next 4 - coverage intermittently missed in full suite */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create file ${path}: ${message}`);\n }\n }\n}\n"]}
|
|
@@ -194,7 +194,7 @@ class HttpTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAccessors {
|
|
|
194
194
|
if (!this._autoSync) {
|
|
195
195
|
return result;
|
|
196
196
|
}
|
|
197
|
-
|
|
197
|
+
this._runAutoSyncTask(path).catch(() => undefined);
|
|
198
198
|
return result;
|
|
199
199
|
}
|
|
200
200
|
/**
|
|
@@ -213,7 +213,7 @@ class HttpTreeAccessors extends ts_json_base_1.FileTree.InMemoryTreeAccessors {
|
|
|
213
213
|
return result;
|
|
214
214
|
}
|
|
215
215
|
// fire-and-log-on-failure automatic sync for immediate persistence workflow
|
|
216
|
-
|
|
216
|
+
this._runAutoSyncTask(path).catch(() => undefined);
|
|
217
217
|
return result;
|
|
218
218
|
}
|
|
219
219
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":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,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAA,eAAI,EAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,IAAA,kBAAO,EAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF;AAzZD,8CAyZC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n // Wait for the in-flight sync — it drains the queue in a loop,\n // so any items added before it finishes will be included.\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n // Drain loop: keep processing as long as new items arrive.\n // This is critical for bulk operations (e.g. reset) where many\n // deleteFile/saveFileContents calls happen synchronously — only\n // the first may be in the set when we snapshot, but the rest\n // arrive during the async gaps and must be picked up before\n // we return.\n let didWork = false;\n while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {\n didWork = true;\n // Snapshot and clear so that changes arriving during the async\n // requests land in the live sets for the next iteration.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n }\n\n if (didWork) {\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n if (syncResult.isFailure()) {\n return fail(syncResult.message);\n }\n }\n return succeed(undefined);\n }\n\n /**\n * Restores snapshotted items back into the live dirty sets so they\n * are retried on the next sync attempt. Items that were added to\n * the live sets while the sync was in flight are preserved.\n */\n private _restoreUnsynced(deletions: Set<string>, dirty: Set<string>): void {\n for (const path of deletions) {\n this._pendingDeletions.add(path);\n }\n for (const path of dirty) {\n this._dirtyFiles.add(path);\n }\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAuG;AACvG,oDAA6C;AAuB7C,SAAS,cAAc,CAAC,SAAwB;IAC9C,MAAM,QAAQ,GAAG,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAiB,CAAC;AACnD,CAAC;AAeD;;;GAGG;AACH,MAAa,iBACX,SAAQ,uBAAQ,CAAC,qBAA0B;IAe3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAVN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAU1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,SAAS,GAAG,MAAA,MAAM,CAAC,QAAQ,mCAAI,KAAK,CAAC;QAC1C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,CAAC,MAAM,mCAAI,IAAI,kBAAO,CAAC,WAAW,EAAW,CAAC;IACrE,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,IAAY;QACzC,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAA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tB,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5F,OAAO,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,IAAA,eAAI,EAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAA,eAAI,EAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,IAAA,kBAAO,EAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF;AAzZD,8CAyZC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n // Wait for the in-flight sync — it drains the queue in a loop,\n // so any items added before it finishes will be included.\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n // Drain loop: keep processing as long as new items arrive.\n // This is critical for bulk operations (e.g. reset) where many\n // deleteFile/saveFileContents calls happen synchronously — only\n // the first may be in the set when we snapshot, but the rest\n // arrive during the async gaps and must be picked up before\n // we return.\n let didWork = false;\n while (this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0) {\n didWork = true;\n // Snapshot and clear so that changes arriving during the async\n // requests land in the live sets for the next iteration.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n this._restoreUnsynced(deletions, dirty);\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n }\n\n if (didWork) {\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n if (syncResult.isFailure()) {\n return fail(syncResult.message);\n }\n }\n return succeed(undefined);\n }\n\n /**\n * Restores snapshotted items back into the live dirty sets so they\n * are retried on the next sync attempt. Items that were added to\n * the live sets while the sync was in flight are preserved.\n */\n private _restoreUnsynced(deletions: Set<string>, dirty: Set<string>): void {\n for (const path of deletions) {\n this._pendingDeletions.add(path);\n }\n for (const path of dirty) {\n this._dirtyFiles.add(path);\n }\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n this._runAutoSyncTask(path).catch(() => undefined);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n this._runAutoSyncTask(path).catch(() => undefined);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|