@fgv/ts-web-extras 5.0.2 → 5.1.0-0

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 (208) hide show
  1. package/.rush/temp/81e0881271ff236956b2f52e8ca99da6574c6e1e.tar.log +223 -0
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +35 -25
  3. package/.rush/temp/operation/build/all.log +35 -25
  4. package/.rush/temp/operation/build/log-chunks.jsonl +35 -25
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +175 -163
  7. package/config/jest.config.json +4 -1
  8. package/config/typedoc.json +6 -0
  9. package/dist/index.js +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/packlets/crypto-utils/browserCryptoProvider.js +254 -0
  12. package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  13. package/dist/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  14. package/dist/packlets/{crypto → crypto-utils}/index.js +1 -0
  15. package/dist/packlets/crypto-utils/index.js.map +1 -0
  16. package/dist/packlets/file-api-types/index.js +27 -3
  17. package/dist/packlets/file-api-types/index.js.map +1 -1
  18. package/dist/packlets/file-tree/directoryHandleStore.js +124 -0
  19. package/dist/packlets/file-tree/directoryHandleStore.js.map +1 -0
  20. package/dist/packlets/file-tree/fileApiTreeAccessors.js +76 -0
  21. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  22. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +345 -0
  23. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  24. package/dist/packlets/file-tree/index.js +3 -0
  25. package/dist/packlets/file-tree/index.js.map +1 -1
  26. package/dist/packlets/file-tree/localStorageTreeAccessors.js +308 -0
  27. package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  28. package/dist/test/mocks/idb-keyval.js +6 -0
  29. package/dist/test/mocks/idb-keyval.js.map +1 -0
  30. package/dist/test/unit/browserHashProvider.test.js +1 -1
  31. package/dist/test/unit/browserHashProvider.test.js.map +1 -1
  32. package/dist/test/unit/directoryHandleStore.test.js +190 -0
  33. package/dist/test/unit/directoryHandleStore.test.js.map +1 -0
  34. package/dist/test/unit/fileApiTypes.test.js +30 -0
  35. package/dist/test/unit/fileApiTypes.test.js.map +1 -1
  36. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +517 -0
  37. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  38. package/dist/test/unit/localStorageTreeAccessors.test.js +595 -0
  39. package/dist/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  40. package/dist/test/utils/fileSystemAccessMocks.js +271 -0
  41. package/dist/test/utils/fileSystemAccessMocks.js.map +1 -0
  42. package/dist/ts-web-extras.d.ts +460 -1
  43. package/dist/tsdoc-metadata.json +1 -1
  44. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider._constructor_.md +50 -0
  45. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.decrypt.md +104 -0
  46. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.derivekey.md +88 -0
  47. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.encrypt.md +72 -0
  48. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.frombase64.md +56 -0
  49. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generatekey.md +19 -0
  50. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generaterandombytes.md +56 -0
  51. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.md +169 -0
  52. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.tobase64.md +56 -0
  53. package/docs/{ts-web-extras.browserhashprovider.hashparts.md → ts-web-extras.cryptoutils.browserhashprovider.hashparts.md} +2 -2
  54. package/docs/{ts-web-extras.browserhashprovider.hashstring.md → ts-web-extras.cryptoutils.browserhashprovider.hashstring.md} +2 -2
  55. package/docs/{ts-web-extras.browserhashprovider.md → ts-web-extras.cryptoutils.browserhashprovider.md} +4 -4
  56. package/docs/ts-web-extras.cryptoutils.createbrowsercryptoprovider.md +19 -0
  57. package/docs/ts-web-extras.cryptoutils.md +71 -0
  58. package/docs/ts-web-extras.fileapitreeaccessors.createfromlocalstorage.md +74 -0
  59. package/docs/ts-web-extras.fileapitreeaccessors.createpersistent.md +76 -0
  60. package/docs/ts-web-extras.fileapitreeaccessors.md +32 -0
  61. package/docs/ts-web-extras.filesystemaccesstreeaccessors._constructor_.md +114 -0
  62. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fileismutable.md +52 -0
  63. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fromdirectoryhandle.md +72 -0
  64. package/docs/ts-web-extras.filesystemaccesstreeaccessors.getdirtypaths.md +17 -0
  65. package/docs/ts-web-extras.filesystemaccesstreeaccessors.isdirty.md +17 -0
  66. package/docs/ts-web-extras.filesystemaccesstreeaccessors.md +159 -0
  67. package/docs/ts-web-extras.filesystemaccesstreeaccessors.savefilecontents.md +66 -0
  68. package/docs/ts-web-extras.filesystemaccesstreeaccessors.synctodisk.md +17 -0
  69. package/docs/ts-web-extras.ifilesystemaccesstreeparams.autosync.md +13 -0
  70. package/docs/ts-web-extras.ifilesystemaccesstreeparams.md +78 -0
  71. package/docs/ts-web-extras.ifilesystemaccesstreeparams.requirewritepermission.md +13 -0
  72. package/docs/ts-web-extras.ilocalstoragetreeparams.autosync.md +13 -0
  73. package/docs/ts-web-extras.ilocalstoragetreeparams.md +97 -0
  74. package/docs/ts-web-extras.ilocalstoragetreeparams.pathtokeymap.md +13 -0
  75. package/docs/ts-web-extras.ilocalstoragetreeparams.storage.md +13 -0
  76. package/docs/ts-web-extras.localstoragetreeaccessors.fileismutable.md +56 -0
  77. package/docs/ts-web-extras.localstoragetreeaccessors.fromstorage.md +56 -0
  78. package/docs/ts-web-extras.localstoragetreeaccessors.getdirtypaths.md +19 -0
  79. package/docs/ts-web-extras.localstoragetreeaccessors.isdirty.md +19 -0
  80. package/docs/ts-web-extras.localstoragetreeaccessors.md +131 -0
  81. package/docs/ts-web-extras.localstoragetreeaccessors.savefilecontents.md +72 -0
  82. package/docs/ts-web-extras.localstoragetreeaccessors.synctodisk.md +19 -0
  83. package/docs/ts-web-extras.md +50 -4
  84. package/etc/ts-web-extras.api.md +91 -1
  85. package/lib/index.d.ts +2 -1
  86. package/lib/index.d.ts.map +1 -1
  87. package/lib/index.js +25 -2
  88. package/lib/index.js.map +1 -1
  89. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +77 -0
  90. package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -0
  91. package/lib/packlets/crypto-utils/browserCryptoProvider.js +259 -0
  92. package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -0
  93. package/lib/packlets/crypto-utils/browserHashProvider.d.ts.map +1 -0
  94. package/lib/packlets/crypto-utils/browserHashProvider.js.map +1 -0
  95. package/lib/packlets/{crypto → crypto-utils}/index.d.ts +1 -0
  96. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  97. package/lib/packlets/{crypto → crypto-utils}/index.js +1 -0
  98. package/lib/packlets/crypto-utils/index.js.map +1 -0
  99. package/lib/packlets/file-api-types/index.d.ts.map +1 -1
  100. package/lib/packlets/file-api-types/index.js +27 -3
  101. package/lib/packlets/file-api-types/index.js.map +1 -1
  102. package/lib/packlets/file-tree/directoryHandleStore.d.ts +59 -0
  103. package/lib/packlets/file-tree/directoryHandleStore.d.ts.map +1 -0
  104. package/lib/packlets/file-tree/directoryHandleStore.js +128 -0
  105. package/lib/packlets/file-tree/directoryHandleStore.js.map +1 -0
  106. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +57 -0
  107. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
  108. package/lib/packlets/file-tree/fileApiTreeAccessors.js +76 -0
  109. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  110. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts +136 -0
  111. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -0
  112. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +349 -0
  113. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -0
  114. package/lib/packlets/file-tree/index.d.ts +3 -0
  115. package/lib/packlets/file-tree/index.d.ts.map +1 -1
  116. package/lib/packlets/file-tree/index.js +3 -0
  117. package/lib/packlets/file-tree/index.js.map +1 -1
  118. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts +129 -0
  119. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts.map +1 -0
  120. package/lib/packlets/file-tree/localStorageTreeAccessors.js +312 -0
  121. package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -0
  122. package/lib/test/mocks/idb-keyval.d.ts +6 -0
  123. package/lib/test/mocks/idb-keyval.d.ts.map +1 -0
  124. package/lib/test/mocks/idb-keyval.js +9 -0
  125. package/lib/test/mocks/idb-keyval.js.map +1 -0
  126. package/lib/test/unit/browserHashProvider.test.js +21 -21
  127. package/lib/test/unit/browserHashProvider.test.js.map +1 -1
  128. package/lib/test/unit/directoryHandleStore.test.d.ts +2 -0
  129. package/lib/test/unit/directoryHandleStore.test.d.ts.map +1 -0
  130. package/lib/test/unit/directoryHandleStore.test.js +192 -0
  131. package/lib/test/unit/directoryHandleStore.test.js.map +1 -0
  132. package/lib/test/unit/fileApiTypes.test.js +30 -0
  133. package/lib/test/unit/fileApiTypes.test.js.map +1 -1
  134. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts +2 -0
  135. package/lib/test/unit/fileSystemAccessTreeAccessors.test.d.ts.map +1 -0
  136. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +519 -0
  137. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -0
  138. package/lib/test/unit/localStorageTreeAccessors.test.d.ts +2 -0
  139. package/lib/test/unit/localStorageTreeAccessors.test.d.ts.map +1 -0
  140. package/lib/test/unit/localStorageTreeAccessors.test.js +597 -0
  141. package/lib/test/unit/localStorageTreeAccessors.test.js.map +1 -0
  142. package/lib/test/utils/fileSystemAccessMocks.d.ts +53 -0
  143. package/lib/test/utils/fileSystemAccessMocks.d.ts.map +1 -0
  144. package/lib/test/utils/fileSystemAccessMocks.js +277 -0
  145. package/lib/test/utils/fileSystemAccessMocks.js.map +1 -0
  146. package/package.json +27 -20
  147. package/rush-logs/ts-web-extras.build.cache.log +3 -1
  148. package/rush-logs/ts-web-extras.build.log +35 -25
  149. package/src/index.ts +2 -2
  150. package/src/packlets/crypto-utils/browserCryptoProvider.ts +311 -0
  151. package/src/packlets/{crypto → crypto-utils}/index.ts +1 -0
  152. package/src/packlets/file-api-types/index.ts +24 -3
  153. package/src/packlets/file-tree/directoryHandleStore.ts +136 -0
  154. package/src/packlets/file-tree/fileApiTreeAccessors.ts +90 -0
  155. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +427 -0
  156. package/src/packlets/file-tree/index.ts +3 -0
  157. package/src/packlets/file-tree/localStorageTreeAccessors.ts +377 -0
  158. package/src/test/mocks/idb-keyval.ts +5 -0
  159. package/src/test/unit/browserHashProvider.test.ts +1 -1
  160. package/src/test/unit/directoryHandleStore.test.ts +251 -0
  161. package/src/test/unit/fileApiTypes.test.ts +36 -0
  162. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +732 -0
  163. package/src/test/unit/localStorageTreeAccessors.test.ts +746 -0
  164. package/src/test/utils/fileSystemAccessMocks.ts +353 -0
  165. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  166. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  167. package/temp/coverage/{crypto → crypto-utils}/browserHashProvider.ts.html +3 -3
  168. package/temp/coverage/{lcov-report/crypto → crypto-utils}/index.html +21 -6
  169. package/temp/coverage/file-tree/directoryHandleStore.ts.html +493 -0
  170. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +276 -6
  171. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1366 -0
  172. package/temp/coverage/file-tree/index.html +55 -10
  173. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1216 -0
  174. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  175. package/temp/coverage/helpers/index.html +1 -1
  176. package/temp/coverage/index.html +15 -15
  177. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1018 -0
  178. package/temp/coverage/lcov-report/{crypto → crypto-utils}/browserHashProvider.ts.html +3 -3
  179. package/temp/coverage/{crypto → lcov-report/crypto-utils}/index.html +21 -6
  180. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +493 -0
  181. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +276 -6
  182. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1366 -0
  183. package/temp/coverage/lcov-report/file-tree/index.html +55 -10
  184. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1216 -0
  185. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  186. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  187. package/temp/coverage/lcov-report/index.html +15 -15
  188. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  189. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  190. package/temp/coverage/lcov.info +2128 -451
  191. package/temp/coverage/url-utils/index.html +1 -1
  192. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  193. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  194. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
  195. package/temp/ts-web-extras.api.json +3236 -385
  196. package/temp/ts-web-extras.api.md +91 -1
  197. package/dist/packlets/crypto/browserHashProvider.js.map +0 -1
  198. package/dist/packlets/crypto/index.js.map +0 -1
  199. package/lib/packlets/crypto/browserHashProvider.d.ts.map +0 -1
  200. package/lib/packlets/crypto/browserHashProvider.js.map +0 -1
  201. package/lib/packlets/crypto/index.d.ts.map +0 -1
  202. package/lib/packlets/crypto/index.js.map +0 -1
  203. package/temp/build/typescript/ts_vnCx6LlY.json +0 -1
  204. /package/dist/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  205. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.d.ts +0 -0
  206. /package/lib/packlets/{crypto → crypto-utils}/browserHashProvider.js +0 -0
  207. /package/src/packlets/{crypto → crypto-utils}/browserHashProvider.ts +0 -0
  208. /package/temp/test/jest/jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/{0e/package_0eb6535f5987849d93ea51ef33a14cf6 → 8d/package_8dcbedef69e4299f0f51fcda8f4f1c8e} +0 -0
@@ -0,0 +1,308 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail, succeed, succeedWithDetail } from '@fgv/ts-utils';
23
+ import { FileTree } from '@fgv/ts-json-base';
24
+ import { isJsonObject } from '@fgv/ts-json-base';
25
+ /**
26
+ * Browser localStorage-backed file tree accessors with persistence support.
27
+ *
28
+ * Maps filesystem-like directory paths to localStorage keys, where each key stores
29
+ * multiple collections as a JSON object. This provides a general-purpose implementation
30
+ * for browser-based file tree persistence without requiring File System Access API.
31
+ *
32
+ * Storage format per key: `{ "collection-id": "<raw file content>" }`
33
+ * File paths map as: `/data/ingredients/collection-id.yaml` → stored in key for `/data/ingredients`
34
+ *
35
+ * Legacy format (v1): `{ "collection-id": { ...parsedJsonObject } }` is auto-migrated on load.
36
+ *
37
+ * @public
38
+ */
39
+ export class LocalStorageTreeAccessors extends FileTree.InMemoryTreeAccessors {
40
+ /**
41
+ * Private constructor. Use fromStorage() factory method instead.
42
+ * @internal
43
+ */
44
+ constructor(files, storage, pathToKeyMap, params) {
45
+ var _a;
46
+ super(files, params);
47
+ this._storage = storage;
48
+ this._pathToKeyMap = pathToKeyMap;
49
+ this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));
50
+ this._dirtyFiles = new Set();
51
+ this._autoSync = (_a = params === null || params === void 0 ? void 0 : params.autoSync) !== null && _a !== void 0 ? _a : false;
52
+ }
53
+ /**
54
+ * Create LocalStorageTreeAccessors from browser localStorage.
55
+ * Loads all collections from the configured storage keys.
56
+ *
57
+ * @param params - Configuration including path-to-key mappings
58
+ * @returns Result containing the accessors or an error
59
+ * @public
60
+ */
61
+ static fromStorage(params) {
62
+ var _a;
63
+ try {
64
+ const storage = (_a = params.storage) !== null && _a !== void 0 ? _a : (typeof window !== 'undefined' ? window.localStorage : undefined);
65
+ if (!storage) {
66
+ return fail('localStorage is not available');
67
+ }
68
+ const pathToKeyMap = new Map(Object.entries(params.pathToKeyMap));
69
+ const files = this._loadFromStorage(storage, pathToKeyMap, params);
70
+ return succeed(new LocalStorageTreeAccessors(files, storage, pathToKeyMap, params));
71
+ /* c8 ignore next 4 - defensive: outer catch for unexpected errors */
72
+ }
73
+ catch (error) {
74
+ const message = error instanceof Error ? error.message : String(error);
75
+ return fail(`Failed to create LocalStorageTreeAccessors: ${message}`);
76
+ }
77
+ }
78
+ /**
79
+ * Load all files from localStorage based on path-to-key mappings.
80
+ * @internal
81
+ */
82
+ static _loadFromStorage(storage, pathToKeyMap, params) {
83
+ const files = [];
84
+ for (const [dataPath, storageKey] of pathToKeyMap.entries()) {
85
+ const rawJson = storage.getItem(storageKey);
86
+ if (!rawJson) {
87
+ continue;
88
+ }
89
+ try {
90
+ const parsed = JSON.parse(rawJson);
91
+ if (!isJsonObject(parsed)) {
92
+ continue;
93
+ }
94
+ for (const [collectionId, contents] of Object.entries(parsed)) {
95
+ // Support both new format (string values) and legacy format (JsonObject values)
96
+ let rawContent;
97
+ let extension;
98
+ if (typeof contents === 'string') {
99
+ rawContent = contents;
100
+ // Infer extension: if content looks like JSON, use .json; otherwise .yaml
101
+ extension = this._looksLikeJson(contents) ? '.json' : '.yaml';
102
+ }
103
+ else if (isJsonObject(contents)) {
104
+ // Legacy format: migrate by stringifying
105
+ rawContent = JSON.stringify(contents);
106
+ extension = '.json';
107
+ }
108
+ else {
109
+ continue;
110
+ }
111
+ const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);
112
+ const contentType = (params === null || params === void 0 ? void 0 : params.inferContentType)
113
+ ? params.inferContentType(filePath, undefined).orDefault()
114
+ : undefined;
115
+ files.push({
116
+ path: filePath,
117
+ contents: rawContent,
118
+ contentType
119
+ });
120
+ }
121
+ }
122
+ catch (_a) {
123
+ // Skip corrupted data
124
+ continue;
125
+ }
126
+ }
127
+ return files;
128
+ }
129
+ /**
130
+ * Heuristic check: does the content look like JSON?
131
+ * @internal
132
+ */
133
+ static _looksLikeJson(content) {
134
+ const trimmed = content.trimStart();
135
+ return trimmed.startsWith('{') || trimmed.startsWith('[');
136
+ }
137
+ /**
138
+ * Join path components, handling leading/trailing slashes.
139
+ * @internal
140
+ */
141
+ static _joinPath(base, name) {
142
+ const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;
143
+ const cleanName = name.startsWith('/') ? name.slice(1) : name;
144
+ return `${cleanBase}/${cleanName}`;
145
+ }
146
+ /**
147
+ * Get the storage key for a given file path.
148
+ * @internal
149
+ */
150
+ _getStorageKeyForPath(path) {
151
+ // Find the longest matching prefix
152
+ let bestMatch;
153
+ for (const [prefix, key] of this._pathToKeyMap.entries()) {
154
+ if (path.startsWith(prefix)) {
155
+ if (!bestMatch || prefix.length > bestMatch.prefix.length) {
156
+ bestMatch = { prefix, key };
157
+ }
158
+ }
159
+ }
160
+ return bestMatch === null || bestMatch === void 0 ? void 0 : bestMatch.key;
161
+ }
162
+ /**
163
+ * Get the data path prefix for a given file path.
164
+ * @internal
165
+ */
166
+ _getDataPathForPath(path) {
167
+ for (const prefix of this._pathToKeyMap.keys()) {
168
+ if (path.startsWith(prefix)) {
169
+ return prefix;
170
+ }
171
+ }
172
+ /* c8 ignore next 2 - coverage intermittently missed in full suite */
173
+ return undefined;
174
+ }
175
+ /**
176
+ * Extract collection ID from a file path.
177
+ * Example: '/data/ingredients/my-collection.yaml' → 'my-collection'
178
+ * @internal
179
+ */
180
+ _getCollectionIdFromPath(path) {
181
+ const dataPath = this._getDataPathForPath(path);
182
+ /* c8 ignore next 3 - coverage intermittently missed in full suite */
183
+ if (!dataPath) {
184
+ return path;
185
+ }
186
+ const relativePath = path.slice(dataPath.length);
187
+ const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;
188
+ // Remove any file extension
189
+ const dotIndex = cleanPath.lastIndexOf('.');
190
+ return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;
191
+ }
192
+ /**
193
+ * Sync a single dirty file to localStorage.
194
+ * @internal
195
+ */
196
+ _syncFile(path) {
197
+ const storageKey = this._getStorageKeyForPath(path);
198
+ if (!storageKey) {
199
+ return fail(`No storage key configured for path: ${path}`);
200
+ }
201
+ const collectionId = this._getCollectionIdFromPath(path);
202
+ const contentsResult = this.getFileContents(path);
203
+ if (contentsResult.isFailure()) {
204
+ return fail(`Failed to get file contents for ${path}: ${contentsResult.message}`);
205
+ }
206
+ try {
207
+ const contents = contentsResult.value;
208
+ // Load existing data from storage
209
+ const existingJson = this._storage.getItem(storageKey);
210
+ let existing = {};
211
+ if (existingJson) {
212
+ try {
213
+ const parsed = JSON.parse(existingJson);
214
+ if (isJsonObject(parsed)) {
215
+ existing = parsed;
216
+ }
217
+ }
218
+ catch (_a) {
219
+ // Start fresh if corrupted
220
+ }
221
+ }
222
+ // Store raw content string (content-agnostic: JSON, YAML, etc.)
223
+ existing[collectionId] = contents;
224
+ this._storage.setItem(storageKey, JSON.stringify(existing));
225
+ return succeed(undefined);
226
+ /* c8 ignore next 4 - defensive: only triggers on storage quota or similar runtime errors */
227
+ }
228
+ catch (error) {
229
+ const message = error instanceof Error ? error.message : String(error);
230
+ return fail(`Failed to sync file ${path}: ${message}`);
231
+ }
232
+ }
233
+ /**
234
+ * Sync all dirty files to localStorage.
235
+ * @returns Result indicating success or failure
236
+ * @public
237
+ */
238
+ async syncToDisk() {
239
+ if (this._dirtyFiles.size === 0) {
240
+ return succeed(undefined);
241
+ }
242
+ const errors = [];
243
+ for (const path of this._dirtyFiles) {
244
+ const result = this._syncFile(path);
245
+ if (result.isFailure()) {
246
+ errors.push(result.message);
247
+ }
248
+ }
249
+ if (errors.length > 0) {
250
+ return fail(`Failed to sync ${errors.length} file(s): ${errors.join('; ')}`);
251
+ }
252
+ this._dirtyFiles.clear();
253
+ return succeed(undefined);
254
+ }
255
+ /**
256
+ * Check if there are unsaved changes.
257
+ * @returns True if there are dirty files
258
+ * @public
259
+ */
260
+ isDirty() {
261
+ return this._dirtyFiles.size > 0;
262
+ }
263
+ /**
264
+ * Get list of file paths with unsaved changes.
265
+ * @returns Array of dirty file paths
266
+ * @public
267
+ */
268
+ getDirtyPaths() {
269
+ return Array.from(this._dirtyFiles);
270
+ }
271
+ /**
272
+ * Save file contents. Marks file as dirty and optionally auto-syncs.
273
+ * @param path - File path
274
+ * @param contents - New file contents
275
+ * @returns Result with the saved contents or error
276
+ * @public
277
+ */
278
+ saveFileContents(path, contents) {
279
+ const result = super.saveFileContents(path, contents);
280
+ if (result.isSuccess()) {
281
+ this._dirtyFiles.add(path);
282
+ if (this._autoSync) {
283
+ const syncResult = this._syncFile(path);
284
+ if (syncResult.isSuccess()) {
285
+ this._dirtyFiles.delete(path);
286
+ }
287
+ else {
288
+ return fail(syncResult.message);
289
+ }
290
+ }
291
+ }
292
+ return result;
293
+ }
294
+ /**
295
+ * Check if a file is mutable and return persistence detail.
296
+ * @param path - File path to check
297
+ * @returns DetailedResult with mutability status and 'persistent' detail if mutable
298
+ * @public
299
+ */
300
+ fileIsMutable(path) {
301
+ const baseResult = super.fileIsMutable(path);
302
+ if (baseResult.isSuccess() && baseResult.value === true) {
303
+ return succeedWithDetail(true, 'persistent');
304
+ }
305
+ return baseResult;
306
+ }
307
+ }
308
+ //# sourceMappingURL=localStorageTreeAccessors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localStorageTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/localStorageTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAU,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAmB,MAAM,mBAAmB,CAAC;AA4BlE;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,yBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAS3C;;;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;;;;OAIG;IACI,OAAO;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,CAAC;IACnC,CAAC;IAED;;;;OAIG;IACI,aAAa;QAClB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACtC,CAAC;IAED;;;;;;OAMG;IACI,gBAAgB,CAAC,IAAY,EAAE,QAAgB;QACpD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC3B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACnB,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBACxC,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;oBAC3B,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAChC,CAAC;qBAAM,CAAC;oBACN,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAClC,CAAC;YACH,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,aAAa,CAAC,IAAY;QAC/B,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,UAAU,CAAC,SAAS,EAAE,IAAI,UAAU,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;YACxD,OAAO,iBAAiB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, Result, succeed, succeedWithDetail } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\n/**\n * Configuration for LocalStorageTreeAccessors.\n * @public\n */\nexport interface ILocalStorageTreeParams<TCT extends string = string>\n extends FileTree.IFileTreeInitParams<TCT> {\n /**\n * Map of directory path prefixes to localStorage keys.\n * Files under each prefix are stored in the corresponding localStorage key.\n * Example: \\{ '/data/ingredients': 'myapp:ingredients:v1' \\}\n */\n pathToKeyMap: Record<string, string>;\n\n /**\n * Storage instance to use. Defaults to window.localStorage.\n * Can be overridden for testing with mock storage.\n */\n storage?: Storage;\n\n /**\n * If true, automatically sync changes to localStorage on every modification.\n * If false (default), changes are only synced when syncToDisk() is called.\n */\n autoSync?: boolean;\n}\n\n/**\n * Browser localStorage-backed file tree accessors with persistence support.\n *\n * Maps filesystem-like directory paths to localStorage keys, where each key stores\n * multiple collections as a JSON object. This provides a general-purpose implementation\n * for browser-based file tree persistence without requiring File System Access API.\n *\n * Storage format per key: `{ \"collection-id\": \"<raw file content>\" }`\n * File paths map as: `/data/ingredients/collection-id.yaml` → stored in key for `/data/ingredients`\n *\n * Legacy format (v1): `{ \"collection-id\": { ...parsedJsonObject } }` is auto-migrated on load.\n *\n * @public\n */\nexport class LocalStorageTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _storage: Storage;\n private readonly _pathToKeyMap: Map<string, string>;\n private readonly _keyToPathMap: Map<string, string>;\n private readonly _dirtyFiles: Set<string>;\n private readonly _autoSync: boolean;\n\n /**\n * Private constructor. Use fromStorage() factory method instead.\n * @internal\n */\n private constructor(\n files: FileTree.IInMemoryFile<TCT>[],\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ) {\n super(files, params);\n this._storage = storage;\n this._pathToKeyMap = pathToKeyMap;\n this._keyToPathMap = new Map(Array.from(pathToKeyMap.entries()).map(([k, v]) => [v, k]));\n this._dirtyFiles = new Set();\n this._autoSync = params?.autoSync ?? false;\n }\n\n /**\n * Create LocalStorageTreeAccessors from browser localStorage.\n * Loads all collections from the configured storage keys.\n *\n * @param params - Configuration including path-to-key mappings\n * @returns Result containing the accessors or an error\n * @public\n */\n public static fromStorage<TCT extends string = string>(\n params: ILocalStorageTreeParams<TCT>\n ): Result<LocalStorageTreeAccessors<TCT>> {\n try {\n const storage = params.storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);\n if (!storage) {\n return fail('localStorage is not available');\n }\n\n const pathToKeyMap = new Map(Object.entries(params.pathToKeyMap));\n const files = this._loadFromStorage<TCT>(storage, pathToKeyMap, params);\n\n return succeed(new LocalStorageTreeAccessors<TCT>(files, storage, pathToKeyMap, params));\n /* c8 ignore next 4 - defensive: outer catch for unexpected errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to create LocalStorageTreeAccessors: ${message}`);\n }\n }\n\n /**\n * Load all files from localStorage based on path-to-key mappings.\n * @internal\n */\n private static _loadFromStorage<TCT extends string = string>(\n storage: Storage,\n pathToKeyMap: Map<string, string>,\n params?: ILocalStorageTreeParams<TCT>\n ): FileTree.IInMemoryFile<TCT>[] {\n const files: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const [dataPath, storageKey] of pathToKeyMap.entries()) {\n const rawJson = storage.getItem(storageKey);\n if (!rawJson) {\n continue;\n }\n\n try {\n const parsed: unknown = JSON.parse(rawJson);\n if (!isJsonObject(parsed)) {\n continue;\n }\n\n for (const [collectionId, contents] of Object.entries(parsed)) {\n // Support both new format (string values) and legacy format (JsonObject values)\n let rawContent: string;\n let extension: string;\n if (typeof contents === 'string') {\n rawContent = contents;\n // Infer extension: if content looks like JSON, use .json; otherwise .yaml\n extension = this._looksLikeJson(contents) ? '.json' : '.yaml';\n } else if (isJsonObject(contents)) {\n // Legacy format: migrate by stringifying\n rawContent = JSON.stringify(contents);\n extension = '.json';\n } else {\n continue;\n }\n\n const filePath = this._joinPath(dataPath, `${collectionId}${extension}`);\n const contentType = params?.inferContentType\n ? params.inferContentType(filePath, undefined).orDefault()\n : undefined;\n\n files.push({\n path: filePath,\n contents: rawContent,\n contentType\n });\n }\n } catch {\n // Skip corrupted data\n continue;\n }\n }\n\n return files;\n }\n\n /**\n * Heuristic check: does the content look like JSON?\n * @internal\n */\n private static _looksLikeJson(content: string): boolean {\n const trimmed = content.trimStart();\n return trimmed.startsWith('{') || trimmed.startsWith('[');\n }\n\n /**\n * Join path components, handling leading/trailing slashes.\n * @internal\n */\n private static _joinPath(base: string, name: string): string {\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanName = name.startsWith('/') ? name.slice(1) : name;\n return `${cleanBase}/${cleanName}`;\n }\n\n /**\n * Get the storage key for a given file path.\n * @internal\n */\n private _getStorageKeyForPath(path: string): string | undefined {\n // Find the longest matching prefix\n let bestMatch: { prefix: string; key: string } | undefined;\n for (const [prefix, key] of this._pathToKeyMap.entries()) {\n if (path.startsWith(prefix)) {\n if (!bestMatch || prefix.length > bestMatch.prefix.length) {\n bestMatch = { prefix, key };\n }\n }\n }\n return bestMatch?.key;\n }\n\n /**\n * Get the data path prefix for a given file path.\n * @internal\n */\n private _getDataPathForPath(path: string): string | undefined {\n for (const prefix of this._pathToKeyMap.keys()) {\n if (path.startsWith(prefix)) {\n return prefix;\n }\n }\n /* c8 ignore next 2 - coverage intermittently missed in full suite */\n return undefined;\n }\n\n /**\n * Extract collection ID from a file path.\n * Example: '/data/ingredients/my-collection.yaml' → 'my-collection'\n * @internal\n */\n private _getCollectionIdFromPath(path: string): string {\n const dataPath = this._getDataPathForPath(path);\n /* c8 ignore next 3 - coverage intermittently missed in full suite */\n if (!dataPath) {\n return path;\n }\n\n const relativePath = path.slice(dataPath.length);\n const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath;\n\n // Remove any file extension\n const dotIndex = cleanPath.lastIndexOf('.');\n return dotIndex > 0 ? cleanPath.slice(0, dotIndex) : cleanPath;\n }\n\n /**\n * Sync a single dirty file to localStorage.\n * @internal\n */\n private _syncFile(path: string): Result<void> {\n const storageKey = this._getStorageKeyForPath(path);\n if (!storageKey) {\n return fail(`No storage key configured for path: ${path}`);\n }\n\n const collectionId = this._getCollectionIdFromPath(path);\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`Failed to get file contents for ${path}: ${contentsResult.message}`);\n }\n\n try {\n const contents = contentsResult.value;\n\n // Load existing data from storage\n const existingJson = this._storage.getItem(storageKey);\n let existing: Record<string, unknown> = {};\n if (existingJson) {\n try {\n const parsed = JSON.parse(existingJson);\n if (isJsonObject(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch {\n // Start fresh if corrupted\n }\n }\n\n // Store raw content string (content-agnostic: JSON, YAML, etc.)\n existing[collectionId] = contents;\n this._storage.setItem(storageKey, JSON.stringify(existing));\n\n return succeed(undefined);\n /* c8 ignore next 4 - defensive: only triggers on storage quota or similar runtime errors */\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Failed to sync file ${path}: ${message}`);\n }\n }\n\n /**\n * Sync all dirty files to localStorage.\n * @returns Result indicating success or failure\n * @public\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0) {\n return succeed(undefined);\n }\n\n const errors: string[] = [];\n for (const path of this._dirtyFiles) {\n const result = this._syncFile(path);\n if (result.isFailure()) {\n errors.push(result.message);\n }\n }\n\n if (errors.length > 0) {\n return fail(`Failed to sync ${errors.length} file(s): ${errors.join('; ')}`);\n }\n\n this._dirtyFiles.clear();\n return succeed(undefined);\n }\n\n /**\n * Check if there are unsaved changes.\n * @returns True if there are dirty files\n * @public\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0;\n }\n\n /**\n * Get list of file paths with unsaved changes.\n * @returns Array of dirty file paths\n * @public\n */\n public getDirtyPaths(): string[] {\n return Array.from(this._dirtyFiles);\n }\n\n /**\n * Save file contents. Marks file as dirty and optionally auto-syncs.\n * @param path - File path\n * @param contents - New file contents\n * @returns Result with the saved contents or error\n * @public\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isSuccess()) {\n this._dirtyFiles.add(path);\n if (this._autoSync) {\n const syncResult = this._syncFile(path);\n if (syncResult.isSuccess()) {\n this._dirtyFiles.delete(path);\n } else {\n return fail(syncResult.message);\n }\n }\n }\n return result;\n }\n\n /**\n * Check if a file is mutable and return persistence detail.\n * @param path - File path to check\n * @returns DetailedResult with mutability status and 'persistent' detail if mutable\n * @public\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const baseResult = super.fileIsMutable(path);\n if (baseResult.isSuccess() && baseResult.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return baseResult;\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export const createStore = jest.fn(() => ({}));
2
+ export const get = jest.fn();
3
+ export const set = jest.fn();
4
+ export const del = jest.fn();
5
+ export const keys = jest.fn();
6
+ //# sourceMappingURL=idb-keyval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idb-keyval.js","sourceRoot":"","sources":["../../../src/test/mocks/idb-keyval.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC","sourcesContent":["export const createStore = jest.fn(() => ({}));\nexport const get = jest.fn();\nexport const set = jest.fn();\nexport const del = jest.fn();\nexport const keys = jest.fn();\n"]}
@@ -20,7 +20,7 @@
20
20
  * SOFTWARE.
21
21
  */
22
22
  import '@fgv/ts-utils-jest';
23
- import { BrowserHashProvider } from '../../packlets/crypto';
23
+ import { BrowserHashProvider } from '../../packlets/crypto-utils';
24
24
  describe('BrowserHashProvider', () => {
25
25
  describe('hashString', () => {
26
26
  test('successfully hashes a string with SHA-256', async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"browserHashProvider.test.js","sourceRoot":"","sources":["../../../src/test/unit/browserHashProvider.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,QAAQ,CAAC,YAAY,EAAE,GAAG,EAAE;QAC1B,IAAI,CAAC,2CAA2C,EAAE,KAAK,IAAI,EAAE;YA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C,SAAS,EAAE,EAAE,CAAC;gBACnD,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAChD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport '@fgv/ts-utils-jest';\nimport { BrowserHashProvider } from '../../packlets/crypto';\n\ndescribe('BrowserHashProvider', () => {\n describe('hashString', () => {\n test('successfully hashes a string with SHA-256', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-256');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{64}$/); // SHA-256 produces 64 hex characters\n });\n });\n\n test('successfully hashes a string with SHA-1', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-1');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{40}$/); // SHA-1 produces 40 hex characters\n });\n });\n\n test('successfully hashes a string with SHA-512', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-512');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{128}$/); // SHA-512 produces 128 hex characters\n });\n });\n\n test('uses SHA-256 as default algorithm', async () => {\n const result = await BrowserHashProvider.hashString('test data');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/); // SHA-256 produces 64 hex characters\n });\n });\n\n test('produces consistent hash for same input', async () => {\n const input = 'consistent input';\n const result1 = await BrowserHashProvider.hashString(input);\n const result2 = await BrowserHashProvider.hashString(input);\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).toBe(result2.value);\n }\n });\n\n test('produces different hashes for different inputs', async () => {\n const result1 = await BrowserHashProvider.hashString('input1');\n const result2 = await BrowserHashProvider.hashString('input2');\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).not.toBe(result2.value);\n }\n });\n\n test('handles empty string input', async () => {\n const result = await BrowserHashProvider.hashString('');\n expect(result).toSucceed();\n });\n\n test('handles unicode input', async () => {\n const result = await BrowserHashProvider.hashString('🚀 Unicode test 测试');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/);\n });\n });\n\n test('fails when crypto.subtle is unavailable', async () => {\n const originalCrypto = global.crypto;\n // @ts-ignore - Intentionally removing crypto for test\n delete global.crypto;\n const result = await BrowserHashProvider.hashString('test');\n expect(result).toFailWith(/Hash computation failed/);\n global.crypto = originalCrypto;\n });\n\n test('handles invalid algorithm gracefully', async () => {\n const result = await BrowserHashProvider.hashString('test', 'INVALID-ALG');\n expect(result).toFailWith(/Hash computation failed/);\n });\n });\n\n describe('hashParts', () => {\n test('hashes multiple parts with default separator', async () => {\n const parts = ['part1', 'part2', 'part3'];\n const result = await BrowserHashProvider.hashParts(parts);\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/);\n });\n });\n\n test('hashes multiple parts with custom separator', async () => {\n const parts = ['part1', 'part2', 'part3'];\n const result1 = await BrowserHashProvider.hashParts(parts, 'SHA-256', '|');\n const result2 = await BrowserHashProvider.hashParts(parts, 'SHA-256', ',');\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).not.toBe(result2.value);\n }\n });\n\n test('produces same hash as hashString for joined parts', async () => {\n const parts = ['a', 'b', 'c'];\n const separator = '-';\n const joined = parts.join(separator);\n const partsResult = await BrowserHashProvider.hashParts(parts, 'SHA-256', separator);\n const stringResult = await BrowserHashProvider.hashString(joined);\n expect(partsResult).toSucceed();\n expect(stringResult).toSucceed();\n if (partsResult.isSuccess() && stringResult.isSuccess()) {\n expect(partsResult.value).toBe(stringResult.value);\n }\n });\n\n test('handles empty array', async () => {\n const result = await BrowserHashProvider.hashParts([]);\n expect(result).toSucceed();\n });\n\n test('handles single part', async () => {\n const result = await BrowserHashProvider.hashParts(['single']);\n const stringResult = await BrowserHashProvider.hashString('single');\n expect(result).toSucceed();\n expect(stringResult).toSucceed();\n if (result.isSuccess() && stringResult.isSuccess()) {\n expect(result.value).toBe(stringResult.value);\n }\n });\n });\n});\n"]}
1
+ {"version":3,"file":"browserHashProvider.test.js","sourceRoot":"","sources":["../../../src/test/unit/browserHashProvider.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,QAAQ,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Y,CAAC,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,MAAM,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC;gBACnD,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAChD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport '@fgv/ts-utils-jest';\nimport { BrowserHashProvider } from '../../packlets/crypto-utils';\n\ndescribe('BrowserHashProvider', () => {\n describe('hashString', () => {\n test('successfully hashes a string with SHA-256', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-256');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{64}$/); // SHA-256 produces 64 hex characters\n });\n });\n\n test('successfully hashes a string with SHA-1', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-1');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{40}$/); // SHA-1 produces 40 hex characters\n });\n });\n\n test('successfully hashes a string with SHA-512', async () => {\n const result = await BrowserHashProvider.hashString('test data', 'SHA-512');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(typeof hash).toBe('string');\n expect(hash).toMatch(/^[a-f0-9]{128}$/); // SHA-512 produces 128 hex characters\n });\n });\n\n test('uses SHA-256 as default algorithm', async () => {\n const result = await BrowserHashProvider.hashString('test data');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/); // SHA-256 produces 64 hex characters\n });\n });\n\n test('produces consistent hash for same input', async () => {\n const input = 'consistent input';\n const result1 = await BrowserHashProvider.hashString(input);\n const result2 = await BrowserHashProvider.hashString(input);\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).toBe(result2.value);\n }\n });\n\n test('produces different hashes for different inputs', async () => {\n const result1 = await BrowserHashProvider.hashString('input1');\n const result2 = await BrowserHashProvider.hashString('input2');\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).not.toBe(result2.value);\n }\n });\n\n test('handles empty string input', async () => {\n const result = await BrowserHashProvider.hashString('');\n expect(result).toSucceed();\n });\n\n test('handles unicode input', async () => {\n const result = await BrowserHashProvider.hashString('🚀 Unicode test 测试');\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/);\n });\n });\n\n test('fails when crypto.subtle is unavailable', async () => {\n const originalCrypto = global.crypto;\n // @ts-ignore - Intentionally removing crypto for test\n delete global.crypto;\n const result = await BrowserHashProvider.hashString('test');\n expect(result).toFailWith(/Hash computation failed/);\n global.crypto = originalCrypto;\n });\n\n test('handles invalid algorithm gracefully', async () => {\n const result = await BrowserHashProvider.hashString('test', 'INVALID-ALG');\n expect(result).toFailWith(/Hash computation failed/);\n });\n });\n\n describe('hashParts', () => {\n test('hashes multiple parts with default separator', async () => {\n const parts = ['part1', 'part2', 'part3'];\n const result = await BrowserHashProvider.hashParts(parts);\n expect(result).toSucceedAndSatisfy((hash) => {\n expect(hash).toMatch(/^[a-f0-9]{64}$/);\n });\n });\n\n test('hashes multiple parts with custom separator', async () => {\n const parts = ['part1', 'part2', 'part3'];\n const result1 = await BrowserHashProvider.hashParts(parts, 'SHA-256', '|');\n const result2 = await BrowserHashProvider.hashParts(parts, 'SHA-256', ',');\n expect(result1).toSucceed();\n expect(result2).toSucceed();\n if (result1.isSuccess() && result2.isSuccess()) {\n expect(result1.value).not.toBe(result2.value);\n }\n });\n\n test('produces same hash as hashString for joined parts', async () => {\n const parts = ['a', 'b', 'c'];\n const separator = '-';\n const joined = parts.join(separator);\n const partsResult = await BrowserHashProvider.hashParts(parts, 'SHA-256', separator);\n const stringResult = await BrowserHashProvider.hashString(joined);\n expect(partsResult).toSucceed();\n expect(stringResult).toSucceed();\n if (partsResult.isSuccess() && stringResult.isSuccess()) {\n expect(partsResult.value).toBe(stringResult.value);\n }\n });\n\n test('handles empty array', async () => {\n const result = await BrowserHashProvider.hashParts([]);\n expect(result).toSucceed();\n });\n\n test('handles single part', async () => {\n const result = await BrowserHashProvider.hashParts(['single']);\n const stringResult = await BrowserHashProvider.hashString('single');\n expect(result).toSucceed();\n expect(stringResult).toSucceed();\n if (result.isSuccess() && stringResult.isSuccess()) {\n expect(result.value).toBe(stringResult.value);\n }\n });\n });\n});\n"]}
@@ -0,0 +1,190 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import '@fgv/ts-utils-jest';
23
+ import { DirectoryHandleStore, DEFAULT_DIRECTORY_HANDLE_DB, DEFAULT_DIRECTORY_HANDLE_STORE } from '../../packlets/file-tree/directoryHandleStore';
24
+ import { get, set, del, keys, createStore } from 'idb-keyval';
25
+ const mockGet = jest.mocked(get);
26
+ const mockSet = jest.mocked(set);
27
+ const mockDel = jest.mocked(del);
28
+ const mockKeys = jest.mocked(keys);
29
+ const mockCreateStore = jest.mocked(createStore);
30
+ function makeMockHandle(name) {
31
+ return {
32
+ kind: 'directory',
33
+ name,
34
+ isSameEntry: jest.fn(),
35
+ queryPermission: jest.fn(),
36
+ requestPermission: jest.fn(),
37
+ getDirectoryHandle: jest.fn(),
38
+ getFileHandle: jest.fn(),
39
+ removeEntry: jest.fn(),
40
+ resolve: jest.fn(),
41
+ keys: jest.fn(),
42
+ values: jest.fn(),
43
+ entries: jest.fn(),
44
+ [Symbol.asyncIterator]: jest.fn()
45
+ };
46
+ }
47
+ describe('DirectoryHandleStore', () => {
48
+ beforeEach(() => {
49
+ jest.clearAllMocks();
50
+ });
51
+ describe('constants', () => {
52
+ test('DEFAULT_DIRECTORY_HANDLE_DB has expected value', () => {
53
+ expect(DEFAULT_DIRECTORY_HANDLE_DB).toBe('chocolate-lab-storage');
54
+ });
55
+ test('DEFAULT_DIRECTORY_HANDLE_STORE has expected value', () => {
56
+ expect(DEFAULT_DIRECTORY_HANDLE_STORE).toBe('directory-handles');
57
+ });
58
+ });
59
+ describe('constructor', () => {
60
+ test('uses default db and store names', () => {
61
+ new DirectoryHandleStore();
62
+ expect(mockCreateStore).toHaveBeenCalledWith(DEFAULT_DIRECTORY_HANDLE_DB, DEFAULT_DIRECTORY_HANDLE_STORE);
63
+ });
64
+ test('uses custom db and store names', () => {
65
+ new DirectoryHandleStore('custom-db', 'custom-store');
66
+ expect(mockCreateStore).toHaveBeenCalledWith('custom-db', 'custom-store');
67
+ });
68
+ });
69
+ describe('save', () => {
70
+ test('saves a handle successfully', async () => {
71
+ mockSet.mockResolvedValue(undefined);
72
+ const store = new DirectoryHandleStore();
73
+ const handle = makeMockHandle('my-dir');
74
+ const result = await store.save('my-dir', handle);
75
+ expect(result).toSucceed();
76
+ expect(mockSet).toHaveBeenCalledWith('my-dir', handle, expect.anything());
77
+ });
78
+ test('returns failure when set throws', async () => {
79
+ mockSet.mockRejectedValue(new Error('IndexedDB unavailable'));
80
+ const store = new DirectoryHandleStore();
81
+ const handle = makeMockHandle('my-dir');
82
+ const result = await store.save('my-dir', handle);
83
+ expect(result).toFailWith(/IndexedDB unavailable/);
84
+ });
85
+ });
86
+ describe('load', () => {
87
+ test('returns the handle when found', async () => {
88
+ const handle = makeMockHandle('my-dir');
89
+ mockGet.mockResolvedValue(handle);
90
+ const store = new DirectoryHandleStore();
91
+ const result = await store.load('my-dir');
92
+ expect(result).toSucceedWith(handle);
93
+ expect(mockGet).toHaveBeenCalledWith('my-dir', expect.anything());
94
+ });
95
+ test('returns undefined when not found', async () => {
96
+ mockGet.mockResolvedValue(undefined);
97
+ const store = new DirectoryHandleStore();
98
+ const result = await store.load('missing');
99
+ expect(result).toSucceedWith(undefined);
100
+ });
101
+ test('returns failure when get throws', async () => {
102
+ mockGet.mockRejectedValue(new Error('read error'));
103
+ const store = new DirectoryHandleStore();
104
+ const result = await store.load('my-dir');
105
+ expect(result).toFailWith(/read error/);
106
+ });
107
+ });
108
+ describe('remove', () => {
109
+ test('removes a handle successfully', async () => {
110
+ mockDel.mockResolvedValue(undefined);
111
+ const store = new DirectoryHandleStore();
112
+ const result = await store.remove('my-dir');
113
+ expect(result).toSucceed();
114
+ expect(mockDel).toHaveBeenCalledWith('my-dir', expect.anything());
115
+ });
116
+ test('returns failure when del throws', async () => {
117
+ mockDel.mockRejectedValue(new Error('delete error'));
118
+ const store = new DirectoryHandleStore();
119
+ const result = await store.remove('my-dir');
120
+ expect(result).toFailWith(/delete error/);
121
+ });
122
+ });
123
+ describe('getAllLabels', () => {
124
+ test('returns all keys', async () => {
125
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
126
+ const store = new DirectoryHandleStore();
127
+ const result = await store.getAllLabels();
128
+ expect(result).toSucceedWith(['dir-a', 'dir-b']);
129
+ expect(mockKeys).toHaveBeenCalledWith(expect.anything());
130
+ });
131
+ test('returns empty array when no keys', async () => {
132
+ mockKeys.mockResolvedValue([]);
133
+ const store = new DirectoryHandleStore();
134
+ const result = await store.getAllLabels();
135
+ expect(result).toSucceedWith([]);
136
+ });
137
+ test('returns failure when keys throws', async () => {
138
+ mockKeys.mockRejectedValue(new Error('keys error'));
139
+ const store = new DirectoryHandleStore();
140
+ const result = await store.getAllLabels();
141
+ expect(result).toFailWith(/keys error/);
142
+ });
143
+ });
144
+ describe('getAll', () => {
145
+ test('returns all label/handle pairs', async () => {
146
+ const handleA = makeMockHandle('dir-a');
147
+ const handleB = makeMockHandle('dir-b');
148
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
149
+ mockGet.mockResolvedValueOnce(handleA).mockResolvedValueOnce(handleB);
150
+ const store = new DirectoryHandleStore();
151
+ const result = await store.getAll();
152
+ expect(result).toSucceedAndSatisfy((entries) => {
153
+ expect(entries).toHaveLength(2);
154
+ expect(entries[0]).toEqual({ label: 'dir-a', handle: handleA });
155
+ expect(entries[1]).toEqual({ label: 'dir-b', handle: handleB });
156
+ });
157
+ });
158
+ test('returns empty array when no handles stored', async () => {
159
+ mockKeys.mockResolvedValue([]);
160
+ const store = new DirectoryHandleStore();
161
+ const result = await store.getAll();
162
+ expect(result).toSucceedWith([]);
163
+ });
164
+ test('skips entries where handle is undefined', async () => {
165
+ const handleA = makeMockHandle('dir-a');
166
+ mockKeys.mockResolvedValue(['dir-a', 'dir-b']);
167
+ mockGet.mockResolvedValueOnce(handleA).mockResolvedValueOnce(undefined);
168
+ const store = new DirectoryHandleStore();
169
+ const result = await store.getAll();
170
+ expect(result).toSucceedAndSatisfy((entries) => {
171
+ expect(entries).toHaveLength(1);
172
+ expect(entries[0]).toEqual({ label: 'dir-a', handle: handleA });
173
+ });
174
+ });
175
+ test('returns failure when getAllLabels fails', async () => {
176
+ mockKeys.mockRejectedValue(new Error('keys error'));
177
+ const store = new DirectoryHandleStore();
178
+ const result = await store.getAll();
179
+ expect(result).toFailWith(/keys error/);
180
+ });
181
+ test('returns failure when load fails for a key', async () => {
182
+ mockKeys.mockResolvedValue(['dir-a']);
183
+ mockGet.mockRejectedValue(new Error('load error'));
184
+ const store = new DirectoryHandleStore();
185
+ const result = await store.getAll();
186
+ expect(result).toFailWith(/load error/);
187
+ });
188
+ });
189
+ });
190
+ //# sourceMappingURL=directoryHandleStore.test.js.map