@fgv/ts-web-extras 5.0.1-8 → 5.0.1
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/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +9 -9
- package/.rush/temp/operation/build/all.log +9 -9
- package/.rush/temp/operation/build/log-chunks.jsonl +9 -9
- package/.rush/temp/operation/build/state.json +1 -1
- package/.rush/temp/shrinkwrap-deps.json +40 -38
- package/config/jest.config.json +1 -1
- package/config/rig.json +1 -1
- package/dist/index.browser.js +24 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/crypto/browserHashProvider.js +66 -0
- package/dist/packlets/crypto/browserHashProvider.js.map +1 -0
- package/dist/packlets/crypto/index.js +27 -0
- package/dist/packlets/crypto/index.js.map +1 -0
- package/dist/packlets/file-api-types/index.js +156 -0
- package/dist/packlets/file-api-types/index.js.map +1 -0
- package/dist/packlets/file-tree/fileApiTreeAccessors.js +330 -0
- package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -0
- package/dist/packlets/file-tree/index.js +27 -0
- package/dist/packlets/file-tree/index.js.map +1 -0
- package/dist/packlets/helpers/fileTreeHelpers.js +94 -0
- package/dist/packlets/helpers/fileTreeHelpers.js.map +1 -0
- package/dist/packlets/helpers/index.js +27 -0
- package/dist/packlets/helpers/index.js.map +1 -0
- package/dist/packlets/url-utils/index.js +27 -0
- package/dist/packlets/url-utils/index.js.map +1 -0
- package/dist/packlets/url-utils/urlParams.js +157 -0
- package/dist/packlets/url-utils/urlParams.js.map +1 -0
- package/dist/test/setupTests.js +74 -0
- package/dist/test/setupTests.js.map +1 -0
- package/dist/test/unit/browserHashProvider.test.js +140 -0
- package/dist/test/unit/browserHashProvider.test.js.map +1 -0
- package/dist/test/unit/fileApiTreeAccessors.test.js +1137 -0
- package/dist/test/unit/fileApiTreeAccessors.test.js.map +1 -0
- package/dist/test/unit/fileApiTypes.test.js +442 -0
- package/dist/test/unit/fileApiTypes.test.js.map +1 -0
- package/dist/test/unit/fileTreeHelpers.test.js +590 -0
- package/dist/test/unit/fileTreeHelpers.test.js.map +1 -0
- package/dist/test/unit/urlParams.test.js +393 -0
- package/dist/test/unit/urlParams.test.js.map +1 -0
- package/dist/test/utils/testHelpers.js +124 -0
- package/dist/test/utils/testHelpers.js.map +1 -0
- package/dist/tsdoc-metadata.json +1 -1
- package/lib/index.browser.d.ts +2 -0
- package/lib/index.browser.d.ts.map +1 -0
- package/lib/index.browser.js +40 -0
- package/lib/index.browser.js.map +1 -0
- package/package.json +20 -6
- package/rush-logs/ts-web-extras.build.cache.log +1 -3
- package/rush-logs/ts-web-extras.build.log +9 -9
- package/src/index.browser.ts +24 -0
- package/temp/build/typescript/ts_vnCx6LlY.json +1 -0
- package/temp/coverage/crypto/browserHashProvider.ts.html +1 -1
- package/temp/coverage/crypto/index.html +1 -1
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/index.html +1 -1
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/helpers/index.html +1 -1
- package/temp/coverage/index.html +1 -1
- package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto/index.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/index.html +1 -1
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/index.html +1 -1
- package/temp/coverage/lcov-report/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
- package/temp/coverage/url-utils/index.html +1 -1
- package/temp/coverage/url-utils/urlParams.ts.html +1 -1
- package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
- package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
- package/temp/ts-web-extras.api.json +1 -1
- package/.rush/temp/3b013d9faf7f9da4019da446f1d05aef5eb5f80d.tar.log +0 -121
- package/temp/build/typescript/ts_l9Fw4VUO.json +0 -1
- /package/temp/test/jest/jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/{3f/package_3fe59327dabcb949f1b2ad415f67debd → 0e/package_0eb6535f5987849d93ea51ef33a14cf6} +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2025 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Type guard to check if the browser supports the File System Access API
|
|
24
|
+
* @param window - The window object to check
|
|
25
|
+
* @returns True if the window supports File System Access API
|
|
26
|
+
* @public
|
|
27
|
+
*/
|
|
28
|
+
export function supportsFileSystemAccess(window) {
|
|
29
|
+
return 'showOpenFilePicker' in window && 'showSaveFilePicker' in window && 'showDirectoryPicker' in window;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Type guard to check if a FileSystemHandle is a file handle
|
|
33
|
+
* @param handle - The handle to check
|
|
34
|
+
* @returns True if the handle is a FileSystemFileHandle
|
|
35
|
+
* @public
|
|
36
|
+
*/
|
|
37
|
+
export function isFileHandle(handle) {
|
|
38
|
+
return handle.kind === 'file';
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Type guard to check if a FileSystemHandle is a directory handle
|
|
42
|
+
* @param handle - The handle to check
|
|
43
|
+
* @returns True if the handle is a FileSystemDirectoryHandle
|
|
44
|
+
* @public
|
|
45
|
+
*/
|
|
46
|
+
export function isDirectoryHandle(handle) {
|
|
47
|
+
return handle.kind === 'directory';
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Safely access showOpenFilePicker with proper type checking
|
|
51
|
+
* @param window - The window object
|
|
52
|
+
* @param options - Options for the file picker
|
|
53
|
+
* @returns Promise with file handles or null if not supported
|
|
54
|
+
* @public
|
|
55
|
+
*/
|
|
56
|
+
export async function safeShowOpenFilePicker(window, options) {
|
|
57
|
+
if (supportsFileSystemAccess(window)) {
|
|
58
|
+
return window.showOpenFilePicker(options);
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Safely access showSaveFilePicker with proper type checking
|
|
64
|
+
* @param window - The window object
|
|
65
|
+
* @param options - Options for the file picker
|
|
66
|
+
* @returns Promise with file handle or null if not supported
|
|
67
|
+
* @public
|
|
68
|
+
*/
|
|
69
|
+
export async function safeShowSaveFilePicker(window, options) {
|
|
70
|
+
if (supportsFileSystemAccess(window)) {
|
|
71
|
+
return window.showSaveFilePicker(options);
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Safely access showDirectoryPicker with proper type checking
|
|
77
|
+
* @param window - The window object
|
|
78
|
+
* @param options - Options for the directory picker
|
|
79
|
+
* @returns Promise with directory handle or null if not supported
|
|
80
|
+
* @public
|
|
81
|
+
*/
|
|
82
|
+
export async function safeShowDirectoryPicker(window, options) {
|
|
83
|
+
if (supportsFileSystemAccess(window)) {
|
|
84
|
+
return window.showDirectoryPicker(options);
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Export data as JSON file using legacy blob download method.
|
|
90
|
+
* Creates a temporary download link and triggers file download.
|
|
91
|
+
* @param data - Data to export as JSON
|
|
92
|
+
* @param filename - Name for the downloaded file
|
|
93
|
+
* @public
|
|
94
|
+
*/
|
|
95
|
+
export function exportAsJson(data, filename) {
|
|
96
|
+
const json = JSON.stringify(data, null, 2);
|
|
97
|
+
const blob = new Blob([json], { type: 'application/json' });
|
|
98
|
+
const url = URL.createObjectURL(blob);
|
|
99
|
+
const a = document.createElement('a');
|
|
100
|
+
a.href = url;
|
|
101
|
+
a.download = filename;
|
|
102
|
+
document.body.appendChild(a);
|
|
103
|
+
a.click();
|
|
104
|
+
document.body.removeChild(a);
|
|
105
|
+
URL.revokeObjectURL(url);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Export data using File System Access API with fallback to blob download.
|
|
109
|
+
* @param data - Data to export as JSON
|
|
110
|
+
* @param suggestedName - Suggested filename for the save dialog
|
|
111
|
+
* @param description - Description for file type filter (default: 'JSON files')
|
|
112
|
+
* @param window - Window object for API access (default: globalThis.window)
|
|
113
|
+
* @returns Promise resolving to true if saved via File System Access API, false if fallback used
|
|
114
|
+
* @public
|
|
115
|
+
*/
|
|
116
|
+
export async function exportUsingFileSystemAPI(data, suggestedName, description = 'JSON files', window = globalThis.window) {
|
|
117
|
+
if (!supportsFileSystemAccess(window)) {
|
|
118
|
+
// Fallback to blob download
|
|
119
|
+
exportAsJson(data, suggestedName);
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const fileHandle = await safeShowSaveFilePicker(window, {
|
|
124
|
+
suggestedName,
|
|
125
|
+
types: [
|
|
126
|
+
{
|
|
127
|
+
description,
|
|
128
|
+
accept: {
|
|
129
|
+
'application/json': ['.json']
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
]
|
|
133
|
+
});
|
|
134
|
+
if (!fileHandle) {
|
|
135
|
+
// User cancelled - fallback to blob download
|
|
136
|
+
exportAsJson(data, suggestedName);
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
const json = JSON.stringify(data, null, 2);
|
|
140
|
+
const writable = await fileHandle.createWritable();
|
|
141
|
+
await writable.write(json);
|
|
142
|
+
await writable.close();
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
// Handle errors by falling back to blob download
|
|
147
|
+
if (error.name === 'AbortError') {
|
|
148
|
+
// User cancelled - fallback
|
|
149
|
+
exportAsJson(data, suggestedName);
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
// Other errors - re-throw as they indicate a real problem
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-api-types/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAsKH;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,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AAC,CAAC,CAAC;QAC3C,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,cAAc,EAAE,CAAC;QACnD,MAAM,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC3B,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;QAEvB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,iDAAiD;QACjD,IAAK,KAAe,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAC3C,4BAA4B;YAC5B,YAAY,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YAClC,OAAO,KAAK,CAAC;QACf,CAAC;QACD,0DAA0D;QAC1D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","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/**\n * File System Access API type definitions and utilities for browser compatibility.\n * @packageDocumentation\n */\n\n// Local type definitions for File System Access API\n// Based on https://wicg.github.io/file-system-access/\n\n/**\n * File System Access API methods available on Window\n * @public\n */\nexport interface IFsAccessApis {\n showDirectoryPicker(options?: ShowDirectoryPickerOptions): Promise<FileSystemDirectoryHandle>;\n showOpenFilePicker(options?: ShowOpenFilePickerOptions): Promise<FileSystemFileHandle[]>;\n showSaveFilePicker(options?: ShowSaveFilePickerOptions): Promise<FileSystemFileHandle>;\n}\n\n/**\n * Window interface extended with File System Access API\n * @public\n */\nexport type WindowWithFsAccess = Window & IFsAccessApis;\n\n/**\n * Base interface for file system handles\n * @public\n */\nexport interface FileSystemHandle {\n readonly kind: 'file' | 'directory';\n readonly name: string;\n isSameEntry(other: FileSystemHandle): Promise<boolean>;\n queryPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n requestPermission(descriptor?: FileSystemHandlePermissionDescriptor): Promise<PermissionState>;\n}\n\n/**\n * File handle interface\n * @public\n */\nexport interface FileSystemFileHandle extends FileSystemHandle {\n readonly kind: 'file';\n getFile(): Promise<File>;\n createWritable(options?: FileSystemCreateWritableOptions): Promise<FileSystemWritableFileStream>;\n}\n\n/**\n * Directory handle interface\n * @public\n */\nexport interface FileSystemDirectoryHandle extends FileSystemHandle {\n readonly kind: 'directory';\n getDirectoryHandle(\n name: string,\n options?: FileSystemGetDirectoryOptions\n ): Promise<FileSystemDirectoryHandle>;\n getFileHandle(name: string, options?: FileSystemGetFileOptions): Promise<FileSystemFileHandle>;\n removeEntry(name: string, options?: FileSystemRemoveOptions): Promise<void>;\n resolve(possibleDescendant: FileSystemHandle): Promise<string[] | null>;\n keys(): AsyncIterableIterator<string>;\n values(): AsyncIterableIterator<FileSystemHandle>;\n entries(): AsyncIterableIterator<[string, FileSystemHandle]>;\n [Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;\n}\n\n/**\n * Permission descriptor for file system handles\n * @public\n */\nexport interface FileSystemHandlePermissionDescriptor {\n mode?: 'read' | 'readwrite';\n}\n\n/**\n * Options for creating writable file streams\n * @public\n */\nexport interface FileSystemCreateWritableOptions {\n keepExistingData?: boolean;\n}\n\n/**\n * Options for getting directory handles\n * @public\n */\nexport interface FileSystemGetDirectoryOptions {\n create?: boolean;\n}\n\n/**\n * Options for getting file handles\n * @public\n */\nexport interface FileSystemGetFileOptions {\n create?: boolean;\n}\n\n/**\n * Options for removing entries\n * @public\n */\nexport interface FileSystemRemoveOptions {\n recursive?: boolean;\n}\n\n/**\n * Writable file stream interface\n * @public\n */\nexport interface FileSystemWritableFileStream extends WritableStream {\n write(data: BufferSource | Blob | string): Promise<void>;\n seek(position: number): Promise<void>;\n truncate(size: number): Promise<void>;\n}\n\n/**\n * Directory picker options\n * @public\n */\nexport interface ShowDirectoryPickerOptions {\n id?: string;\n mode?: 'read' | 'readwrite';\n startIn?: FileSystemHandle | WellKnownDirectory;\n}\n\n/**\n * File picker options\n * @public\n */\nexport interface ShowOpenFilePickerOptions {\n multiple?: boolean;\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * Save file picker options\n * @public\n */\nexport interface ShowSaveFilePickerOptions {\n excludeAcceptAllOption?: boolean;\n id?: string;\n startIn?: FileSystemHandle | WellKnownDirectory;\n suggestedName?: string;\n types?: FilePickerAcceptType[];\n}\n\n/**\n * File picker accept type\n * @public\n */\nexport interface FilePickerAcceptType {\n description?: string;\n accept: Record<string, string | string[]>;\n}\n\n/**\n * Well-known directory type\n * @public\n */\nexport type WellKnownDirectory = 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos';\n\n/**\n * Type guard to check if the browser supports the File System Access API\n * @param window - The window object to check\n * @returns True if the window supports File System Access API\n * @public\n */\nexport function supportsFileSystemAccess(window: Window): window is WindowWithFsAccess {\n return 'showOpenFilePicker' in window && 'showSaveFilePicker' in window && 'showDirectoryPicker' in window;\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a file handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemFileHandle\n * @public\n */\nexport function isFileHandle(handle: FileSystemHandle): handle is FileSystemFileHandle {\n return handle.kind === 'file';\n}\n\n/**\n * Type guard to check if a FileSystemHandle is a directory handle\n * @param handle - The handle to check\n * @returns True if the handle is a FileSystemDirectoryHandle\n * @public\n */\nexport function isDirectoryHandle(handle: FileSystemHandle): handle is FileSystemDirectoryHandle {\n return handle.kind === 'directory';\n}\n\n/**\n * Safely access showOpenFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handles or null if not supported\n * @public\n */\nexport async function safeShowOpenFilePicker(\n window: Window,\n options?: ShowOpenFilePickerOptions\n): Promise<FileSystemFileHandle[] | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showOpenFilePicker(options);\n }\n return null;\n}\n\n/**\n * Safely access showSaveFilePicker with proper type checking\n * @param window - The window object\n * @param options - Options for the file picker\n * @returns Promise with file handle or null if not supported\n * @public\n */\nexport async function safeShowSaveFilePicker(\n window: Window,\n options?: ShowSaveFilePickerOptions\n): Promise<FileSystemFileHandle | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showSaveFilePicker(options);\n }\n return null;\n}\n\n/**\n * Safely access showDirectoryPicker with proper type checking\n * @param window - The window object\n * @param options - Options for the directory picker\n * @returns Promise with directory handle or null if not supported\n * @public\n */\nexport async function safeShowDirectoryPicker(\n window: Window,\n options?: ShowDirectoryPickerOptions\n): Promise<FileSystemDirectoryHandle | null> {\n if (supportsFileSystemAccess(window)) {\n return window.showDirectoryPicker(options);\n }\n return null;\n}\n\n/**\n * Export data as JSON file using legacy blob download method.\n * Creates a temporary download link and triggers file download.\n * @param data - Data to export as JSON\n * @param filename - Name for the downloaded file\n * @public\n */\nexport function exportAsJson(data: unknown, filename: string): void {\n const json = JSON.stringify(data, null, 2);\n const blob = new Blob([json], { type: 'application/json' });\n const url = URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n}\n\n/**\n * Export data using File System Access API with fallback to blob download.\n * @param data - Data to export as JSON\n * @param suggestedName - Suggested filename for the save dialog\n * @param description - Description for file type filter (default: 'JSON files')\n * @param window - Window object for API access (default: globalThis.window)\n * @returns Promise resolving to true if saved via File System Access API, false if fallback used\n * @public\n */\nexport async function exportUsingFileSystemAPI(\n data: unknown,\n suggestedName: string,\n description: string = 'JSON files',\n window: Window = globalThis.window\n): Promise<boolean> {\n if (!supportsFileSystemAccess(window)) {\n // Fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n try {\n const fileHandle = await safeShowSaveFilePicker(window, {\n suggestedName,\n types: [\n {\n description,\n accept: {\n 'application/json': ['.json']\n }\n }\n ]\n });\n\n if (!fileHandle) {\n // User cancelled - fallback to blob download\n exportAsJson(data, suggestedName);\n return false;\n }\n\n const json = JSON.stringify(data, null, 2);\n const writable = await fileHandle.createWritable();\n await writable.write(json);\n await writable.close();\n\n return true;\n } catch (error) {\n // Handle errors by falling back to blob download\n if ((error as Error).name === 'AbortError') {\n // User cancelled - fallback\n exportAsJson(data, suggestedName);\n return false;\n }\n // Other errors - re-throw as they indicate a real problem\n throw error;\n }\n}\n"]}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2025 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
23
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
24
|
+
var m = o[Symbol.asyncIterator], i;
|
|
25
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
26
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
27
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
28
|
+
};
|
|
29
|
+
// File System Access API types are imported via the file-api-types module
|
|
30
|
+
import { succeed, fail } from '@fgv/ts-utils';
|
|
31
|
+
import { FileTree } from '@fgv/ts-json-base';
|
|
32
|
+
import { isFileHandle, isDirectoryHandle } from '../file-api-types';
|
|
33
|
+
/**
|
|
34
|
+
* Helper function to safely get webkitRelativePath from a File object.
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
function getFileRelativePath(file) {
|
|
38
|
+
return file.webkitRelativePath || file.name;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Helper class to create FileTree instances from various file sources.
|
|
42
|
+
* Supports File API (FileList) and File System Access API handles.
|
|
43
|
+
* @public
|
|
44
|
+
*/
|
|
45
|
+
export class FileApiTreeAccessors {
|
|
46
|
+
/**
|
|
47
|
+
* Create FileTree from various file sources using TreeInitializer array.
|
|
48
|
+
* @param initializers - Array of TreeInitializer objects specifying file sources
|
|
49
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
50
|
+
* @returns Promise resolving to a FileTree with all content pre-loaded
|
|
51
|
+
*/
|
|
52
|
+
static async create(initializers, params) {
|
|
53
|
+
try {
|
|
54
|
+
const allFiles = [];
|
|
55
|
+
for (const initializer of initializers) {
|
|
56
|
+
const filesResult = await this._processInitializer(initializer, params);
|
|
57
|
+
if (filesResult.isFailure()) {
|
|
58
|
+
return fail(filesResult.message);
|
|
59
|
+
}
|
|
60
|
+
allFiles.push(...filesResult.value);
|
|
61
|
+
}
|
|
62
|
+
return FileTree.inMemory(allFiles, params);
|
|
63
|
+
/* c8 ignore next 5 - defense in depth */
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
67
|
+
return fail(`Failed to process initializers: ${message}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Create FileTree from FileList (e.g., from input[type="file"]).
|
|
72
|
+
* @param fileList - FileList from a file input element
|
|
73
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
74
|
+
* @returns Promise resolving to a FileTree with all content pre-loaded
|
|
75
|
+
*/
|
|
76
|
+
static async fromFileList(fileList, params) {
|
|
77
|
+
var _a;
|
|
78
|
+
const files = [];
|
|
79
|
+
for (let i = 0; i < fileList.length; i++) {
|
|
80
|
+
const file = fileList[i];
|
|
81
|
+
const path = this._normalizePath((params === null || params === void 0 ? void 0 : params.prefix) || '', file.name);
|
|
82
|
+
try {
|
|
83
|
+
const contents = await file.text();
|
|
84
|
+
const contentType = (_a = params === null || params === void 0 ? void 0 : params.inferContentType) === null || _a === void 0 ? void 0 : _a.call(params, path, file.type).orDefault();
|
|
85
|
+
files.push({
|
|
86
|
+
path,
|
|
87
|
+
contents,
|
|
88
|
+
contentType
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
/* c8 ignore next 1 - defense in depth */
|
|
93
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
94
|
+
return fail(`Failed to read file ${file.name}: ${message}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return FileTree.inMemory(files, params);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Create FileTree from directory upload with webkitRelativePath.
|
|
101
|
+
* @param fileList - FileList from a directory upload (input with webkitdirectory)
|
|
102
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
103
|
+
* @returns Promise resolving to a FileTree with all content pre-loaded
|
|
104
|
+
*/
|
|
105
|
+
static async fromDirectoryUpload(fileList, params) {
|
|
106
|
+
var _a;
|
|
107
|
+
const files = [];
|
|
108
|
+
for (let i = 0; i < fileList.length; i++) {
|
|
109
|
+
const file = fileList[i];
|
|
110
|
+
const relativePath = getFileRelativePath(file);
|
|
111
|
+
const path = this._normalizePath((params === null || params === void 0 ? void 0 : params.prefix) || '', relativePath);
|
|
112
|
+
try {
|
|
113
|
+
const contents = await file.text();
|
|
114
|
+
const contentType = (_a = params === null || params === void 0 ? void 0 : params.inferContentType) === null || _a === void 0 ? void 0 : _a.call(params, path, file.type).orDefault();
|
|
115
|
+
files.push({
|
|
116
|
+
path,
|
|
117
|
+
contents,
|
|
118
|
+
contentType
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
/* c8 ignore next 1 - defense in depth */
|
|
123
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
124
|
+
return fail(`Failed to read file ${relativePath}: ${message}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return FileTree.inMemory(files, params);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Get the File object for a specific path from the original FileList.
|
|
131
|
+
* This is useful for accessing the original File API object for operations
|
|
132
|
+
* like getting file metadata, MIME type, etc.
|
|
133
|
+
* @param fileList - The original FileList
|
|
134
|
+
* @param targetPath - The path to find
|
|
135
|
+
* @returns Result containing the File object if found
|
|
136
|
+
*/
|
|
137
|
+
static getOriginalFile(fileList, targetPath) {
|
|
138
|
+
for (const file of Array.from(fileList)) {
|
|
139
|
+
const filePath = getFileRelativePath(file);
|
|
140
|
+
if (filePath === targetPath) {
|
|
141
|
+
return succeed(file);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return fail(`File not found: ${targetPath}`);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Extract file metadata from a File.
|
|
148
|
+
* @param fileList - The File to extract metadata from
|
|
149
|
+
* @returns The {@link IFileMetadata | file metadata}
|
|
150
|
+
*/
|
|
151
|
+
static extractFileMetadata(file) {
|
|
152
|
+
return {
|
|
153
|
+
path: getFileRelativePath(file),
|
|
154
|
+
name: file.name,
|
|
155
|
+
size: file.size,
|
|
156
|
+
type: file.type,
|
|
157
|
+
lastModified: file.lastModified
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Process a single TreeInitializer and return the resulting files.
|
|
162
|
+
* @param initializer - The TreeInitializer to process
|
|
163
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
164
|
+
* @returns Promise resolving to an array of `IInMemoryFile` objects
|
|
165
|
+
* @internal
|
|
166
|
+
*/
|
|
167
|
+
static async _processInitializer(initializer, params) {
|
|
168
|
+
var _a;
|
|
169
|
+
if ('fileList' in initializer) {
|
|
170
|
+
return this._processFileList(initializer.fileList, params);
|
|
171
|
+
}
|
|
172
|
+
else if ('fileHandles' in initializer) {
|
|
173
|
+
return this._processFileHandles(initializer.fileHandles, params);
|
|
174
|
+
}
|
|
175
|
+
else if ('dirHandles' in initializer) {
|
|
176
|
+
return this._processDirectoryHandles(initializer.dirHandles, (_a = initializer.prefix) !== null && _a !== void 0 ? _a : params === null || params === void 0 ? void 0 : params.prefix, !initializer.nonRecursive, params);
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
return fail('Unknown initializer type');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Process a FileList and return IInMemoryFile array.
|
|
184
|
+
* @param fileList - The FileList to process
|
|
185
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
186
|
+
* @returns Promise resolving to an array of `IInMemoryFile` objects
|
|
187
|
+
* @internal
|
|
188
|
+
*/
|
|
189
|
+
static async _processFileList(fileList, params) {
|
|
190
|
+
var _a;
|
|
191
|
+
const files = [];
|
|
192
|
+
for (let i = 0; i < fileList.length; i++) {
|
|
193
|
+
const file = fileList[i];
|
|
194
|
+
const metadata = this.extractFileMetadata(file);
|
|
195
|
+
const relativePath = metadata.path;
|
|
196
|
+
const path = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
|
|
197
|
+
try {
|
|
198
|
+
const contents = await file.text();
|
|
199
|
+
const contentType = (_a = params === null || params === void 0 ? void 0 : params.inferContentType) === null || _a === void 0 ? void 0 : _a.call(params, path, metadata.type).orDefault();
|
|
200
|
+
files.push({
|
|
201
|
+
path,
|
|
202
|
+
contents,
|
|
203
|
+
contentType
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
/* c8 ignore next 1 - defense in depth */
|
|
208
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
209
|
+
return fail(`Failed to read file ${relativePath}: ${message}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return succeed(files);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Process FileSystemFileHandles and return IInMemoryFile array.
|
|
216
|
+
* @internal
|
|
217
|
+
*/
|
|
218
|
+
static async _processFileHandles(handles, params) {
|
|
219
|
+
var _a, _b;
|
|
220
|
+
const files = [];
|
|
221
|
+
for (const handle of handles) {
|
|
222
|
+
try {
|
|
223
|
+
const file = await handle.getFile();
|
|
224
|
+
const contents = await file.text();
|
|
225
|
+
const metadata = this.extractFileMetadata(file);
|
|
226
|
+
/* c8 ignore next 1 - defense in depth */
|
|
227
|
+
const path = this._normalizePath((_a = params === null || params === void 0 ? void 0 : params.prefix) !== null && _a !== void 0 ? _a : '', handle.name);
|
|
228
|
+
const contentType = (_b = params === null || params === void 0 ? void 0 : params.inferContentType) === null || _b === void 0 ? void 0 : _b.call(params, path, metadata.type).orDefault();
|
|
229
|
+
files.push({
|
|
230
|
+
path,
|
|
231
|
+
contents,
|
|
232
|
+
contentType
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
/* c8 ignore next 1 - defense in depth */
|
|
237
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
238
|
+
return fail(`Failed to read file handle ${handle.name}: ${message}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return succeed(files);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Process FileSystemDirectoryHandles and return IInMemoryFile array.
|
|
245
|
+
* @param handles - The FileSystemDirectoryHandle[] to process
|
|
246
|
+
* @param prefix - The prefix to use for the file paths
|
|
247
|
+
* @param recursive - Whether to process the directory recursively
|
|
248
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
249
|
+
* @returns Promise resolving to an array of `IInMemoryFile` objects
|
|
250
|
+
* @internal
|
|
251
|
+
*/
|
|
252
|
+
static async _processDirectoryHandles(handles, prefix, recursive = true, params) {
|
|
253
|
+
const allFiles = [];
|
|
254
|
+
prefix = prefix !== null && prefix !== void 0 ? prefix : params === null || params === void 0 ? void 0 : params.prefix;
|
|
255
|
+
for (const handle of handles) {
|
|
256
|
+
const dirPrefix = this._normalizePath(prefix !== null && prefix !== void 0 ? prefix : '', handle.name);
|
|
257
|
+
const filesResult = await this._processDirectoryHandle(handle, dirPrefix, recursive, params);
|
|
258
|
+
if (filesResult.isFailure()) {
|
|
259
|
+
return filesResult;
|
|
260
|
+
}
|
|
261
|
+
allFiles.push(...filesResult.value);
|
|
262
|
+
}
|
|
263
|
+
return succeed(allFiles);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Process a single FileSystemDirectoryHandle recursively.
|
|
267
|
+
* @param handle - The FileSystemDirectoryHandle to process
|
|
268
|
+
* @param basePath - The base path to use for the file paths
|
|
269
|
+
* @param recursive - Whether to process the directory recursively
|
|
270
|
+
* @param params - Optional `IFileTreeInitParams` for the file tree.
|
|
271
|
+
* @returns Promise resolving to an array of `IInMemoryFile` objects
|
|
272
|
+
* @internal
|
|
273
|
+
*/
|
|
274
|
+
static async _processDirectoryHandle(handle, basePath, recursive, params) {
|
|
275
|
+
var _a, e_1, _b, _c;
|
|
276
|
+
var _d;
|
|
277
|
+
const files = [];
|
|
278
|
+
try {
|
|
279
|
+
try {
|
|
280
|
+
for (var _e = true, _f = __asyncValues(handle.values()), _g; _g = await _f.next(), _a = _g.done, !_a; _e = true) {
|
|
281
|
+
_c = _g.value;
|
|
282
|
+
_e = false;
|
|
283
|
+
const entry = _c;
|
|
284
|
+
if (isFileHandle(entry)) {
|
|
285
|
+
const file = await entry.getFile();
|
|
286
|
+
const contents = await file.text();
|
|
287
|
+
const path = this._normalizePath(basePath, entry.name);
|
|
288
|
+
const contentType = (_d = params === null || params === void 0 ? void 0 : params.inferContentType) === null || _d === void 0 ? void 0 : _d.call(params, path).orDefault();
|
|
289
|
+
files.push({
|
|
290
|
+
path,
|
|
291
|
+
contents,
|
|
292
|
+
contentType
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
else if (isDirectoryHandle(entry) && recursive) {
|
|
296
|
+
const subDirPath = this._normalizePath(basePath, entry.name);
|
|
297
|
+
const subdirResult = await this._processDirectoryHandle(entry, subDirPath, recursive, params);
|
|
298
|
+
if (subdirResult.isFailure()) {
|
|
299
|
+
return subdirResult;
|
|
300
|
+
}
|
|
301
|
+
files.push(...subdirResult.value);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
306
|
+
finally {
|
|
307
|
+
try {
|
|
308
|
+
if (!_e && !_a && (_b = _f.return)) await _b.call(_f);
|
|
309
|
+
}
|
|
310
|
+
finally { if (e_1) throw e_1.error; }
|
|
311
|
+
}
|
|
312
|
+
return succeed(files);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
/* c8 ignore next 1 - defense in depth */
|
|
316
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
317
|
+
return fail(`Failed to process directory ${handle.name}: ${message}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
static _normalizePath(prefix, path) {
|
|
321
|
+
// Remove leading slash from prefix if it exists to avoid double slashes
|
|
322
|
+
const cleanPrefix = prefix ? prefix.replace(/^\/+/, '') : '';
|
|
323
|
+
const combined = cleanPrefix ? `${cleanPrefix}/${path}` : path;
|
|
324
|
+
// Normalize multiple slashes and ensure it starts with / for FileTree compatibility
|
|
325
|
+
const normalized = combined.replace(/\/+/g, '/').replace(/\/$/, '');
|
|
326
|
+
/* c8 ignore next 1 - tested but coverage intermittently missed */
|
|
327
|
+
return normalized.startsWith('/') ? normalized : `/${normalized}`;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
//# sourceMappingURL=fileApiTreeAccessors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileApiTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/fileApiTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;AAEH,0EAA0E;AAC1E,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,MAAM,eAA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AAC;IACpE,CAAC;CACF","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';\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 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 fileList - 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"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2025 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Browser-compatible FileTree implementations using the File API.
|
|
24
|
+
* @packageDocumentation
|
|
25
|
+
*/
|
|
26
|
+
export * from './fileApiTreeAccessors';
|
|
27
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AAEH,cAAc,wBAAwB,CAAC","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/**\n * Browser-compatible FileTree implementations using the File API.\n * @packageDocumentation\n */\n\nexport * from './fileApiTreeAccessors';\n"]}
|