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

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 (332) hide show
  1. package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +56 -33
  2. package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +75 -0
  3. package/.rush/temp/operation/build/all.log +56 -33
  4. package/.rush/temp/operation/build/error.log +18 -0
  5. package/.rush/temp/operation/build/log-chunks.jsonl +56 -33
  6. package/.rush/temp/operation/build/state.json +1 -1
  7. package/.rush/temp/operation/test/all.log +75 -0
  8. package/.rush/temp/operation/test/error.log +18 -0
  9. package/.rush/temp/operation/test/log-chunks.jsonl +75 -0
  10. package/.rush/temp/operation/test/state.json +3 -0
  11. package/dist/packlets/file-tree/fileApiTreeAccessors.js +15 -0
  12. package/dist/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  13. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js +79 -10
  14. package/dist/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
  15. package/dist/packlets/file-tree/httpTreeAccessors.js +336 -0
  16. package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -0
  17. package/dist/packlets/file-tree/index.js +1 -0
  18. package/dist/packlets/file-tree/index.js.map +1 -1
  19. package/dist/packlets/file-tree/localStorageTreeAccessors.js +51 -0
  20. package/dist/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
  21. package/dist/test/unit/fileApiTreeAccessors.test.js +51 -0
  22. package/dist/test/unit/fileApiTreeAccessors.test.js.map +1 -1
  23. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js +265 -160
  24. package/dist/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -1
  25. package/dist/test/unit/httpTreeAccessors.test.js +1229 -0
  26. package/dist/test/unit/httpTreeAccessors.test.js.map +1 -0
  27. package/dist/test/unit/localStorageTreeAccessors.test.js +218 -1
  28. package/dist/test/unit/localStorageTreeAccessors.test.js.map +1 -1
  29. package/dist/ts-web-extras.d.ts +138 -0
  30. package/docs/@fgv/namespaces/CryptoUtils/README.md +18 -0
  31. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserCryptoProvider.md +203 -0
  32. package/docs/@fgv/namespaces/CryptoUtils/classes/BrowserHashProvider.md +63 -0
  33. package/docs/@fgv/namespaces/CryptoUtils/functions/createBrowserCryptoProvider.md +18 -0
  34. package/docs/@fgv/namespaces/FileTreeHelpers/README.md +19 -0
  35. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileListMetadata.md +23 -0
  36. package/docs/@fgv/namespaces/FileTreeHelpers/functions/extractFileMetadata.md +23 -0
  37. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromDirectoryUpload.md +33 -0
  38. package/docs/@fgv/namespaces/FileTreeHelpers/functions/fromFileList.md +33 -0
  39. package/docs/@fgv/namespaces/FileTreeHelpers/functions/getOriginalFile.md +25 -0
  40. package/docs/@fgv/namespaces/FileTreeHelpers/variables/defaultFileApiTreeInitParams.md +11 -0
  41. package/docs/README.md +78 -0
  42. package/docs/classes/DirectoryHandleStore.md +116 -0
  43. package/docs/classes/FileApiTreeAccessors.md +286 -0
  44. package/docs/classes/FileSystemAccessTreeAccessors.md +557 -0
  45. package/docs/classes/HttpTreeAccessors.md +508 -0
  46. package/docs/classes/LocalStorageTreeAccessors.md +520 -0
  47. package/docs/functions/exportAsJson.md +23 -0
  48. package/docs/functions/exportUsingFileSystemAPI.md +26 -0
  49. package/docs/functions/extractDirectoryPath.md +23 -0
  50. package/docs/functions/isDirectoryHandle.md +23 -0
  51. package/docs/functions/isFileHandle.md +23 -0
  52. package/docs/functions/isFilePath.md +21 -0
  53. package/docs/functions/parseContextFilter.md +22 -0
  54. package/docs/functions/parseQualifierDefaults.md +22 -0
  55. package/docs/functions/parseResourceTypes.md +22 -0
  56. package/docs/functions/parseUrlParameters.md +15 -0
  57. package/docs/functions/safeShowDirectoryPicker.md +24 -0
  58. package/docs/functions/safeShowOpenFilePicker.md +24 -0
  59. package/docs/functions/safeShowSaveFilePicker.md +24 -0
  60. package/docs/functions/supportsFileSystemAccess.md +23 -0
  61. package/docs/interfaces/FilePickerAcceptType.md +16 -0
  62. package/docs/interfaces/FileSystemCreateWritableOptions.md +15 -0
  63. package/docs/interfaces/FileSystemDirectoryHandle.md +187 -0
  64. package/docs/interfaces/FileSystemFileHandle.md +106 -0
  65. package/docs/interfaces/FileSystemGetDirectoryOptions.md +15 -0
  66. package/docs/interfaces/FileSystemGetFileOptions.md +15 -0
  67. package/docs/interfaces/FileSystemHandle.md +69 -0
  68. package/docs/interfaces/FileSystemHandlePermissionDescriptor.md +15 -0
  69. package/docs/interfaces/FileSystemRemoveOptions.md +15 -0
  70. package/docs/interfaces/FileSystemWritableFileStream.md +127 -0
  71. package/docs/interfaces/IDirectoryHandleTreeInitializer.md +17 -0
  72. package/docs/interfaces/IFileHandleTreeInitializer.md +16 -0
  73. package/docs/interfaces/IFileListTreeInitializer.md +15 -0
  74. package/docs/interfaces/IFileMetadata.md +19 -0
  75. package/docs/interfaces/IFileSystemAccessTreeParams.md +30 -0
  76. package/docs/interfaces/IFsAccessApis.md +57 -0
  77. package/docs/interfaces/IHttpTreeParams.md +32 -0
  78. package/docs/interfaces/ILocalStorageTreeParams.md +30 -0
  79. package/docs/interfaces/IUrlConfigOptions.md +27 -0
  80. package/docs/interfaces/ShowDirectoryPickerOptions.md +17 -0
  81. package/docs/interfaces/ShowOpenFilePickerOptions.md +19 -0
  82. package/docs/interfaces/ShowSaveFilePickerOptions.md +19 -0
  83. package/docs/type-aliases/TreeInitializer.md +11 -0
  84. package/docs/type-aliases/WellKnownDirectory.md +11 -0
  85. package/docs/type-aliases/WindowWithFsAccess.md +11 -0
  86. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_DB.md +11 -0
  87. package/docs/variables/DEFAULT_DIRECTORY_HANDLE_STORE.md +11 -0
  88. package/etc/ts-web-extras.api.md +33 -0
  89. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts +9 -0
  90. package/lib/packlets/file-tree/fileApiTreeAccessors.d.ts.map +1 -1
  91. package/lib/packlets/file-tree/fileApiTreeAccessors.js +15 -0
  92. package/lib/packlets/file-tree/fileApiTreeAccessors.js.map +1 -1
  93. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts +17 -1
  94. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.d.ts.map +1 -1
  95. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js +78 -9
  96. package/lib/packlets/file-tree/fileSystemAccessTreeAccessors.js.map +1 -1
  97. package/lib/packlets/file-tree/httpTreeAccessors.d.ts +102 -0
  98. package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -0
  99. package/lib/packlets/file-tree/httpTreeAccessors.js +340 -0
  100. package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -0
  101. package/lib/packlets/file-tree/index.d.ts +1 -0
  102. package/lib/packlets/file-tree/index.d.ts.map +1 -1
  103. package/lib/packlets/file-tree/index.js +1 -0
  104. package/lib/packlets/file-tree/index.js.map +1 -1
  105. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts +12 -0
  106. package/lib/packlets/file-tree/localStorageTreeAccessors.d.ts.map +1 -1
  107. package/lib/packlets/file-tree/localStorageTreeAccessors.js +51 -0
  108. package/lib/packlets/file-tree/localStorageTreeAccessors.js.map +1 -1
  109. package/lib/test/unit/fileApiTreeAccessors.test.js +51 -0
  110. package/lib/test/unit/fileApiTreeAccessors.test.js.map +1 -1
  111. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js +265 -160
  112. package/lib/test/unit/fileSystemAccessTreeAccessors.test.js.map +1 -1
  113. package/lib/test/unit/httpTreeAccessors.test.d.ts +2 -0
  114. package/lib/test/unit/httpTreeAccessors.test.d.ts.map +1 -0
  115. package/lib/test/unit/httpTreeAccessors.test.js +1231 -0
  116. package/lib/test/unit/httpTreeAccessors.test.js.map +1 -0
  117. package/lib/test/unit/localStorageTreeAccessors.test.js +218 -1
  118. package/lib/test/unit/localStorageTreeAccessors.test.js.map +1 -1
  119. package/package.json +25 -25
  120. package/rush-logs/ts-web-extras.build.cache.log +0 -3
  121. package/rush-logs/ts-web-extras.build.error.log +18 -0
  122. package/rush-logs/ts-web-extras.build.log +56 -33
  123. package/rush-logs/ts-web-extras.test.cache.log +1 -0
  124. package/rush-logs/ts-web-extras.test.error.log +18 -0
  125. package/rush-logs/ts-web-extras.test.log +75 -0
  126. package/src/packlets/file-tree/fileApiTreeAccessors.ts +18 -0
  127. package/src/packlets/file-tree/fileSystemAccessTreeAccessors.ts +100 -8
  128. package/src/packlets/file-tree/httpTreeAccessors.ts +448 -0
  129. package/src/packlets/file-tree/index.ts +1 -0
  130. package/src/packlets/file-tree/localStorageTreeAccessors.ts +53 -0
  131. package/src/test/unit/fileApiTreeAccessors.test.ts +69 -0
  132. package/src/test/unit/fileSystemAccessTreeAccessors.test.ts +341 -188
  133. package/src/test/unit/httpTreeAccessors.test.ts +1571 -0
  134. package/src/test/unit/localStorageTreeAccessors.test.ts +269 -1
  135. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  136. package/temp/coverage/crypto/browserHashProvider.ts.html +304 -0
  137. package/temp/coverage/crypto/index.html +116 -0
  138. package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1 -1
  139. package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
  140. package/temp/coverage/crypto-utils/index.html +1 -1
  141. package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
  142. package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +60 -6
  143. package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +410 -134
  144. package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1429 -0
  145. package/temp/coverage/file-tree/index.html +35 -20
  146. package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +318 -159
  147. package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
  148. package/temp/coverage/helpers/index.html +1 -1
  149. package/temp/coverage/index.html +11 -11
  150. package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +304 -0
  151. package/temp/coverage/lcov-report/crypto/index.html +116 -0
  152. package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1 -1
  153. package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
  154. package/temp/coverage/lcov-report/crypto-utils/index.html +1 -1
  155. package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
  156. package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +60 -6
  157. package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +410 -134
  158. package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1429 -0
  159. package/temp/coverage/lcov-report/file-tree/index.html +35 -20
  160. package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +318 -159
  161. package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
  162. package/temp/coverage/lcov-report/helpers/index.html +1 -1
  163. package/temp/coverage/lcov-report/index.html +11 -11
  164. package/temp/coverage/lcov-report/url-utils/index.html +1 -1
  165. package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
  166. package/temp/coverage/lcov.info +2021 -1197
  167. package/temp/coverage/url-utils/index.html +1 -1
  168. package/temp/coverage/url-utils/urlParams.ts.html +1 -1
  169. package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
  170. package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +1 -0
  171. package/temp/ts-web-extras.api.json +1313 -354
  172. package/temp/ts-web-extras.api.md +33 -0
  173. package/.rush/temp/81e0881271ff236956b2f52e8ca99da6574c6e1e.tar.log +0 -223
  174. package/docs/index.md +0 -34
  175. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider._constructor_.md +0 -50
  176. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.decrypt.md +0 -104
  177. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.derivekey.md +0 -88
  178. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.encrypt.md +0 -72
  179. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.frombase64.md +0 -56
  180. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generatekey.md +0 -19
  181. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.generaterandombytes.md +0 -56
  182. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.md +0 -169
  183. package/docs/ts-web-extras.cryptoutils.browsercryptoprovider.tobase64.md +0 -56
  184. package/docs/ts-web-extras.cryptoutils.browserhashprovider.hashparts.md +0 -88
  185. package/docs/ts-web-extras.cryptoutils.browserhashprovider.hashstring.md +0 -72
  186. package/docs/ts-web-extras.cryptoutils.browserhashprovider.md +0 -66
  187. package/docs/ts-web-extras.cryptoutils.createbrowsercryptoprovider.md +0 -19
  188. package/docs/ts-web-extras.cryptoutils.md +0 -71
  189. package/docs/ts-web-extras.exportasjson.md +0 -70
  190. package/docs/ts-web-extras.exportusingfilesystemapi.md +0 -104
  191. package/docs/ts-web-extras.extractdirectorypath.md +0 -52
  192. package/docs/ts-web-extras.fileapitreeaccessors.create.md +0 -72
  193. package/docs/ts-web-extras.fileapitreeaccessors.createfromlocalstorage.md +0 -74
  194. package/docs/ts-web-extras.fileapitreeaccessors.createpersistent.md +0 -76
  195. package/docs/ts-web-extras.fileapitreeaccessors.extractfilemetadata.md +0 -54
  196. package/docs/ts-web-extras.fileapitreeaccessors.fromdirectoryupload.md +0 -72
  197. package/docs/ts-web-extras.fileapitreeaccessors.fromfilelist.md +0 -72
  198. package/docs/ts-web-extras.fileapitreeaccessors.getoriginalfile.md +0 -72
  199. package/docs/ts-web-extras.fileapitreeaccessors.md +0 -146
  200. package/docs/ts-web-extras.filepickeraccepttype.accept.md +0 -11
  201. package/docs/ts-web-extras.filepickeraccepttype.description.md +0 -11
  202. package/docs/ts-web-extras.filepickeraccepttype.md +0 -75
  203. package/docs/ts-web-extras.filesystemaccesstreeaccessors._constructor_.md +0 -114
  204. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fileismutable.md +0 -52
  205. package/docs/ts-web-extras.filesystemaccesstreeaccessors.fromdirectoryhandle.md +0 -72
  206. package/docs/ts-web-extras.filesystemaccesstreeaccessors.getdirtypaths.md +0 -17
  207. package/docs/ts-web-extras.filesystemaccesstreeaccessors.isdirty.md +0 -17
  208. package/docs/ts-web-extras.filesystemaccesstreeaccessors.md +0 -159
  209. package/docs/ts-web-extras.filesystemaccesstreeaccessors.savefilecontents.md +0 -66
  210. package/docs/ts-web-extras.filesystemaccesstreeaccessors.synctodisk.md +0 -17
  211. package/docs/ts-web-extras.filesystemcreatewritableoptions_2.keepexistingdata.md +0 -11
  212. package/docs/ts-web-extras.filesystemcreatewritableoptions_2.md +0 -58
  213. package/docs/ts-web-extras.filesystemdirectoryhandle_2._symbol.asynciterator_.md +0 -15
  214. package/docs/ts-web-extras.filesystemdirectoryhandle_2.entries.md +0 -15
  215. package/docs/ts-web-extras.filesystemdirectoryhandle_2.getdirectoryhandle.md +0 -66
  216. package/docs/ts-web-extras.filesystemdirectoryhandle_2.getfilehandle.md +0 -66
  217. package/docs/ts-web-extras.filesystemdirectoryhandle_2.keys.md +0 -15
  218. package/docs/ts-web-extras.filesystemdirectoryhandle_2.kind.md +0 -11
  219. package/docs/ts-web-extras.filesystemdirectoryhandle_2.md +0 -146
  220. package/docs/ts-web-extras.filesystemdirectoryhandle_2.removeentry.md +0 -66
  221. package/docs/ts-web-extras.filesystemdirectoryhandle_2.resolve.md +0 -50
  222. package/docs/ts-web-extras.filesystemdirectoryhandle_2.values.md +0 -15
  223. package/docs/ts-web-extras.filesystemfilehandle_2.createwritable.md +0 -52
  224. package/docs/ts-web-extras.filesystemfilehandle_2.getfile.md +0 -15
  225. package/docs/ts-web-extras.filesystemfilehandle_2.kind.md +0 -11
  226. package/docs/ts-web-extras.filesystemfilehandle_2.md +0 -92
  227. package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.create.md +0 -11
  228. package/docs/ts-web-extras.filesystemgetdirectoryoptions_2.md +0 -58
  229. package/docs/ts-web-extras.filesystemgetfileoptions_2.create.md +0 -11
  230. package/docs/ts-web-extras.filesystemgetfileoptions_2.md +0 -58
  231. package/docs/ts-web-extras.filesystemhandle_2.issameentry.md +0 -50
  232. package/docs/ts-web-extras.filesystemhandle_2.kind.md +0 -11
  233. package/docs/ts-web-extras.filesystemhandle_2.md +0 -119
  234. package/docs/ts-web-extras.filesystemhandle_2.name.md +0 -11
  235. package/docs/ts-web-extras.filesystemhandle_2.querypermission.md +0 -52
  236. package/docs/ts-web-extras.filesystemhandle_2.requestpermission.md +0 -52
  237. package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.md +0 -58
  238. package/docs/ts-web-extras.filesystemhandlepermissiondescriptor.mode.md +0 -11
  239. package/docs/ts-web-extras.filesystemremoveoptions_2.md +0 -58
  240. package/docs/ts-web-extras.filesystemremoveoptions_2.recursive.md +0 -11
  241. package/docs/ts-web-extras.filesystemwritablefilestream_2.md +0 -57
  242. package/docs/ts-web-extras.filesystemwritablefilestream_2.seek.md +0 -50
  243. package/docs/ts-web-extras.filesystemwritablefilestream_2.truncate.md +0 -50
  244. package/docs/ts-web-extras.filesystemwritablefilestream_2.write.md +0 -50
  245. package/docs/ts-web-extras.filetreehelpers.defaultfileapitreeinitparams.md +0 -13
  246. package/docs/ts-web-extras.filetreehelpers.extractfilelistmetadata.md +0 -56
  247. package/docs/ts-web-extras.filetreehelpers.extractfilemetadata.md +0 -56
  248. package/docs/ts-web-extras.filetreehelpers.fromdirectoryupload.md +0 -76
  249. package/docs/ts-web-extras.filetreehelpers.fromfilelist.md +0 -76
  250. package/docs/ts-web-extras.filetreehelpers.getoriginalfile.md +0 -72
  251. package/docs/ts-web-extras.filetreehelpers.md +0 -102
  252. package/docs/ts-web-extras.idirectoryhandletreeinitializer.dirhandles.md +0 -11
  253. package/docs/ts-web-extras.idirectoryhandletreeinitializer.md +0 -100
  254. package/docs/ts-web-extras.idirectoryhandletreeinitializer.nonrecursive.md +0 -11
  255. package/docs/ts-web-extras.idirectoryhandletreeinitializer.prefix.md +0 -11
  256. package/docs/ts-web-extras.ifilehandletreeinitializer.filehandles.md +0 -11
  257. package/docs/ts-web-extras.ifilehandletreeinitializer.md +0 -79
  258. package/docs/ts-web-extras.ifilehandletreeinitializer.prefix.md +0 -11
  259. package/docs/ts-web-extras.ifilelisttreeinitializer.filelist.md +0 -11
  260. package/docs/ts-web-extras.ifilelisttreeinitializer.md +0 -58
  261. package/docs/ts-web-extras.ifilemetadata.lastmodified.md +0 -11
  262. package/docs/ts-web-extras.ifilemetadata.md +0 -124
  263. package/docs/ts-web-extras.ifilemetadata.name.md +0 -11
  264. package/docs/ts-web-extras.ifilemetadata.path.md +0 -11
  265. package/docs/ts-web-extras.ifilemetadata.size.md +0 -11
  266. package/docs/ts-web-extras.ifilemetadata.type.md +0 -11
  267. package/docs/ts-web-extras.ifilesystemaccesstreeparams.autosync.md +0 -13
  268. package/docs/ts-web-extras.ifilesystemaccesstreeparams.md +0 -78
  269. package/docs/ts-web-extras.ifilesystemaccesstreeparams.requirewritepermission.md +0 -13
  270. package/docs/ts-web-extras.ifsaccessapis.md +0 -56
  271. package/docs/ts-web-extras.ifsaccessapis.showdirectorypicker.md +0 -52
  272. package/docs/ts-web-extras.ifsaccessapis.showopenfilepicker.md +0 -52
  273. package/docs/ts-web-extras.ifsaccessapis.showsavefilepicker.md +0 -52
  274. package/docs/ts-web-extras.ilocalstoragetreeparams.autosync.md +0 -13
  275. package/docs/ts-web-extras.ilocalstoragetreeparams.md +0 -97
  276. package/docs/ts-web-extras.ilocalstoragetreeparams.pathtokeymap.md +0 -13
  277. package/docs/ts-web-extras.ilocalstoragetreeparams.storage.md +0 -13
  278. package/docs/ts-web-extras.isdirectoryhandle.md +0 -56
  279. package/docs/ts-web-extras.isfilehandle.md +0 -56
  280. package/docs/ts-web-extras.isfilepath.md +0 -52
  281. package/docs/ts-web-extras.iurlconfigoptions.config.md +0 -13
  282. package/docs/ts-web-extras.iurlconfigoptions.configstartdir.md +0 -13
  283. package/docs/ts-web-extras.iurlconfigoptions.contextfilter.md +0 -13
  284. package/docs/ts-web-extras.iurlconfigoptions.input.md +0 -13
  285. package/docs/ts-web-extras.iurlconfigoptions.inputstartdir.md +0 -13
  286. package/docs/ts-web-extras.iurlconfigoptions.interactive.md +0 -13
  287. package/docs/ts-web-extras.iurlconfigoptions.loadzip.md +0 -13
  288. package/docs/ts-web-extras.iurlconfigoptions.maxdistance.md +0 -13
  289. package/docs/ts-web-extras.iurlconfigoptions.md +0 -286
  290. package/docs/ts-web-extras.iurlconfigoptions.qualifierdefaults.md +0 -13
  291. package/docs/ts-web-extras.iurlconfigoptions.reducequalifiers.md +0 -13
  292. package/docs/ts-web-extras.iurlconfigoptions.resourcetypes.md +0 -13
  293. package/docs/ts-web-extras.iurlconfigoptions.zipfile.md +0 -13
  294. package/docs/ts-web-extras.iurlconfigoptions.zippath.md +0 -13
  295. package/docs/ts-web-extras.localstoragetreeaccessors.fileismutable.md +0 -56
  296. package/docs/ts-web-extras.localstoragetreeaccessors.fromstorage.md +0 -56
  297. package/docs/ts-web-extras.localstoragetreeaccessors.getdirtypaths.md +0 -19
  298. package/docs/ts-web-extras.localstoragetreeaccessors.isdirty.md +0 -19
  299. package/docs/ts-web-extras.localstoragetreeaccessors.md +0 -131
  300. package/docs/ts-web-extras.localstoragetreeaccessors.savefilecontents.md +0 -72
  301. package/docs/ts-web-extras.localstoragetreeaccessors.synctodisk.md +0 -19
  302. package/docs/ts-web-extras.md +0 -558
  303. package/docs/ts-web-extras.parsecontextfilter.md +0 -52
  304. package/docs/ts-web-extras.parsequalifierdefaults.md +0 -52
  305. package/docs/ts-web-extras.parseresourcetypes.md +0 -52
  306. package/docs/ts-web-extras.parseurlparameters.md +0 -17
  307. package/docs/ts-web-extras.safeshowdirectorypicker.md +0 -72
  308. package/docs/ts-web-extras.safeshowopenfilepicker.md +0 -72
  309. package/docs/ts-web-extras.safeshowsavefilepicker.md +0 -72
  310. package/docs/ts-web-extras.showdirectorypickeroptions.id.md +0 -11
  311. package/docs/ts-web-extras.showdirectorypickeroptions.md +0 -96
  312. package/docs/ts-web-extras.showdirectorypickeroptions.mode.md +0 -11
  313. package/docs/ts-web-extras.showdirectorypickeroptions.startin.md +0 -11
  314. package/docs/ts-web-extras.showopenfilepickeroptions.excludeacceptalloption.md +0 -11
  315. package/docs/ts-web-extras.showopenfilepickeroptions.id.md +0 -11
  316. package/docs/ts-web-extras.showopenfilepickeroptions.md +0 -134
  317. package/docs/ts-web-extras.showopenfilepickeroptions.multiple.md +0 -11
  318. package/docs/ts-web-extras.showopenfilepickeroptions.startin.md +0 -11
  319. package/docs/ts-web-extras.showopenfilepickeroptions.types.md +0 -11
  320. package/docs/ts-web-extras.showsavefilepickeroptions.excludeacceptalloption.md +0 -11
  321. package/docs/ts-web-extras.showsavefilepickeroptions.id.md +0 -11
  322. package/docs/ts-web-extras.showsavefilepickeroptions.md +0 -134
  323. package/docs/ts-web-extras.showsavefilepickeroptions.startin.md +0 -11
  324. package/docs/ts-web-extras.showsavefilepickeroptions.suggestedname.md +0 -11
  325. package/docs/ts-web-extras.showsavefilepickeroptions.types.md +0 -11
  326. package/docs/ts-web-extras.supportsfilesystemaccess.md +0 -56
  327. package/docs/ts-web-extras.treeinitializer.md +0 -15
  328. package/docs/ts-web-extras.wellknowndirectory.md +0 -13
  329. package/docs/ts-web-extras.windowwithfsaccess.md +0 -15
  330. package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
  331. package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
  332. /package/temp/test/jest/{jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/8d/package_8dcbedef69e4299f0f51fcda8f4f1c8e → jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5} +0 -0
@@ -0,0 +1,1571 @@
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
+
23
+ import '@fgv/ts-utils-jest';
24
+ import { fail, Logging } from '@fgv/ts-utils';
25
+ import { HttpTreeAccessors } from '../../packlets/file-tree';
26
+
27
+ // ---- Mock fetch helpers ----
28
+
29
+ interface IMockResponse {
30
+ ok: boolean;
31
+ status?: number;
32
+ jsonValue?: unknown;
33
+ textValue?: string;
34
+ throwOnJson?: boolean;
35
+ throwOnText?: boolean;
36
+ }
37
+
38
+ function makeMockResponse(options: IMockResponse): Response {
39
+ const { ok, status = ok ? 200 : 400, jsonValue, textValue, throwOnJson, throwOnText } = options;
40
+ return {
41
+ ok,
42
+ status,
43
+ statusText: ok ? 'OK' : `Error ${status}`,
44
+ json: throwOnJson
45
+ ? () => Promise.reject(new Error('JSON parse error'))
46
+ : () => Promise.resolve(jsonValue),
47
+ text: throwOnText
48
+ ? () => Promise.reject(new Error('text error'))
49
+ : () => Promise.resolve(textValue ?? `HTTP ${status}`)
50
+ } as unknown as Response;
51
+ }
52
+
53
+ type FetchCall = { url: string; init?: RequestInit };
54
+
55
+ /**
56
+ * Creates a mock fetch function that returns responses for each call in order.
57
+ * Each entry maps to one fetch() invocation in call order.
58
+ */
59
+ function makeMockFetch(responses: IMockResponse[]): { fetchImpl: typeof fetch; calls: FetchCall[] } {
60
+ const calls: FetchCall[] = [];
61
+ let callIndex = 0;
62
+
63
+ const fetchImpl = (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
64
+ calls.push({ url: url.toString(), init });
65
+ const response = responses[callIndex++];
66
+ if (response === undefined) {
67
+ return Promise.reject(new Error(`Unexpected fetch call #${callIndex} to ${url.toString()}`));
68
+ }
69
+ return Promise.resolve(makeMockResponse(response));
70
+ };
71
+
72
+ return { fetchImpl: fetchImpl as typeof fetch, calls };
73
+ }
74
+
75
+ /**
76
+ * Creates a mock fetch function that throws a network error on every call.
77
+ */
78
+ function makeThrowingFetch(message: string): typeof fetch {
79
+ return (_url: string | URL | Request, _init?: RequestInit): Promise<Response> => {
80
+ return Promise.reject(new Error(message));
81
+ };
82
+ }
83
+
84
+ // ---- Shared test data builders ----
85
+
86
+ /** Minimal tree-children response for a single file at root. */
87
+ function rootWithOneFile(fileName = 'data.json'): unknown {
88
+ return {
89
+ path: '/',
90
+ children: [{ path: `/${fileName}`, name: fileName, type: 'file' }]
91
+ };
92
+ }
93
+
94
+ /** File response for a JSON file. */
95
+ function fileResponse(path: string, contents: string, contentType?: string): unknown {
96
+ const response: Record<string, unknown> = { path, contents };
97
+ if (contentType !== undefined) {
98
+ response.contentType = contentType;
99
+ }
100
+ return response;
101
+ }
102
+
103
+ /** Root children response containing a subdirectory and a file. */
104
+ function rootWithDirAndFile(): unknown {
105
+ return {
106
+ path: '/',
107
+ children: [
108
+ { path: '/subdir', name: 'subdir', type: 'directory' },
109
+ { path: '/root.json', name: 'root.json', type: 'file' }
110
+ ]
111
+ };
112
+ }
113
+
114
+ /** Children response for /subdir containing one file. */
115
+ function subdirWithOneFile(): unknown {
116
+ return {
117
+ path: '/subdir',
118
+ children: [{ path: '/subdir/nested.json', name: 'nested.json', type: 'file' }]
119
+ };
120
+ }
121
+
122
+ // ---- Tests ----
123
+
124
+ describe('HttpTreeAccessors', () => {
125
+ describe('fromHttp()', () => {
126
+ test('succeeds with an empty directory (no children)', async () => {
127
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
128
+
129
+ const result = await HttpTreeAccessors.fromHttp({
130
+ baseUrl: 'http://localhost:3000',
131
+ fetchImpl
132
+ });
133
+
134
+ expect(result).toSucceedAndSatisfy((accessors) => {
135
+ expect(accessors).toBeInstanceOf(HttpTreeAccessors);
136
+ expect(accessors.isDirty()).toBe(false);
137
+ });
138
+ });
139
+
140
+ test('succeeds and loads a single file at root', async () => {
141
+ const { fetchImpl } = makeMockFetch([
142
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
143
+ { ok: true, jsonValue: fileResponse('/data.json', '{"items":{}}') }
144
+ ]);
145
+
146
+ const result = await HttpTreeAccessors.fromHttp({
147
+ baseUrl: 'http://localhost:3000',
148
+ fetchImpl,
149
+ mutable: true
150
+ });
151
+
152
+ expect(result).toSucceedAndSatisfy((accessors) => {
153
+ expect(accessors.getFileContents('/data.json')).toSucceedWith('{"items":{}}');
154
+ });
155
+ });
156
+
157
+ test('succeeds with multiple files at root', async () => {
158
+ const { fetchImpl } = makeMockFetch([
159
+ {
160
+ ok: true,
161
+ jsonValue: {
162
+ path: '/',
163
+ children: [
164
+ { path: '/alpha.json', name: 'alpha.json', type: 'file' },
165
+ { path: '/beta.json', name: 'beta.json', type: 'file' }
166
+ ]
167
+ }
168
+ },
169
+ { ok: true, jsonValue: fileResponse('/alpha.json', '"alpha"') },
170
+ { ok: true, jsonValue: fileResponse('/beta.json', '"beta"') }
171
+ ]);
172
+
173
+ const result = await HttpTreeAccessors.fromHttp({
174
+ baseUrl: 'http://localhost:3000',
175
+ fetchImpl,
176
+ mutable: true
177
+ });
178
+
179
+ expect(result).toSucceedAndSatisfy((accessors) => {
180
+ expect(accessors.getFileContents('/alpha.json')).toSucceedWith('"alpha"');
181
+ expect(accessors.getFileContents('/beta.json')).toSucceedWith('"beta"');
182
+ });
183
+ });
184
+
185
+ test('succeeds and recursively loads files in subdirectories', async () => {
186
+ const { fetchImpl } = makeMockFetch([
187
+ { ok: true, jsonValue: rootWithDirAndFile() },
188
+ { ok: true, jsonValue: subdirWithOneFile() },
189
+ { ok: true, jsonValue: fileResponse('/subdir/nested.json', '"nested"') },
190
+ { ok: true, jsonValue: fileResponse('/root.json', '"root"') }
191
+ ]);
192
+
193
+ const result = await HttpTreeAccessors.fromHttp({
194
+ baseUrl: 'http://localhost:3000',
195
+ fetchImpl,
196
+ mutable: true
197
+ });
198
+
199
+ expect(result).toSucceedAndSatisfy((accessors) => {
200
+ expect(accessors.getFileContents('/subdir/nested.json')).toSucceedWith('"nested"');
201
+ expect(accessors.getFileContents('/root.json')).toSucceedWith('"root"');
202
+ });
203
+ });
204
+
205
+ test('strips trailing slash from baseUrl', async () => {
206
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
207
+
208
+ await HttpTreeAccessors.fromHttp({
209
+ baseUrl: 'http://localhost:3000/',
210
+ fetchImpl
211
+ });
212
+
213
+ // The URL should start with the base URL without a trailing slash, then /tree/children
214
+ expect(calls[0].url).toMatch(/^http:\/\/localhost:3000\/tree\/children/);
215
+ // There should be no double slash in the path portion (after the protocol)
216
+ const urlPath = calls[0].url.replace('http://', '');
217
+ expect(urlPath).not.toContain('//');
218
+ });
219
+
220
+ test('includes namespace in query parameters when provided', async () => {
221
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
222
+
223
+ await HttpTreeAccessors.fromHttp({
224
+ baseUrl: 'http://localhost:3000',
225
+ namespace: 'my-namespace',
226
+ fetchImpl
227
+ });
228
+
229
+ expect(calls[0].url).toContain('namespace=my-namespace');
230
+ });
231
+
232
+ test('omits namespace from query parameters when not provided', async () => {
233
+ const { fetchImpl, calls } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
234
+
235
+ await HttpTreeAccessors.fromHttp({
236
+ baseUrl: 'http://localhost:3000',
237
+ fetchImpl
238
+ });
239
+
240
+ expect(calls[0].url).not.toContain('namespace');
241
+ });
242
+
243
+ test('applies prefix parameter to loaded file paths', async () => {
244
+ const { fetchImpl } = makeMockFetch([
245
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
246
+ { ok: true, jsonValue: fileResponse('/data.json', '{"items":{}}') }
247
+ ]);
248
+
249
+ const result = await HttpTreeAccessors.fromHttp({
250
+ baseUrl: 'http://localhost:3000',
251
+ prefix: '/app',
252
+ fetchImpl,
253
+ mutable: true
254
+ });
255
+
256
+ expect(result).toSucceedAndSatisfy((accessors) => {
257
+ expect(accessors.getFileContents('/app/data.json')).toSucceedWith('{"items":{}}');
258
+ });
259
+ });
260
+
261
+ test('fails when the initial children fetch fails with a network error', async () => {
262
+ const result = await HttpTreeAccessors.fromHttp({
263
+ baseUrl: 'http://localhost:3000',
264
+ fetchImpl: makeThrowingFetch('Network unreachable')
265
+ });
266
+
267
+ expect(result).toFailWith(/network unreachable/i);
268
+ });
269
+
270
+ test('fails when the children response is not ok', async () => {
271
+ const { fetchImpl } = makeMockFetch([{ ok: false, status: 404, textValue: 'Not Found' }]);
272
+
273
+ const result = await HttpTreeAccessors.fromHttp({
274
+ baseUrl: 'http://localhost:3000',
275
+ fetchImpl
276
+ });
277
+
278
+ expect(result).toFailWith(/not found/i);
279
+ });
280
+
281
+ test('fails when the children response contains invalid JSON', async () => {
282
+ const { fetchImpl } = makeMockFetch([{ ok: true, throwOnJson: true }]);
283
+
284
+ const result = await HttpTreeAccessors.fromHttp({
285
+ baseUrl: 'http://localhost:3000',
286
+ fetchImpl
287
+ });
288
+
289
+ expect(result).toFailWith(/invalid json/i);
290
+ });
291
+
292
+ test('fails when a file fetch fails with a network error', async () => {
293
+ let callCount = 0;
294
+ const fetchImpl: typeof fetch = (_url, _init) => {
295
+ callCount++;
296
+ if (callCount === 1) {
297
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
298
+ }
299
+ return Promise.reject(new Error('File fetch failed'));
300
+ };
301
+
302
+ const result = await HttpTreeAccessors.fromHttp({
303
+ baseUrl: 'http://localhost:3000',
304
+ fetchImpl
305
+ });
306
+
307
+ expect(result).toFailWith(/file fetch failed/i);
308
+ });
309
+
310
+ test('fails when a file response is not ok', async () => {
311
+ const { fetchImpl } = makeMockFetch([
312
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
313
+ { ok: false, status: 403, textValue: 'Forbidden' }
314
+ ]);
315
+
316
+ const result = await HttpTreeAccessors.fromHttp({
317
+ baseUrl: 'http://localhost:3000',
318
+ fetchImpl
319
+ });
320
+
321
+ expect(result).toFailWith(/forbidden/i);
322
+ });
323
+
324
+ test('fails when a file response contains invalid JSON', async () => {
325
+ const { fetchImpl } = makeMockFetch([
326
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
327
+ { ok: true, throwOnJson: true }
328
+ ]);
329
+
330
+ const result = await HttpTreeAccessors.fromHttp({
331
+ baseUrl: 'http://localhost:3000',
332
+ fetchImpl
333
+ });
334
+
335
+ expect(result).toFailWith(/invalid json/i);
336
+ });
337
+
338
+ test('fails when a nested directory fetch fails', async () => {
339
+ const { fetchImpl } = makeMockFetch([
340
+ { ok: true, jsonValue: rootWithDirAndFile() },
341
+ { ok: false, status: 500, textValue: 'Internal Server Error' }
342
+ ]);
343
+
344
+ const result = await HttpTreeAccessors.fromHttp({
345
+ baseUrl: 'http://localhost:3000',
346
+ fetchImpl
347
+ });
348
+
349
+ expect(result).toFailWith(/internal server error/i);
350
+ });
351
+ });
352
+
353
+ describe('isDirty() and getDirtyPaths()', () => {
354
+ test('starts not dirty after loading', async () => {
355
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
356
+
357
+ const accessors = (
358
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
359
+ ).orThrow();
360
+
361
+ expect(accessors.isDirty()).toBe(false);
362
+ expect(accessors.getDirtyPaths()).toEqual([]);
363
+ });
364
+
365
+ test('becomes dirty after saveFileContents', async () => {
366
+ const { fetchImpl } = makeMockFetch([
367
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
368
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
369
+ ]);
370
+
371
+ const accessors = (
372
+ await HttpTreeAccessors.fromHttp({
373
+ baseUrl: 'http://localhost:3000',
374
+ fetchImpl,
375
+ mutable: true
376
+ })
377
+ ).orThrow();
378
+
379
+ accessors.saveFileContents('/data.json', '{"modified":true}').orThrow();
380
+
381
+ expect(accessors.isDirty()).toBe(true);
382
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
383
+ });
384
+
385
+ test('tracks multiple dirty files', async () => {
386
+ const { fetchImpl } = makeMockFetch([
387
+ {
388
+ ok: true,
389
+ jsonValue: {
390
+ path: '/',
391
+ children: [
392
+ { path: '/a.json', name: 'a.json', type: 'file' },
393
+ { path: '/b.json', name: 'b.json', type: 'file' }
394
+ ]
395
+ }
396
+ },
397
+ { ok: true, jsonValue: fileResponse('/a.json', '{}') },
398
+ { ok: true, jsonValue: fileResponse('/b.json', '{}') }
399
+ ]);
400
+
401
+ const accessors = (
402
+ await HttpTreeAccessors.fromHttp({
403
+ baseUrl: 'http://localhost:3000',
404
+ fetchImpl,
405
+ mutable: true
406
+ })
407
+ ).orThrow();
408
+
409
+ accessors.saveFileContents('/a.json', '"a"').orThrow();
410
+ accessors.saveFileContents('/b.json', '"b"').orThrow();
411
+
412
+ expect(accessors.getDirtyPaths()).toHaveLength(2);
413
+ expect(accessors.getDirtyPaths()).toContain('/a.json');
414
+ expect(accessors.getDirtyPaths()).toContain('/b.json');
415
+ });
416
+
417
+ test('tracks deleted files as pending dirty paths', async () => {
418
+ const { fetchImpl } = makeMockFetch([
419
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
420
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
421
+ ]);
422
+
423
+ const accessors = (
424
+ await HttpTreeAccessors.fromHttp({
425
+ baseUrl: 'http://localhost:3000',
426
+ fetchImpl,
427
+ mutable: true
428
+ })
429
+ ).orThrow();
430
+
431
+ accessors.deleteFile('/data.json').orThrow();
432
+
433
+ expect(accessors.isDirty()).toBe(true);
434
+ expect(accessors.getDirtyPaths()).toContain('/data.json');
435
+ });
436
+ });
437
+
438
+ describe('saveFileContents()', () => {
439
+ test('fails when the file is not found (immutable tree has no matching path)', async () => {
440
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
441
+
442
+ const accessors = (
443
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
444
+ ).orThrow();
445
+
446
+ // With mutable: false (default), saveFileContents should fail
447
+ const result = accessors.saveFileContents('/missing.json', '{}');
448
+ expect(result).toFail();
449
+ });
450
+
451
+ test('marks the file as dirty without autoSync', async () => {
452
+ const { fetchImpl } = makeMockFetch([
453
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
454
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
455
+ ]);
456
+
457
+ const accessors = (
458
+ await HttpTreeAccessors.fromHttp({
459
+ baseUrl: 'http://localhost:3000',
460
+ fetchImpl,
461
+ mutable: true
462
+ })
463
+ ).orThrow();
464
+
465
+ const result = accessors.saveFileContents('/data.json', '{"updated":true}');
466
+ expect(result).toSucceedWith('{"updated":true}');
467
+ expect(accessors.isDirty()).toBe(true);
468
+ // No additional fetch calls should have occurred (no autoSync)
469
+ });
470
+
471
+ test('triggers fire-and-forget autoSync when autoSync is enabled', async () => {
472
+ const syncResponses: IMockResponse[] = [
473
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
474
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
475
+ // PUT /file response for sync
476
+ { ok: true, jsonValue: { path: '/data.json', contents: '{"auto":true}' } },
477
+ // POST /sync response
478
+ { ok: true, jsonValue: { synced: 1 } }
479
+ ];
480
+ const { fetchImpl, calls } = makeMockFetch(syncResponses);
481
+
482
+ const accessors = (
483
+ await HttpTreeAccessors.fromHttp({
484
+ baseUrl: 'http://localhost:3000',
485
+ fetchImpl,
486
+ mutable: true,
487
+ autoSync: true
488
+ })
489
+ ).orThrow();
490
+
491
+ const result = accessors.saveFileContents('/data.json', '{"auto":true}');
492
+ expect(result).toSucceedWith('{"auto":true}');
493
+
494
+ // autoSync fires-and-forgets; wait for microtasks to drain
495
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
496
+
497
+ // Verify that PUT + POST /sync were called
498
+ const methodCalls = calls.slice(2).map((c) => c.init?.method);
499
+ expect(methodCalls).toContain('PUT');
500
+ expect(methodCalls).toContain('POST');
501
+ });
502
+
503
+ test('logs when autoSync returns a failure Result', async () => {
504
+ const logger = {
505
+ detail: jest.fn(),
506
+ info: jest.fn(),
507
+ warn: jest.fn(),
508
+ error: jest.fn()
509
+ } as unknown as Logging.LogReporter<unknown>;
510
+
511
+ const { fetchImpl } = makeMockFetch([
512
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
513
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
514
+ ]);
515
+
516
+ const accessors = (
517
+ await HttpTreeAccessors.fromHttp({
518
+ baseUrl: 'http://localhost:3000',
519
+ fetchImpl,
520
+ mutable: true,
521
+ autoSync: true,
522
+ logger
523
+ })
524
+ ).orThrow();
525
+
526
+ (accessors as unknown as { syncToDisk: () => Promise<ReturnType<typeof fail<void>>> }).syncToDisk =
527
+ async () => fail<void>('simulated sync failure');
528
+
529
+ accessors.saveFileContents('/data.json', '{"auto":true}').orThrow();
530
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
531
+
532
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('simulated sync failure'));
533
+ });
534
+
535
+ test('logs when autoSync throws unexpectedly', async () => {
536
+ const logger = {
537
+ detail: jest.fn(),
538
+ info: jest.fn(),
539
+ warn: jest.fn(),
540
+ error: jest.fn()
541
+ } as unknown as Logging.LogReporter<unknown>;
542
+
543
+ const { fetchImpl } = makeMockFetch([
544
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
545
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
546
+ ]);
547
+
548
+ const accessors = (
549
+ await HttpTreeAccessors.fromHttp({
550
+ baseUrl: 'http://localhost:3000',
551
+ fetchImpl,
552
+ mutable: true,
553
+ autoSync: true,
554
+ logger
555
+ })
556
+ ).orThrow();
557
+
558
+ (accessors as unknown as { syncToDisk: () => Promise<unknown> }).syncToDisk = async () => {
559
+ throw new Error('simulated throw');
560
+ };
561
+
562
+ accessors.saveFileContents('/data.json', '{"auto":true}').orThrow();
563
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
564
+
565
+ expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('simulated throw'));
566
+ });
567
+ });
568
+
569
+ describe('fileIsMutable()', () => {
570
+ test('returns persistent detail when file exists and mutable is true', async () => {
571
+ const { fetchImpl } = makeMockFetch([
572
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
573
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
574
+ ]);
575
+
576
+ const accessors = (
577
+ await HttpTreeAccessors.fromHttp({
578
+ baseUrl: 'http://localhost:3000',
579
+ fetchImpl,
580
+ mutable: true
581
+ })
582
+ ).orThrow();
583
+
584
+ const result = accessors.fileIsMutable('/data.json');
585
+ expect(result.isSuccess()).toBe(true);
586
+ if (result.isSuccess()) {
587
+ expect(result.value).toBe(true);
588
+ expect(result.detail).toBe('persistent');
589
+ }
590
+ });
591
+
592
+ test('returns not-mutable detail when mutable is false', async () => {
593
+ const { fetchImpl } = makeMockFetch([
594
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
595
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
596
+ ]);
597
+
598
+ const accessors = (
599
+ await HttpTreeAccessors.fromHttp({
600
+ baseUrl: 'http://localhost:3000',
601
+ fetchImpl,
602
+ mutable: false
603
+ })
604
+ ).orThrow();
605
+
606
+ const result = accessors.fileIsMutable('/data.json');
607
+ expect(result.isFailure()).toBe(true);
608
+ if (result.isFailure()) {
609
+ expect(result.detail).toBe('not-mutable');
610
+ }
611
+ });
612
+
613
+ test('returns persistent detail for any path when mutable is true (no path existence check)', async () => {
614
+ // InMemoryTreeAccessors checks the mutable config, not path existence.
615
+ // HttpTreeAccessors layers "persistent" on top of a successful mutable check.
616
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
617
+
618
+ const accessors = (
619
+ await HttpTreeAccessors.fromHttp({
620
+ baseUrl: 'http://localhost:3000',
621
+ fetchImpl,
622
+ mutable: true
623
+ })
624
+ ).orThrow();
625
+
626
+ // Any path succeeds as "persistent" when mutable: true
627
+ const result = accessors.fileIsMutable('/nonexistent.json');
628
+ expect(result.isSuccess()).toBe(true);
629
+ if (result.isSuccess()) {
630
+ expect(result.value).toBe(true);
631
+ expect(result.detail).toBe('persistent');
632
+ }
633
+ });
634
+ });
635
+
636
+ describe('syncToDisk()', () => {
637
+ test('succeeds immediately with no dirty files', async () => {
638
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
639
+
640
+ const accessors = (
641
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl })
642
+ ).orThrow();
643
+
644
+ const result = await accessors.syncToDisk();
645
+ expect(result).toSucceed();
646
+ });
647
+
648
+ test('PUTs each dirty file then POSTs /sync', async () => {
649
+ const { fetchImpl, calls } = makeMockFetch([
650
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
651
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
652
+ { ok: true, jsonValue: fileResponse('/data.json', '{"new":1}') },
653
+ { ok: true, jsonValue: { synced: 1 } }
654
+ ]);
655
+
656
+ const accessors = (
657
+ await HttpTreeAccessors.fromHttp({
658
+ baseUrl: 'http://localhost:3000',
659
+ fetchImpl,
660
+ mutable: true
661
+ })
662
+ ).orThrow();
663
+
664
+ accessors.saveFileContents('/data.json', '{"new":1}').orThrow();
665
+ const result = await accessors.syncToDisk();
666
+
667
+ expect(result).toSucceed();
668
+ const syncCalls = calls.slice(2);
669
+ expect(syncCalls[0].url).toContain('/file');
670
+ expect(syncCalls[0].init?.method).toBe('PUT');
671
+ expect(syncCalls[1].url).toContain('/sync');
672
+ expect(syncCalls[1].init?.method).toBe('POST');
673
+ });
674
+
675
+ test('clears dirty state after successful sync', async () => {
676
+ const { fetchImpl } = makeMockFetch([
677
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
678
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
679
+ { ok: true, jsonValue: fileResponse('/data.json', '"updated"') },
680
+ { ok: true, jsonValue: { synced: 1 } }
681
+ ]);
682
+
683
+ const accessors = (
684
+ await HttpTreeAccessors.fromHttp({
685
+ baseUrl: 'http://localhost:3000',
686
+ fetchImpl,
687
+ mutable: true
688
+ })
689
+ ).orThrow();
690
+
691
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
692
+ expect(accessors.isDirty()).toBe(true);
693
+
694
+ await accessors.syncToDisk();
695
+ expect(accessors.isDirty()).toBe(false);
696
+ expect(accessors.getDirtyPaths()).toEqual([]);
697
+ });
698
+
699
+ test('includes namespace in PUT body and POST /sync body when provided', async () => {
700
+ const { fetchImpl, calls } = makeMockFetch([
701
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
702
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
703
+ { ok: true, jsonValue: fileResponse('/data.json', '"v2"') },
704
+ { ok: true, jsonValue: { synced: 1 } }
705
+ ]);
706
+
707
+ const accessors = (
708
+ await HttpTreeAccessors.fromHttp({
709
+ baseUrl: 'http://localhost:3000',
710
+ namespace: 'myns',
711
+ fetchImpl,
712
+ mutable: true
713
+ })
714
+ ).orThrow();
715
+
716
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
717
+ await accessors.syncToDisk();
718
+
719
+ const putBody = JSON.parse(calls[2].init?.body as string) as Record<string, unknown>;
720
+ expect(putBody.namespace).toBe('myns');
721
+
722
+ const syncBody = JSON.parse(calls[3].init?.body as string) as Record<string, unknown>;
723
+ expect(syncBody.namespace).toBe('myns');
724
+ });
725
+
726
+ test('omits namespace from PUT body and POST /sync body when not provided', async () => {
727
+ const { fetchImpl, calls } = makeMockFetch([
728
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
729
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
730
+ { ok: true, jsonValue: fileResponse('/data.json', '"v2"') },
731
+ { ok: true, jsonValue: { synced: 1 } }
732
+ ]);
733
+
734
+ const accessors = (
735
+ await HttpTreeAccessors.fromHttp({
736
+ baseUrl: 'http://localhost:3000',
737
+ fetchImpl,
738
+ mutable: true
739
+ })
740
+ ).orThrow();
741
+
742
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
743
+ await accessors.syncToDisk();
744
+
745
+ const putBody = JSON.parse(calls[2].init?.body as string) as Record<string, unknown>;
746
+ expect(putBody.namespace).toBeUndefined();
747
+
748
+ const syncBody = JSON.parse(calls[3].init?.body as string) as Record<string, unknown>;
749
+ expect(syncBody.namespace).toBeUndefined();
750
+ });
751
+
752
+ test('fails when PUT for a dirty file returns a non-ok response', async () => {
753
+ const { fetchImpl } = makeMockFetch([
754
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
755
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
756
+ { ok: false, status: 500, textValue: 'Server Error' }
757
+ ]);
758
+
759
+ const accessors = (
760
+ await HttpTreeAccessors.fromHttp({
761
+ baseUrl: 'http://localhost:3000',
762
+ fetchImpl,
763
+ mutable: true
764
+ })
765
+ ).orThrow();
766
+
767
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
768
+ const result = await accessors.syncToDisk();
769
+
770
+ expect(result).toFailWith(/sync.*data\.json.*server error/i);
771
+ });
772
+
773
+ test('fails when PUT for a dirty file encounters a network error', async () => {
774
+ jest.useFakeTimers();
775
+ try {
776
+ let callCount = 0;
777
+ const fetchImpl: typeof fetch = (_url, _init) => {
778
+ callCount++;
779
+ if (callCount === 1) {
780
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
781
+ }
782
+ if (callCount === 2) {
783
+ return Promise.resolve(
784
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
785
+ );
786
+ }
787
+ return Promise.reject(new Error('PUT network error'));
788
+ };
789
+
790
+ const accessors = (
791
+ await HttpTreeAccessors.fromHttp({
792
+ baseUrl: 'http://localhost:3000',
793
+ fetchImpl,
794
+ mutable: true
795
+ })
796
+ ).orThrow();
797
+
798
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
799
+
800
+ const syncPromise = accessors.syncToDisk();
801
+ await jest.advanceTimersByTimeAsync(1500);
802
+
803
+ const result = await syncPromise;
804
+ expect(result).toFailWith(/put network error/i);
805
+ } finally {
806
+ jest.useRealTimers();
807
+ }
808
+ });
809
+
810
+ test('fails when POST /sync returns a non-ok response', async () => {
811
+ jest.useFakeTimers();
812
+ try {
813
+ let callCount = 0;
814
+ const fetchImpl: typeof fetch = (_url, _init) => {
815
+ callCount++;
816
+ if (callCount === 1) {
817
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
818
+ }
819
+ if (callCount === 2) {
820
+ return Promise.resolve(
821
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
822
+ );
823
+ }
824
+ if (callCount === 3) {
825
+ return Promise.resolve(
826
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"v2"') })
827
+ );
828
+ }
829
+ // All /sync attempts: persistent 503
830
+ return Promise.resolve(
831
+ makeMockResponse({ ok: false, status: 503, textValue: 'Service Unavailable' })
832
+ );
833
+ };
834
+
835
+ const accessors = (
836
+ await HttpTreeAccessors.fromHttp({
837
+ baseUrl: 'http://localhost:3000',
838
+ fetchImpl,
839
+ mutable: true
840
+ })
841
+ ).orThrow();
842
+
843
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
844
+
845
+ const syncPromise = accessors.syncToDisk();
846
+ // Advance past both backoff delays: 500ms + 1000ms
847
+ await jest.advanceTimersByTimeAsync(1500);
848
+
849
+ const result = await syncPromise;
850
+ expect(result).toFailWith(/service unavailable/i);
851
+ } finally {
852
+ jest.useRealTimers();
853
+ }
854
+ });
855
+
856
+ test('fails when POST /sync encounters a network error', async () => {
857
+ jest.useFakeTimers();
858
+ try {
859
+ let callCount = 0;
860
+ const fetchImpl: typeof fetch = (_url, _init) => {
861
+ callCount++;
862
+ if (callCount === 1) {
863
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
864
+ }
865
+ if (callCount === 2) {
866
+ return Promise.resolve(
867
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
868
+ );
869
+ }
870
+ if (callCount === 3) {
871
+ return Promise.resolve(
872
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"v2"') })
873
+ );
874
+ }
875
+ return Promise.reject(new Error('POST network error'));
876
+ };
877
+
878
+ const accessors = (
879
+ await HttpTreeAccessors.fromHttp({
880
+ baseUrl: 'http://localhost:3000',
881
+ fetchImpl,
882
+ mutable: true
883
+ })
884
+ ).orThrow();
885
+
886
+ accessors.saveFileContents('/data.json', '"v2"').orThrow();
887
+
888
+ const syncPromise = accessors.syncToDisk();
889
+ await jest.advanceTimersByTimeAsync(1500);
890
+
891
+ const result = await syncPromise;
892
+ expect(result).toFailWith(/post network error/i);
893
+ } finally {
894
+ jest.useRealTimers();
895
+ }
896
+ });
897
+
898
+ test('syncs multiple dirty files in order', async () => {
899
+ const { fetchImpl, calls } = makeMockFetch([
900
+ {
901
+ ok: true,
902
+ jsonValue: {
903
+ path: '/',
904
+ children: [
905
+ { path: '/a.json', name: 'a.json', type: 'file' },
906
+ { path: '/b.json', name: 'b.json', type: 'file' }
907
+ ]
908
+ }
909
+ },
910
+ { ok: true, jsonValue: fileResponse('/a.json', '{}') },
911
+ { ok: true, jsonValue: fileResponse('/b.json', '{}') },
912
+ { ok: true, jsonValue: fileResponse('/a.json', '"a-updated"') },
913
+ { ok: true, jsonValue: fileResponse('/b.json', '"b-updated"') },
914
+ { ok: true, jsonValue: { synced: 2 } }
915
+ ]);
916
+
917
+ const accessors = (
918
+ await HttpTreeAccessors.fromHttp({
919
+ baseUrl: 'http://localhost:3000',
920
+ fetchImpl,
921
+ mutable: true
922
+ })
923
+ ).orThrow();
924
+
925
+ accessors.saveFileContents('/a.json', '"a-updated"').orThrow();
926
+ accessors.saveFileContents('/b.json', '"b-updated"').orThrow();
927
+
928
+ const result = await accessors.syncToDisk();
929
+ expect(result).toSucceed();
930
+
931
+ // Verify 2 PUTs + 1 POST
932
+ const syncCalls = calls.slice(3);
933
+ const methods = syncCalls.map((c) => c.init?.method);
934
+ expect(methods.filter((m) => m === 'PUT')).toHaveLength(2);
935
+ expect(methods.filter((m) => m === 'POST')).toHaveLength(1);
936
+ });
937
+
938
+ test('DELETEs pending deletions before POST /sync', async () => {
939
+ const { fetchImpl, calls } = makeMockFetch([
940
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
941
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
942
+ { ok: true, jsonValue: { deleted: true } },
943
+ { ok: true, jsonValue: { synced: 0 } }
944
+ ]);
945
+
946
+ const accessors = (
947
+ await HttpTreeAccessors.fromHttp({
948
+ baseUrl: 'http://localhost:3000',
949
+ fetchImpl,
950
+ mutable: true
951
+ })
952
+ ).orThrow();
953
+
954
+ accessors.deleteFile('/data.json').orThrow();
955
+ const result = await accessors.syncToDisk();
956
+
957
+ expect(result).toSucceed();
958
+ const syncCalls = calls.slice(2);
959
+ expect(syncCalls[0].init?.method).toBe('DELETE');
960
+ expect(syncCalls[0].url).toContain('/file?');
961
+ expect(syncCalls[1].init?.method).toBe('POST');
962
+ expect(accessors.isDirty()).toBe(false);
963
+ });
964
+
965
+ test('fails when DELETE for pending deletion returns non-ok response', async () => {
966
+ const { fetchImpl } = makeMockFetch([
967
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
968
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
969
+ { ok: false, status: 500, textValue: 'Delete failed' }
970
+ ]);
971
+
972
+ const accessors = (
973
+ await HttpTreeAccessors.fromHttp({
974
+ baseUrl: 'http://localhost:3000',
975
+ fetchImpl,
976
+ mutable: true
977
+ })
978
+ ).orThrow();
979
+
980
+ accessors.deleteFile('/data.json').orThrow();
981
+ const result = await accessors.syncToDisk();
982
+
983
+ expect(result).toFailWith(/delete.*data\.json.*delete failed/i);
984
+ });
985
+ });
986
+
987
+ describe('syncToDisk() - getFileContents failure', () => {
988
+ test('fails when getFileContents returns failure for a dirty file during sync', async () => {
989
+ // This covers lines 112-113: the contentsResult.isFailure() branch in syncToDisk.
990
+ // We load a file, mark it dirty, then sabotage getFileContents to fail.
991
+ const { fetchImpl } = makeMockFetch([
992
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
993
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') }
994
+ ]);
995
+
996
+ const accessors = (
997
+ await HttpTreeAccessors.fromHttp({
998
+ baseUrl: 'http://localhost:3000',
999
+ fetchImpl,
1000
+ mutable: true
1001
+ })
1002
+ ).orThrow();
1003
+
1004
+ accessors.saveFileContents('/data.json', '{"new":1}').orThrow();
1005
+
1006
+ // Sabotage the base getFileContents to simulate a failure
1007
+ const originalGet = accessors.getFileContents.bind(accessors);
1008
+ accessors.getFileContents = (path: string) => {
1009
+ if (path === '/data.json') {
1010
+ // eslint-disable-next-line import/no-internal-modules
1011
+ const { fail: failResult } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
1012
+ return failResult('simulated get failure');
1013
+ }
1014
+ return originalGet(path);
1015
+ };
1016
+
1017
+ const result = await accessors.syncToDisk();
1018
+ expect(result).toFailWith(/simulated get failure/i);
1019
+ });
1020
+ });
1021
+
1022
+ describe('_request() invalid JSON during sync', () => {
1023
+ test('fails when PUT /file returns invalid JSON', async () => {
1024
+ // Covers lines 225-226: _request() returns fail('invalid JSON response')
1025
+ // when response.json() throws during a sync PUT.
1026
+ const { fetchImpl } = makeMockFetch([
1027
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1028
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1029
+ // PUT response with ok=true but throwOnJson simulates invalid JSON body
1030
+ { ok: true, throwOnJson: true }
1031
+ ]);
1032
+
1033
+ const accessors = (
1034
+ await HttpTreeAccessors.fromHttp({
1035
+ baseUrl: 'http://localhost:3000',
1036
+ fetchImpl,
1037
+ mutable: true
1038
+ })
1039
+ ).orThrow();
1040
+
1041
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1042
+ const result = await accessors.syncToDisk();
1043
+
1044
+ expect(result).toFailWith(/invalid json/i);
1045
+ });
1046
+ });
1047
+
1048
+ describe('fromHttp() with inferContentType', () => {
1049
+ test('calls inferContentType when provided and uses the result', async () => {
1050
+ // Covers line 270: params.inferContentType?.(...).orDefault()
1051
+ const { fetchImpl } = makeMockFetch([
1052
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1053
+ { ok: true, jsonValue: fileResponse('/data.json', '{}', 'application/json') }
1054
+ ]);
1055
+
1056
+ const result = await HttpTreeAccessors.fromHttp({
1057
+ baseUrl: 'http://localhost:3000',
1058
+ fetchImpl,
1059
+ inferContentType: (path, provided) => {
1060
+ if (provided === 'application/json') {
1061
+ const { succeed: s } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
1062
+ return s('json' as string);
1063
+ }
1064
+ const { succeed: s } = require('@fgv/ts-utils') as typeof import('@fgv/ts-utils');
1065
+ return s(undefined);
1066
+ }
1067
+ });
1068
+
1069
+ expect(result).toSucceed();
1070
+ });
1071
+ });
1072
+
1073
+ describe('_request() error handling', () => {
1074
+ test('returns failure with error message for network error (Error instance throw) during sync', async () => {
1075
+ // Covers line 214 true branch: response.err instanceof Error -> uses .message
1076
+ let callCount = 0;
1077
+ const fetchImpl: typeof fetch = (_url, _init) => {
1078
+ callCount++;
1079
+ if (callCount === 1) {
1080
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1081
+ }
1082
+ if (callCount === 2) {
1083
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1084
+ }
1085
+ // PUT request throws an Error instance
1086
+ return Promise.reject(new Error('real Error instance'));
1087
+ };
1088
+
1089
+ const accessors = (
1090
+ await HttpTreeAccessors.fromHttp({
1091
+ baseUrl: 'http://localhost:3000',
1092
+ fetchImpl,
1093
+ mutable: true
1094
+ })
1095
+ ).orThrow();
1096
+
1097
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1098
+ const result = await accessors.syncToDisk();
1099
+
1100
+ expect(result).toFailWith(/real error instance/i);
1101
+ });
1102
+
1103
+ test('returns failure with error message for non-Error throw during sync PUT', async () => {
1104
+ // Covers line 214 false branch: thrown value is not an Error instance -> uses String(response.err)
1105
+ // Must be triggered via syncToDisk() which uses the instance _request() method.
1106
+ let callCount = 0;
1107
+ const fetchImpl: typeof fetch = (_url, _init) => {
1108
+ callCount++;
1109
+ if (callCount === 1) {
1110
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1111
+ }
1112
+ if (callCount === 2) {
1113
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') }));
1114
+ }
1115
+ // Non-Error throw (e.g., a plain string)
1116
+ return Promise.reject('non-error string rejection');
1117
+ };
1118
+
1119
+ const accessors = (
1120
+ await HttpTreeAccessors.fromHttp({
1121
+ baseUrl: 'http://localhost:3000',
1122
+ fetchImpl,
1123
+ mutable: true
1124
+ })
1125
+ ).orThrow();
1126
+
1127
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1128
+ const result = await accessors.syncToDisk();
1129
+
1130
+ expect(result).toFailWith(/non-error string rejection/i);
1131
+ });
1132
+
1133
+ test('returns failure with HTTP status fallback when response.text() throws during sync', async () => {
1134
+ // Covers the text() catch branch in _request(): uses `HTTP ${status}` fallback
1135
+ // 502 is transient so retries will be attempted; use fake timers to avoid real delays
1136
+ jest.useFakeTimers();
1137
+ try {
1138
+ let callCount = 0;
1139
+ const fetchImpl: typeof fetch = (_url, _init) => {
1140
+ callCount++;
1141
+ if (callCount === 1) {
1142
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1143
+ }
1144
+ if (callCount === 2) {
1145
+ return Promise.resolve(
1146
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
1147
+ );
1148
+ }
1149
+ return Promise.resolve(makeMockResponse({ ok: false, status: 502, throwOnText: true }));
1150
+ };
1151
+
1152
+ const accessors = (
1153
+ await HttpTreeAccessors.fromHttp({
1154
+ baseUrl: 'http://localhost:3000',
1155
+ fetchImpl,
1156
+ mutable: true
1157
+ })
1158
+ ).orThrow();
1159
+
1160
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1161
+
1162
+ const syncPromise = accessors.syncToDisk();
1163
+ await jest.advanceTimersByTimeAsync(1500);
1164
+
1165
+ const result = await syncPromise;
1166
+ expect(result).toFailWith(/http 502/i);
1167
+ } finally {
1168
+ jest.useRealTimers();
1169
+ }
1170
+ });
1171
+ });
1172
+
1173
+ describe('_requestWithParams() error handling', () => {
1174
+ test('returns failure with error message for non-Error network throw during init', async () => {
1175
+ // _requestWithParams is used for GET requests during fromHttp(); test non-Error throw branch
1176
+ const fetchImpl: typeof fetch = (_url, _init) => {
1177
+ return Promise.reject(42);
1178
+ };
1179
+
1180
+ const result = await HttpTreeAccessors.fromHttp({
1181
+ baseUrl: 'http://localhost:3000',
1182
+ fetchImpl
1183
+ });
1184
+
1185
+ expect(result).toFailWith(/42/);
1186
+ });
1187
+
1188
+ test('returns failure with HTTP status fallback when response.text() throws during init', async () => {
1189
+ const fetchImpl: typeof fetch = (_url, _init) => {
1190
+ return Promise.resolve(makeMockResponse({ ok: false, status: 504, throwOnText: true }));
1191
+ };
1192
+
1193
+ const result = await HttpTreeAccessors.fromHttp({
1194
+ baseUrl: 'http://localhost:3000',
1195
+ fetchImpl
1196
+ });
1197
+
1198
+ expect(result).toFailWith(/http 504/i);
1199
+ });
1200
+
1201
+ test('uses globalThis.fetch when no fetchImpl provided', async () => {
1202
+ // Covers line 48: the `fetchImpl ?? globalThis.fetch` right-side branch.
1203
+ // We temporarily replace globalThis.fetch with a mock that returns an empty tree.
1204
+ const originalFetch = globalThis.fetch;
1205
+ let fetchCallCount = 0;
1206
+
1207
+ globalThis.fetch = (_url: string | URL | Request, _init?: RequestInit) => {
1208
+ fetchCallCount++;
1209
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: { path: '/', children: [] } }));
1210
+ };
1211
+
1212
+ try {
1213
+ const result = await HttpTreeAccessors.fromHttp({
1214
+ baseUrl: 'http://localhost:3000'
1215
+ // No fetchImpl - should fall back to globalThis.fetch
1216
+ });
1217
+
1218
+ expect(result).toSucceed();
1219
+ expect(fetchCallCount).toBeGreaterThan(0);
1220
+ } finally {
1221
+ globalThis.fetch = originalFetch;
1222
+ }
1223
+ });
1224
+ });
1225
+
1226
+ describe('userId header in _request()', () => {
1227
+ test('includes X-User-Id header in PUT /file and POST /sync requests when userId is set', async () => {
1228
+ // Covers line 259: the this._userId branch in _request()
1229
+ const { fetchImpl, calls } = makeMockFetch([
1230
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1231
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1232
+ { ok: true, jsonValue: fileResponse('/data.json', '"updated"') },
1233
+ { ok: true, jsonValue: { synced: 1 } }
1234
+ ]);
1235
+
1236
+ const accessors = (
1237
+ await HttpTreeAccessors.fromHttp({
1238
+ baseUrl: 'http://localhost:3000',
1239
+ fetchImpl,
1240
+ mutable: true,
1241
+ userId: 'test-user-123'
1242
+ })
1243
+ ).orThrow();
1244
+
1245
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1246
+ const result = await accessors.syncToDisk();
1247
+ expect(result).toSucceed();
1248
+
1249
+ // The PUT and POST requests should include the X-User-Id header
1250
+ const syncCalls = calls.slice(2);
1251
+ for (const call of syncCalls) {
1252
+ const headers = call.init?.headers as Record<string, string> | undefined;
1253
+ expect(headers?.['X-User-Id']).toBe('test-user-123');
1254
+ }
1255
+ });
1256
+ });
1257
+
1258
+ describe('deleteFile()', () => {
1259
+ test('fails when the underlying InMemoryTreeAccessors deleteFile fails (file not found)', async () => {
1260
+ // Covers lines 200-201: result.isFailure() branch in deleteFile
1261
+ const { fetchImpl } = makeMockFetch([{ ok: true, jsonValue: { path: '/', children: [] } }]);
1262
+
1263
+ const accessors = (
1264
+ await HttpTreeAccessors.fromHttp({ baseUrl: 'http://localhost:3000', fetchImpl, mutable: true })
1265
+ ).orThrow();
1266
+
1267
+ // Delete a file that does not exist — super.deleteFile should fail
1268
+ const result = accessors.deleteFile('/nonexistent.json');
1269
+ expect(result).toFail();
1270
+ });
1271
+
1272
+ test('includes namespace in DELETE query params when namespace is configured', async () => {
1273
+ // Covers lines 131-132: the namespace branch in syncToDisk's pending-deletion loop
1274
+ const { fetchImpl, calls } = makeMockFetch([
1275
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1276
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1277
+ { ok: true, jsonValue: { deleted: true } },
1278
+ { ok: true, jsonValue: { synced: 0 } }
1279
+ ]);
1280
+
1281
+ const accessors = (
1282
+ await HttpTreeAccessors.fromHttp({
1283
+ baseUrl: 'http://localhost:3000',
1284
+ namespace: 'my-namespace',
1285
+ fetchImpl,
1286
+ mutable: true
1287
+ })
1288
+ ).orThrow();
1289
+
1290
+ accessors.deleteFile('/data.json').orThrow();
1291
+ const result = await accessors.syncToDisk();
1292
+
1293
+ expect(result).toSucceed();
1294
+
1295
+ // The DELETE request URL should include namespace as a query parameter
1296
+ const deleteCalls = calls.filter((c) => c.init?.method === 'DELETE');
1297
+ expect(deleteCalls).toHaveLength(1);
1298
+ expect(deleteCalls[0].url).toContain('namespace=my-namespace');
1299
+ });
1300
+
1301
+ test('triggers fire-and-forget autoSync after successful delete when autoSync is enabled', async () => {
1302
+ // Covers lines 209-212: the autoSync branch in deleteFile
1303
+ const syncResponses: IMockResponse[] = [
1304
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1305
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1306
+ // DELETE /file response for pending deletion
1307
+ { ok: true, jsonValue: { deleted: true } },
1308
+ // POST /sync response
1309
+ { ok: true, jsonValue: { synced: 0 } }
1310
+ ];
1311
+ const { fetchImpl, calls } = makeMockFetch(syncResponses);
1312
+
1313
+ const accessors = (
1314
+ await HttpTreeAccessors.fromHttp({
1315
+ baseUrl: 'http://localhost:3000',
1316
+ fetchImpl,
1317
+ mutable: true,
1318
+ autoSync: true
1319
+ })
1320
+ ).orThrow();
1321
+
1322
+ const result = accessors.deleteFile('/data.json');
1323
+ expect(result).toSucceedWith(true);
1324
+
1325
+ // autoSync fires-and-forgets; wait for microtasks to drain
1326
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
1327
+
1328
+ // Verify that DELETE + POST /sync were called
1329
+ const methodCalls = calls.slice(2).map((c) => c.init?.method);
1330
+ expect(methodCalls).toContain('DELETE');
1331
+ expect(methodCalls).toContain('POST');
1332
+ });
1333
+ });
1334
+
1335
+ describe('_requestWithRetry()', () => {
1336
+ test('succeeds on second attempt after a transient 503 error', async () => {
1337
+ jest.useFakeTimers();
1338
+ try {
1339
+ // Responses: init (GET tree/children), then PUT fails with 503, then PUT succeeds, then POST /sync succeeds
1340
+ let callCount = 0;
1341
+ const fetchImpl: typeof fetch = (_url, _init) => {
1342
+ callCount++;
1343
+ if (callCount === 1) {
1344
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1345
+ }
1346
+ if (callCount === 2) {
1347
+ return Promise.resolve(
1348
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
1349
+ );
1350
+ }
1351
+ // First PUT attempt: transient 503
1352
+ if (callCount === 3) {
1353
+ return Promise.resolve(
1354
+ makeMockResponse({ ok: false, status: 503, textValue: '503 Service Unavailable' })
1355
+ );
1356
+ }
1357
+ // Second PUT attempt: success
1358
+ if (callCount === 4) {
1359
+ return Promise.resolve(
1360
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"updated"') })
1361
+ );
1362
+ }
1363
+ // POST /sync
1364
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: { synced: 1 } }));
1365
+ };
1366
+
1367
+ const accessors = (
1368
+ await HttpTreeAccessors.fromHttp({
1369
+ baseUrl: 'http://localhost:3000',
1370
+ fetchImpl,
1371
+ mutable: true
1372
+ })
1373
+ ).orThrow();
1374
+
1375
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1376
+
1377
+ const syncPromise = accessors.syncToDisk();
1378
+
1379
+ // Advance past the 500ms backoff for the first retry
1380
+ await jest.advanceTimersByTimeAsync(500);
1381
+
1382
+ const result = await syncPromise;
1383
+ expect(result).toSucceed();
1384
+ // Three PUT-related calls: init (2) + first PUT attempt (1) + retry PUT (1) + POST sync (1)
1385
+ expect(callCount).toBe(5);
1386
+ } finally {
1387
+ jest.useRealTimers();
1388
+ }
1389
+ });
1390
+
1391
+ test('does not retry on a non-transient error (e.g. 404)', async () => {
1392
+ jest.useFakeTimers();
1393
+ try {
1394
+ let callCount = 0;
1395
+ const fetchImpl: typeof fetch = (_url, _init) => {
1396
+ callCount++;
1397
+ if (callCount === 1) {
1398
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1399
+ }
1400
+ if (callCount === 2) {
1401
+ return Promise.resolve(
1402
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
1403
+ );
1404
+ }
1405
+ // PUT attempt: non-transient 404
1406
+ return Promise.resolve(makeMockResponse({ ok: false, status: 404, textValue: 'Not Found' }));
1407
+ };
1408
+
1409
+ const accessors = (
1410
+ await HttpTreeAccessors.fromHttp({
1411
+ baseUrl: 'http://localhost:3000',
1412
+ fetchImpl,
1413
+ mutable: true
1414
+ })
1415
+ ).orThrow();
1416
+
1417
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1418
+
1419
+ const result = await accessors.syncToDisk();
1420
+
1421
+ // No timers should need advancing - non-transient errors return immediately
1422
+ expect(result).toFailWith(/not found/i);
1423
+ // Only 3 calls: 2 init + 1 PUT (no retries)
1424
+ expect(callCount).toBe(3);
1425
+ } finally {
1426
+ jest.useRealTimers();
1427
+ }
1428
+ });
1429
+
1430
+ test('returns the last error after exhausting all retries on persistent transient errors', async () => {
1431
+ jest.useFakeTimers();
1432
+ try {
1433
+ let callCount = 0;
1434
+ const fetchImpl: typeof fetch = (_url, _init) => {
1435
+ callCount++;
1436
+ if (callCount === 1) {
1437
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1438
+ }
1439
+ if (callCount === 2) {
1440
+ return Promise.resolve(
1441
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
1442
+ );
1443
+ }
1444
+ // All PUT attempts: transient 502 every time
1445
+ return Promise.resolve(makeMockResponse({ ok: false, status: 502, textValue: '502 Bad Gateway' }));
1446
+ };
1447
+
1448
+ const accessors = (
1449
+ await HttpTreeAccessors.fromHttp({
1450
+ baseUrl: 'http://localhost:3000',
1451
+ fetchImpl,
1452
+ mutable: true
1453
+ })
1454
+ ).orThrow();
1455
+
1456
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1457
+
1458
+ const syncPromise = accessors.syncToDisk();
1459
+
1460
+ // Advance past both backoff delays: 500ms (attempt 1) + 1000ms (attempt 2)
1461
+ await jest.advanceTimersByTimeAsync(1500);
1462
+
1463
+ const result = await syncPromise;
1464
+ expect(result).toFailWith(/502 bad gateway/i);
1465
+ // 2 init + 3 PUT attempts (maxAttempts = 3)
1466
+ expect(callCount).toBe(5);
1467
+ } finally {
1468
+ jest.useRealTimers();
1469
+ }
1470
+ });
1471
+
1472
+ test('logs retry message with method name from init when retrying', async () => {
1473
+ jest.useFakeTimers();
1474
+ try {
1475
+ const logger = {
1476
+ detail: jest.fn(),
1477
+ info: jest.fn(),
1478
+ warn: jest.fn(),
1479
+ error: jest.fn()
1480
+ } as unknown as Logging.LogReporter<unknown>;
1481
+
1482
+ let callCount = 0;
1483
+ const fetchImpl: typeof fetch = (_url, _init) => {
1484
+ callCount++;
1485
+ if (callCount === 1) {
1486
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: rootWithOneFile('data.json') }));
1487
+ }
1488
+ if (callCount === 2) {
1489
+ return Promise.resolve(
1490
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '{}') })
1491
+ );
1492
+ }
1493
+ // First PUT attempt: transient 503
1494
+ if (callCount === 3) {
1495
+ return Promise.resolve(
1496
+ makeMockResponse({ ok: false, status: 503, textValue: '503 Service Unavailable' })
1497
+ );
1498
+ }
1499
+ // Second PUT attempt: success
1500
+ if (callCount === 4) {
1501
+ return Promise.resolve(
1502
+ makeMockResponse({ ok: true, jsonValue: fileResponse('/data.json', '"updated"') })
1503
+ );
1504
+ }
1505
+ // POST /sync
1506
+ return Promise.resolve(makeMockResponse({ ok: true, jsonValue: { synced: 1 } }));
1507
+ };
1508
+
1509
+ const accessors = (
1510
+ await HttpTreeAccessors.fromHttp({
1511
+ baseUrl: 'http://localhost:3000',
1512
+ fetchImpl,
1513
+ mutable: true,
1514
+ logger
1515
+ })
1516
+ ).orThrow();
1517
+
1518
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1519
+
1520
+ const syncPromise = accessors.syncToDisk();
1521
+ await jest.advanceTimersByTimeAsync(500);
1522
+ await syncPromise;
1523
+
1524
+ // The retry log message should include the method name (PUT) from init
1525
+ expect(logger.detail).toHaveBeenCalledWith(expect.stringContaining('PUT'));
1526
+ } finally {
1527
+ jest.useRealTimers();
1528
+ }
1529
+ });
1530
+ });
1531
+
1532
+ describe('syncToDisk() concurrency guard', () => {
1533
+ test('concurrent syncToDisk calls share the same promise and only make one set of network calls', async () => {
1534
+ const { fetchImpl, calls } = makeMockFetch([
1535
+ { ok: true, jsonValue: rootWithOneFile('data.json') },
1536
+ { ok: true, jsonValue: fileResponse('/data.json', '{}') },
1537
+ // PUT /file for the single sync
1538
+ { ok: true, jsonValue: fileResponse('/data.json', '"updated"') },
1539
+ // POST /sync
1540
+ { ok: true, jsonValue: { synced: 1 } }
1541
+ ]);
1542
+
1543
+ const accessors = (
1544
+ await HttpTreeAccessors.fromHttp({
1545
+ baseUrl: 'http://localhost:3000',
1546
+ fetchImpl,
1547
+ mutable: true
1548
+ })
1549
+ ).orThrow();
1550
+
1551
+ accessors.saveFileContents('/data.json', '"updated"').orThrow();
1552
+
1553
+ // Start two concurrent syncToDisk calls without awaiting the first
1554
+ const promise1 = accessors.syncToDisk();
1555
+ const promise2 = accessors.syncToDisk();
1556
+
1557
+ const [result1, result2] = await Promise.all([promise1, promise2]);
1558
+
1559
+ expect(result1).toSucceed();
1560
+ expect(result2).toSucceed();
1561
+
1562
+ // Both promises should have resolved to the same underlying promise result.
1563
+ // Only one PUT and one POST /sync should have been issued (not doubled).
1564
+ const syncCalls = calls.slice(2);
1565
+ const putCalls = syncCalls.filter((c) => c.init?.method === 'PUT');
1566
+ const postCalls = syncCalls.filter((c) => c.init?.method === 'POST');
1567
+ expect(putCalls).toHaveLength(1);
1568
+ expect(postCalls).toHaveLength(1);
1569
+ });
1570
+ });
1571
+ });