@fgv/ts-web-extras 5.1.0-2 → 5.1.0-21
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 +208 -18
- package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/dist/packlets/file-tree/fileApiTreeAccessors.js +1 -1
- package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/dist/packlets/file-tree/httpTreeAccessors.js +72 -42
- package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/dist/ts-web-extras.d.ts +59 -7
- package/dist/tsdoc-metadata.json +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +52 -5
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.js +207 -17
- package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.js +1 -1
- package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts +6 -0
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.js +72 -42
- package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/package.json +27 -26
- package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +0 -75
- package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +0 -75
- package/.rush/temp/operation/build/all.log +0 -75
- package/.rush/temp/operation/build/error.log +0 -18
- package/.rush/temp/operation/build/log-chunks.jsonl +0 -75
- package/.rush/temp/operation/build/state.json +0 -3
- package/.rush/temp/operation/test/all.log +0 -75
- package/.rush/temp/operation/test/error.log +0 -18
- package/.rush/temp/operation/test/log-chunks.jsonl +0 -75
- package/.rush/temp/operation/test/state.json +0 -3
- package/.rush/temp/shrinkwrap-deps.json +0 -635
- package/CHANGELOG.md +0 -23
- package/config/api-extractor.json +0 -343
- package/config/jest.config.json +0 -19
- package/config/rig.json +0 -16
- package/config/typedoc.json +0 -6
- package/dist/test/mocks/idb-keyval.js +0 -6
- package/dist/test/mocks/idb-keyval.js.map +0 -1
- package/dist/test/setupTests.js +0 -74
- package/dist/test/setupTests.js.map +0 -1
- package/dist/test/unit/browserHashProvider.test.js +0 -140
- package/dist/test/unit/browserHashProvider.test.js.map +0 -1
- package/dist/test/unit/directoryHandleStore.test.js +0 -190
- package/dist/test/unit/directoryHandleStore.test.js.map +0 -1
- package/dist/test/unit/fileApiTreeAccessors.test.js +0 -1188
- package/dist/test/unit/fileApiTreeAccessors.test.js.map +0 -1
- package/dist/test/unit/fileApiTypes.test.js +0 -472
- package/dist/test/unit/fileApiTypes.test.js.map +0 -1
- package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +0 -622
- package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
- package/dist/test/unit/fileTreeHelpers.test.js +0 -590
- package/dist/test/unit/fileTreeHelpers.test.js.map +0 -1
- package/dist/test/unit/httpTreeAccessors.test.js +0 -1229
- package/dist/test/unit/httpTreeAccessors.test.js.map +0 -1
- package/dist/test/unit/localStorageTreeAccessors.test.js +0 -812
- package/dist/test/unit/localStorageTreeAccessors.test.js.map +0 -1
- package/dist/test/unit/urlParams.test.js +0 -393
- package/dist/test/unit/urlParams.test.js.map +0 -1
- package/dist/test/utils/fileSystemAccessMocks.js +0 -271
- package/dist/test/utils/fileSystemAccessMocks.js.map +0 -1
- package/dist/test/utils/testHelpers.js +0 -124
- package/dist/test/utils/testHelpers.js.map +0 -1
- package/docs/@fgv/namespaces/CryptoUtils/README.md +0 -18
- package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +0 -203
- package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +0 -63
- package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +0 -18
- package/docs/@fgv/namespaces/FileTreeHelpers/README.md +0 -19
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +0 -23
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +0 -23
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +0 -33
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +0 -33
- package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +0 -25
- package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +0 -11
- package/docs/README.md +0 -78
- package/docs/classes/DirectoryHandleStore.md +0 -116
- package/docs/classes/FileApiTreeAccessors.md +0 -286
- package/docs/classes/FileSystemAccessTreeAccessors.md +0 -557
- package/docs/classes/HttpTreeAccessors.md +0 -508
- package/docs/classes/LocalStorageTreeAccessors.md +0 -520
- package/docs/functions/exportAsJson.md +0 -23
- package/docs/functions/exportUsingFileSystemAPI.md +0 -26
- package/docs/functions/extractDirectoryPath.md +0 -23
- package/docs/functions/isDirectoryHandle.md +0 -23
- package/docs/functions/isFileHandle.md +0 -23
- package/docs/functions/isFilePath.md +0 -21
- package/docs/functions/parseContextFilter.md +0 -22
- package/docs/functions/parseQualifierDefaults.md +0 -22
- package/docs/functions/parseResourceTypes.md +0 -22
- package/docs/functions/parseUrlParameters.md +0 -15
- package/docs/functions/safeShowDirectoryPicker.md +0 -24
- package/docs/functions/safeShowOpenFilePicker.md +0 -24
- package/docs/functions/safeShowSaveFilePicker.md +0 -24
- package/docs/functions/supportsFileSystemAccess.md +0 -23
- package/docs/interfaces/FilePickerAcceptType.md +0 -16
- package/docs/interfaces/FileSystemCreateWritableOptions.md +0 -15
- package/docs/interfaces/FileSystemDirectoryHandle.md +0 -187
- package/docs/interfaces/FileSystemFileHandle.md +0 -106
- package/docs/interfaces/FileSystemGetDirectoryOptions.md +0 -15
- package/docs/interfaces/FileSystemGetFileOptions.md +0 -15
- package/docs/interfaces/FileSystemHandle.md +0 -69
- package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +0 -15
- package/docs/interfaces/FileSystemRemoveOptions.md +0 -15
- package/docs/interfaces/FileSystemWritableFileStream.md +0 -127
- package/docs/interfaces/IDirectoryHandleTreeInitializer.md +0 -17
- package/docs/interfaces/IFileHandleTreeInitializer.md +0 -16
- package/docs/interfaces/IFileListTreeInitializer.md +0 -15
- package/docs/interfaces/IFileMetadata.md +0 -19
- package/docs/interfaces/IFileSystemAccessTreeParams.md +0 -30
- package/docs/interfaces/IFsAccessApis.md +0 -57
- package/docs/interfaces/IHttpTreeParams.md +0 -32
- package/docs/interfaces/ILocalStorageTreeParams.md +0 -30
- package/docs/interfaces/IUrlConfigOptions.md +0 -27
- package/docs/interfaces/ShowDirectoryPickerOptions.md +0 -17
- package/docs/interfaces/ShowOpenFilePickerOptions.md +0 -19
- package/docs/interfaces/ShowSaveFilePickerOptions.md +0 -19
- package/docs/type-aliases/TreeInitializer.md +0 -11
- package/docs/type-aliases/WellKnownDirectory.md +0 -11
- package/docs/type-aliases/WindowWithFsAccess.md +0 -11
- package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +0 -11
- package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +0 -11
- package/etc/ts-web-extras.api.md +0 -433
- package/lib/test/mocks/idb-keyval.d.ts +0 -6
- package/lib/test/mocks/idb-keyval.d.ts.map +0 -1
- package/lib/test/mocks/idb-keyval.js +0 -9
- package/lib/test/mocks/idb-keyval.js.map +0 -1
- package/lib/test/setupTests.d.ts +0 -2
- package/lib/test/setupTests.d.ts.map +0 -1
- package/lib/test/setupTests.js +0 -76
- package/lib/test/setupTests.js.map +0 -1
- package/lib/test/unit/browserHashProvider.test.d.ts +0 -2
- package/lib/test/unit/browserHashProvider.test.d.ts.map +0 -1
- package/lib/test/unit/browserHashProvider.test.js +0 -142
- package/lib/test/unit/browserHashProvider.test.js.map +0 -1
- package/lib/test/unit/directoryHandleStore.test.d.ts +0 -2
- package/lib/test/unit/directoryHandleStore.test.d.ts.map +0 -1
- package/lib/test/unit/directoryHandleStore.test.js +0 -192
- package/lib/test/unit/directoryHandleStore.test.js.map +0 -1
- package/lib/test/unit/fileApiTreeAccessors.test.d.ts +0 -2
- package/lib/test/unit/fileApiTreeAccessors.test.d.ts.map +0 -1
- package/lib/test/unit/fileApiTreeAccessors.test.js +0 -1190
- package/lib/test/unit/fileApiTreeAccessors.test.js.map +0 -1
- package/lib/test/unit/fileApiTypes.test.d.ts +0 -2
- package/lib/test/unit/fileApiTypes.test.d.ts.map +0 -1
- package/lib/test/unit/fileApiTypes.test.js +0 -474
- package/lib/test/unit/fileApiTypes.test.js.map +0 -1
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +0 -2
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +0 -1
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +0 -624
- package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
- package/lib/test/unit/fileTreeHelpers.test.d.ts +0 -2
- package/lib/test/unit/fileTreeHelpers.test.d.ts.map +0 -1
- package/lib/test/unit/fileTreeHelpers.test.js +0 -592
- package/lib/test/unit/fileTreeHelpers.test.js.map +0 -1
- package/lib/test/unit/httpTreeAccessors.test.d.ts +0 -2
- package/lib/test/unit/httpTreeAccessors.test.d.ts.map +0 -1
- package/lib/test/unit/httpTreeAccessors.test.js +0 -1231
- package/lib/test/unit/httpTreeAccessors.test.js.map +0 -1
- package/lib/test/unit/localStorageTreeAccessors.test.d.ts +0 -2
- package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +0 -1
- package/lib/test/unit/localStorageTreeAccessors.test.js +0 -814
- package/lib/test/unit/localStorageTreeAccessors.test.js.map +0 -1
- package/lib/test/unit/urlParams.test.d.ts +0 -2
- package/lib/test/unit/urlParams.test.d.ts.map +0 -1
- package/lib/test/unit/urlParams.test.js +0 -395
- package/lib/test/unit/urlParams.test.js.map +0 -1
- package/lib/test/utils/fileSystemAccessMocks.d.ts +0 -53
- package/lib/test/utils/fileSystemAccessMocks.d.ts.map +0 -1
- package/lib/test/utils/fileSystemAccessMocks.js +0 -277
- package/lib/test/utils/fileSystemAccessMocks.js.map +0 -1
- package/lib/test/utils/testHelpers.d.ts +0 -51
- package/lib/test/utils/testHelpers.d.ts.map +0 -1
- package/lib/test/utils/testHelpers.js +0 -133
- package/lib/test/utils/testHelpers.js.map +0 -1
- package/rush-logs/ts-web-extras.build.cache.log +0 -0
- package/rush-logs/ts-web-extras.build.error.log +0 -18
- package/rush-logs/ts-web-extras.build.log +0 -75
- package/rush-logs/ts-web-extras.test.cache.log +0 -1
- package/rush-logs/ts-web-extras.test.error.log +0 -18
- package/rush-logs/ts-web-extras.test.log +0 -75
- package/src/index.browser.ts +0 -24
- package/src/index.ts +0 -47
- package/src/packlets/crypto-utils/browserCryptoProvider.ts +0 -311
- package/src/packlets/crypto-utils/browserHashProvider.ts +0 -73
- package/src/packlets/crypto-utils/index.ts +0 -29
- package/src/packlets/file-api-types/index.ts +0 -366
- package/src/packlets/file-tree/directoryHandleStore.ts +0 -136
- package/src/packlets/file-tree/fileApiTreeAccessors.ts +0 -528
- package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +0 -519
- package/src/packlets/file-tree/httpTreeAccessors.ts +0 -448
- package/src/packlets/file-tree/index.ts +0 -32
- package/src/packlets/file-tree/localStorageTreeAccessors.ts +0 -430
- package/src/packlets/helpers/fileTreeHelpers.ts +0 -107
- package/src/packlets/helpers/index.ts +0 -28
- package/src/packlets/url-utils/index.ts +0 -28
- package/src/packlets/url-utils/urlParams.ts +0 -245
- package/src/test/mocks/idb-keyval.ts +0 -5
- package/src/test/setupTests.ts +0 -87
- package/src/test/unit/browserHashProvider.test.ts +0 -155
- package/src/test/unit/browserHashProvider.test.ts.bak +0 -376
- package/src/test/unit/directoryHandleStore.test.ts +0 -251
- package/src/test/unit/fileApiTreeAccessors.test.ts +0 -1387
- package/src/test/unit/fileApiTypes.test.ts +0 -587
- package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +0 -885
- package/src/test/unit/fileTreeHelpers.test.ts +0 -694
- package/src/test/unit/httpTreeAccessors.test.ts +0 -1571
- package/src/test/unit/localStorageTreeAccessors.test.ts +0 -1014
- package/src/test/unit/urlParams.test.ts +0 -464
- package/src/test/utils/fileSystemAccessMocks.ts +0 -353
- package/src/test/utils/testHelpers.ts +0 -155
- package/temp/build/typescript/ts_8nwakTlr.json +0 -1
- package/temp/coverage/base.css +0 -224
- package/temp/coverage/block-navigation.js +0 -87
- package/temp/coverage/crypto/browserHashProvider.ts.html +0 -304
- package/temp/coverage/crypto/index.html +0 -116
- package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +0 -1018
- package/temp/coverage/crypto-utils/browserHashProvider.ts.html +0 -304
- package/temp/coverage/crypto-utils/index.html +0 -131
- package/temp/coverage/favicon.png +0 -0
- package/temp/coverage/file-tree/directoryHandleStore.ts.html +0 -493
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +0 -1669
- package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
- package/temp/coverage/file-tree/httpTreeAccessors.ts.html +0 -1429
- package/temp/coverage/file-tree/index.html +0 -176
- package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +0 -1375
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +0 -406
- package/temp/coverage/helpers/index.html +0 -116
- package/temp/coverage/index.html +0 -161
- package/temp/coverage/lcov-report/base.css +0 -224
- package/temp/coverage/lcov-report/block-navigation.js +0 -87
- package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +0 -304
- package/temp/coverage/lcov-report/crypto/index.html +0 -116
- package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +0 -1018
- package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +0 -304
- package/temp/coverage/lcov-report/crypto-utils/index.html +0 -131
- package/temp/coverage/lcov-report/favicon.png +0 -0
- package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +0 -493
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +0 -1669
- package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
- package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +0 -1429
- package/temp/coverage/lcov-report/file-tree/index.html +0 -176
- package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +0 -1375
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +0 -406
- package/temp/coverage/lcov-report/helpers/index.html +0 -116
- package/temp/coverage/lcov-report/index.html +0 -161
- package/temp/coverage/lcov-report/prettify.css +0 -1
- package/temp/coverage/lcov-report/prettify.js +0 -2
- package/temp/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/temp/coverage/lcov-report/sorter.js +0 -210
- package/temp/coverage/lcov-report/url-utils/index.html +0 -116
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +0 -820
- package/temp/coverage/lcov.info +0 -3597
- package/temp/coverage/prettify.css +0 -1
- package/temp/coverage/prettify.js +0 -2
- package/temp/coverage/sort-arrow-sprite.png +0 -0
- package/temp/coverage/sorter.js +0 -210
- package/temp/coverage/url-utils/index.html +0 -116
- package/temp/coverage/url-utils/urlParams.ts.html +0 -820
- package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
- package/temp/test/jest/jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5 +0 -53
- package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
- package/temp/ts-web-extras.api.json +0 -8850
- package/temp/ts-web-extras.api.md +0 -433
- package/tsconfig.json +0 -7
|
@@ -21,10 +21,9 @@
|
|
|
21
21
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
22
|
exports.BrowserCryptoProvider = void 0;
|
|
23
23
|
exports.createBrowserCryptoProvider = createBrowserCryptoProvider;
|
|
24
|
-
/* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */
|
|
25
24
|
const ts_utils_1 = require("@fgv/ts-utils");
|
|
26
25
|
const ts_extras_1 = require("@fgv/ts-extras");
|
|
27
|
-
|
|
26
|
+
/* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */
|
|
28
27
|
/**
|
|
29
28
|
* Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.
|
|
30
29
|
* @param arr - The Uint8Array to extract from
|
|
@@ -36,6 +35,24 @@ function toArrayBuffer(arr) {
|
|
|
36
35
|
new Uint8Array(buffer).set(arr);
|
|
37
36
|
return buffer;
|
|
38
37
|
}
|
|
38
|
+
/* c8 ignore stop */
|
|
39
|
+
/**
|
|
40
|
+
* Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.
|
|
41
|
+
* Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and
|
|
42
|
+
* {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's
|
|
43
|
+
* webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`
|
|
44
|
+
* parameters with "is not instance of ArrayBuffer, Buffer, TypedArray, or
|
|
45
|
+
* DataView" even though `ArrayBuffer` should be valid per the spec; a
|
|
46
|
+
* TypedArray view is accepted on Node 20+ and on browsers, and the explicit
|
|
47
|
+
* `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`
|
|
48
|
+
* (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).
|
|
49
|
+
*/
|
|
50
|
+
function toBufferView(arr) {
|
|
51
|
+
const buffer = new ArrayBuffer(arr.byteLength);
|
|
52
|
+
const view = new Uint8Array(buffer);
|
|
53
|
+
view.set(arr);
|
|
54
|
+
return view;
|
|
55
|
+
}
|
|
39
56
|
/**
|
|
40
57
|
* Browser implementation of `ICryptoProvider` using the Web Crypto API.
|
|
41
58
|
* Uses AES-256-GCM for authenticated encryption.
|
|
@@ -46,6 +63,7 @@ function toArrayBuffer(arr) {
|
|
|
46
63
|
* @public
|
|
47
64
|
*/
|
|
48
65
|
class BrowserCryptoProvider {
|
|
66
|
+
/* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */
|
|
49
67
|
/**
|
|
50
68
|
* Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
|
|
51
69
|
* @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)
|
|
@@ -71,12 +89,12 @@ class BrowserCryptoProvider {
|
|
|
71
89
|
* @returns `Success` with encryption result, or `Failure` with an error.
|
|
72
90
|
*/
|
|
73
91
|
async encrypt(plaintext, key) {
|
|
74
|
-
if (key.length !==
|
|
75
|
-
return ts_utils_1.Failure.with(`Key must be ${
|
|
92
|
+
if (key.length !== ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE) {
|
|
93
|
+
return ts_utils_1.Failure.with(`Key must be ${ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
76
94
|
}
|
|
77
95
|
try {
|
|
78
96
|
// Generate random IV
|
|
79
|
-
const iv = this._crypto.getRandomValues(new Uint8Array(
|
|
97
|
+
const iv = this._crypto.getRandomValues(new Uint8Array(ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE));
|
|
80
98
|
// Import the key
|
|
81
99
|
const cryptoKey = await this._crypto.subtle.importKey('raw', toArrayBuffer(key), { name: 'AES-GCM' }, false, ['encrypt']);
|
|
82
100
|
// Encode plaintext to bytes
|
|
@@ -86,12 +104,12 @@ class BrowserCryptoProvider {
|
|
|
86
104
|
const encryptedWithTag = await this._crypto.subtle.encrypt({
|
|
87
105
|
name: 'AES-GCM',
|
|
88
106
|
iv: iv,
|
|
89
|
-
tagLength:
|
|
107
|
+
tagLength: ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
|
|
90
108
|
}, cryptoKey, plaintextBytes);
|
|
91
109
|
// Split ciphertext and auth tag (auth tag is last 16 bytes)
|
|
92
110
|
const encryptedArray = new Uint8Array(encryptedWithTag);
|
|
93
|
-
const encryptedData = encryptedArray.slice(0, encryptedArray.length -
|
|
94
|
-
const authTag = encryptedArray.slice(encryptedArray.length -
|
|
111
|
+
const encryptedData = encryptedArray.slice(0, encryptedArray.length - ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);
|
|
112
|
+
const authTag = encryptedArray.slice(encryptedArray.length - ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);
|
|
95
113
|
return ts_utils_1.Success.with({
|
|
96
114
|
iv,
|
|
97
115
|
authTag,
|
|
@@ -112,14 +130,14 @@ class BrowserCryptoProvider {
|
|
|
112
130
|
* @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.
|
|
113
131
|
*/
|
|
114
132
|
async decrypt(encryptedData, key, iv, authTag) {
|
|
115
|
-
if (key.length !==
|
|
116
|
-
return ts_utils_1.Failure.with(`Key must be ${
|
|
133
|
+
if (key.length !== ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE) {
|
|
134
|
+
return ts_utils_1.Failure.with(`Key must be ${ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
117
135
|
}
|
|
118
|
-
if (iv.length !==
|
|
119
|
-
return ts_utils_1.Failure.with(`IV must be ${
|
|
136
|
+
if (iv.length !== ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE) {
|
|
137
|
+
return ts_utils_1.Failure.with(`IV must be ${ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);
|
|
120
138
|
}
|
|
121
|
-
if (authTag.length !==
|
|
122
|
-
return ts_utils_1.Failure.with(`Auth tag must be ${
|
|
139
|
+
if (authTag.length !== ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
|
|
140
|
+
return ts_utils_1.Failure.with(`Auth tag must be ${ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);
|
|
123
141
|
}
|
|
124
142
|
try {
|
|
125
143
|
// Import the key
|
|
@@ -132,7 +150,7 @@ class BrowserCryptoProvider {
|
|
|
132
150
|
const decrypted = await this._crypto.subtle.decrypt({
|
|
133
151
|
name: 'AES-GCM',
|
|
134
152
|
iv: toArrayBuffer(iv),
|
|
135
|
-
tagLength:
|
|
153
|
+
tagLength: ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
|
|
136
154
|
}, cryptoKey, encryptedWithTag);
|
|
137
155
|
// Decode to string
|
|
138
156
|
const decoder = new TextDecoder();
|
|
@@ -149,7 +167,7 @@ class BrowserCryptoProvider {
|
|
|
149
167
|
*/
|
|
150
168
|
async generateKey() {
|
|
151
169
|
try {
|
|
152
|
-
return ts_utils_1.Success.with(this._crypto.getRandomValues(new Uint8Array(
|
|
170
|
+
return ts_utils_1.Success.with(this._crypto.getRandomValues(new Uint8Array(ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE)));
|
|
153
171
|
}
|
|
154
172
|
catch (e) {
|
|
155
173
|
const message = e instanceof Error ? e.message : String(e);
|
|
@@ -184,7 +202,7 @@ class BrowserCryptoProvider {
|
|
|
184
202
|
salt: toArrayBuffer(salt),
|
|
185
203
|
iterations: iterations,
|
|
186
204
|
hash: 'SHA-256'
|
|
187
|
-
}, keyMaterial,
|
|
205
|
+
}, keyMaterial, ts_extras_1.CryptoUtils.Constants.AES_256_KEY_SIZE * 8 // bits
|
|
188
206
|
);
|
|
189
207
|
return ts_utils_1.Success.with(new Uint8Array(derivedBits));
|
|
190
208
|
}
|
|
@@ -193,6 +211,27 @@ class BrowserCryptoProvider {
|
|
|
193
211
|
return ts_utils_1.Failure.with(`Key derivation failed: ${message}`);
|
|
194
212
|
}
|
|
195
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Computes a SHA-256 hash of the given data.
|
|
216
|
+
* @param data - UTF-8 string to hash
|
|
217
|
+
* @returns `Success` with hex-encoded hash string, or `Failure` with an error.
|
|
218
|
+
*/
|
|
219
|
+
async sha256(data) {
|
|
220
|
+
try {
|
|
221
|
+
const encoder = new TextEncoder();
|
|
222
|
+
const dataBuffer = encoder.encode(data);
|
|
223
|
+
const hashBuffer = await this._crypto.subtle.digest('SHA-256', dataBuffer);
|
|
224
|
+
const hashArray = new Uint8Array(hashBuffer);
|
|
225
|
+
const hashHex = Array.from(hashArray)
|
|
226
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
227
|
+
.join('');
|
|
228
|
+
return (0, ts_utils_1.succeed)(hashHex);
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
232
|
+
return (0, ts_utils_1.fail)(`SHA-256 hash failed: ${message}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
196
235
|
// ============================================================================
|
|
197
236
|
// Platform Utility Methods
|
|
198
237
|
// ============================================================================
|
|
@@ -244,8 +283,159 @@ class BrowserCryptoProvider {
|
|
|
244
283
|
return ts_utils_1.Failure.with('Invalid base64 string');
|
|
245
284
|
}
|
|
246
285
|
}
|
|
286
|
+
// ============================================================================
|
|
287
|
+
// Asymmetric Key Operations
|
|
288
|
+
// ============================================================================
|
|
289
|
+
/**
|
|
290
|
+
* Generates a new asymmetric keypair via Web Crypto.
|
|
291
|
+
* @param algorithm - The algorithm to use.
|
|
292
|
+
* @param extractable - Whether the resulting keys may be exported.
|
|
293
|
+
* @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
294
|
+
*/
|
|
295
|
+
async generateKeyPair(algorithm, extractable) {
|
|
296
|
+
const params = ts_extras_1.CryptoUtils.keyPairAlgorithmParams[algorithm];
|
|
297
|
+
// Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's
|
|
298
|
+
// broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and
|
|
299
|
+
// returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`
|
|
300
|
+
// is a runtime check via the `in` operator, not a type assertion.
|
|
301
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(async () => {
|
|
302
|
+
const generated = await this._crypto.subtle.generateKey(params.generateKey, extractable, [...params.keyPairUsages]);
|
|
303
|
+
if ('privateKey' in generated && 'publicKey' in generated) {
|
|
304
|
+
return generated;
|
|
305
|
+
}
|
|
306
|
+
/* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */
|
|
307
|
+
throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);
|
|
308
|
+
});
|
|
309
|
+
return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Exports a public `CryptoKey` as a JSON Web Key.
|
|
313
|
+
* @remarks
|
|
314
|
+
* Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
|
|
315
|
+
* does not enforce public-vs-private; without this guard a caller that
|
|
316
|
+
* passed an extractable private key would receive its private fields
|
|
317
|
+
* (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
|
|
318
|
+
* @param publicKey - Extractable public key to export.
|
|
319
|
+
* @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
320
|
+
*/
|
|
321
|
+
async exportPublicKeyJwk(publicKey) {
|
|
322
|
+
if (publicKey.type !== 'public') {
|
|
323
|
+
return ts_utils_1.Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);
|
|
324
|
+
}
|
|
325
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(() => this._crypto.subtle.exportKey('jwk', publicKey));
|
|
326
|
+
return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
330
|
+
* @param jwk - The JSON Web Key produced by a prior export.
|
|
331
|
+
* @param algorithm - The algorithm the key was generated for.
|
|
332
|
+
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
|
|
333
|
+
*/
|
|
334
|
+
async importPublicKeyJwk(jwk, algorithm) {
|
|
335
|
+
const params = ts_extras_1.CryptoUtils.keyPairAlgorithmParams[algorithm];
|
|
336
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(() => this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages));
|
|
337
|
+
return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
|
|
338
|
+
}
|
|
339
|
+
/* c8 ignore stop */
|
|
340
|
+
/**
|
|
341
|
+
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
342
|
+
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
343
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
|
|
344
|
+
* @param plaintext - The bytes to wrap.
|
|
345
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
346
|
+
* @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
347
|
+
* @returns `Success` with the wrapped payload, or `Failure` with an error.
|
|
348
|
+
*/
|
|
349
|
+
async wrapBytes(plaintext, recipientPublicKey, options) {
|
|
350
|
+
const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
|
|
351
|
+
if (recipientCheck.isFailure()) {
|
|
352
|
+
return ts_utils_1.Failure.with(`wrapBytes failed: ${recipientCheck.message}`);
|
|
353
|
+
}
|
|
354
|
+
const subtle = this._crypto.subtle;
|
|
355
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(async () => {
|
|
356
|
+
const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
|
|
357
|
+
'deriveKey'
|
|
358
|
+
]));
|
|
359
|
+
const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: recipientPublicKey }, ephemeral.privateKey, { name: 'HKDF' }, false, ['deriveKey']);
|
|
360
|
+
const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
|
|
361
|
+
const nonce = this._crypto.getRandomValues(new Uint8Array(ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE));
|
|
362
|
+
const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));
|
|
363
|
+
const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
|
|
364
|
+
return {
|
|
365
|
+
ephemeralPublicKey,
|
|
366
|
+
nonce: this.toBase64(nonce),
|
|
367
|
+
ciphertext: this.toBase64(new Uint8Array(ctBuf))
|
|
368
|
+
};
|
|
369
|
+
});
|
|
370
|
+
return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Unwraps a payload produced by `wrapBytes` using the recipient's private
|
|
374
|
+
* key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
|
|
375
|
+
* @param wrapped - The wrapped payload.
|
|
376
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
|
|
377
|
+
* @param options - HKDF salt and info matching the wrap call.
|
|
378
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with an error.
|
|
379
|
+
*/
|
|
380
|
+
async unwrapBytes(wrapped, recipientPrivateKey, options) {
|
|
381
|
+
const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
|
|
382
|
+
if (recipientCheck.isFailure()) {
|
|
383
|
+
return ts_utils_1.Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);
|
|
384
|
+
}
|
|
385
|
+
const nonceResult = this.fromBase64(wrapped.nonce);
|
|
386
|
+
if (nonceResult.isFailure()) {
|
|
387
|
+
return ts_utils_1.Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);
|
|
388
|
+
}
|
|
389
|
+
if (nonceResult.value.length !== ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE) {
|
|
390
|
+
return ts_utils_1.Failure.with(`unwrapBytes failed: nonce must be ${ts_extras_1.CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`);
|
|
391
|
+
}
|
|
392
|
+
const ciphertextResult = this.fromBase64(wrapped.ciphertext);
|
|
393
|
+
if (ciphertextResult.isFailure()) {
|
|
394
|
+
return ts_utils_1.Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
|
|
395
|
+
}
|
|
396
|
+
if (ciphertextResult.value.length < ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
|
|
397
|
+
return ts_utils_1.Failure.with(`unwrapBytes failed: ciphertext must be at least ${ts_extras_1.CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`);
|
|
398
|
+
}
|
|
399
|
+
const subtle = this._crypto.subtle;
|
|
400
|
+
const result = await (0, ts_utils_1.captureAsyncResult)(async () => {
|
|
401
|
+
const ephemeralPub = await subtle.importKey('jwk', wrapped.ephemeralPublicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
|
|
402
|
+
const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: ephemeralPub }, recipientPrivateKey, { name: 'HKDF' }, false, ['deriveKey']);
|
|
403
|
+
const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
|
|
404
|
+
const ptBuf = await subtle.decrypt({ name: 'AES-GCM', iv: toBufferView(nonceResult.value) }, wrapKey, toBufferView(ciphertextResult.value));
|
|
405
|
+
return new Uint8Array(ptBuf);
|
|
406
|
+
});
|
|
407
|
+
return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
|
|
408
|
+
}
|
|
247
409
|
}
|
|
248
410
|
exports.BrowserCryptoProvider = BrowserCryptoProvider;
|
|
411
|
+
/**
|
|
412
|
+
* Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
|
|
413
|
+
* (public or private). Used by the wrap/unwrap methods to surface a clean
|
|
414
|
+
* `Failure` instead of letting the WebCrypto deriveKey call throw a less
|
|
415
|
+
* informative error later in the pipeline. Key usages are intentionally not
|
|
416
|
+
* checked here: WebCrypto already produces a specific error if `deriveKey` is
|
|
417
|
+
* not in `usages`, and `deriveBits` is an equally valid alternative usage that
|
|
418
|
+
* an explicit check would have to track.
|
|
419
|
+
* @param key - The CryptoKey to validate.
|
|
420
|
+
* @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
|
|
421
|
+
* @param label - Human-readable role label included in the failure message.
|
|
422
|
+
* @returns `Success` with the key (unchanged) when the algorithm, curve, and
|
|
423
|
+
* type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
|
|
424
|
+
*/
|
|
425
|
+
function checkEcdhP256(key, keyType, label) {
|
|
426
|
+
if (key.algorithm.name !== 'ECDH') {
|
|
427
|
+
return ts_utils_1.Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
|
|
428
|
+
}
|
|
429
|
+
const namedCurve = key.algorithm.namedCurve;
|
|
430
|
+
if (namedCurve !== 'P-256') {
|
|
431
|
+
return ts_utils_1.Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
|
|
432
|
+
}
|
|
433
|
+
if (key.type !== keyType) {
|
|
434
|
+
return ts_utils_1.Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
|
|
435
|
+
}
|
|
436
|
+
return (0, ts_utils_1.succeed)(key);
|
|
437
|
+
}
|
|
438
|
+
/* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */
|
|
249
439
|
/**
|
|
250
440
|
* Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web
|
|
251
441
|
* Crypto API is available.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browserCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserCryptoProvider.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AAiSZ,kEAEC;AAjSD,2FAA2F;AAC3F,4CAAwE;AACxE,8CAA6C;AAI7C,MAAM,eAAe,GAAG,uBAAW,CAAC,SAAS,CAAC;AAE9C;;;;GAIG;AACH,SAAS,aAAa,CAAC,GAAe;IACpC,mGAAmG;IACnG,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAa,qBAAqB;IAGhC;;;OAGG;IACH,YAAmB,SAAkB;QACnC,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QAC3B,CAAC;aAAM,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,UAAU,CAAC,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AAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACI,UAAU,CAAC,MAAc;QAC9B,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5B,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACvC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,kBAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,kBAAO,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF;AA1PD,sDA0PC;AAED;;;;;GAKG;AACH,SAAgB,2BAA2B;IACzC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC;AAC1D,CAAC;AACD,oBAAoB","sourcesContent":["// Copyright (c) 2024 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/* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */\nimport { captureResult, Failure, Result, Success } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\ntype ICryptoProvider = CryptoUtils.ICryptoProvider;\ntype IEncryptionResult = CryptoUtils.IEncryptionResult;\nconst CryptoConstants = CryptoUtils.Constants;\n\n/**\n * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.\n * @param arr - The Uint8Array to extract from\n * @returns An `ArrayBuffer` containing a copy of the data.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer\n const buffer = new ArrayBuffer(arr.byteLength);\n new Uint8Array(buffer).set(arr);\n return buffer;\n}\n\n/**\n * Browser implementation of `ICryptoProvider` using the Web Crypto API.\n * Uses AES-256-GCM for authenticated encryption.\n *\n * Note: This provider requires a browser environment with Web Crypto API support.\n * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.\n *\n * @public\n */\nexport class BrowserCryptoProvider implements ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /**\n * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.\n * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)\n */\n public constructor(cryptoApi?: Crypto) {\n if (cryptoApi) {\n this._crypto = cryptoApi;\n } else if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n this._crypto = globalThis.crypto;\n } else if (typeof window !== 'undefined' && window.crypto) {\n this._crypto = window.crypto;\n } else {\n throw new Error('Web Crypto API not available');\n }\n }\n\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoConstants.GCM_IV_SIZE));\n\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n\n // Encode plaintext to bytes\n const encoder = new TextEncoder();\n const plaintextBytes = encoder.encode(plaintext);\n\n // Encrypt (Web Crypto appends auth tag to ciphertext)\n const encryptedWithTag = await this._crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n plaintextBytes\n );\n\n // Split ciphertext and auth tag (auth tag is last 16 bytes)\n const encryptedArray = new Uint8Array(encryptedWithTag);\n const encryptedData = encryptedArray.slice(\n 0,\n encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);\n return Success.with({\n iv,\n authTag,\n encryptedData\n });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Encryption failed: ${message}`);\n }\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoConstants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoConstants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoConstants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoConstants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n\n try {\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n\n // Web Crypto expects ciphertext + auth tag concatenated\n const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);\n encryptedWithTag.set(encryptedData);\n encryptedWithTag.set(authTag, encryptedData.length);\n\n // Decrypt\n const decrypted = await this._crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(iv),\n tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n encryptedWithTag\n );\n\n // Decode to string\n const decoder = new TextDecoder();\n return Success.with(decoder.decode(decrypted));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Decryption failed: ${message}`);\n }\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoConstants.AES_256_KEY_SIZE)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key generation failed: ${message}`);\n }\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return Failure.with('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return Failure.with('Salt should be at least 8 bytes');\n }\n\n try {\n // Encode password\n const encoder = new TextEncoder();\n const passwordBytes = encoder.encode(password);\n\n // Import password as key material\n const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [\n 'deriveBits'\n ]);\n\n // Derive key bits\n const derivedBits = await this._crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: toArrayBuffer(salt),\n iterations: iterations,\n hash: 'SHA-256'\n },\n keyMaterial,\n CryptoConstants.AES_256_KEY_SIZE * 8 // bits\n );\n\n return Success.with(new Uint8Array(derivedBits));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key derivation failed: ${message}`);\n }\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Random bytes generation failed: ${message}`);\n }\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n // Convert Uint8Array to binary string, then to base64\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n try {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return Success.with(bytes);\n } catch (e) {\n return Failure.with('Invalid base64 string');\n }\n }\n}\n\n/**\n * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web\n * Crypto API is available.\n * @returns `Success` with provider, or `Failure` if not available\n * @public\n */\nexport function createBrowserCryptoProvider(): Result<BrowserCryptoProvider> {\n return captureResult(() => new BrowserCryptoProvider());\n}\n/* c8 ignore stop */\n"]}
|
|
1
|
+
{"version":3,"file":"browserCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/browserCryptoProvider.ts"],"names":[],"mappings":";AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;AAgiBZ,kEAEC;AAhiBD,4CAA2G;AAC3G,8CAA6C;AAE7C,sGAAsG;AACtG;;;;GAIG;AACH,SAAS,aAAa,CAAC,GAAe;IACpC,mGAAmG;IACnG,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,oBAAoB;AAEpB;;;;;;;;;;GAUG;AACH,SAAS,YAAY,CAAC,GAAe;IACnC,MAA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uC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7F,CAAC;IACD,MAAM,UAAU,GAAI,GAAG,CAAC,SAA4B,CAAC,UAAU,CAAC;IAChE,IAAI,UAAU,KAAK,OAAO,EAAE,CAAC;QAC3B,OAAO,kBAAO,CAAC,IAAI,CAAC,GAAG,KAAK,mCAAmC,UAAU,IAAI,CAAC,CAAC;IACjF,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,kBAAO,CAAC,IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED,4FAA4F;AAC5F;;;;;GAKG;AACH,SAAgB,2BAA2B;IACzC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,qBAAqB,EAAE,CAAC,CAAC;AAC1D,CAAC;AACD,oBAAoB","sourcesContent":["// Copyright (c) 2024 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\nimport { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';\nimport { CryptoUtils } from '@fgv/ts-extras';\n\n/* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */\n/**\n * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.\n * @param arr - The Uint8Array to extract from\n * @returns An `ArrayBuffer` containing a copy of the data.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n // Create a new ArrayBuffer and copy the data - this handles both ArrayBuffer and SharedArrayBuffer\n const buffer = new ArrayBuffer(arr.byteLength);\n new Uint8Array(buffer).set(arr);\n return buffer;\n}\n/* c8 ignore stop */\n\n/**\n * Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.\n * Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and\n * {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's\n * webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`\n * parameters with \"is not instance of ArrayBuffer, Buffer, TypedArray, or\n * DataView\" even though `ArrayBuffer` should be valid per the spec; a\n * TypedArray view is accepted on Node 20+ and on browsers, and the explicit\n * `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`\n * (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).\n */\nfunction toBufferView(arr: Uint8Array): Uint8Array<ArrayBuffer> {\n const buffer = new ArrayBuffer(arr.byteLength);\n const view = new Uint8Array(buffer);\n view.set(arr);\n return view;\n}\n\n/**\n * Browser implementation of `ICryptoProvider` using the Web Crypto API.\n * Uses AES-256-GCM for authenticated encryption.\n *\n * Note: This provider requires a browser environment with Web Crypto API support.\n * In Node.js 15+, Web Crypto is available via globalThis.crypto or require('crypto').webcrypto.\n *\n * @public\n */\nexport class BrowserCryptoProvider implements CryptoUtils.ICryptoProvider {\n private readonly _crypto: Crypto;\n\n /* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */\n /**\n * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.\n * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)\n */\n public constructor(cryptoApi?: Crypto) {\n if (cryptoApi) {\n this._crypto = cryptoApi;\n } else if (typeof globalThis !== 'undefined' && globalThis.crypto) {\n this._crypto = globalThis.crypto;\n } else if (typeof window !== 'undefined' && window.crypto) {\n this._crypto = window.crypto;\n } else {\n throw new Error('Web Crypto API not available');\n }\n }\n\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<CryptoUtils.IEncryptionResult>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n try {\n // Generate random IV\n const iv = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));\n\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['encrypt']\n );\n\n // Encode plaintext to bytes\n const encoder = new TextEncoder();\n const plaintextBytes = encoder.encode(plaintext);\n\n // Encrypt (Web Crypto appends auth tag to ciphertext)\n const encryptedWithTag = await this._crypto.subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: iv,\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n plaintextBytes\n );\n\n // Split ciphertext and auth tag (auth tag is last 16 bytes)\n const encryptedArray = new Uint8Array(encryptedWithTag);\n const encryptedData = encryptedArray.slice(\n 0,\n encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE\n );\n const authTag = encryptedArray.slice(encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);\n return Success.with({\n iv,\n authTag,\n encryptedData\n });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Encryption failed: ${message}`);\n }\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {\n return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(`IV must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `Auth tag must be ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`\n );\n }\n\n try {\n // Import the key\n const cryptoKey = await this._crypto.subtle.importKey(\n 'raw',\n toArrayBuffer(key),\n { name: 'AES-GCM' },\n false,\n ['decrypt']\n );\n\n // Web Crypto expects ciphertext + auth tag concatenated\n const encryptedWithTag = new Uint8Array(encryptedData.length + authTag.length);\n encryptedWithTag.set(encryptedData);\n encryptedWithTag.set(authTag, encryptedData.length);\n\n // Decrypt\n const decrypted = await this._crypto.subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(iv),\n tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits\n },\n cryptoKey,\n encryptedWithTag\n );\n\n // Decode to string\n const decoder = new TextDecoder();\n return Success.with(decoder.decode(decrypted));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Decryption failed: ${message}`);\n }\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n try {\n return Success.with(\n this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.AES_256_KEY_SIZE))\n );\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key generation failed: ${message}`);\n }\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return Failure.with('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return Failure.with('Salt should be at least 8 bytes');\n }\n\n try {\n // Encode password\n const encoder = new TextEncoder();\n const passwordBytes = encoder.encode(password);\n\n // Import password as key material\n const keyMaterial = await this._crypto.subtle.importKey('raw', passwordBytes, 'PBKDF2', false, [\n 'deriveBits'\n ]);\n\n // Derive key bits\n const derivedBits = await this._crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: toArrayBuffer(salt),\n iterations: iterations,\n hash: 'SHA-256'\n },\n keyMaterial,\n CryptoUtils.Constants.AES_256_KEY_SIZE * 8 // bits\n );\n\n return Success.with(new Uint8Array(derivedBits));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Key derivation failed: ${message}`);\n }\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n try {\n const encoder = new TextEncoder();\n const dataBuffer = encoder.encode(data);\n const hashBuffer = await this._crypto.subtle.digest('SHA-256', dataBuffer);\n const hashArray = new Uint8Array(hashBuffer);\n const hashHex = Array.from(hashArray)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return succeed(hashHex);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return fail(`SHA-256 hash failed: ${message}`);\n }\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n try {\n return Success.with(this._crypto.getRandomValues(new Uint8Array(length)));\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n return Failure.with(`Random bytes generation failed: ${message}`);\n }\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n // Convert Uint8Array to binary string, then to base64\n let binary = '';\n for (let i = 0; i < data.length; i++) {\n binary += String.fromCharCode(data[i]);\n }\n return btoa(binary);\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n try {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return Success.with(bytes);\n } catch (e) {\n return Failure.with('Invalid base64 string');\n }\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair via Web Crypto.\n * @param algorithm - The algorithm to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: CryptoUtils.KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's\n // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and\n // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`\n // is a runtime check via the `in` operator, not a type assertion.\n const result = await captureAsyncResult(async () => {\n const generated = await this._crypto.subtle.generateKey(\n params.generateKey as AlgorithmIdentifier,\n extractable,\n [...params.keyPairUsages]\n );\n if ('privateKey' in generated && 'publicKey' in generated) {\n return generated;\n }\n /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */\n throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);\n });\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(\n jwk: JsonWebKey,\n algorithm: CryptoUtils.KeyPairAlgorithm\n ): Promise<Result<CryptoKey>> {\n const params = CryptoUtils.keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n /* c8 ignore stop */\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<CryptoUtils.IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: CryptoUtils.IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: CryptoUtils.IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {\n return Failure.with(\n `unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {\n return Failure.with(\n `unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = this._crypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: toBufferView(nonceResult.value) },\n wrapKey,\n toBufferView(ciphertextResult.value)\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */\n/**\n * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web\n * Crypto API is available.\n * @returns `Success` with provider, or `Failure` if not available\n * @public\n */\nexport function createBrowserCryptoProvider(): Result<BrowserCryptoProvider> {\n return captureResult(() => new BrowserCryptoProvider());\n}\n/* c8 ignore stop */\n"]}
|
|
@@ -145,7 +145,7 @@ export declare class FileApiTreeAccessors<TCT extends string = string> {
|
|
|
145
145
|
static getOriginalFile(fileList: FileList, targetPath: string): Result<File>;
|
|
146
146
|
/**
|
|
147
147
|
* Extract file metadata from a File.
|
|
148
|
-
* @param
|
|
148
|
+
* @param file - The File to extract metadata from
|
|
149
149
|
* @returns The {@link IFileMetadata | file metadata}
|
|
150
150
|
*/
|
|
151
151
|
static extractFileMetadata(file: File): IFileMetadata;
|
|
@@ -239,7 +239,7 @@ class FileApiTreeAccessors {
|
|
|
239
239
|
}
|
|
240
240
|
/**
|
|
241
241
|
* Extract file metadata from a File.
|
|
242
|
-
* @param
|
|
242
|
+
* @param file - The File to extract metadata from
|
|
243
243
|
* @returns The {@link IFileMetadata | file metadata}
|
|
244
244
|
*/
|
|
245
245
|
static extractFileMetadata(file) {
|
|
@@ -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,S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,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 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"]}
|
|
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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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"]}
|
|
@@ -47,6 +47,12 @@ export declare class HttpTreeAccessors<TCT extends string = string> extends File
|
|
|
47
47
|
*/
|
|
48
48
|
syncToDisk(): Promise<Result<void>>;
|
|
49
49
|
private _doSync;
|
|
50
|
+
/**
|
|
51
|
+
* Restores snapshotted items back into the live dirty sets so they
|
|
52
|
+
* are retried on the next sync attempt. Items that were added to
|
|
53
|
+
* the live sets while the sync was in flight are preserved.
|
|
54
|
+
*/
|
|
55
|
+
private _restoreUnsynced;
|
|
50
56
|
/**
|
|
51
57
|
* Checks if there are any dirty files that need synchronization.
|
|
52
58
|
* @returns True if there are dirty files, false otherwise.
|