@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.
Files changed (263) hide show
  1. package/dist/packlets/crypto-utils/browserCryptoProvider.js +208 -18
  2. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  3. package/dist/packlets/file-tree/fileApiTreeAccessors.js +1 -1
  4. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  5. package/dist/packlets/file-tree/httpTreeAccessors.js +72 -42
  6. package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  7. package/dist/ts-web-extras.d.ts +59 -7
  8. package/dist/tsdoc-metadata.json +1 -1
  9. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +52 -5
  10. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
  11. package/lib/packlets/crypto-utils/browserCryptoProvider.js +207 -17
  12. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
  13. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +1 -1
  14. package/lib/packlets/file-tree/fileApiTreeAccessors.js +1 -1
  15. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  16. package/lib/packlets/file-tree/httpTreeAccessors.d.ts +6 -0
  17. package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -1
  18. package/lib/packlets/file-tree/httpTreeAccessors.js +72 -42
  19. package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
  20. package/package.json +27 -26
  21. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +0 -75
  22. package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +0 -75
  23. package/.rush/temp/operation/build/all.log +0 -75
  24. package/.rush/temp/operation/build/error.log +0 -18
  25. package/.rush/temp/operation/build/log-chunks.jsonl +0 -75
  26. package/.rush/temp/operation/build/state.json +0 -3
  27. package/.rush/temp/operation/test/all.log +0 -75
  28. package/.rush/temp/operation/test/error.log +0 -18
  29. package/.rush/temp/operation/test/log-chunks.jsonl +0 -75
  30. package/.rush/temp/operation/test/state.json +0 -3
  31. package/.rush/temp/shrinkwrap-deps.json +0 -635
  32. package/CHANGELOG.md +0 -23
  33. package/config/api-extractor.json +0 -343
  34. package/config/jest.config.json +0 -19
  35. package/config/rig.json +0 -16
  36. package/config/typedoc.json +0 -6
  37. package/dist/test/mocks/idb-keyval.js +0 -6
  38. package/dist/test/mocks/idb-keyval.js.map +0 -1
  39. package/dist/test/setupTests.js +0 -74
  40. package/dist/test/setupTests.js.map +0 -1
  41. package/dist/test/unit/browserHashProvider.test.js +0 -140
  42. package/dist/test/unit/browserHashProvider.test.js.map +0 -1
  43. package/dist/test/unit/directoryHandleStore.test.js +0 -190
  44. package/dist/test/unit/directoryHandleStore.test.js.map +0 -1
  45. package/dist/test/unit/fileApiTreeAccessors.test.js +0 -1188
  46. package/dist/test/unit/fileApiTreeAccessors.test.js.map +0 -1
  47. package/dist/test/unit/fileApiTypes.test.js +0 -472
  48. package/dist/test/unit/fileApiTypes.test.js.map +0 -1
  49. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +0 -622
  50. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
  51. package/dist/test/unit/fileTreeHelpers.test.js +0 -590
  52. package/dist/test/unit/fileTreeHelpers.test.js.map +0 -1
  53. package/dist/test/unit/httpTreeAccessors.test.js +0 -1229
  54. package/dist/test/unit/httpTreeAccessors.test.js.map +0 -1
  55. package/dist/test/unit/localStorageTreeAccessors.test.js +0 -812
  56. package/dist/test/unit/localStorageTreeAccessors.test.js.map +0 -1
  57. package/dist/test/unit/urlParams.test.js +0 -393
  58. package/dist/test/unit/urlParams.test.js.map +0 -1
  59. package/dist/test/utils/fileSystemAccessMocks.js +0 -271
  60. package/dist/test/utils/fileSystemAccessMocks.js.map +0 -1
  61. package/dist/test/utils/testHelpers.js +0 -124
  62. package/dist/test/utils/testHelpers.js.map +0 -1
  63. package/docs/@fgv/namespaces/CryptoUtils/README.md +0 -18
  64. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +0 -203
  65. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +0 -63
  66. package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +0 -18
  67. package/docs/@fgv/namespaces/FileTreeHelpers/README.md +0 -19
  68. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +0 -23
  69. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +0 -23
  70. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +0 -33
  71. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +0 -33
  72. package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +0 -25
  73. package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +0 -11
  74. package/docs/README.md +0 -78
  75. package/docs/classes/DirectoryHandleStore.md +0 -116
  76. package/docs/classes/FileApiTreeAccessors.md +0 -286
  77. package/docs/classes/FileSystemAccessTreeAccessors.md +0 -557
  78. package/docs/classes/HttpTreeAccessors.md +0 -508
  79. package/docs/classes/LocalStorageTreeAccessors.md +0 -520
  80. package/docs/functions/exportAsJson.md +0 -23
  81. package/docs/functions/exportUsingFileSystemAPI.md +0 -26
  82. package/docs/functions/extractDirectoryPath.md +0 -23
  83. package/docs/functions/isDirectoryHandle.md +0 -23
  84. package/docs/functions/isFileHandle.md +0 -23
  85. package/docs/functions/isFilePath.md +0 -21
  86. package/docs/functions/parseContextFilter.md +0 -22
  87. package/docs/functions/parseQualifierDefaults.md +0 -22
  88. package/docs/functions/parseResourceTypes.md +0 -22
  89. package/docs/functions/parseUrlParameters.md +0 -15
  90. package/docs/functions/safeShowDirectoryPicker.md +0 -24
  91. package/docs/functions/safeShowOpenFilePicker.md +0 -24
  92. package/docs/functions/safeShowSaveFilePicker.md +0 -24
  93. package/docs/functions/supportsFileSystemAccess.md +0 -23
  94. package/docs/interfaces/FilePickerAcceptType.md +0 -16
  95. package/docs/interfaces/FileSystemCreateWritableOptions.md +0 -15
  96. package/docs/interfaces/FileSystemDirectoryHandle.md +0 -187
  97. package/docs/interfaces/FileSystemFileHandle.md +0 -106
  98. package/docs/interfaces/FileSystemGetDirectoryOptions.md +0 -15
  99. package/docs/interfaces/FileSystemGetFileOptions.md +0 -15
  100. package/docs/interfaces/FileSystemHandle.md +0 -69
  101. package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +0 -15
  102. package/docs/interfaces/FileSystemRemoveOptions.md +0 -15
  103. package/docs/interfaces/FileSystemWritableFileStream.md +0 -127
  104. package/docs/interfaces/IDirectoryHandleTreeInitializer.md +0 -17
  105. package/docs/interfaces/IFileHandleTreeInitializer.md +0 -16
  106. package/docs/interfaces/IFileListTreeInitializer.md +0 -15
  107. package/docs/interfaces/IFileMetadata.md +0 -19
  108. package/docs/interfaces/IFileSystemAccessTreeParams.md +0 -30
  109. package/docs/interfaces/IFsAccessApis.md +0 -57
  110. package/docs/interfaces/IHttpTreeParams.md +0 -32
  111. package/docs/interfaces/ILocalStorageTreeParams.md +0 -30
  112. package/docs/interfaces/IUrlConfigOptions.md +0 -27
  113. package/docs/interfaces/ShowDirectoryPickerOptions.md +0 -17
  114. package/docs/interfaces/ShowOpenFilePickerOptions.md +0 -19
  115. package/docs/interfaces/ShowSaveFilePickerOptions.md +0 -19
  116. package/docs/type-aliases/TreeInitializer.md +0 -11
  117. package/docs/type-aliases/WellKnownDirectory.md +0 -11
  118. package/docs/type-aliases/WindowWithFsAccess.md +0 -11
  119. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +0 -11
  120. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +0 -11
  121. package/etc/ts-web-extras.api.md +0 -433
  122. package/lib/test/mocks/idb-keyval.d.ts +0 -6
  123. package/lib/test/mocks/idb-keyval.d.ts.map +0 -1
  124. package/lib/test/mocks/idb-keyval.js +0 -9
  125. package/lib/test/mocks/idb-keyval.js.map +0 -1
  126. package/lib/test/setupTests.d.ts +0 -2
  127. package/lib/test/setupTests.d.ts.map +0 -1
  128. package/lib/test/setupTests.js +0 -76
  129. package/lib/test/setupTests.js.map +0 -1
  130. package/lib/test/unit/browserHashProvider.test.d.ts +0 -2
  131. package/lib/test/unit/browserHashProvider.test.d.ts.map +0 -1
  132. package/lib/test/unit/browserHashProvider.test.js +0 -142
  133. package/lib/test/unit/browserHashProvider.test.js.map +0 -1
  134. package/lib/test/unit/directoryHandleStore.test.d.ts +0 -2
  135. package/lib/test/unit/directoryHandleStore.test.d.ts.map +0 -1
  136. package/lib/test/unit/directoryHandleStore.test.js +0 -192
  137. package/lib/test/unit/directoryHandleStore.test.js.map +0 -1
  138. package/lib/test/unit/fileApiTreeAccessors.test.d.ts +0 -2
  139. package/lib/test/unit/fileApiTreeAccessors.test.d.ts.map +0 -1
  140. package/lib/test/unit/fileApiTreeAccessors.test.js +0 -1190
  141. package/lib/test/unit/fileApiTreeAccessors.test.js.map +0 -1
  142. package/lib/test/unit/fileApiTypes.test.d.ts +0 -2
  143. package/lib/test/unit/fileApiTypes.test.d.ts.map +0 -1
  144. package/lib/test/unit/fileApiTypes.test.js +0 -474
  145. package/lib/test/unit/fileApiTypes.test.js.map +0 -1
  146. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +0 -2
  147. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +0 -1
  148. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +0 -624
  149. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +0 -1
  150. package/lib/test/unit/fileTreeHelpers.test.d.ts +0 -2
  151. package/lib/test/unit/fileTreeHelpers.test.d.ts.map +0 -1
  152. package/lib/test/unit/fileTreeHelpers.test.js +0 -592
  153. package/lib/test/unit/fileTreeHelpers.test.js.map +0 -1
  154. package/lib/test/unit/httpTreeAccessors.test.d.ts +0 -2
  155. package/lib/test/unit/httpTreeAccessors.test.d.ts.map +0 -1
  156. package/lib/test/unit/httpTreeAccessors.test.js +0 -1231
  157. package/lib/test/unit/httpTreeAccessors.test.js.map +0 -1
  158. package/lib/test/unit/localStorageTreeAccessors.test.d.ts +0 -2
  159. package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +0 -1
  160. package/lib/test/unit/localStorageTreeAccessors.test.js +0 -814
  161. package/lib/test/unit/localStorageTreeAccessors.test.js.map +0 -1
  162. package/lib/test/unit/urlParams.test.d.ts +0 -2
  163. package/lib/test/unit/urlParams.test.d.ts.map +0 -1
  164. package/lib/test/unit/urlParams.test.js +0 -395
  165. package/lib/test/unit/urlParams.test.js.map +0 -1
  166. package/lib/test/utils/fileSystemAccessMocks.d.ts +0 -53
  167. package/lib/test/utils/fileSystemAccessMocks.d.ts.map +0 -1
  168. package/lib/test/utils/fileSystemAccessMocks.js +0 -277
  169. package/lib/test/utils/fileSystemAccessMocks.js.map +0 -1
  170. package/lib/test/utils/testHelpers.d.ts +0 -51
  171. package/lib/test/utils/testHelpers.d.ts.map +0 -1
  172. package/lib/test/utils/testHelpers.js +0 -133
  173. package/lib/test/utils/testHelpers.js.map +0 -1
  174. package/rush-logs/ts-web-extras.build.cache.log +0 -0
  175. package/rush-logs/ts-web-extras.build.error.log +0 -18
  176. package/rush-logs/ts-web-extras.build.log +0 -75
  177. package/rush-logs/ts-web-extras.test.cache.log +0 -1
  178. package/rush-logs/ts-web-extras.test.error.log +0 -18
  179. package/rush-logs/ts-web-extras.test.log +0 -75
  180. package/src/index.browser.ts +0 -24
  181. package/src/index.ts +0 -47
  182. package/src/packlets/crypto-utils/browserCryptoProvider.ts +0 -311
  183. package/src/packlets/crypto-utils/browserHashProvider.ts +0 -73
  184. package/src/packlets/crypto-utils/index.ts +0 -29
  185. package/src/packlets/file-api-types/index.ts +0 -366
  186. package/src/packlets/file-tree/directoryHandleStore.ts +0 -136
  187. package/src/packlets/file-tree/fileApiTreeAccessors.ts +0 -528
  188. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +0 -519
  189. package/src/packlets/file-tree/httpTreeAccessors.ts +0 -448
  190. package/src/packlets/file-tree/index.ts +0 -32
  191. package/src/packlets/file-tree/localStorageTreeAccessors.ts +0 -430
  192. package/src/packlets/helpers/fileTreeHelpers.ts +0 -107
  193. package/src/packlets/helpers/index.ts +0 -28
  194. package/src/packlets/url-utils/index.ts +0 -28
  195. package/src/packlets/url-utils/urlParams.ts +0 -245
  196. package/src/test/mocks/idb-keyval.ts +0 -5
  197. package/src/test/setupTests.ts +0 -87
  198. package/src/test/unit/browserHashProvider.test.ts +0 -155
  199. package/src/test/unit/browserHashProvider.test.ts.bak +0 -376
  200. package/src/test/unit/directoryHandleStore.test.ts +0 -251
  201. package/src/test/unit/fileApiTreeAccessors.test.ts +0 -1387
  202. package/src/test/unit/fileApiTypes.test.ts +0 -587
  203. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +0 -885
  204. package/src/test/unit/fileTreeHelpers.test.ts +0 -694
  205. package/src/test/unit/httpTreeAccessors.test.ts +0 -1571
  206. package/src/test/unit/localStorageTreeAccessors.test.ts +0 -1014
  207. package/src/test/unit/urlParams.test.ts +0 -464
  208. package/src/test/utils/fileSystemAccessMocks.ts +0 -353
  209. package/src/test/utils/testHelpers.ts +0 -155
  210. package/temp/build/typescript/ts_8nwakTlr.json +0 -1
  211. package/temp/coverage/base.css +0 -224
  212. package/temp/coverage/block-navigation.js +0 -87
  213. package/temp/coverage/crypto/browserHashProvider.ts.html +0 -304
  214. package/temp/coverage/crypto/index.html +0 -116
  215. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +0 -1018
  216. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +0 -304
  217. package/temp/coverage/crypto-utils/index.html +0 -131
  218. package/temp/coverage/favicon.png +0 -0
  219. package/temp/coverage/file-tree/directoryHandleStore.ts.html +0 -493
  220. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +0 -1669
  221. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
  222. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +0 -1429
  223. package/temp/coverage/file-tree/index.html +0 -176
  224. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +0 -1375
  225. package/temp/coverage/helpers/fileTreeHelpers.ts.html +0 -406
  226. package/temp/coverage/helpers/index.html +0 -116
  227. package/temp/coverage/index.html +0 -161
  228. package/temp/coverage/lcov-report/base.css +0 -224
  229. package/temp/coverage/lcov-report/block-navigation.js +0 -87
  230. package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +0 -304
  231. package/temp/coverage/lcov-report/crypto/index.html +0 -116
  232. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +0 -1018
  233. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +0 -304
  234. package/temp/coverage/lcov-report/crypto-utils/index.html +0 -131
  235. package/temp/coverage/lcov-report/favicon.png +0 -0
  236. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +0 -493
  237. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +0 -1669
  238. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +0 -1642
  239. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +0 -1429
  240. package/temp/coverage/lcov-report/file-tree/index.html +0 -176
  241. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +0 -1375
  242. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +0 -406
  243. package/temp/coverage/lcov-report/helpers/index.html +0 -116
  244. package/temp/coverage/lcov-report/index.html +0 -161
  245. package/temp/coverage/lcov-report/prettify.css +0 -1
  246. package/temp/coverage/lcov-report/prettify.js +0 -2
  247. package/temp/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  248. package/temp/coverage/lcov-report/sorter.js +0 -210
  249. package/temp/coverage/lcov-report/url-utils/index.html +0 -116
  250. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +0 -820
  251. package/temp/coverage/lcov.info +0 -3597
  252. package/temp/coverage/prettify.css +0 -1
  253. package/temp/coverage/prettify.js +0 -2
  254. package/temp/coverage/sort-arrow-sprite.png +0 -0
  255. package/temp/coverage/sorter.js +0 -210
  256. package/temp/coverage/url-utils/index.html +0 -116
  257. package/temp/coverage/url-utils/urlParams.ts.html +0 -820
  258. package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
  259. package/temp/test/jest/jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5 +0 -53
  260. package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
  261. package/temp/ts-web-extras.api.json +0 -8850
  262. package/temp/ts-web-extras.api.md +0 -433
  263. package/tsconfig.json +0 -7
@@ -17,10 +17,9 @@
17
17
  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
- /* c8 ignore start - Browser-only implementation cannot be tested in Node.js environment */
21
- import { captureResult, Failure, Success } from '@fgv/ts-utils';
20
+ import { captureAsyncResult, captureResult, fail, Failure, succeed, Success } from '@fgv/ts-utils';
22
21
  import { CryptoUtils } from '@fgv/ts-extras';
23
- const CryptoConstants = CryptoUtils.Constants;
22
+ /* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */
24
23
  /**
25
24
  * Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.
26
25
  * @param arr - The Uint8Array to extract from
@@ -32,6 +31,24 @@ function toArrayBuffer(arr) {
32
31
  new Uint8Array(buffer).set(arr);
33
32
  return buffer;
34
33
  }
34
+ /* c8 ignore stop */
35
+ /**
36
+ * Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.
37
+ * Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and
38
+ * {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's
39
+ * webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`
40
+ * parameters with "is not instance of ArrayBuffer, Buffer, TypedArray, or
41
+ * DataView" even though `ArrayBuffer` should be valid per the spec; a
42
+ * TypedArray view is accepted on Node 20+ and on browsers, and the explicit
43
+ * `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`
44
+ * (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).
45
+ */
46
+ function toBufferView(arr) {
47
+ const buffer = new ArrayBuffer(arr.byteLength);
48
+ const view = new Uint8Array(buffer);
49
+ view.set(arr);
50
+ return view;
51
+ }
35
52
  /**
36
53
  * Browser implementation of `ICryptoProvider` using the Web Crypto API.
37
54
  * Uses AES-256-GCM for authenticated encryption.
@@ -42,6 +59,7 @@ function toArrayBuffer(arr) {
42
59
  * @public
43
60
  */
44
61
  export class BrowserCryptoProvider {
62
+ /* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */
45
63
  /**
46
64
  * Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
47
65
  * @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)
@@ -67,12 +85,12 @@ export class BrowserCryptoProvider {
67
85
  * @returns `Success` with encryption result, or `Failure` with an error.
68
86
  */
69
87
  async encrypt(plaintext, key) {
70
- if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {
71
- return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
88
+ if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {
89
+ return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
72
90
  }
73
91
  try {
74
92
  // Generate random IV
75
- const iv = this._crypto.getRandomValues(new Uint8Array(CryptoConstants.GCM_IV_SIZE));
93
+ const iv = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));
76
94
  // Import the key
77
95
  const cryptoKey = await this._crypto.subtle.importKey('raw', toArrayBuffer(key), { name: 'AES-GCM' }, false, ['encrypt']);
78
96
  // Encode plaintext to bytes
@@ -82,12 +100,12 @@ export class BrowserCryptoProvider {
82
100
  const encryptedWithTag = await this._crypto.subtle.encrypt({
83
101
  name: 'AES-GCM',
84
102
  iv: iv,
85
- tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits
103
+ tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
86
104
  }, cryptoKey, plaintextBytes);
87
105
  // Split ciphertext and auth tag (auth tag is last 16 bytes)
88
106
  const encryptedArray = new Uint8Array(encryptedWithTag);
89
- const encryptedData = encryptedArray.slice(0, encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);
90
- const authTag = encryptedArray.slice(encryptedArray.length - CryptoConstants.GCM_AUTH_TAG_SIZE);
107
+ const encryptedData = encryptedArray.slice(0, encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);
108
+ const authTag = encryptedArray.slice(encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);
91
109
  return Success.with({
92
110
  iv,
93
111
  authTag,
@@ -108,14 +126,14 @@ export class BrowserCryptoProvider {
108
126
  * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.
109
127
  */
110
128
  async decrypt(encryptedData, key, iv, authTag) {
111
- if (key.length !== CryptoConstants.AES_256_KEY_SIZE) {
112
- return Failure.with(`Key must be ${CryptoConstants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
129
+ if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {
130
+ return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
113
131
  }
114
- if (iv.length !== CryptoConstants.GCM_IV_SIZE) {
115
- return Failure.with(`IV must be ${CryptoConstants.GCM_IV_SIZE} bytes, got ${iv.length}`);
132
+ if (iv.length !== CryptoUtils.Constants.GCM_IV_SIZE) {
133
+ return Failure.with(`IV must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);
116
134
  }
117
- if (authTag.length !== CryptoConstants.GCM_AUTH_TAG_SIZE) {
118
- return Failure.with(`Auth tag must be ${CryptoConstants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);
135
+ if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
136
+ return Failure.with(`Auth tag must be ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);
119
137
  }
120
138
  try {
121
139
  // Import the key
@@ -128,7 +146,7 @@ export class BrowserCryptoProvider {
128
146
  const decrypted = await this._crypto.subtle.decrypt({
129
147
  name: 'AES-GCM',
130
148
  iv: toArrayBuffer(iv),
131
- tagLength: CryptoConstants.GCM_AUTH_TAG_SIZE * 8 // bits
149
+ tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
132
150
  }, cryptoKey, encryptedWithTag);
133
151
  // Decode to string
134
152
  const decoder = new TextDecoder();
@@ -145,7 +163,7 @@ export class BrowserCryptoProvider {
145
163
  */
146
164
  async generateKey() {
147
165
  try {
148
- return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoConstants.AES_256_KEY_SIZE)));
166
+ return Success.with(this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.AES_256_KEY_SIZE)));
149
167
  }
150
168
  catch (e) {
151
169
  const message = e instanceof Error ? e.message : String(e);
@@ -180,7 +198,7 @@ export class BrowserCryptoProvider {
180
198
  salt: toArrayBuffer(salt),
181
199
  iterations: iterations,
182
200
  hash: 'SHA-256'
183
- }, keyMaterial, CryptoConstants.AES_256_KEY_SIZE * 8 // bits
201
+ }, keyMaterial, CryptoUtils.Constants.AES_256_KEY_SIZE * 8 // bits
184
202
  );
185
203
  return Success.with(new Uint8Array(derivedBits));
186
204
  }
@@ -189,6 +207,27 @@ export class BrowserCryptoProvider {
189
207
  return Failure.with(`Key derivation failed: ${message}`);
190
208
  }
191
209
  }
210
+ /**
211
+ * Computes a SHA-256 hash of the given data.
212
+ * @param data - UTF-8 string to hash
213
+ * @returns `Success` with hex-encoded hash string, or `Failure` with an error.
214
+ */
215
+ async sha256(data) {
216
+ try {
217
+ const encoder = new TextEncoder();
218
+ const dataBuffer = encoder.encode(data);
219
+ const hashBuffer = await this._crypto.subtle.digest('SHA-256', dataBuffer);
220
+ const hashArray = new Uint8Array(hashBuffer);
221
+ const hashHex = Array.from(hashArray)
222
+ .map((b) => b.toString(16).padStart(2, '0'))
223
+ .join('');
224
+ return succeed(hashHex);
225
+ }
226
+ catch (e) {
227
+ const message = e instanceof Error ? e.message : String(e);
228
+ return fail(`SHA-256 hash failed: ${message}`);
229
+ }
230
+ }
192
231
  // ============================================================================
193
232
  // Platform Utility Methods
194
233
  // ============================================================================
@@ -240,7 +279,158 @@ export class BrowserCryptoProvider {
240
279
  return Failure.with('Invalid base64 string');
241
280
  }
242
281
  }
282
+ // ============================================================================
283
+ // Asymmetric Key Operations
284
+ // ============================================================================
285
+ /**
286
+ * Generates a new asymmetric keypair via Web Crypto.
287
+ * @param algorithm - The algorithm to use.
288
+ * @param extractable - Whether the resulting keys may be exported.
289
+ * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
290
+ */
291
+ async generateKeyPair(algorithm, extractable) {
292
+ const params = CryptoUtils.keyPairAlgorithmParams[algorithm];
293
+ // Widening upcast to `AlgorithmIdentifier` steers TS to subtle.generateKey's
294
+ // broad overload, which accepts the Ed25519 `{ name: 'Ed25519' }` shape and
295
+ // returns `CryptoKey | CryptoKeyPair`. The narrowing back to `CryptoKeyPair`
296
+ // is a runtime check via the `in` operator, not a type assertion.
297
+ const result = await captureAsyncResult(async () => {
298
+ const generated = await this._crypto.subtle.generateKey(params.generateKey, extractable, [...params.keyPairUsages]);
299
+ if ('privateKey' in generated && 'publicKey' in generated) {
300
+ return generated;
301
+ }
302
+ /* c8 ignore next - unreachable: every entry in keyPairAlgorithmParams produces a keypair */
303
+ throw new Error(`${algorithm} unexpectedly produced a single CryptoKey`);
304
+ });
305
+ return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);
306
+ }
307
+ /**
308
+ * Exports a public `CryptoKey` as a JSON Web Key.
309
+ * @remarks
310
+ * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
311
+ * does not enforce public-vs-private; without this guard a caller that
312
+ * passed an extractable private key would receive its private fields
313
+ * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
314
+ * @param publicKey - Extractable public key to export.
315
+ * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
316
+ */
317
+ async exportPublicKeyJwk(publicKey) {
318
+ if (publicKey.type !== 'public') {
319
+ return Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);
320
+ }
321
+ const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('jwk', publicKey));
322
+ return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);
323
+ }
324
+ /**
325
+ * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
326
+ * @param jwk - The JSON Web Key produced by a prior export.
327
+ * @param algorithm - The algorithm the key was generated for.
328
+ * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
329
+ */
330
+ async importPublicKeyJwk(jwk, algorithm) {
331
+ const params = CryptoUtils.keyPairAlgorithmParams[algorithm];
332
+ const result = await captureAsyncResult(() => this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages));
333
+ return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
334
+ }
335
+ /* c8 ignore stop */
336
+ /**
337
+ * Wraps `plaintext` for the holder of `recipientPublicKey` using
338
+ * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
339
+ * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
340
+ * @param plaintext - The bytes to wrap.
341
+ * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
342
+ * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
343
+ * @returns `Success` with the wrapped payload, or `Failure` with an error.
344
+ */
345
+ async wrapBytes(plaintext, recipientPublicKey, options) {
346
+ const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
347
+ if (recipientCheck.isFailure()) {
348
+ return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);
349
+ }
350
+ const subtle = this._crypto.subtle;
351
+ const result = await captureAsyncResult(async () => {
352
+ const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
353
+ 'deriveKey'
354
+ ]));
355
+ const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: recipientPublicKey }, ephemeral.privateKey, { name: 'HKDF' }, false, ['deriveKey']);
356
+ 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']);
357
+ const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));
358
+ const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));
359
+ const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
360
+ return {
361
+ ephemeralPublicKey,
362
+ nonce: this.toBase64(nonce),
363
+ ciphertext: this.toBase64(new Uint8Array(ctBuf))
364
+ };
365
+ });
366
+ return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
367
+ }
368
+ /**
369
+ * Unwraps a payload produced by `wrapBytes` using the recipient's private
370
+ * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
371
+ * @param wrapped - The wrapped payload.
372
+ * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
373
+ * @param options - HKDF salt and info matching the wrap call.
374
+ * @returns `Success` with the original `plaintext`, or `Failure` with an error.
375
+ */
376
+ async unwrapBytes(wrapped, recipientPrivateKey, options) {
377
+ const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
378
+ if (recipientCheck.isFailure()) {
379
+ return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);
380
+ }
381
+ const nonceResult = this.fromBase64(wrapped.nonce);
382
+ if (nonceResult.isFailure()) {
383
+ return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);
384
+ }
385
+ if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {
386
+ return Failure.with(`unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`);
387
+ }
388
+ const ciphertextResult = this.fromBase64(wrapped.ciphertext);
389
+ if (ciphertextResult.isFailure()) {
390
+ return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
391
+ }
392
+ if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
393
+ return Failure.with(`unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`);
394
+ }
395
+ const subtle = this._crypto.subtle;
396
+ const result = await captureAsyncResult(async () => {
397
+ const ephemeralPub = await subtle.importKey('jwk', wrapped.ephemeralPublicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
398
+ const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: ephemeralPub }, recipientPrivateKey, { name: 'HKDF' }, false, ['deriveKey']);
399
+ 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']);
400
+ const ptBuf = await subtle.decrypt({ name: 'AES-GCM', iv: toBufferView(nonceResult.value) }, wrapKey, toBufferView(ciphertextResult.value));
401
+ return new Uint8Array(ptBuf);
402
+ });
403
+ return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
404
+ }
405
+ }
406
+ /**
407
+ * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
408
+ * (public or private). Used by the wrap/unwrap methods to surface a clean
409
+ * `Failure` instead of letting the WebCrypto deriveKey call throw a less
410
+ * informative error later in the pipeline. Key usages are intentionally not
411
+ * checked here: WebCrypto already produces a specific error if `deriveKey` is
412
+ * not in `usages`, and `deriveBits` is an equally valid alternative usage that
413
+ * an explicit check would have to track.
414
+ * @param key - The CryptoKey to validate.
415
+ * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
416
+ * @param label - Human-readable role label included in the failure message.
417
+ * @returns `Success` with the key (unchanged) when the algorithm, curve, and
418
+ * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
419
+ */
420
+ function checkEcdhP256(key, keyType, label) {
421
+ if (key.algorithm.name !== 'ECDH') {
422
+ return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
423
+ }
424
+ const namedCurve = key.algorithm.namedCurve;
425
+ if (namedCurve !== 'P-256') {
426
+ return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
427
+ }
428
+ if (key.type !== keyType) {
429
+ return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
430
+ }
431
+ return succeed(key);
243
432
  }
433
+ /* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */
244
434
  /**
245
435
  * Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web
246
436
  * 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;AAEZ,2FAA2F;AAC3F,OAAO,EAAE,aAAa,EAAE,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAI7C,MAAM,eAAe,GAAG,WAAW,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,MAAM,OAAO,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,MAAM,EAAE,CAAC;YAClE,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC;QACnC,CAAC;aAAM,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAC1D,IAAI,CAAC,OAAO,GAAG,MAAM,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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,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,OAAO,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,aAAa,CAAC,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;AAEZ,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAU,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC3G,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;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,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/C,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACpC,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,CAAC;IACjF,CAAC;IACD,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED,4FAA4F;AAC5F;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,aAAa,CAAC,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"]}
@@ -236,7 +236,7 @@ export class FileApiTreeAccessors {
236
236
  }
237
237
  /**
238
238
  * Extract file metadata from a File.
239
- * @param fileList - The File to extract metadata from
239
+ * @param file - The File to extract metadata from
240
240
  * @returns The {@link IFileMetadata | file metadata}
241
241
  */
242
242
  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,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EACL,YAAY,EACZ,iBAAiB,EAGlB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAA+B,MAAM,iCAAiC,CAAC;AAC7G,OAAO,EAAE,iBAAiB,EAAmB,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAA2B,MAAM,6BAA6B,CAAC;AAWjG;;;GAGG;AACH,SAAS,mBAAmB,CAAC,IAAU;IACrC,OAAQ,IAAuC,CAAC,kBAAkB,IAAI,IAAI,CAAC,IAAI,CAAC;AAClF,CAAC;AAkDD;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IAC/B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAClC,SAAoC,EACpC,MAAyC;QAEzC,MAAM,eAAe,GAAG,MAAM,6BAA6B,CAAC,mBAAmB,CAAM,SAAS,EAAE,MAAM,CAAC,CAAC;QACxG,IAAI,eAAe,CAAC,SAAS,EAAE,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAM,eAAe,CAAC,KAAK,CAAC,CAAC;IAC9D,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC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,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAI,CAAC,+BAA+B,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,MAAc,EAAE,IAAY;QACxD,wEAAwE;QACxE,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/D,oFAAoF;QACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACpE,kEAAkE;QAClE,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC;IACpE,CAAC;CACF","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,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EACL,YAAY,EACZ,iBAAiB,EAGlB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAA+B,MAAM,iCAAiC,CAAC;AAC7G,OAAO,EAAE,iBAAiB,EAAmB,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAA2B,MAAM,6BAA6B,CAAC;AAWjG;;;GAGG;AACH,SAAS,mBAAmB,CAAC,IAAU;IACrC,OAAQ,IAAuC,CAAC,kBAAkB,IAAI,IAAI,CAAC,IAAI,CAAC;AAClF,CAAC;AAkDD;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IAC/B;;;;;;;;;;;;;;OAcG;IACI,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAClC,SAAoC,EACpC,MAAyC;QAEzC,MAAM,eAAe,GAAG,MAAM,6BAA6B,CAAC,mBAAmB,CAAM,SAAS,EAAE,MAAM,CAAC,CAAC;QACxG,IAAI,eAAe,CAAC,SAAS,EAAE,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC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AC;;;;;;;;;YAED,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,yCAAyC;YACzC,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,OAAO,IAAI,CAAC,+BAA+B,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC;QACxE,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,MAAc,EAAE,IAAY;QACxD,wEAAwE;QACxE,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/D,oFAAoF;QACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACpE,kEAAkE;QAClE,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE,CAAC;IACpE,CAAC;CACF","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"]}