@delali/narsil 0.3.1-next.153 → 0.3.1-next.154

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 (268) hide show
  1. package/README.md +2 -1
  2. package/dist/adapters/filesystem.mjs +2 -2
  3. package/dist/adapters/gcs.mjs +2 -2
  4. package/dist/adapters/indexeddb.mjs +1 -1
  5. package/dist/adapters/s3.mjs +2 -2
  6. package/dist/{analysis-change-2OYM7ARW.mjs → analysis-change-4GCRVRBW.mjs} +27 -18
  7. package/dist/{react-native/chunks/analysis-change-entry-CXNRW324.mjs → analysis-change-entry-KYGSXW4K.mjs} +1 -1
  8. package/dist/browser/{analysis-change-2V2HZ2NY.mjs → analysis-change-IXWPXXJJ.mjs} +17 -7
  9. package/dist/{analysis-change-entry-QD7YNDEE.mjs → browser/analysis-change-entry-FCSHFQSS.mjs} +1 -1
  10. package/dist/browser/{chunk-TQ5UMFG5.mjs → chunk-2FX6ROWR.mjs} +15 -6
  11. package/dist/browser/{chunk-KWYQ6KX4.mjs → chunk-2SHAKW2Z.mjs} +119 -1922
  12. package/dist/browser/{chunk-55WYRLDZ.mjs → chunk-3U3QR5YP.mjs} +2 -2
  13. package/dist/browser/chunk-4PD752F6.mjs +85 -0
  14. package/dist/browser/chunk-5W3MMTLG.mjs +19 -0
  15. package/dist/browser/{chunk-IAXZAVYL.mjs → chunk-7MEYN7V6.mjs} +1 -151
  16. package/dist/browser/chunk-7TTWXUH6.mjs +1828 -0
  17. package/dist/browser/{chunk-CSCKZBVJ.mjs → chunk-AJ4HHOVT.mjs} +4 -4
  18. package/dist/{react-native/chunks/chunk-DFQJ4IJB.mjs → browser/chunk-AYY6PIKL.mjs} +2 -2
  19. package/dist/browser/{chunk-VD7JEUIR.mjs → chunk-C4KS2QNF.mjs} +9 -8
  20. package/dist/browser/chunk-DSXIBE6N.mjs +78 -0
  21. package/dist/browser/chunk-ELV4OZOI.mjs +29 -0
  22. package/dist/browser/{chunk-PM4MUM5N.mjs → chunk-EUNBNLKM.mjs} +6 -5
  23. package/dist/browser/{chunk-GJKXW3SF.mjs → chunk-G7LUMBSG.mjs} +137 -253
  24. package/dist/browser/{chunk-B3JM6Z74.mjs → chunk-H6QFBMVE.mjs} +3 -2
  25. package/dist/browser/chunk-J433A7P3.mjs +241 -0
  26. package/dist/browser/chunk-ML6HY7T7.mjs +96 -0
  27. package/dist/browser/chunk-ML7THVLJ.mjs +38 -0
  28. package/dist/{chunk-MDF6PDIA.mjs → browser/chunk-MYITLCHT.mjs} +7 -1
  29. package/dist/browser/{chunk-QJCO3TJU.mjs → chunk-QXTPSX2H.mjs} +9 -150
  30. package/dist/browser/{chunk-MPK76GVS.mjs → chunk-RA6LSBCM.mjs} +1 -21
  31. package/dist/browser/{chunk-7ZJTRUVW.mjs → chunk-SIR3LMTV.mjs} +2 -2
  32. package/dist/browser/{chunk-LURXVCHG.mjs → chunk-SJB6VIZG.mjs} +1 -1
  33. package/dist/browser/chunk-TTD27VXX.mjs +298 -0
  34. package/dist/browser/chunk-U2E3HMYW.mjs +151 -0
  35. package/dist/browser/{chunk-2A2IPRC3.mjs → chunk-VCOYGVP7.mjs} +5 -31
  36. package/dist/browser/chunk-VI7BQR4U.mjs +21 -0
  37. package/dist/browser/chunk-W5X2UFWQ.mjs +102 -0
  38. package/dist/browser/{chunk-HT7J73QL.mjs → chunk-XRV72TJD.mjs} +2 -2
  39. package/dist/browser/chunk-YJHGOJAC.mjs +15 -0
  40. package/dist/browser/chunk-ZI2V4VD7.mjs +21 -0
  41. package/dist/{react-native/chunks/chunk-QC4ZRBSX.mjs → browser/chunk-ZPTA75ZC.mjs} +2 -79
  42. package/dist/browser/{cold-module-YECAK4MN.mjs → cold-module-VTUGDYNY.mjs} +20 -14
  43. package/dist/browser/{durability-wiring-LM7WFL6X.mjs → durability-wiring-GL4A7KDV.mjs} +1886 -1364
  44. package/dist/browser/import-YI5GNB4H.mjs +17 -0
  45. package/dist/browser/methods-LMUTS7OI.mjs +30 -0
  46. package/dist/browser/{module-XQLEOYNM.mjs → module-EC3FYW7N.mjs} +9 -8
  47. package/dist/browser/{module-KAMRAJLE.mjs → module-M4JNBV6V.mjs} +16 -10
  48. package/dist/browser/operations-WVYLF72Q.mjs +5 -0
  49. package/dist/browser/{phrase-module-CNKMUY4U.mjs → phrase-module-NPYUVX75.mjs} +1 -1
  50. package/dist/browser/{pool-DTYSPBMQ.mjs → pool-WCGDZHJP.mjs} +3 -2
  51. package/dist/{restore-queue-AOF5OTQV.mjs → browser/restore-queue-TYIGDL5L.mjs} +2 -2
  52. package/dist/browser/retention-6QMRS5VK.mjs +207 -0
  53. package/dist/browser/{runtime-D2ULZGCN.mjs → runtime-3EW2AGB6.mjs} +1 -1
  54. package/dist/browser/{snapshot-UGZVMP4H.mjs → snapshot-DN3CRVUQ.mjs} +38 -307
  55. package/dist/browser/sync-state-P5XG6LTQ.mjs +15 -0
  56. package/dist/browser/{write-I5P5MW4O.mjs → write-WAWAFGKQ.mjs} +16 -11
  57. package/dist/{capabilities-BT-HLDC8.d.ts → capabilities-B3Brs1Rc.d.ts} +62 -7
  58. package/dist/{chunk-DGRM4EZZ.mjs → chunk-37IVJLP6.mjs} +1 -1
  59. package/dist/{chunk-KYVRZAYP.mjs → chunk-3A5KI24C.mjs} +2 -69
  60. package/dist/{chunk-POUYICOU.mjs → chunk-3OFU3NJT.mjs} +1 -1
  61. package/dist/{chunk-3TVDTACC.mjs → chunk-3Y3J4V2R.mjs} +1 -1
  62. package/dist/{chunk-FNBNZCGP.mjs → chunk-466PYR4P.mjs} +2 -2
  63. package/dist/{chunk-SEAJS664.mjs → chunk-4HWZV5MK.mjs} +5 -5
  64. package/dist/{chunk-UGVUW27S.mjs → chunk-5FUOVJKG.mjs} +13 -9
  65. package/dist/{chunk-ZHAXP7SD.mjs → chunk-5KGYQT6W.mjs} +6 -235
  66. package/dist/{chunk-NPXVQS33.mjs → chunk-62G63NMH.mjs} +4 -3
  67. package/dist/chunk-6MSZ543Y.mjs +32 -0
  68. package/dist/chunk-7GXJUJ24.mjs +49 -0
  69. package/dist/{chunk-3E4RRF5J.mjs → chunk-7HCZWC7B.mjs} +58 -8
  70. package/dist/{chunk-6RKSY3BX.mjs → chunk-7NTMUDC5.mjs} +5 -5
  71. package/dist/chunk-7QUGDVFC.mjs +101 -0
  72. package/dist/{chunk-G5KHSM6E.mjs → chunk-AO2FAYIZ.mjs} +1 -1
  73. package/dist/chunk-B7S6YEBP.mjs +102 -0
  74. package/dist/{chunk-AWNHDBKV.mjs → chunk-BPSKLCS7.mjs} +15 -7
  75. package/dist/chunk-BUMREPLU.mjs +15 -0
  76. package/dist/{chunk-T4CJDBBE.mjs → chunk-C6ASEFZI.mjs} +1 -1
  77. package/dist/{chunk-NITCPDFL.mjs → chunk-C73JLU4E.mjs} +2 -2
  78. package/dist/{chunk-NYSONUB7.mjs → chunk-CP5RRPJR.mjs} +1 -1
  79. package/dist/{chunk-TTCKT2RT.mjs → chunk-DMQPFLGI.mjs} +134 -11
  80. package/dist/{chunk-3SBJVQLL.mjs → chunk-DVWYODEB.mjs} +2 -2
  81. package/dist/chunk-ECX4SGX6.mjs +167 -0
  82. package/dist/chunk-GES7U2PM.mjs +68 -0
  83. package/dist/{chunk-NVTFQFUL.mjs → chunk-HVKXNBFL.mjs} +1 -1
  84. package/dist/chunk-HVYICDY3.mjs +214 -0
  85. package/dist/{chunk-3HV7M5OJ.mjs → chunk-HWEDFLB7.mjs} +9 -133
  86. package/dist/{chunk-52QQWEBS.mjs → chunk-IBNLW3AV.mjs} +21 -6
  87. package/dist/chunk-IJU7LL7D.mjs +242 -0
  88. package/dist/chunk-IPN7S4KX.mjs +130 -0
  89. package/dist/{chunk-5QMHMELB.mjs → chunk-IQ4R2I6N.mjs} +4 -1
  90. package/dist/chunk-JCLTESFN.mjs +96 -0
  91. package/dist/{chunk-J4BDAH2W.mjs → chunk-JFNKIBDT.mjs} +2 -2
  92. package/dist/{chunk-LDGGR7YT.mjs → chunk-K4B7OH65.mjs} +2 -2
  93. package/dist/{chunk-7TE2AJIH.mjs → chunk-K7KLL263.mjs} +13 -10
  94. package/dist/{chunk-CSHHU7PA.mjs → chunk-KCUIFVVW.mjs} +11 -30
  95. package/dist/{react-native/chunks/chunk-YH7W556M.mjs → chunk-KUZKUONM.mjs} +11 -2
  96. package/dist/chunk-KYYABCSW.mjs +72 -0
  97. package/dist/{chunk-B2FTZNNF.mjs → chunk-LKUE5GXS.mjs} +34 -14
  98. package/dist/{chunk-2PNYKG2D.mjs → chunk-LSM2YTKM.mjs} +100 -335
  99. package/dist/{chunk-DMNPYF54.mjs → chunk-LTUGDMV4.mjs} +2 -2
  100. package/dist/{chunk-FDG4KXX5.mjs → chunk-MLHNSAPK.mjs} +5 -3
  101. package/dist/{chunk-VP6XRMWR.mjs → chunk-MMBEANB2.mjs} +6 -32
  102. package/dist/{chunk-LJ4ENXOD.mjs → chunk-MMEMEUOO.mjs} +2 -2
  103. package/dist/{chunk-2HJWQPR6.mjs → chunk-NTZOXVUZ.mjs} +6 -122
  104. package/dist/{chunk-5WB2A3XU.mjs → chunk-NZMAXR2S.mjs} +397 -24
  105. package/dist/{chunk-IZT3G24Q.mjs → chunk-O43Z4MS6.mjs} +2 -2
  106. package/dist/{chunk-U46IZNCW.mjs → chunk-OKX2BBNW.mjs} +3 -2
  107. package/dist/{chunk-RBEHLIKX.mjs → chunk-PFKM7VNZ.mjs} +14 -8
  108. package/dist/chunk-PGVPE7GJ.mjs +96 -0
  109. package/dist/chunk-Q3TCTQCC.mjs +85 -0
  110. package/dist/chunk-Q7MS6P2J.mjs +74 -0
  111. package/dist/chunk-QDZJM7NI.mjs +23 -0
  112. package/dist/{chunk-ZS6CMXAE.mjs → chunk-QKZHLADX.mjs} +89 -250
  113. package/dist/{chunk-IJSFWGVW.mjs → chunk-REL7LFLR.mjs} +3 -3
  114. package/dist/chunk-RVKFI3A2.mjs +237 -0
  115. package/dist/chunk-S2N75OTN.mjs +83 -0
  116. package/dist/chunk-TRISKD4Q.mjs +50 -0
  117. package/dist/{chunk-6F6USYII.mjs → chunk-TV2L3BN7.mjs} +13 -11
  118. package/dist/{chunk-6BWLDLS3.mjs → chunk-URPCYQVJ.mjs} +1 -1
  119. package/dist/chunk-USR7FQRZ.mjs +34 -0
  120. package/dist/chunk-V6EUBAIT.mjs +19 -0
  121. package/dist/{chunk-SOUZMPME.mjs → chunk-VMXSVVXG.mjs} +7 -194
  122. package/dist/{chunk-4QCSHLNM.mjs → chunk-VREK3MYG.mjs} +3 -3
  123. package/dist/{chunk-YGQOPB2Z.mjs → chunk-WCBA2LVZ.mjs} +1 -1
  124. package/dist/{chunk-KQJVNPRM.mjs → chunk-X6NSJYQ3.mjs} +19 -16
  125. package/dist/chunk-Y4WPNHMC.mjs +50 -0
  126. package/dist/{chunk-IRWP524D.mjs → chunk-YBJDOA2T.mjs} +1 -1
  127. package/dist/{chunk-IJPK5PGM.mjs → chunk-YPUEV6ZC.mjs} +1 -1
  128. package/dist/{chunk-J7M73VY7.mjs → chunk-YROWNOMH.mjs} +1 -1
  129. package/dist/chunk-Z3TNWCI5.mjs +196 -0
  130. package/dist/{chunk-65WCV5JO.mjs → chunk-ZIFJXCKA.mjs} +1 -1
  131. package/dist/chunk-ZYAY26KG.mjs +29 -0
  132. package/dist/{client-Cn3gNxUU.d.ts → client-Df76GNKm.d.ts} +76 -6
  133. package/dist/client.d.ts +8 -7
  134. package/dist/client.mjs +56 -5
  135. package/dist/{cold-module-PYSSBIL7.mjs → cold-module-YLWMTTZG.mjs} +38 -28
  136. package/dist/{config-CfhH1IWQ.d.ts → config-05G_hy-1.d.ts} +3 -3
  137. package/dist/config-B8DP2VwR.d.ts +463 -0
  138. package/dist/{direct-executor-WYALQSMD.mjs → direct-executor-FI5GJHWX.mjs} +14 -9
  139. package/dist/distribution/coordinator/etcd.d.ts +2 -2
  140. package/dist/distribution/coordinator/etcd.mjs +1 -1
  141. package/dist/distribution/coordinator/in-memory.d.ts +2 -2
  142. package/dist/distribution/transport/grpc.mjs +4 -4
  143. package/dist/distribution/transport/in-memory.mjs +2 -2
  144. package/dist/distribution/transport/tcp.mjs +3 -3
  145. package/dist/distribution.d.ts +41 -9
  146. package/dist/distribution.mjs +1296 -117
  147. package/dist/{durability-wiring-7VBZEJLG.mjs → durability-wiring-RHLXDIVF.mjs} +1751 -1226
  148. package/dist/embeddings/openai.mjs +2 -2
  149. package/dist/{engine-CJRUHXgf.d.ts → engine-DYu-e0oR.d.ts} +50 -40
  150. package/dist/{import-GJOMB2HC.mjs → import-SRBNC6TE.mjs} +27 -19
  151. package/dist/{index-MsF7e5hL.d.ts → index-nRqDM6uS.d.ts} +1 -1
  152. package/dist/index.browser.mjs +8 -4
  153. package/dist/index.d.ts +7 -6
  154. package/dist/index.mjs +24 -16
  155. package/dist/index.react-native.mjs +17 -11
  156. package/dist/{long-query-thread-SCUE62TO.mjs → long-query-thread-EMYTGSJP.mjs} +28 -15
  157. package/dist/methods-ABM5ELBR.mjs +30 -0
  158. package/dist/{module-AVQEIB7O.mjs → module-3OMJZUFT.mjs} +12 -12
  159. package/dist/{module-6RLIKSZQ.mjs → module-MG7JMV2U.mjs} +33 -23
  160. package/dist/operations-PGOAY2KS.mjs +5 -0
  161. package/dist/{paged-partition-archive-KGRW366Y.mjs → paged-partition-archive-UOLHOEZJ.mjs} +37 -26
  162. package/dist/partial-words.mjs +6 -4
  163. package/dist/pattern.mjs +4 -3
  164. package/dist/persistence/durability/checkpoint-worker.d.ts +9 -1
  165. package/dist/persistence/durability/checkpoint-worker.mjs +34 -23
  166. package/dist/{phrase-module-OUQIRUQU.mjs → phrase-module-O3MDRQXP.mjs} +1 -1
  167. package/dist/{pool-UPV5PVPY.mjs → pool-CQXYPFLG.mjs} +2 -2
  168. package/dist/react-native/chunks/{analysis-change-DXPZRGWF.mjs → analysis-change-EAYO3Y6Q.mjs} +27 -15
  169. package/dist/{browser/analysis-change-entry-JL5U2N3Q.mjs → react-native/chunks/analysis-change-entry-TNLUC6IZ.mjs} +1 -1
  170. package/dist/react-native/chunks/{chunk-D7LFYPYI.mjs → chunk-2CGSQM4O.mjs} +12 -10
  171. package/dist/react-native/chunks/chunk-3NQOVO3K.mjs +1 -0
  172. package/dist/react-native/chunks/{chunk-R4OPUZQ5.mjs → chunk-3O57C2ZO.mjs} +2 -2
  173. package/dist/react-native/chunks/chunk-3XKMRNRE.mjs +298 -0
  174. package/dist/react-native/chunks/{chunk-IDFMNRIC.mjs → chunk-63YSZOXB.mjs} +97 -333
  175. package/dist/react-native/chunks/{chunk-UFNCLEQM.mjs → chunk-75VWIY35.mjs} +1 -1
  176. package/dist/react-native/chunks/{chunk-2J2727V4.mjs → chunk-7GWPJDOA.mjs} +1 -1
  177. package/dist/react-native/chunks/{chunk-PU55IOG4.mjs → chunk-AUT7PMA4.mjs} +6 -190
  178. package/dist/react-native/chunks/chunk-C2H2QQFW.mjs +288 -0
  179. package/dist/react-native/chunks/chunk-CHPTFFJM.mjs +43 -0
  180. package/dist/{browser/chunk-PIS7ZAP7.mjs → react-native/chunks/chunk-CUNGPR5R.mjs} +11 -2
  181. package/dist/{browser/chunk-NVEJJP4R.mjs → react-native/chunks/chunk-DCKMICOB.mjs} +2 -79
  182. package/dist/react-native/chunks/chunk-DH3TVWWK.mjs +102 -0
  183. package/dist/react-native/chunks/{chunk-ZCKNBPQ4.mjs → chunk-EH5CFV6Z.mjs} +2 -2
  184. package/dist/react-native/chunks/chunk-F753DA54.mjs +23 -0
  185. package/dist/{browser/chunk-VBX2TI5V.mjs → react-native/chunks/chunk-GFYFQLJD.mjs} +2 -2
  186. package/dist/react-native/chunks/{chunk-7IQR3SZO.mjs → chunk-I5PGWQJF.mjs} +142 -257
  187. package/dist/react-native/chunks/{chunk-NFGBOI46.mjs → chunk-IOY2SM2P.mjs} +1 -1
  188. package/dist/react-native/chunks/chunk-JDOEEMEF.mjs +38 -0
  189. package/dist/react-native/chunks/{chunk-TLYD7IJ2.mjs → chunk-JPAJWO6D.mjs} +1 -1
  190. package/dist/react-native/chunks/chunk-JWUCMVRK.mjs +15 -0
  191. package/dist/react-native/chunks/{chunk-KLZGAOLT.mjs → chunk-JX2RIAXH.mjs} +4 -4
  192. package/dist/react-native/chunks/chunk-LU3Y3P63.mjs +68 -0
  193. package/dist/react-native/chunks/{chunk-LQAKO5QV.mjs → chunk-NCJS3WIY.mjs} +2 -2
  194. package/dist/react-native/chunks/{chunk-BRNAVOKP.mjs → chunk-NKIZX26F.mjs} +2 -2
  195. package/dist/react-native/chunks/{chunk-CLE3LZ77.mjs → chunk-NP7DD4G5.mjs} +5 -4
  196. package/dist/react-native/chunks/chunk-NVVRSRX5.mjs +78 -0
  197. package/dist/react-native/chunks/chunk-O32RB3BL.mjs +191 -0
  198. package/dist/react-native/chunks/{chunk-DKJTZ625.mjs → chunk-OQQVRWZ2.mjs} +2 -69
  199. package/dist/react-native/chunks/chunk-PB2YXVQW.mjs +29 -0
  200. package/dist/react-native/chunks/chunk-Q32DDFKX.mjs +19 -0
  201. package/dist/react-native/chunks/{chunk-LRGWK367.mjs → chunk-RVAEBN74.mjs} +1 -1
  202. package/dist/react-native/chunks/{chunk-KOCTCUXW.mjs → chunk-RYMDHGL4.mjs} +16 -8
  203. package/dist/react-native/chunks/chunk-SJWDBRNP.mjs +85 -0
  204. package/dist/react-native/chunks/chunk-UNUFZ2QY.mjs +68 -0
  205. package/dist/react-native/chunks/chunk-UWDNZDWK.mjs +242 -0
  206. package/dist/react-native/chunks/{chunk-FS7BYE23.mjs → chunk-VQSKZ3EZ.mjs} +9 -152
  207. package/dist/react-native/chunks/{chunk-UCJU6WNH.mjs → chunk-VVFYOADG.mjs} +7 -6
  208. package/dist/react-native/chunks/{chunk-VGUWIZFQ.mjs → chunk-YBEW6YTR.mjs} +1 -1
  209. package/dist/react-native/chunks/{chunk-JYL35A4A.mjs → chunk-YHKZSLOC.mjs} +7 -33
  210. package/dist/react-native/chunks/{chunk-3CTWSQRW.mjs → chunk-ZBSWRSBG.mjs} +4 -30
  211. package/dist/react-native/chunks/chunk-ZYDKJXQJ.mjs +96 -0
  212. package/dist/react-native/chunks/{cold-module-KFGEWYEL.mjs → cold-module-TJL6AFAD.mjs} +29 -21
  213. package/dist/react-native/chunks/{durability-wiring-QKJB2QBT.mjs → durability-wiring-RRDYJLLM.mjs} +1882 -1358
  214. package/dist/react-native/chunks/gzip.react-native-DNB5YNFA.mjs +3 -0
  215. package/dist/react-native/chunks/import-JYBMEJPQ.mjs +29 -0
  216. package/dist/react-native/chunks/methods-X6F36SJE.mjs +30 -0
  217. package/dist/react-native/chunks/module-QT5HZAY4.mjs +33 -0
  218. package/dist/react-native/chunks/{module-UJ5VUARS.mjs → module-S4DKSWMF.mjs} +10 -9
  219. package/dist/react-native/chunks/operations-RYKTSZQA.mjs +5 -0
  220. package/dist/react-native/chunks/{phrase-module-76UAPPSG.mjs → phrase-module-JZ37TB7N.mjs} +1 -1
  221. package/dist/react-native/chunks/{pool-CD4ANYUI.mjs → pool-RTGXJXPU.mjs} +3 -2
  222. package/dist/{browser/restore-queue-UQ6AAUVX.mjs → react-native/chunks/restore-queue-ZBVIKJWI.mjs} +2 -2
  223. package/dist/react-native/chunks/retention-PPCTP2VY.mjs +219 -0
  224. package/dist/react-native/chunks/{runtime-3MCDLJAF.mjs → runtime-KUATOLYB.mjs} +1 -1
  225. package/dist/react-native/chunks/{snapshot-KVBD4LRC.mjs → snapshot-ZBIEOZTZ.mjs} +47 -314
  226. package/dist/react-native/chunks/sync-state-PASCIHHT.mjs +15 -0
  227. package/dist/react-native/chunks/{write-ES5A3WUA.mjs → write-2W4FTX7J.mjs} +25 -18
  228. package/dist/react-native/partial-words.mjs +6 -4
  229. package/dist/react-native/pattern.mjs +4 -3
  230. package/dist/react-native/sync.mjs +2236 -0
  231. package/dist/react-native/synonyms.mjs +7 -4
  232. package/dist/react.d.ts +10 -9
  233. package/dist/react.mjs +7 -1
  234. package/dist/{rerank-3W54N6P2.mjs → rerank-IZOB6NII.mjs} +4 -4
  235. package/dist/rerankers/http.mjs +2 -2
  236. package/dist/{react-native/chunks/restore-queue-H5VCN453.mjs → restore-queue-COI2GSSK.mjs} +2 -2
  237. package/dist/retention-55WA7GPU.mjs +58 -0
  238. package/dist/{runtime-L2DZYY6N.mjs → runtime-UZOC3NPY.mjs} +5 -5
  239. package/dist/{schema-D33CyXCy.d.ts → schema-DDauvDOv.d.ts} +1 -1
  240. package/dist/server.d.ts +22 -19
  241. package/dist/server.mjs +868 -50
  242. package/dist/{snapshot-WMX6JCLP.mjs → snapshot-NFX2EYN2.mjs} +62 -36
  243. package/dist/sync/filesystem.d.ts +30 -0
  244. package/dist/sync/filesystem.mjs +271 -0
  245. package/dist/sync/indexeddb.d.ts +30 -0
  246. package/dist/sync/indexeddb.mjs +237 -0
  247. package/dist/sync-state-ZWHLAFLE.mjs +15 -0
  248. package/dist/{config-aIsy7mcL.d.ts → sync-uXR7MmM7.d.ts} +53 -444
  249. package/dist/sync.browser.mjs +2231 -0
  250. package/dist/sync.d.ts +23 -0
  251. package/dist/sync.mjs +2206 -0
  252. package/dist/synonyms.mjs +5 -3
  253. package/dist/{tasks-C4ElXr4P.d.ts → tasks-BShx8pdK.d.ts} +4 -4
  254. package/dist/thread-P2G2FWM2.mjs +44 -0
  255. package/dist/types-SnO7_tAI.d.ts +228 -0
  256. package/dist/vector/search-worker.d.ts +1 -1
  257. package/dist/vector/search-worker.mjs +6 -6
  258. package/dist/workers/entry.mjs +7 -7
  259. package/dist/{write-SKJ6HW7O.mjs → write-FGB62BHQ.mjs} +31 -23
  260. package/openapi.json +119 -3
  261. package/package.json +28 -8
  262. package/dist/browser/import-QOY6ZH6X.mjs +0 -12
  263. package/dist/chunk-7LDMWKP6.mjs +0 -209
  264. package/dist/react-native/chunks/chunk-L4M7QJNP.mjs +0 -110
  265. package/dist/react-native/chunks/gzip.react-native-7JWCLVOB.mjs +0 -3
  266. package/dist/react-native/chunks/import-XFBCCENV.mjs +0 -22
  267. package/dist/react-native/chunks/module-FHJ2GOBI.mjs +0 -25
  268. package/dist/thread-I7DVHHW7.mjs +0 -31
@@ -0,0 +1,2236 @@
1
+ import { readSnapshotArchive } from './chunks/chunk-3XKMRNRE.mjs';
2
+ import './chunks/chunk-UWDNZDWK.mjs';
3
+ import { createByteReader } from './chunks/chunk-NVVRSRX5.mjs';
4
+ import { isSyncEpoch } from './chunks/chunk-JWUCMVRK.mjs';
5
+ import './chunks/chunk-SJWDBRNP.mjs';
6
+ import './chunks/chunk-YBEW6YTR.mjs';
7
+ import { readHeapStatistics, decodeIndexConfiguration } from './chunks/chunk-C2H2QQFW.mjs';
8
+ import './chunks/chunk-CHPTFFJM.mjs';
9
+ import { encodeDocument } from './chunks/chunk-O32RB3BL.mjs';
10
+ import './chunks/chunk-TJMSKBEM.mjs';
11
+ import './chunks/chunk-OQQVRWZ2.mjs';
12
+ import { hasLanguage, hasTokenizer, hasStopWords, getLanguage } from './chunks/chunk-ZBSWRSBG.mjs';
13
+ import './chunks/chunk-KWRW5U65.mjs';
14
+ import './chunks/chunk-PPEPTUVV.mjs';
15
+ import { NarsilError, ErrorCodes, ClientErrorCodes, ServerErrorCodes, describeError } from './chunks/chunk-CUNGPR5R.mjs';
16
+ import { decode, encode } from '@msgpack/msgpack';
17
+
18
+ // src/json-encoding.ts
19
+ function toPlainNumbers(key, value) {
20
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
21
+ return Array.from(value);
22
+ }
23
+ return value;
24
+ }
25
+ function encodeJson(value) {
26
+ return JSON.stringify(value, toPlainNumbers);
27
+ }
28
+
29
+ // src/client/constants.ts
30
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
31
+ var NO_TIMEOUT = 0;
32
+ var DEFAULT_TASK_POLL_INTERVAL_MS = 250;
33
+ var DEFAULT_URL_SKIP_MS = 1e3;
34
+ var DEFAULT_MAX_URL_SKIP_MS = 3e4;
35
+
36
+ // src/client/paths.ts
37
+ function indexPath(indexName) {
38
+ return `/indexes/${encodeURIComponent(indexName)}`;
39
+ }
40
+ function documentPath(indexName, docId) {
41
+ return `${indexPath(indexName)}/documents/${encodeURIComponent(docId)}`;
42
+ }
43
+ function backupPath(backupName) {
44
+ return `/backups/${encodeURIComponent(backupName)}`;
45
+ }
46
+ function taskPath(taskId) {
47
+ return `/tasks/${encodeURIComponent(taskId)}`;
48
+ }
49
+
50
+ // src/client/response-shape.ts
51
+ function isRecord(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+ function malformed(path, expected) {
55
+ return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, `The answer from ${path} holds no ${expected}`, {
56
+ route: path
57
+ });
58
+ }
59
+ function readArray(payload, key, path) {
60
+ if (!isRecord(payload) || !Array.isArray(payload[key])) throw malformed(path, `"${key}" array`);
61
+ return payload[key];
62
+ }
63
+ function readNumber(payload, key, path) {
64
+ if (!isRecord(payload) || typeof payload[key] !== "number") throw malformed(path, `"${key}" number`);
65
+ return payload[key];
66
+ }
67
+ function readBoolean(payload, key, path) {
68
+ if (!isRecord(payload) || typeof payload[key] !== "boolean") throw malformed(path, `"${key}" flag`);
69
+ return payload[key];
70
+ }
71
+ function readString(payload, key, path) {
72
+ if (!isRecord(payload) || typeof payload[key] !== "string") throw malformed(path, `"${key}" string`);
73
+ return payload[key];
74
+ }
75
+ function readObject(payload, key, path) {
76
+ if (!isRecord(payload) || !isRecord(payload[key])) throw malformed(path, `"${key}" object`);
77
+ return payload[key];
78
+ }
79
+ function readBody(payload, path) {
80
+ if (!isRecord(payload)) throw malformed(path, "JSON object");
81
+ return payload;
82
+ }
83
+
84
+ // src/client/admin.ts
85
+ function createAdminOperations(transport) {
86
+ async function postJson(path, body, options) {
87
+ const payload = await transport.json({
88
+ method: "POST",
89
+ path,
90
+ body: encodeJson(body),
91
+ contentType: "application/json",
92
+ options
93
+ });
94
+ return readBody(payload, path);
95
+ }
96
+ return {
97
+ async checkpoint(indexName, options) {
98
+ await transport.json({ method: "POST", path: `${indexPath(indexName)}/_checkpoint`, options });
99
+ },
100
+ snapshot(indexName, options) {
101
+ return transport.stream({
102
+ method: "GET",
103
+ path: `${indexPath(indexName)}/snapshot`,
104
+ defaultTimeoutMs: NO_TIMEOUT,
105
+ options
106
+ });
107
+ },
108
+ async restore(indexName, data, options) {
109
+ const path = `${indexPath(indexName)}/restore`;
110
+ const payload = await transport.json({
111
+ method: "POST",
112
+ path,
113
+ body: data,
114
+ contentType: "application/octet-stream",
115
+ defaultTimeoutMs: NO_TIMEOUT,
116
+ options
117
+ });
118
+ return readBody(payload, path);
119
+ },
120
+ exportDocuments(indexName, options) {
121
+ return transport.stream({
122
+ method: "GET",
123
+ path: `${indexPath(indexName)}/export`,
124
+ defaultTimeoutMs: NO_TIMEOUT,
125
+ options
126
+ });
127
+ },
128
+ async importDocumentExport(indexName, data, options) {
129
+ const path = `${indexPath(indexName)}/import`;
130
+ const payload = await transport.json({
131
+ method: "POST",
132
+ path,
133
+ body: data,
134
+ contentType: "application/x-ndjson",
135
+ defaultTimeoutMs: NO_TIMEOUT,
136
+ options
137
+ });
138
+ return readBody(payload, path);
139
+ },
140
+ async vectorMaintenanceStatus(indexName, options) {
141
+ const path = `${indexPath(indexName)}/vector-maintenance`;
142
+ const payload = await transport.json({ method: "GET", path, options });
143
+ return readArray(payload, "fields", path);
144
+ },
145
+ async compactVectors(indexName, fieldName, options) {
146
+ await postJson(
147
+ `${indexPath(indexName)}/vectors/_compact`,
148
+ fieldName === void 0 ? {} : { field: fieldName },
149
+ options
150
+ );
151
+ },
152
+ optimizeVectors(indexName, fieldName, options) {
153
+ return postJson(
154
+ `${indexPath(indexName)}/vectors/_optimize`,
155
+ fieldName === void 0 ? {} : { field: fieldName },
156
+ options
157
+ );
158
+ },
159
+ rebalance(indexName, targetPartitionCount, options) {
160
+ return postJson(`${indexPath(indexName)}/_rebalance`, { targetPartitionCount }, options);
161
+ },
162
+ async updatePartitionConfig(indexName, partitionConfig, options) {
163
+ await postJson(`${indexPath(indexName)}/partition-config`, partitionConfig, options);
164
+ },
165
+ async updateSynonyms(indexName, synonyms, options) {
166
+ await postJson(`${indexPath(indexName)}/synonyms`, { synonyms }, options);
167
+ },
168
+ async updateBM25(indexName, bm25, options) {
169
+ await postJson(`${indexPath(indexName)}/bm25`, bm25, options);
170
+ },
171
+ async getSynonyms(indexName, options) {
172
+ const path = `${indexPath(indexName)}/synonyms`;
173
+ const body = await readBody(
174
+ await transport.json({ method: "GET", path, options }),
175
+ path
176
+ );
177
+ return body.synonyms;
178
+ },
179
+ async rebuildAnalysis(indexName, options) {
180
+ const path = `${indexPath(indexName)}/_rebuild-analysis`;
181
+ return readBody(await transport.json({ method: "POST", path, options }), path);
182
+ },
183
+ async changeAnalysis(indexName, change, options) {
184
+ const path = `${indexPath(indexName)}/_change-analysis`;
185
+ return postJson(path, change, options);
186
+ },
187
+ async getMemoryStats(options) {
188
+ const path = "/stats/memory";
189
+ return readBody(await transport.json({ method: "GET", path, options }), path);
190
+ }
191
+ };
192
+ }
193
+
194
+ // src/client/backups.ts
195
+ function createBackupOperations(transport) {
196
+ async function postTask(path, body, options) {
197
+ const payload = await transport.json({
198
+ method: "POST",
199
+ path,
200
+ body: encodeJson(body),
201
+ contentType: "application/json",
202
+ options
203
+ });
204
+ return readBody(payload, path);
205
+ }
206
+ return {
207
+ createBackup(indexName, backupName, options) {
208
+ return postTask(`${indexPath(indexName)}/backups`, { backup: backupName }, options);
209
+ },
210
+ async listBackups(options) {
211
+ const path = "/backups";
212
+ const payload = await transport.json({ method: "GET", path, defaultTimeoutMs: NO_TIMEOUT, options });
213
+ return readArray(payload, "backups", path);
214
+ },
215
+ restoreBackup(backupName, restore, options) {
216
+ return postTask(`${backupPath(backupName)}/_restore`, restore, options);
217
+ },
218
+ async deleteBackup(backupName, options) {
219
+ const path = backupPath(backupName);
220
+ return readBody(await transport.json({ method: "DELETE", path, options }), path);
221
+ }
222
+ };
223
+ }
224
+
225
+ // src/client/bulk.ts
226
+ function toNdjson(source) {
227
+ if (typeof source === "string") return source;
228
+ if (Array.isArray(source)) return source.map((document) => encodeJson(document)).join("\n");
229
+ return source;
230
+ }
231
+ function toBatchResult(payload, path) {
232
+ const failed = readArray(payload, "failed", path);
233
+ return {
234
+ succeeded: readArray(payload, "succeeded", path),
235
+ failed: failed.map((entry) => {
236
+ const record = readBody(entry, path);
237
+ const docId = typeof record.docId === "string" ? record.docId : "";
238
+ const error = readBody(record.error, path);
239
+ const code = typeof error.code === "string" ? error.code : ServerErrorCodes.INTERNAL_ERROR;
240
+ const message = typeof error.message === "string" ? error.message : "The server refused the document";
241
+ const details = typeof error.details === "object" && error.details !== null ? error.details : void 0;
242
+ return { docId, error: new NarsilError(code, message, details) };
243
+ })
244
+ };
245
+ }
246
+ function createBulkOperations(transport) {
247
+ function batch(indexName, body, options) {
248
+ const path = `${indexPath(indexName)}/documents/_batch`;
249
+ return transport.json({ method: "POST", path, body: encodeJson(body), contentType: "application/json", options }).then((payload) => toBatchResult(payload, path));
250
+ }
251
+ function importBody(indexName, source, asynchronous, options) {
252
+ return {
253
+ method: "POST",
254
+ path: `${indexPath(indexName)}/documents/_import`,
255
+ ...asynchronous ? { query: { async: "true" } } : {},
256
+ body: toNdjson(source),
257
+ contentType: "application/x-ndjson",
258
+ defaultTimeoutMs: NO_TIMEOUT,
259
+ options
260
+ };
261
+ }
262
+ return {
263
+ insertBatch(indexName, documents, insertOptions, options) {
264
+ return batch(
265
+ indexName,
266
+ { action: "insert", documents, ...insertOptions === void 0 ? {} : { options: insertOptions } },
267
+ options
268
+ );
269
+ },
270
+ updateBatch(indexName, updates, writeOptions, options) {
271
+ return batch(
272
+ indexName,
273
+ { action: "update", updates, ...writeOptions === void 0 ? {} : { options: writeOptions } },
274
+ options
275
+ );
276
+ },
277
+ removeBatch(indexName, docIds, writeOptions, options) {
278
+ return batch(
279
+ indexName,
280
+ { action: "delete", docIds, ...writeOptions === void 0 ? {} : { options: writeOptions } },
281
+ options
282
+ );
283
+ },
284
+ async getMultiple(indexName, docIds, options) {
285
+ const path = `${indexPath(indexName)}/documents/_multi-get`;
286
+ const payload = await transport.json({
287
+ method: "POST",
288
+ path,
289
+ body: encodeJson({ docIds }),
290
+ contentType: "application/json",
291
+ repeatable: true,
292
+ options
293
+ });
294
+ const documents = readObject(payload, "documents", path);
295
+ return new Map(Object.entries(documents));
296
+ },
297
+ async listDocuments(indexName, params, options) {
298
+ const path = `${indexPath(indexName)}/documents/_list`;
299
+ const payload = await transport.json({
300
+ method: "POST",
301
+ path,
302
+ body: encodeJson(params ?? {}),
303
+ contentType: "application/json",
304
+ repeatable: true,
305
+ options
306
+ });
307
+ return readBody(payload, path);
308
+ },
309
+ async importDocuments(indexName, source, options) {
310
+ const spec = importBody(indexName, source, false, options);
311
+ return readBody(await transport.json(spec), spec.path);
312
+ },
313
+ async startImport(indexName, source, options) {
314
+ const spec = importBody(indexName, source, true, options);
315
+ return readBody(await transport.json(spec), spec.path);
316
+ }
317
+ };
318
+ }
319
+
320
+ // src/client/documents.ts
321
+ function createDocumentOperations(transport) {
322
+ return {
323
+ async insert(indexName, document, docId, insertOptions, options) {
324
+ const path = `${indexPath(indexName)}/documents`;
325
+ const payload = await transport.json({
326
+ method: "POST",
327
+ path,
328
+ body: encodeJson({
329
+ document,
330
+ ...docId === void 0 ? {} : { id: docId },
331
+ ...insertOptions === void 0 ? {} : { options: insertOptions }
332
+ }),
333
+ contentType: "application/json",
334
+ options
335
+ });
336
+ return readString(payload, "id", path);
337
+ },
338
+ async get(indexName, docId, options) {
339
+ const path = documentPath(indexName, docId);
340
+ const payload = await transport.jsonOrNull({ method: "GET", path, options }, ErrorCodes.DOC_NOT_FOUND);
341
+ if (payload === null) return void 0;
342
+ return readObject(payload, "document", path);
343
+ },
344
+ async has(indexName, docId, options) {
345
+ const path = `${documentPath(indexName, docId)}/_exists`;
346
+ return readBoolean(await transport.json({ method: "GET", path, options }), "exists", path);
347
+ },
348
+ async put(indexName, docId, document, writeOptions, options) {
349
+ const path = documentPath(indexName, docId);
350
+ const payload = await transport.json({
351
+ method: "PUT",
352
+ path,
353
+ body: encodeJson({ document, ...writeOptions === void 0 ? {} : { options: writeOptions } }),
354
+ contentType: "application/json",
355
+ options
356
+ });
357
+ return { id: readString(payload, "id", path), created: readBoolean(payload, "created", path) };
358
+ },
359
+ async update(indexName, docId, document, writeOptions, options) {
360
+ await transport.json({
361
+ method: "PATCH",
362
+ path: documentPath(indexName, docId),
363
+ body: encodeJson({ document, ...writeOptions === void 0 ? {} : { options: writeOptions } }),
364
+ contentType: "application/json",
365
+ options
366
+ });
367
+ },
368
+ async remove(indexName, docId, writeOptions, options) {
369
+ await transport.json({
370
+ method: "DELETE",
371
+ path: documentPath(indexName, docId),
372
+ ...writeOptions?.wait === true ? { query: { wait: "true" } } : {},
373
+ options
374
+ });
375
+ },
376
+ async waitForWrites(indexName, options) {
377
+ await transport.json({ method: "POST", path: `${indexPath(indexName)}/_wait-for-writes`, options });
378
+ },
379
+ async countDocuments(indexName, options) {
380
+ const path = `${indexPath(indexName)}/count`;
381
+ return readNumber(await transport.json({ method: "GET", path, options }), "count", path);
382
+ }
383
+ };
384
+ }
385
+
386
+ // src/client/failover.ts
387
+ var UNSENT_CONNECTION_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ConnectionRefused"]);
388
+ var MAX_CAUSE_DEPTH = 4;
389
+ var SKIP_DOUBLING_CEILING = 30;
390
+ var RETRIED_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
391
+ function readSkip(value, fallback, field) {
392
+ if (value === void 0) return fallback;
393
+ if (!Number.isSafeInteger(value) || value < 0) {
394
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, `"${field}" must be a whole number of milliseconds, 0 or more`, {
395
+ [field]: value
396
+ });
397
+ }
398
+ return value;
399
+ }
400
+ function createUrlPool(bases, options) {
401
+ const skipMs = readSkip(options.urlSkipMs, DEFAULT_URL_SKIP_MS, "urlSkipMs");
402
+ const maxSkipMs = readSkip(options.maxUrlSkipMs, Math.max(DEFAULT_MAX_URL_SKIP_MS, skipMs), "maxUrlSkipMs");
403
+ if (maxSkipMs < skipMs) {
404
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, '"maxUrlSkipMs" must be at least "urlSkipMs"', {
405
+ urlSkipMs: skipMs,
406
+ maxUrlSkipMs: maxSkipMs
407
+ });
408
+ }
409
+ const entries = bases.map((base, position) => ({ base, position, refusals: 0, skipUntil: 0 }));
410
+ let nextStart = 0;
411
+ return {
412
+ order(now) {
413
+ const rotation = [...entries.slice(nextStart), ...entries.slice(0, nextStart)];
414
+ const open = rotation.filter((entry) => entry.skipUntil <= now);
415
+ const skipped = rotation.filter((entry) => entry.skipUntil > now).sort((a, b) => a.skipUntil - b.skipUntil);
416
+ return [...open, ...skipped];
417
+ },
418
+ took(entry) {
419
+ nextStart = (entry.position + 1) % entries.length;
420
+ },
421
+ answered(entry) {
422
+ entry.refusals = 0;
423
+ entry.skipUntil = 0;
424
+ },
425
+ refused(entry, now) {
426
+ entry.refusals += 1;
427
+ const doublings = Math.min(entry.refusals - 1, SKIP_DOUBLING_CEILING);
428
+ entry.skipUntil = now + Math.min(skipMs * 2 ** doublings, maxSkipMs);
429
+ }
430
+ };
431
+ }
432
+ function failedBeforeSending(error, depth = 0) {
433
+ if (depth > MAX_CAUSE_DEPTH || typeof error !== "object" || error === null) return false;
434
+ const { code, cause, errors } = error;
435
+ if (typeof code === "string" && UNSENT_CONNECTION_CODES.has(code)) return true;
436
+ if (failedBeforeSending(cause, depth + 1)) return true;
437
+ return Array.isArray(errors) && errors.length > 0 && errors.every((entry) => failedBeforeSending(entry, depth + 1));
438
+ }
439
+ function answersUnavailable(status) {
440
+ return RETRIED_STATUSES.has(status);
441
+ }
442
+ function movesOnAfterAnswer(status, code, repeatable) {
443
+ if (!answersUnavailable(status)) return false;
444
+ return repeatable || code === ErrorCodes.NODE_NOT_READY;
445
+ }
446
+ function earnsExtraTry(failure) {
447
+ return failure.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED;
448
+ }
449
+ function movesOnAfterFailure(failure, sentNothing, repeatable) {
450
+ if (failure.code === ClientErrorCodes.CLIENT_REQUEST_TIMEOUT) return repeatable;
451
+ if (failure.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED) return repeatable || sentNothing;
452
+ return false;
453
+ }
454
+
455
+ // src/client/http.ts
456
+ function isRecord2(value) {
457
+ return typeof value === "object" && value !== null && !Array.isArray(value);
458
+ }
459
+ function unrefTimer(timer) {
460
+ const unrefable = timer;
461
+ unrefable.unref?.();
462
+ }
463
+ function startDeadline(timeoutMs, caller) {
464
+ const controller = new AbortController();
465
+ let expired = false;
466
+ const abortWithCaller = () => controller.abort();
467
+ if (caller?.aborted) controller.abort();
468
+ else caller?.addEventListener("abort", abortWithCaller);
469
+ let timer;
470
+ if (timeoutMs > 0 && !controller.signal.aborted) {
471
+ timer = setTimeout(() => {
472
+ expired = true;
473
+ controller.abort();
474
+ }, timeoutMs);
475
+ unrefTimer(timer);
476
+ }
477
+ return {
478
+ signal: controller.signal,
479
+ expired: () => expired,
480
+ release: () => {
481
+ if (timer !== void 0) clearTimeout(timer);
482
+ caller?.removeEventListener("abort", abortWithCaller);
483
+ }
484
+ };
485
+ }
486
+ var ResponseTooLargeError = class extends Error {
487
+ constructor(limitBytes) {
488
+ super(`The answer passed the ${limitBytes} byte ceiling this client reads`);
489
+ this.limitBytes = limitBytes;
490
+ }
491
+ };
492
+ async function readStreamCapped(stream, limitBytes) {
493
+ const reader = stream.getReader();
494
+ const chunks = [];
495
+ let total = 0;
496
+ try {
497
+ for (; ; ) {
498
+ const { done, value } = await reader.read();
499
+ if (done) break;
500
+ total += value.byteLength;
501
+ if (total > limitBytes) throw new ResponseTooLargeError(limitBytes);
502
+ chunks.push(value);
503
+ }
504
+ } finally {
505
+ reader.releaseLock();
506
+ if (total > limitBytes) await stream.cancel().catch(() => void 0);
507
+ }
508
+ const body = new Uint8Array(total);
509
+ let offset = 0;
510
+ for (const chunk of chunks) {
511
+ body.set(chunk, offset);
512
+ offset += chunk.byteLength;
513
+ }
514
+ return body;
515
+ }
516
+ async function readAnswer(response, limitBytes) {
517
+ const stream = response.body;
518
+ if (limitBytes > 0 && stream !== null && stream !== void 0) {
519
+ return new TextDecoder().decode(await readStreamCapped(stream, limitBytes));
520
+ }
521
+ const text = await response.text();
522
+ if (limitBytes > 0 && text.length > limitBytes) throw new ResponseTooLargeError(limitBytes);
523
+ return text;
524
+ }
525
+ function invalidResponse(message, details) {
526
+ return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, message, details);
527
+ }
528
+ function errorFromBody(status, payload, url) {
529
+ const envelope = isRecord2(payload) && isRecord2(payload.error) ? payload.error : void 0;
530
+ if (envelope === void 0 || typeof envelope.code !== "string" || typeof envelope.message !== "string") {
531
+ return invalidResponse(`The server answered HTTP ${status} without a Narsil error envelope`, { url, status });
532
+ }
533
+ const details = isRecord2(envelope.details) ? envelope.details : {};
534
+ return new NarsilError(envelope.code, envelope.message, { ...details, status });
535
+ }
536
+ function isHttpUrl(value) {
537
+ try {
538
+ const parsed = new URL(value);
539
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
540
+ } catch {
541
+ return false;
542
+ }
543
+ }
544
+ function normaliseBase(url) {
545
+ const trimmed = url.trim();
546
+ if (trimmed.length === 0) {
547
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'The client needs a server address, and "url" is empty');
548
+ }
549
+ if (!trimmed.startsWith("/") && !isHttpUrl(trimmed)) {
550
+ throw new NarsilError(
551
+ ErrorCodes.CONFIG_INVALID,
552
+ `The client cannot read "${trimmed}" as a server address; pass an http or https URL, or a path starting with "/" that a browser resolves against the page`,
553
+ { url: trimmed }
554
+ );
555
+ }
556
+ return trimmed.replace(/\/+$/, "");
557
+ }
558
+ function normaliseBases(url) {
559
+ if (typeof url === "string") return [normaliseBase(url)];
560
+ if (!Array.isArray(url) || url.length === 0) {
561
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'The client needs a server address, and "url" lists none');
562
+ }
563
+ return url.map((entry) => {
564
+ if (typeof entry !== "string") {
565
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'Every server address in "url" must be a string');
566
+ }
567
+ return normaliseBase(entry);
568
+ });
569
+ }
570
+ function translateFailure(err, url, timeoutMs, expired, caller) {
571
+ if (err instanceof ResponseTooLargeError) {
572
+ return invalidResponse(`The server at ${url} answered more than this client reads: ${err.message}`, {
573
+ url,
574
+ maxResponseBytes: err.limitBytes
575
+ });
576
+ }
577
+ if (expired) {
578
+ return new NarsilError(
579
+ ClientErrorCodes.CLIENT_REQUEST_TIMEOUT,
580
+ `The server at ${url} did not answer within ${timeoutMs} ms`,
581
+ { url, timeoutMs }
582
+ );
583
+ }
584
+ if (caller?.aborted === true) {
585
+ return new NarsilError(ClientErrorCodes.CLIENT_REQUEST_ABORTED, `The caller cancelled the request to ${url}`, {
586
+ url
587
+ });
588
+ }
589
+ return new NarsilError(
590
+ ClientErrorCodes.CLIENT_CONNECTION_FAILED,
591
+ `The client could not reach ${url}: ${describeError(err)}`,
592
+ { url }
593
+ );
594
+ }
595
+ function envelopeCodeOf(text) {
596
+ try {
597
+ const payload = JSON.parse(text);
598
+ return isRecord2(payload) && isRecord2(payload.error) && typeof payload.error.code === "string" ? payload.error.code : void 0;
599
+ } catch {
600
+ return void 0;
601
+ }
602
+ }
603
+ function withQuery(path, query) {
604
+ if (query === void 0) return path;
605
+ const params = new URLSearchParams();
606
+ for (const [key, value] of Object.entries(query)) {
607
+ if (value !== void 0) params.set(key, value);
608
+ }
609
+ const encoded = params.toString();
610
+ return encoded.length === 0 ? path : `${path}?${encoded}`;
611
+ }
612
+ function createTransport(options) {
613
+ const pool = createUrlPool(normaliseBases(options.url), options);
614
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
615
+ const baseHeaders = { ...options.headers };
616
+ if (options.apiKey !== void 0 && options.apiKey.length > 0) {
617
+ baseHeaders.authorization = `Bearer ${options.apiKey}`;
618
+ }
619
+ function resolveTimeout(spec) {
620
+ const perCall = spec.options?.timeoutMs;
621
+ if (perCall !== void 0) return perCall;
622
+ if (options.timeoutMs !== void 0) return options.timeoutMs;
623
+ return spec.defaultTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
624
+ }
625
+ function resolveResponseCeiling(spec) {
626
+ const perCall = spec.options?.maxResponseBytes;
627
+ if (perCall !== void 0) return perCall;
628
+ return options.maxResponseBytes ?? 0;
629
+ }
630
+ function recordAttempt(entry, attempt, repeatable) {
631
+ if (attempt.kind === "answer") {
632
+ if (!answersUnavailable(attempt.status)) {
633
+ pool.answered(entry);
634
+ return false;
635
+ }
636
+ return movesOnAfterAnswer(attempt.status, envelopeCodeOf(attempt.text), repeatable);
637
+ }
638
+ if (attempt.error.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED) pool.refused(entry, Date.now());
639
+ return movesOnAfterFailure(attempt.error, attempt.sentNothing, repeatable);
640
+ }
641
+ function outcomeOf(attempt) {
642
+ if (attempt === null) throw new NarsilError(ErrorCodes.CONFIG_INVALID, "The client holds no server address");
643
+ if (attempt.kind === "failure") throw attempt.error;
644
+ return attempt;
645
+ }
646
+ async function exchange(spec, keepsStream = false) {
647
+ const repeatable = spec.repeatable === true || spec.method === "GET";
648
+ const replayable = !(spec.body instanceof ReadableStream);
649
+ const tryOn = async (entry2) => {
650
+ pool.took(entry2);
651
+ return exchangeOnce(entry2.base, spec, keepsStream);
652
+ };
653
+ let triesOnceMore = repeatable && replayable;
654
+ let last = null;
655
+ for (const entry2 of pool.order(Date.now())) {
656
+ last = await tryOn(entry2);
657
+ const moves = recordAttempt(entry2, last, repeatable);
658
+ if (!replayable || !moves) return outcomeOf(last);
659
+ if (last.kind === "failure" && !earnsExtraTry(last.error)) triesOnceMore = false;
660
+ }
661
+ const [entry] = pool.order(Date.now());
662
+ if (triesOnceMore && entry !== void 0) {
663
+ last = await tryOn(entry);
664
+ recordAttempt(entry, last, repeatable);
665
+ }
666
+ return outcomeOf(last);
667
+ }
668
+ async function exchangeOnce(base, spec, keepsStream) {
669
+ const url = `${base}${withQuery(spec.path, spec.query)}`;
670
+ const headers = { ...baseHeaders, ...spec.headers, ...spec.options?.headers };
671
+ if (spec.contentType !== void 0) headers["content-type"] = spec.contentType;
672
+ const timeoutMs = resolveTimeout(spec);
673
+ const deadline = startDeadline(timeoutMs, spec.options?.signal);
674
+ let handedOver = false;
675
+ try {
676
+ const init = { method: spec.method, headers, signal: deadline.signal };
677
+ if (spec.body !== void 0) init.body = spec.body;
678
+ if (spec.body instanceof ReadableStream) init.duplex = "half";
679
+ const response = await send(url, init);
680
+ if (keepsStream && response.ok && response.body !== null) {
681
+ handedOver = true;
682
+ const stream = response.body.pipeThrough(
683
+ new TransformStream({ flush: () => deadline.release() })
684
+ );
685
+ return { kind: "answer", status: response.status, url, text: "", stream, headers: response.headers };
686
+ }
687
+ const text = await readAnswer(response, resolveResponseCeiling(spec));
688
+ return { kind: "answer", status: response.status, url, stream: null, text, headers: response.headers };
689
+ } catch (err) {
690
+ const error = translateFailure(err, url, timeoutMs, deadline.expired(), spec.options?.signal);
691
+ const sentNothing = error.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED && failedBeforeSending(err);
692
+ return { kind: "failure", error, sentNothing };
693
+ } finally {
694
+ if (!handedOver) deadline.release();
695
+ }
696
+ }
697
+ function parse(status, text, path) {
698
+ if (text.length === 0) return void 0;
699
+ try {
700
+ return JSON.parse(text);
701
+ } catch {
702
+ throw invalidResponse(`The server answered HTTP ${status} with a body that is not JSON`, { url: path, status });
703
+ }
704
+ }
705
+ async function json(spec) {
706
+ const { status, text, url } = await exchange(spec);
707
+ const payload = parse(status, text, url);
708
+ if (status >= 200 && status < 300) return payload;
709
+ throw errorFromBody(status, payload, url);
710
+ }
711
+ return {
712
+ json,
713
+ async jsonOrNull(spec, absentCode) {
714
+ try {
715
+ return await json(spec);
716
+ } catch (err) {
717
+ if (err instanceof NarsilError && err.code === absentCode) return null;
718
+ throw err;
719
+ }
720
+ },
721
+ async stream(spec) {
722
+ const { status, text, stream, url } = await exchange(spec, true);
723
+ if (stream !== null) return stream;
724
+ throw errorFromBody(status, parse(status, text, url), url);
725
+ },
726
+ async download(spec) {
727
+ const { status, text, stream, headers, url } = await exchange(spec, true);
728
+ if (stream !== null && headers !== null) return { status, headers, stream };
729
+ throw errorFromBody(status, parse(status, text, url), url);
730
+ },
731
+ async probe(spec) {
732
+ const { status } = await exchange(spec);
733
+ return status;
734
+ }
735
+ };
736
+ }
737
+
738
+ // src/client/indexes.ts
739
+ function createIndexOperations(transport) {
740
+ return {
741
+ async createIndex(name, config, options) {
742
+ await transport.json({
743
+ method: "POST",
744
+ path: "/indexes",
745
+ body: encodeJson({ name, config }),
746
+ contentType: "application/json",
747
+ options
748
+ });
749
+ },
750
+ async listIndexes(options) {
751
+ const path = "/indexes";
752
+ return readArray(await transport.json({ method: "GET", path, options }), "indexes", path);
753
+ },
754
+ async dropIndex(name, options) {
755
+ await transport.json({ method: "DELETE", path: indexPath(name), options });
756
+ },
757
+ async getStats(indexName, options) {
758
+ const path = `${indexPath(indexName)}/stats`;
759
+ return readBody(await transport.json({ method: "GET", path, options }), path);
760
+ },
761
+ async getPartitionStats(indexName, options) {
762
+ const path = `${indexPath(indexName)}/partitions`;
763
+ const payload = await transport.json({ method: "GET", path, options });
764
+ return readArray(payload, "partitions", path);
765
+ },
766
+ async clear(indexName, options) {
767
+ await transport.json({ method: "POST", path: `${indexPath(indexName)}/_clear`, options });
768
+ },
769
+ async open(indexName, options) {
770
+ await transport.json({ method: "POST", path: `${indexPath(indexName)}/_open`, options });
771
+ },
772
+ async close(indexName, options) {
773
+ await transport.json({ method: "POST", path: `${indexPath(indexName)}/_close`, options });
774
+ }
775
+ };
776
+ }
777
+
778
+ // src/client/search.ts
779
+ function createSearchOperations(transport) {
780
+ async function post(path, params, options) {
781
+ const payload = await transport.json({
782
+ method: "POST",
783
+ path,
784
+ body: encodeJson(params),
785
+ contentType: "application/json",
786
+ repeatable: true,
787
+ options
788
+ });
789
+ return readBody(payload, path);
790
+ }
791
+ return {
792
+ query(indexName, params, options) {
793
+ return post(`${indexPath(indexName)}/search`, params, options);
794
+ },
795
+ preflight(indexName, params, options) {
796
+ return post(`${indexPath(indexName)}/search/preflight`, params, options);
797
+ },
798
+ suggest(indexName, params, options) {
799
+ return post(`${indexPath(indexName)}/suggest`, params, options);
800
+ }
801
+ };
802
+ }
803
+
804
+ // src/client/server-info.ts
805
+ function createServerOperations(transport) {
806
+ let announced = null;
807
+ async function readCapabilities(options) {
808
+ const path = "/capabilities";
809
+ const payload = await transport.jsonOrNull({ method: "GET", path, options }, ServerErrorCodes.NOT_FOUND);
810
+ if (payload === null) return /* @__PURE__ */ new Set();
811
+ return new Set(readArray(payload, "capabilities", path));
812
+ }
813
+ function load(options) {
814
+ if (announced === null) {
815
+ announced = readCapabilities(options).catch((err) => {
816
+ announced = null;
817
+ throw err;
818
+ });
819
+ }
820
+ return announced;
821
+ }
822
+ return {
823
+ async version(options) {
824
+ const path = "/version";
825
+ return readBody(await transport.json({ method: "GET", path, options }), path);
826
+ },
827
+ async capabilities(options) {
828
+ return [...await load(options)];
829
+ },
830
+ async supports(capability, options) {
831
+ return (await load(options)).has(capability);
832
+ },
833
+ async isAlive(options) {
834
+ return await transport.probe({ method: "GET", path: "/livez", options }) === 200;
835
+ },
836
+ async isReady(options) {
837
+ return await transport.probe({ method: "GET", path: "/readyz", options }) === 200;
838
+ }
839
+ };
840
+ }
841
+
842
+ // src/client/sync.ts
843
+ var ENTITY_TAG = /^"([0-9a-f]{64})"$/;
844
+ var CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
845
+ function invalidDownload(message, path) {
846
+ return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, message, { url: path });
847
+ }
848
+ function createSyncSettingOperations(transport) {
849
+ return {
850
+ async updateSync(indexName, setting, options) {
851
+ const path = `${indexPath(indexName)}/sync`;
852
+ await transport.json({ method: "PUT", path, body: encodeJson(setting), contentType: "application/json", options });
853
+ },
854
+ async syncSnapshot(indexName, resume, options) {
855
+ const path = `${indexPath(indexName)}/sync/snapshot`;
856
+ const headers = resume === void 0 || resume.offset <= 0 ? {} : { range: `bytes=${resume.offset}-`, "if-range": `"${resume.entityTag}"` };
857
+ const answer = await transport.download({ method: "GET", path, headers, defaultTimeoutMs: NO_TIMEOUT, options });
858
+ const entityTag = ENTITY_TAG.exec(answer.headers.get("etag") ?? "")?.[1];
859
+ if (entityTag === void 0) {
860
+ await answer.stream.cancel();
861
+ throw invalidDownload("The server sent the snapshot without an entity tag", path);
862
+ }
863
+ if (answer.status === 206) {
864
+ const range = CONTENT_RANGE.exec(answer.headers.get("content-range") ?? "");
865
+ if (range === null || Number(range[1]) !== resume?.offset) {
866
+ await answer.stream.cancel();
867
+ throw invalidDownload("The server sent a byte range other than the one that the client asked for", path);
868
+ }
869
+ return { entityTag, offset: Number(range[1]), totalBytes: Number(range[3]), stream: answer.stream };
870
+ }
871
+ const length = Number(answer.headers.get("content-length") ?? Number.NaN);
872
+ if (!Number.isSafeInteger(length)) {
873
+ await answer.stream.cancel();
874
+ throw invalidDownload("The server sent the snapshot without its length", path);
875
+ }
876
+ return { entityTag, offset: 0, totalBytes: length, stream: answer.stream };
877
+ }
878
+ };
879
+ }
880
+
881
+ // src/client/tasks.ts
882
+ function isTerminal(record) {
883
+ return record.status === "succeeded" || record.status === "failed" || record.status === "cancelled";
884
+ }
885
+ function progressKey(record) {
886
+ const progress = record.progress;
887
+ if (progress === void 0) return record.status;
888
+ return `${record.status}:${progress.bytesProcessed}:${progress.indexed}:${progress.failed}`;
889
+ }
890
+ function sleep(milliseconds, signal) {
891
+ return new Promise((resolve) => {
892
+ const timer = setTimeout(() => {
893
+ signal?.removeEventListener("abort", stop);
894
+ resolve();
895
+ }, milliseconds);
896
+ function stop() {
897
+ clearTimeout(timer);
898
+ resolve();
899
+ }
900
+ signal?.addEventListener("abort", stop, { once: true });
901
+ });
902
+ }
903
+ function listQuery(query) {
904
+ return {
905
+ indexName: query?.indexName,
906
+ type: query?.type === void 0 || query.type.length === 0 ? void 0 : query.type.join(","),
907
+ status: query?.status === void 0 || query.status.length === 0 ? void 0 : query.status.join(","),
908
+ from: query?.from === void 0 ? void 0 : String(query.from),
909
+ limit: query?.limit === void 0 ? void 0 : String(query.limit)
910
+ };
911
+ }
912
+ function createTaskOperations(transport) {
913
+ const operations = {
914
+ async getTask(taskId, options) {
915
+ const path = taskPath(taskId);
916
+ const payload = await transport.jsonOrNull({ method: "GET", path, options }, ServerErrorCodes.TASK_NOT_FOUND);
917
+ return payload === null ? null : readBody(payload, path);
918
+ },
919
+ async listTasks(query, options) {
920
+ const path = "/tasks";
921
+ const payload = await transport.json({ method: "GET", path, query: listQuery(query), options });
922
+ return readBody(payload, path);
923
+ },
924
+ async cancelTask(taskId, options) {
925
+ const path = `${taskPath(taskId)}/_cancel`;
926
+ return readBody(await transport.json({ method: "POST", path, options }), path);
927
+ },
928
+ async waitForTask(taskId, options) {
929
+ const interval = options?.pollIntervalMs ?? DEFAULT_TASK_POLL_INTERVAL_MS;
930
+ const waitTimeoutMs = options?.waitTimeoutMs ?? 0;
931
+ const startedAt = Date.now();
932
+ let reported = null;
933
+ for (; ; ) {
934
+ if (options?.signal?.aborted === true) {
935
+ throw new NarsilError(
936
+ ClientErrorCodes.CLIENT_REQUEST_ABORTED,
937
+ `The caller stopped waiting for task "${taskId}"`,
938
+ { taskId }
939
+ );
940
+ }
941
+ const record = await operations.getTask(taskId, options);
942
+ if (record === null) {
943
+ throw new NarsilError(
944
+ ServerErrorCodes.TASK_NOT_FOUND,
945
+ `The server no longer holds task "${taskId}", so its outcome is unknown`,
946
+ { taskId }
947
+ );
948
+ }
949
+ const key = progressKey(record);
950
+ if (key !== reported) {
951
+ reported = key;
952
+ options?.onProgress?.(record);
953
+ }
954
+ if (isTerminal(record)) return record;
955
+ if (waitTimeoutMs > 0 && Date.now() - startedAt >= waitTimeoutMs) {
956
+ throw new NarsilError(
957
+ ClientErrorCodes.CLIENT_TASK_TIMEOUT,
958
+ `Task "${taskId}" was still ${record.status} after ${waitTimeoutMs} ms, and it keeps running`,
959
+ { taskId, waitTimeoutMs, status: record.status }
960
+ );
961
+ }
962
+ await sleep(interval, options?.signal);
963
+ }
964
+ }
965
+ };
966
+ return operations;
967
+ }
968
+
969
+ // src/client/client.ts
970
+ function createNarsilClient(options) {
971
+ const transport = createTransport(options);
972
+ return {
973
+ ...createIndexOperations(transport),
974
+ ...createDocumentOperations(transport),
975
+ ...createBulkOperations(transport),
976
+ ...createSearchOperations(transport),
977
+ ...createTaskOperations(transport),
978
+ ...createAdminOperations(transport),
979
+ ...createBackupOperations(transport),
980
+ ...createServerOperations(transport),
981
+ ...createSyncSettingOperations(transport)
982
+ };
983
+ }
984
+
985
+ // src/sync/protocol.ts
986
+ var SYNC_SUBPROTOCOL = "narsil.sync.v1";
987
+ var SYNC_CLOSE_CREDENTIAL_EXPIRED = 4401;
988
+ var SYNC_CLOSE_RESYNC = 4410;
989
+
990
+ // src/sync/device/constants.ts
991
+ var RECONNECT_MIN_DELAY_MS = 500;
992
+ var RETRY_MAX_DELAY_MS = 3e4;
993
+ var BACKOFF_DOUBLINGS_LIMIT = 30;
994
+ var DEFAULT_REPLAY_LIMIT_OF_SNAPSHOT = 1;
995
+ var KEPT_ENTRY_FLUSH_BYTES = 4 * 1024 * 1024;
996
+ var KEPT_ENTRY_FLUSH_IDLE_MS = 1e3;
997
+ var UPLOAD_RETRY_DELAY_MS = 1e3;
998
+ var SNAPSHOT_RETRY_DELAY_MS = 5e3;
999
+ var SNAPSHOT_MEMORY_PER_ARCHIVE_BYTE = 3;
1000
+ var DOWNLOAD_SAVE_BYTES = 1024 * 1024;
1001
+ var UPLOAD_BATCH_WRITES = 100;
1002
+ var KEPT_ENTRY_OVERHEAD_BYTES = 32;
1003
+
1004
+ // src/sync/device/context.ts
1005
+ function createChanges() {
1006
+ let waiters = [];
1007
+ return {
1008
+ notify() {
1009
+ const woken = waiters;
1010
+ waiters = [];
1011
+ for (const wake of woken) wake();
1012
+ },
1013
+ next() {
1014
+ return new Promise((resolve) => waiters.push(resolve));
1015
+ }
1016
+ };
1017
+ }
1018
+ function backoffDelayMs(attempt, minimumMs, maximumMs) {
1019
+ const ceiling = Math.min(maximumMs, minimumMs * 2 ** Math.min(attempt, BACKOFF_DOUBLINGS_LIMIT));
1020
+ return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
1021
+ }
1022
+ var RESYNC_REASONS = /* @__PURE__ */ new Set(["epoch", "history", "ahead"]);
1023
+ function isRecord3(value) {
1024
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Uint8Array);
1025
+ }
1026
+ function isCount(value) {
1027
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1028
+ }
1029
+ function malformed2(detail) {
1030
+ return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, `The sync feed sent a malformed message: ${detail}`);
1031
+ }
1032
+ function headsOf(raw) {
1033
+ if (!Array.isArray(raw)) throw malformed2("heads must be a list");
1034
+ const seqNos = new Array(raw.length).fill(-1);
1035
+ for (const item of raw) {
1036
+ if (!isRecord3(item) || !isCount(item.partitionId) || !isCount(item.seqNo)) throw malformed2("a head is invalid");
1037
+ if (item.partitionId >= seqNos.length || seqNos[item.partitionId] !== -1) {
1038
+ throw malformed2("heads must name each partition once");
1039
+ }
1040
+ seqNos[item.partitionId] = item.seqNo;
1041
+ }
1042
+ return seqNos;
1043
+ }
1044
+ function stringList(value) {
1045
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
1046
+ }
1047
+ function settingsOf(raw) {
1048
+ if (!isRecord3(raw) || typeof raw.language !== "string") throw malformed2("settings need a language");
1049
+ const optionalString2 = (key) => {
1050
+ const value = raw[key];
1051
+ if (value === void 0 || value === null) return void 0;
1052
+ if (typeof value !== "string") throw malformed2(`settings.${key} must be a string`);
1053
+ return value;
1054
+ };
1055
+ const tokenizer = optionalString2("tokenizer");
1056
+ const stopWords = optionalString2("stopWords");
1057
+ const analysisRevision = optionalString2("analysisRevision");
1058
+ if (raw.stopWordList !== void 0 && raw.stopWordList !== null && !stringList(raw.stopWordList)) {
1059
+ throw malformed2("settings.stopWordList must be a list of strings");
1060
+ }
1061
+ if (raw.bm25 !== void 0 && raw.bm25 !== null && !isRecord3(raw.bm25)) throw malformed2("settings.bm25 is invalid");
1062
+ if (raw.synonyms !== void 0 && raw.synonyms !== null && !Array.isArray(raw.synonyms)) {
1063
+ throw malformed2("settings.synonyms must be a list");
1064
+ }
1065
+ return {
1066
+ language: raw.language,
1067
+ ...tokenizer !== void 0 ? { tokenizer } : {},
1068
+ ...stopWords !== void 0 ? { stopWords } : {},
1069
+ ...stringList(raw.stopWordList) ? { stopWordList: raw.stopWordList } : {},
1070
+ ...analysisRevision !== void 0 ? { analysisRevision } : {},
1071
+ ...isRecord3(raw.bm25) ? { bm25: raw.bm25 } : {},
1072
+ ...Array.isArray(raw.synonyms) ? { synonyms: raw.synonyms } : {}
1073
+ };
1074
+ }
1075
+ function entriesOf(partitionId, raw) {
1076
+ if (!Array.isArray(raw)) throw malformed2("entries must be a list");
1077
+ let previous = -1;
1078
+ return raw.map((item) => {
1079
+ if (!isRecord3(item) || !isCount(item.seqNo) || typeof item.documentId !== "string") {
1080
+ throw malformed2("an entry is invalid");
1081
+ }
1082
+ if (item.seqNo <= previous) throw malformed2("entries must rise in sequence order");
1083
+ if (item.partitionId !== void 0 && item.partitionId !== partitionId) {
1084
+ throw malformed2("an entry belongs to another partition");
1085
+ }
1086
+ previous = item.seqNo;
1087
+ if (item.operation === "DELETE") {
1088
+ return { partitionId, seqNo: item.seqNo, documentId: item.documentId, document: null };
1089
+ }
1090
+ if (item.operation !== "INDEX" || !(item.document instanceof Uint8Array)) throw malformed2("an entry is invalid");
1091
+ return { partitionId, seqNo: item.seqNo, documentId: item.documentId, document: item.document };
1092
+ });
1093
+ }
1094
+ function decodeFeedMessage(bytes) {
1095
+ let raw;
1096
+ try {
1097
+ raw = decode(bytes);
1098
+ } catch {
1099
+ throw malformed2("a frame is not MessagePack");
1100
+ }
1101
+ if (!isRecord3(raw)) throw malformed2("a frame is not a map");
1102
+ switch (raw.type) {
1103
+ case "subscribed": {
1104
+ if (!isSyncEpoch(raw.epoch) || !isCount(raw.partitionCount)) throw malformed2("subscribed is invalid");
1105
+ if (!isCount(raw.bytesBehind) || !isCount(raw.snapshotBytes) || !isCount(raw.windowBytes)) {
1106
+ throw malformed2("subscribed is invalid");
1107
+ }
1108
+ const heads = headsOf(raw.heads);
1109
+ if (heads.length !== raw.partitionCount) throw malformed2("subscribed needs one head for each partition");
1110
+ return {
1111
+ type: "subscribed",
1112
+ epoch: raw.epoch,
1113
+ partitionCount: raw.partitionCount,
1114
+ heads,
1115
+ bytesBehind: raw.bytesBehind,
1116
+ snapshotBytes: raw.snapshotBytes,
1117
+ windowBytes: raw.windowBytes,
1118
+ settings: settingsOf(raw.settings)
1119
+ };
1120
+ }
1121
+ case "entries":
1122
+ if (!isCount(raw.partitionId)) throw malformed2("entries need a partition");
1123
+ return { type: "entries", partitionId: raw.partitionId, entries: entriesOf(raw.partitionId, raw.entries) };
1124
+ case "settings":
1125
+ return { type: "settings", settings: settingsOf(raw.settings) };
1126
+ case "checkpoint":
1127
+ if (!isCount(raw.id)) throw malformed2("checkpoint needs an id");
1128
+ return { type: "checkpoint", id: raw.id, heads: headsOf(raw.heads) };
1129
+ case "resync":
1130
+ if (typeof raw.reason !== "string" || !RESYNC_REASONS.has(raw.reason)) throw malformed2("resync is invalid");
1131
+ return { type: "resync", reason: raw.reason };
1132
+ default:
1133
+ throw malformed2(`unknown type ${String(raw.type)}`);
1134
+ }
1135
+ }
1136
+ function positionsOf(seqNos) {
1137
+ return seqNos.map((seqNo, partitionId) => ({ partitionId, seqNo }));
1138
+ }
1139
+
1140
+ // src/sync/device/feed.ts
1141
+ var CLOSE_NORMAL = 1e3;
1142
+ function feedUrlOf(base, indexName) {
1143
+ const location = globalThis.location?.href;
1144
+ let parsed;
1145
+ try {
1146
+ parsed = location === void 0 ? new URL(base) : new URL(base, location);
1147
+ } catch {
1148
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, `The device cannot read "${base}" as a server address`, {
1149
+ url: base
1150
+ });
1151
+ }
1152
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1153
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, "The device needs an http or https server address", { url: base });
1154
+ }
1155
+ parsed.protocol = parsed.protocol === "https:" ? "wss:" : "ws:";
1156
+ parsed.pathname = `${parsed.pathname.replace(/\/+$/, "")}/indexes/${encodeURIComponent(indexName)}/sync/feed`;
1157
+ parsed.search = "";
1158
+ parsed.hash = "";
1159
+ return parsed.toString();
1160
+ }
1161
+ function feedFailed(message) {
1162
+ return new NarsilError(ClientErrorCodes.CLIENT_CONNECTION_FAILED, message);
1163
+ }
1164
+ function openFeedConnection(url, credential, handlers) {
1165
+ if (typeof WebSocket === "undefined") {
1166
+ throw new NarsilError(ErrorCodes.CONFIG_INVALID, "Device sync needs a runtime with a global WebSocket");
1167
+ }
1168
+ const socket = new WebSocket(url, credential === null ? [SYNC_SUBPROTOCOL] : [SYNC_SUBPROTOCOL, credential]);
1169
+ socket.binaryType = "arraybuffer";
1170
+ let closed = false;
1171
+ function finish(code) {
1172
+ if (closed) return;
1173
+ closed = true;
1174
+ handlers.onClose(code);
1175
+ }
1176
+ function closeSocket(reason) {
1177
+ if (socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN) {
1178
+ socket.close(CLOSE_NORMAL, reason);
1179
+ }
1180
+ }
1181
+ socket.onopen = () => {
1182
+ if (socket.protocol !== SYNC_SUBPROTOCOL) {
1183
+ handlers.onFailure(
1184
+ new NarsilError(
1185
+ ClientErrorCodes.CLIENT_INVALID_RESPONSE,
1186
+ `The server answered the feed with the subprotocol "${socket.protocol}"`
1187
+ )
1188
+ );
1189
+ closeSocket("subprotocol");
1190
+ finish(CLOSE_NORMAL);
1191
+ return;
1192
+ }
1193
+ handlers.onOpen();
1194
+ };
1195
+ socket.onmessage = (event) => {
1196
+ if (closed) return;
1197
+ if (!(event.data instanceof ArrayBuffer)) {
1198
+ handlers.onFailure(new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, "The feed sent a text frame"));
1199
+ closeSocket("text frame");
1200
+ finish(CLOSE_NORMAL);
1201
+ return;
1202
+ }
1203
+ let message;
1204
+ try {
1205
+ message = decodeFeedMessage(new Uint8Array(event.data));
1206
+ } catch (error) {
1207
+ handlers.onFailure(error);
1208
+ closeSocket("malformed message");
1209
+ finish(CLOSE_NORMAL);
1210
+ return;
1211
+ }
1212
+ handlers.onMessage(message);
1213
+ };
1214
+ socket.onerror = () => {
1215
+ if (!closed) handlers.onFailure(feedFailed(`The feed at ${url} failed`));
1216
+ };
1217
+ socket.onclose = (event) => finish(event.code);
1218
+ return {
1219
+ send(message) {
1220
+ if (!closed && socket.readyState === WebSocket.OPEN) socket.send(encode(message));
1221
+ },
1222
+ close(reason) {
1223
+ closeSocket(reason);
1224
+ finish(CLOSE_NORMAL);
1225
+ }
1226
+ };
1227
+ }
1228
+ function bytesEqual(left, right) {
1229
+ if (left.byteLength !== right.byteLength) return false;
1230
+ for (let at = 0; at < left.byteLength; at++) {
1231
+ if (left[at] !== right[at]) return false;
1232
+ }
1233
+ return true;
1234
+ }
1235
+ function holdsIndex(engine, indexName) {
1236
+ return engine.listIndexes().some((index) => index.name === indexName);
1237
+ }
1238
+ async function putLocally(engine, indexName, documentId, document) {
1239
+ if (await engine.has(indexName, documentId)) {
1240
+ await engine.update(indexName, documentId, document);
1241
+ } else {
1242
+ await engine.insert(indexName, document, documentId);
1243
+ }
1244
+ }
1245
+ async function removeLocally(engine, indexName, documentId) {
1246
+ try {
1247
+ await engine.remove(indexName, documentId);
1248
+ } catch (error) {
1249
+ if (!(error instanceof NarsilError) || error.code !== ErrorCodes.DOC_NOT_FOUND) throw error;
1250
+ }
1251
+ }
1252
+ async function holdsSameDocument(engine, indexName, documentId, encoded) {
1253
+ const held = await engine.get(indexName, documentId);
1254
+ if (encoded === null || held === void 0) return encoded === null && held === void 0;
1255
+ return bytesEqual(encodeDocument(held), encoded);
1256
+ }
1257
+ async function applyEntryLocally(engine, indexName, entry) {
1258
+ if (await holdsSameDocument(engine, indexName, entry.documentId, entry.document)) return;
1259
+ if (entry.document === null) {
1260
+ await removeLocally(engine, indexName, entry.documentId);
1261
+ } else {
1262
+ await putLocally(engine, indexName, entry.documentId, decode(entry.document));
1263
+ }
1264
+ }
1265
+ async function applyWriteLocally(engine, indexName, write) {
1266
+ if (write.document === null) {
1267
+ await removeLocally(engine, indexName, write.documentId);
1268
+ return;
1269
+ }
1270
+ if (await holdsSameDocument(engine, indexName, write.documentId, encodeDocument(write.document))) return;
1271
+ await putLocally(engine, indexName, write.documentId, write.document);
1272
+ }
1273
+ function newestByDocument(entries) {
1274
+ const newest = /* @__PURE__ */ new Map();
1275
+ for (const entry of entries) {
1276
+ newest.delete(entry.documentId);
1277
+ newest.set(entry.documentId, entry);
1278
+ }
1279
+ return newest;
1280
+ }
1281
+
1282
+ // src/sync/device/progress.ts
1283
+ function entryBytes(entry) {
1284
+ return entry.documentId.length * 2 + (entry.document?.byteLength ?? 0) + KEPT_ENTRY_OVERHEAD_BYTES;
1285
+ }
1286
+ function createProgress(context) {
1287
+ const { engine, indexName, store, queue, work } = context;
1288
+ let position = null;
1289
+ let received = [];
1290
+ let unsaved = 0;
1291
+ let flushThreshold = KEPT_ENTRY_FLUSH_BYTES;
1292
+ let flushTimer = null;
1293
+ let acknowledge = null;
1294
+ const deferred = /* @__PURE__ */ new Map();
1295
+ function cancelFlush() {
1296
+ if (flushTimer !== null) clearTimeout(flushTimer);
1297
+ flushTimer = null;
1298
+ }
1299
+ async function saveWithinWork() {
1300
+ cancelFlush();
1301
+ if (position === null) return;
1302
+ if (unsaved === 0 && received.every((seqNo, partitionId) => seqNo === position?.seqNos[partitionId])) return;
1303
+ await context.makeDurable();
1304
+ const next = { epoch: position.epoch, seqNos: [...received] };
1305
+ await store.writePosition(next);
1306
+ position = next;
1307
+ await store.clearKeptEntries();
1308
+ unsaved = 0;
1309
+ acknowledge?.(next.seqNos);
1310
+ }
1311
+ function scheduleFlush() {
1312
+ if (context.stopped() || unsaved === 0) return;
1313
+ if (unsaved >= flushThreshold) {
1314
+ cancelFlush();
1315
+ work.run(saveWithinWork).catch(context.report);
1316
+ return;
1317
+ }
1318
+ if (flushTimer !== null) return;
1319
+ flushTimer = setTimeout(() => {
1320
+ flushTimer = null;
1321
+ work.run(saveWithinWork).catch(context.report);
1322
+ }, KEPT_ENTRY_FLUSH_IDLE_MS);
1323
+ }
1324
+ async function reapplyQueue() {
1325
+ if (!holdsIndex(engine, indexName)) return;
1326
+ for (const write of queue.ordered()) {
1327
+ try {
1328
+ await applyWriteLocally(engine, indexName, write);
1329
+ } catch (error) {
1330
+ await store.removeWrites([write.sequence]);
1331
+ queue.remove([write.sequence]);
1332
+ context.report(error);
1333
+ }
1334
+ }
1335
+ }
1336
+ return {
1337
+ position: () => position,
1338
+ received: () => received,
1339
+ recover: () => work.run(async () => {
1340
+ position = await store.readPosition();
1341
+ if (position !== null && !holdsIndex(engine, indexName)) {
1342
+ position = null;
1343
+ await store.writePosition(null);
1344
+ }
1345
+ queue.reset(await store.queuedWrites());
1346
+ const kept = await store.keptEntries();
1347
+ received = position === null ? [] : [...position.seqNos];
1348
+ const saved = position?.seqNos ?? [];
1349
+ const fresh = kept.filter((entry) => entry.seqNo > (saved[entry.partitionId] ?? Number.POSITIVE_INFINITY));
1350
+ for (const entry of newestByDocument(fresh).values()) {
1351
+ if (!queue.holdsDocument(entry.documentId)) await applyEntryLocally(engine, indexName, entry);
1352
+ }
1353
+ for (const entry of fresh) {
1354
+ received[entry.partitionId] = Math.max(received[entry.partitionId] ?? 0, entry.seqNo);
1355
+ }
1356
+ unsaved = fresh.length;
1357
+ if (fresh.length > 0) await saveWithinWork();
1358
+ else if (kept.length > 0) await store.clearKeptEntries();
1359
+ await reapplyQueue();
1360
+ }),
1361
+ async keep(partitionId, entries) {
1362
+ await work.run(async () => {
1363
+ const last = received[partitionId];
1364
+ if (last === void 0) return;
1365
+ const fresh = entries.filter((entry) => entry.seqNo > last);
1366
+ const newest = fresh[fresh.length - 1];
1367
+ if (newest === void 0) return;
1368
+ await store.keepEntries(fresh);
1369
+ for (const entry of fresh) {
1370
+ unsaved += entryBytes(entry);
1371
+ if (queue.holdsDocument(entry.documentId)) deferred.set(entry.documentId, entry);
1372
+ else await applyEntryLocally(engine, indexName, entry);
1373
+ }
1374
+ received[partitionId] = newest.seqNo;
1375
+ });
1376
+ scheduleFlush();
1377
+ },
1378
+ async settleUploaded(sequences) {
1379
+ await work.run(async () => {
1380
+ await store.removeWrites(sequences);
1381
+ queue.remove(sequences);
1382
+ for (const [documentId, entry] of deferred) {
1383
+ if (queue.holdsDocument(documentId)) continue;
1384
+ deferred.delete(documentId);
1385
+ await applyEntryLocally(engine, indexName, entry);
1386
+ }
1387
+ });
1388
+ scheduleFlush();
1389
+ },
1390
+ forgetDeferred(documentId) {
1391
+ deferred.delete(documentId);
1392
+ },
1393
+ async adopt(next) {
1394
+ cancelFlush();
1395
+ deferred.clear();
1396
+ await reapplyQueue();
1397
+ await context.makeDurable();
1398
+ await store.writePosition(next);
1399
+ position = { epoch: next.epoch, seqNos: [...next.seqNos] };
1400
+ received = [...next.seqNos];
1401
+ unsaved = 0;
1402
+ await store.clearDownload();
1403
+ },
1404
+ reapplyQueue,
1405
+ save: () => work.run(saveWithinWork),
1406
+ reached(heads) {
1407
+ return heads.length === received.length && heads.every((head, partitionId) => (received[partitionId] ?? -1) >= head);
1408
+ },
1409
+ setFlushThreshold(windowBytes) {
1410
+ flushThreshold = Math.max(1, Math.min(KEPT_ENTRY_FLUSH_BYTES, Math.floor(windowBytes / 2)));
1411
+ },
1412
+ setAcknowledge(next) {
1413
+ acknowledge = next;
1414
+ },
1415
+ cancelFlush,
1416
+ unsavedBytes: () => unsaved
1417
+ };
1418
+ }
1419
+
1420
+ // src/sync/device/queue.ts
1421
+ var QueueMirror = class {
1422
+ writes = /* @__PURE__ */ new Map();
1423
+ sequencesByDocument = /* @__PURE__ */ new Map();
1424
+ uploaded = /* @__PURE__ */ new Set();
1425
+ get size() {
1426
+ return this.writes.size;
1427
+ }
1428
+ reset(writes) {
1429
+ this.writes.clear();
1430
+ this.sequencesByDocument.clear();
1431
+ this.uploaded.clear();
1432
+ for (const write of [...writes].sort((a, b) => a.sequence - b.sequence)) this.add(write);
1433
+ }
1434
+ add(write) {
1435
+ this.writes.set(write.sequence, write);
1436
+ const sequences = this.sequencesByDocument.get(write.documentId);
1437
+ if (sequences === void 0) this.sequencesByDocument.set(write.documentId, [write.sequence]);
1438
+ else sequences.push(write.sequence);
1439
+ }
1440
+ remove(sequences) {
1441
+ for (const sequence of sequences) {
1442
+ const write = this.writes.get(sequence);
1443
+ if (write === void 0) continue;
1444
+ this.writes.delete(sequence);
1445
+ this.uploaded.delete(sequence);
1446
+ const remaining = (this.sequencesByDocument.get(write.documentId) ?? []).filter((held) => held !== sequence);
1447
+ if (remaining.length === 0) this.sequencesByDocument.delete(write.documentId);
1448
+ else this.sequencesByDocument.set(write.documentId, remaining);
1449
+ }
1450
+ }
1451
+ holdsDocument(documentId) {
1452
+ return this.sequencesByDocument.has(documentId);
1453
+ }
1454
+ ordered() {
1455
+ return [...this.writes.values()].sort((a, b) => a.sequence - b.sequence);
1456
+ }
1457
+ latestAwaitingUpload() {
1458
+ const latest = [];
1459
+ for (const sequences of this.sequencesByDocument.values()) {
1460
+ const newest = sequences[sequences.length - 1];
1461
+ if (newest === void 0 || this.uploaded.has(newest)) continue;
1462
+ const write = this.writes.get(newest);
1463
+ if (write !== void 0) latest.push(write);
1464
+ }
1465
+ return latest.sort((a, b) => a.sequence - b.sequence);
1466
+ }
1467
+ coveredBy(write) {
1468
+ const sequences = this.sequencesByDocument.get(write.documentId) ?? [];
1469
+ return sequences.filter((sequence) => sequence <= write.sequence && !this.uploaded.has(sequence));
1470
+ }
1471
+ hasLaterWrite(write) {
1472
+ const sequences = this.sequencesByDocument.get(write.documentId) ?? [];
1473
+ return (sequences[sequences.length - 1] ?? 0) > write.sequence;
1474
+ }
1475
+ markUploaded(sequences) {
1476
+ for (const sequence of sequences) {
1477
+ if (this.writes.has(sequence)) this.uploaded.add(sequence);
1478
+ }
1479
+ }
1480
+ forgetUploads() {
1481
+ this.uploaded.clear();
1482
+ }
1483
+ };
1484
+
1485
+ // src/sync/device/session.ts
1486
+ var MAX_CHECKPOINT_ID = 4294967295;
1487
+ function settingsKey(settings) {
1488
+ return JSON.stringify({ bm25: settings.bm25 ?? null, synonyms: settings.synonyms ?? [] });
1489
+ }
1490
+ function createSession(context, progress, state) {
1491
+ const { engine, indexName } = context;
1492
+ let feed = null;
1493
+ let generation = 0;
1494
+ let incoming = Promise.resolve();
1495
+ let hold = null;
1496
+ let nextCheckpointId = 1;
1497
+ let appliedSettings = null;
1498
+ const waiters = /* @__PURE__ */ new Map();
1499
+ let subscribedOnce = false;
1500
+ function sendCheckpoint(onHeads) {
1501
+ const id = nextCheckpointId;
1502
+ nextCheckpointId = id >= MAX_CHECKPOINT_ID ? 1 : id + 1;
1503
+ waiters.set(id, onHeads);
1504
+ feed?.send({ type: "checkpoint", id });
1505
+ }
1506
+ async function applySettings(settings) {
1507
+ state.settings = settings;
1508
+ const key = settingsKey(settings);
1509
+ if (key === appliedSettings) return;
1510
+ await context.work.run(async () => {
1511
+ await engine.updateBM25(indexName, settings.bm25 ?? {});
1512
+ await engine.updateSynonyms(indexName, settings.synonyms ?? []);
1513
+ });
1514
+ appliedSettings = key;
1515
+ }
1516
+ async function completeHold() {
1517
+ const done = hold;
1518
+ if (done === null || done.heads === null || !progress.reached(done.heads)) return;
1519
+ hold = null;
1520
+ await progress.settleUploaded(done.sequences);
1521
+ context.changes.notify();
1522
+ startHold();
1523
+ }
1524
+ function startHold() {
1525
+ if (hold !== null || !state.subscribed || feed === null || state.pendingHold.length === 0) return;
1526
+ const started = { checkpointId: 0, heads: null, sequences: state.pendingHold };
1527
+ state.pendingHold = [];
1528
+ hold = started;
1529
+ sendCheckpoint((heads) => {
1530
+ if (hold !== started || heads === null) return;
1531
+ started.heads = heads;
1532
+ completeHold().catch(context.report);
1533
+ });
1534
+ }
1535
+ function refuse(detail) {
1536
+ throw new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, `The sync feed broke its protocol: ${detail}`);
1537
+ }
1538
+ async function handle(message) {
1539
+ const position = progress.position();
1540
+ if (position === null) refuse("the device holds no copy");
1541
+ switch (message.type) {
1542
+ case "subscribed": {
1543
+ if (message.epoch !== position.epoch || message.partitionCount !== position.seqNos.length) {
1544
+ state.needsSnapshot = "required";
1545
+ feed?.close("epoch");
1546
+ return;
1547
+ }
1548
+ const behind = message.snapshotBytes > 0 && message.bytesBehind > replayLimit() * message.snapshotBytes;
1549
+ if (behind && !state.replayAnyway) {
1550
+ state.needsSnapshot = "behind";
1551
+ feed?.close("behind");
1552
+ return;
1553
+ }
1554
+ state.replayAnyway = false;
1555
+ progress.setFlushThreshold(message.windowBytes);
1556
+ await applySettings(message.settings);
1557
+ state.subscribed = true;
1558
+ subscribedOnce = true;
1559
+ context.changes.notify();
1560
+ startHold();
1561
+ return;
1562
+ }
1563
+ case "entries":
1564
+ if (!state.subscribed) refuse("entries arrived before subscribed");
1565
+ if (message.partitionId >= progress.received().length) refuse("entries name a partition that the index lacks");
1566
+ await progress.keep(message.partitionId, message.entries);
1567
+ await completeHold();
1568
+ context.changes.notify();
1569
+ return;
1570
+ case "settings":
1571
+ await applySettings(message.settings);
1572
+ return;
1573
+ case "checkpoint": {
1574
+ if (message.heads.length !== progress.received().length) refuse("heads name another partition count");
1575
+ const waiter = waiters.get(message.id);
1576
+ waiters.delete(message.id);
1577
+ waiter?.(message.heads);
1578
+ return;
1579
+ }
1580
+ case "resync":
1581
+ state.needsSnapshot = "required";
1582
+ return;
1583
+ }
1584
+ }
1585
+ function replayLimit() {
1586
+ return context.options.replayLimitOfSnapshot ?? DEFAULT_REPLAY_LIMIT_OF_SNAPSHOT;
1587
+ }
1588
+ function closed() {
1589
+ feed = null;
1590
+ generation += 1;
1591
+ state.subscribed = false;
1592
+ progress.setAcknowledge(null);
1593
+ if (hold !== null) {
1594
+ state.pendingHold = [...hold.sequences, ...state.pendingHold];
1595
+ hold = null;
1596
+ }
1597
+ for (const waiter of waiters.values()) waiter(null);
1598
+ waiters.clear();
1599
+ context.changes.notify();
1600
+ }
1601
+ return {
1602
+ async connect(feedUrl) {
1603
+ await incoming;
1604
+ const position = progress.position();
1605
+ if (position === null || context.stopped()) return { code: 0, subscribed: false };
1606
+ const credential = await context.credential();
1607
+ if (context.stopped()) return { code: 0, subscribed: false };
1608
+ const mine = generation;
1609
+ subscribedOnce = false;
1610
+ const code = await new Promise((resolve) => {
1611
+ try {
1612
+ feed = openFeedConnection(feedUrl, credential, {
1613
+ onOpen() {
1614
+ progress.setAcknowledge((seqNos) => feed?.send({ type: "ack", positions: positionsOf(seqNos) }));
1615
+ feed?.send({ type: "subscribe", epoch: position.epoch, positions: positionsOf(progress.received()) });
1616
+ },
1617
+ onMessage(message) {
1618
+ incoming = incoming.then(() => generation === mine ? handle(message) : void 0).catch((error) => {
1619
+ context.report(error);
1620
+ if (generation === mine) feed?.close("device error");
1621
+ });
1622
+ },
1623
+ onFailure: context.report,
1624
+ onClose(code2) {
1625
+ closed();
1626
+ resolve(code2);
1627
+ }
1628
+ });
1629
+ } catch (error) {
1630
+ context.report(error);
1631
+ resolve(0);
1632
+ }
1633
+ });
1634
+ return { code, subscribed: subscribedOnce };
1635
+ },
1636
+ close(reason) {
1637
+ feed?.close(reason);
1638
+ },
1639
+ startHold,
1640
+ requestHeads() {
1641
+ if (feed === null || !state.subscribed) return Promise.resolve(null);
1642
+ return new Promise((resolve) => sendCheckpoint(resolve));
1643
+ },
1644
+ holding: () => hold !== null,
1645
+ forgetAppliedSettings() {
1646
+ appliedSettings = null;
1647
+ }
1648
+ };
1649
+ }
1650
+
1651
+ // src/sync/device/analysis.ts
1652
+ function requireAnalysisOnDevice(indexName, analysis) {
1653
+ const missing = [];
1654
+ if (!hasLanguage(analysis.language)) missing.push(`language "${analysis.language}"`);
1655
+ if (analysis.tokenizer !== void 0 && !hasTokenizer(analysis.tokenizer)) {
1656
+ missing.push(`tokenizer "${analysis.tokenizer}"`);
1657
+ }
1658
+ if (analysis.stopWords !== void 0 && !hasStopWords(analysis.stopWords)) {
1659
+ missing.push(`stop words "${analysis.stopWords}"`);
1660
+ }
1661
+ if (missing.length === 0) return;
1662
+ throw new NarsilError(
1663
+ ClientErrorCodes.SYNC_ANALYSIS_UNAVAILABLE,
1664
+ `Index "${indexName}" on the server analyses text with ${missing.join(", ")}, which this device has not registered, so the device keeps its copy. Register them and sync again`,
1665
+ { indexName, missing }
1666
+ );
1667
+ }
1668
+ function analysisIsStale(analysis) {
1669
+ if (analysis.analysisRevision === void 0 || !hasLanguage(analysis.language)) return false;
1670
+ return getLanguage(analysis.language).revision !== analysis.analysisRevision;
1671
+ }
1672
+
1673
+ // src/sync/device/archive-facts.ts
1674
+ var FactsComplete = class {
1675
+ };
1676
+ function unusable(detail) {
1677
+ return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, `The sync snapshot is unusable: ${detail}`);
1678
+ }
1679
+ function optionalString(value) {
1680
+ return typeof value === "string" ? value : void 0;
1681
+ }
1682
+ async function readArchiveFacts(source) {
1683
+ const reader = createByteReader(source);
1684
+ const read = { config: null, seqNos: null };
1685
+ try {
1686
+ await readSnapshotArchive(reader, {
1687
+ async config(bytes) {
1688
+ read.config = { ...await decodeIndexConfiguration(bytes) };
1689
+ },
1690
+ async manifest(manifest) {
1691
+ const found = new Array(manifest.checkpoint.length).fill(-1);
1692
+ for (const entry of manifest.checkpoint) {
1693
+ if (entry.partitionId >= found.length || found[entry.partitionId] !== -1) {
1694
+ throw unusable("its manifest names a partition twice or skips one");
1695
+ }
1696
+ found[entry.partitionId] = entry.lastSeqNo;
1697
+ }
1698
+ read.seqNos = found;
1699
+ throw new FactsComplete();
1700
+ },
1701
+ async file() {
1702
+ throw unusable("a file comes before its manifest");
1703
+ }
1704
+ });
1705
+ } catch (error) {
1706
+ if (!(error instanceof FactsComplete)) throw error;
1707
+ } finally {
1708
+ await reader.close();
1709
+ }
1710
+ const { config, seqNos } = read;
1711
+ if (config === null || seqNos === null) throw unusable("it holds no configuration or no manifest");
1712
+ if (!isSyncEpoch(config.syncEpoch)) throw unusable("its configuration holds no sync epoch");
1713
+ const language = optionalString(config.language);
1714
+ if (language === void 0) throw unusable("its configuration holds no language");
1715
+ const tokenizer = optionalString(config.tokenizer);
1716
+ const stopWords = optionalString(config.stopWords);
1717
+ const analysisRevision = optionalString(config.analysisRevision);
1718
+ return {
1719
+ epoch: config.syncEpoch,
1720
+ seqNos,
1721
+ analysis: {
1722
+ language,
1723
+ ...tokenizer !== void 0 ? { tokenizer } : {},
1724
+ ...stopWords !== void 0 ? { stopWords } : {},
1725
+ ...analysisRevision !== void 0 ? { analysisRevision } : {}
1726
+ }
1727
+ };
1728
+ }
1729
+
1730
+ // src/sync/device/snapshot.ts
1731
+ var RANGE_NOT_SATISFIABLE = 416;
1732
+ async function startDownload(context) {
1733
+ const saved = await context.store.readDownload();
1734
+ const resume = saved === null ? void 0 : { offset: saved.byteLength, entityTag: saved.entityTag };
1735
+ try {
1736
+ return await context.client.syncSnapshot(context.indexName, resume, await context.requestOptions());
1737
+ } catch (error) {
1738
+ if (resume === void 0 || !(error instanceof NarsilError) || error.details.status !== RANGE_NOT_SATISFIABLE) {
1739
+ throw error;
1740
+ }
1741
+ await context.store.clearDownload();
1742
+ return context.client.syncSnapshot(context.indexName, void 0, await context.requestOptions());
1743
+ }
1744
+ }
1745
+ async function mustDropOldCopy(context, archiveBytes) {
1746
+ if (!holdsIndex(context.engine, context.indexName)) return false;
1747
+ const heap = readHeapStatistics();
1748
+ const requiredBytes = archiveBytes * SNAPSHOT_MEMORY_PER_ARCHIVE_BYTE;
1749
+ if (heap === null || heap.usedBytes + requiredBytes <= heap.limitBytes) return false;
1750
+ if (context.appChoseLoad) return true;
1751
+ const choice = await context.chooseSnapshotLoad({ archiveBytes, requiredBytes, heapLimitBytes: heap.limitBytes });
1752
+ return choice === "keep" ? "keep" : true;
1753
+ }
1754
+ async function saveDownload(context, download) {
1755
+ const reader = download.stream.getReader();
1756
+ let offset = download.offset;
1757
+ let pending = [];
1758
+ let pendingBytes = 0;
1759
+ async function flush() {
1760
+ if (pendingBytes === 0) return;
1761
+ const batch = new Uint8Array(pendingBytes);
1762
+ let at = 0;
1763
+ for (const part of pending) {
1764
+ batch.set(part, at);
1765
+ at += part.byteLength;
1766
+ }
1767
+ await context.store.appendDownload(download.entityTag, offset, batch);
1768
+ offset += pendingBytes;
1769
+ pending = [];
1770
+ pendingBytes = 0;
1771
+ }
1772
+ try {
1773
+ if (download.offset === 0) await context.store.appendDownload(download.entityTag, 0, new Uint8Array(0));
1774
+ for (; ; ) {
1775
+ const { done, value } = await reader.read();
1776
+ if (done) break;
1777
+ if (offset + pendingBytes + value.byteLength > download.totalBytes) {
1778
+ throw new NarsilError(
1779
+ ClientErrorCodes.CLIENT_INVALID_RESPONSE,
1780
+ "The server sent more bytes than the snapshot holds"
1781
+ );
1782
+ }
1783
+ pending.push(value);
1784
+ pendingBytes += value.byteLength;
1785
+ if (pendingBytes >= DOWNLOAD_SAVE_BYTES) await flush();
1786
+ }
1787
+ await flush();
1788
+ } catch (error) {
1789
+ await flush().catch(() => void 0);
1790
+ await reader.cancel().catch(() => void 0);
1791
+ throw error;
1792
+ } finally {
1793
+ reader.releaseLock();
1794
+ }
1795
+ }
1796
+ function completeDownload(saved, entityTag, totalBytes) {
1797
+ if (saved === null || saved.entityTag !== entityTag || saved.byteLength !== totalBytes) {
1798
+ throw new NarsilError(ClientErrorCodes.CLIENT_CONNECTION_FAILED, "The snapshot download ended early", {
1799
+ saved: saved?.byteLength ?? 0,
1800
+ totalBytes
1801
+ });
1802
+ }
1803
+ return saved;
1804
+ }
1805
+ async function downloadPublishedSnapshot(context) {
1806
+ if (context.settings !== null) requireAnalysisOnDevice(context.indexName, context.settings);
1807
+ const download = await startDownload(context);
1808
+ const dropOldCopy = await mustDropOldCopy(context, download.totalBytes);
1809
+ if (dropOldCopy === "keep") {
1810
+ await download.stream.cancel().catch(() => void 0);
1811
+ return { kind: "kept" };
1812
+ }
1813
+ await saveDownload(context, download);
1814
+ const saved = completeDownload(await context.store.readDownload(), download.entityTag, download.totalBytes);
1815
+ const facts = await readArchiveFacts(saved.chunks());
1816
+ requireAnalysisOnDevice(context.indexName, facts.analysis);
1817
+ return { kind: "downloaded", saved, facts, dropOldCopy };
1818
+ }
1819
+ async function restoreDownloadedSnapshot(context, downloaded) {
1820
+ await context.store.clearKeptEntries();
1821
+ if (downloaded.dropOldCopy && holdsIndex(context.engine, context.indexName)) {
1822
+ await context.engine.dropIndex(context.indexName);
1823
+ }
1824
+ await context.engine.restore(context.indexName, downloaded.saved.chunks());
1825
+ if (analysisIsStale(downloaded.facts.analysis)) await context.engine.rebuildAnalysis(context.indexName);
1826
+ return { epoch: downloaded.facts.epoch, seqNos: downloaded.facts.seqNos };
1827
+ }
1828
+
1829
+ // src/sync/device/stores/serial.ts
1830
+ function createSerial() {
1831
+ let tail = Promise.resolve();
1832
+ return {
1833
+ run(task) {
1834
+ const result = tail.then(task, task);
1835
+ tail = result.catch(() => void 0);
1836
+ return result;
1837
+ }
1838
+ };
1839
+ }
1840
+
1841
+ // src/sync/device/upload.ts
1842
+ var REFUSED_STATUSES = /* @__PURE__ */ new Set([400, 413, 422]);
1843
+ function refusedBy(error) {
1844
+ if (!(error instanceof NarsilError)) return false;
1845
+ const status = error.details.status;
1846
+ return typeof status === "number" && REFUSED_STATUSES.has(status);
1847
+ }
1848
+ async function sendOne(client, indexName, write, options) {
1849
+ if (write.document !== null) {
1850
+ await client.put(indexName, write.documentId, write.document, void 0, options);
1851
+ return;
1852
+ }
1853
+ try {
1854
+ await client.remove(indexName, write.documentId, void 0, options);
1855
+ } catch (error) {
1856
+ if (!(error instanceof NarsilError) || error.code !== ErrorCodes.DOC_NOT_FOUND) throw error;
1857
+ }
1858
+ }
1859
+ async function sendThroughServer(client, indexName, writes, options) {
1860
+ const outcomes = [];
1861
+ for (const write of writes) {
1862
+ try {
1863
+ await sendOne(client, indexName, write, await options());
1864
+ outcomes.push({ accepted: true });
1865
+ } catch (error) {
1866
+ if (!refusedBy(error)) return { outcomes, failure: error };
1867
+ outcomes.push({ accepted: false, error });
1868
+ }
1869
+ }
1870
+ return { outcomes, failure: null };
1871
+ }
1872
+ async function sendThroughBackend(upload, writes) {
1873
+ let outcomes;
1874
+ try {
1875
+ outcomes = await upload(writes);
1876
+ } catch (error) {
1877
+ return { outcomes: [], failure: error };
1878
+ }
1879
+ if (!Array.isArray(outcomes) || outcomes.length !== writes.length) {
1880
+ return {
1881
+ outcomes: [],
1882
+ failure: new NarsilError(
1883
+ ClientErrorCodes.CLIENT_INVALID_RESPONSE,
1884
+ `The upload function returned ${Array.isArray(outcomes) ? outcomes.length : "no"} outcomes for ${writes.length} writes`
1885
+ )
1886
+ };
1887
+ }
1888
+ for (const outcome of outcomes) {
1889
+ const valid = outcome !== null && typeof outcome === "object" && (outcome.accepted === true || outcome.accepted === false && outcome.error instanceof NarsilError);
1890
+ if (!valid) {
1891
+ return {
1892
+ outcomes: [],
1893
+ failure: new NarsilError(
1894
+ ClientErrorCodes.CLIENT_INVALID_RESPONSE,
1895
+ "Each outcome of the upload function must be { accepted: true } or { accepted: false, error }"
1896
+ )
1897
+ };
1898
+ }
1899
+ }
1900
+ return { outcomes, failure: null };
1901
+ }
1902
+
1903
+ // src/sync/device/uploader.ts
1904
+ function createUploader(context, progress, session, state) {
1905
+ const { engine, indexName, store, queue, work, client } = context;
1906
+ let running = null;
1907
+ let again = false;
1908
+ async function serverCopyOf(write, outcome) {
1909
+ if (outcome.serverDocument !== void 0) return outcome.serverDocument;
1910
+ return await client.get(indexName, write.documentId, await context.requestOptions()) ?? null;
1911
+ }
1912
+ async function refuse(write, outcome) {
1913
+ const serverDocument = await serverCopyOf(write, outcome);
1914
+ await work.run(async () => {
1915
+ const covered = queue.coveredBy(write);
1916
+ if (!queue.hasLaterWrite(write)) {
1917
+ if (serverDocument === null) await removeLocally(engine, indexName, write.documentId);
1918
+ else await putLocally(engine, indexName, write.documentId, serverDocument);
1919
+ }
1920
+ await store.removeWrites(covered);
1921
+ queue.remove(covered);
1922
+ progress.forgetDeferred(write.documentId);
1923
+ });
1924
+ try {
1925
+ context.options.onRefusedWrite?.({ write, error: outcome.error, serverDocument });
1926
+ } catch (error) {
1927
+ context.report(error);
1928
+ }
1929
+ }
1930
+ async function settle(batch, result) {
1931
+ let failure = result.failure;
1932
+ for (let at = 0; at < result.outcomes.length; at++) {
1933
+ const write = batch[at];
1934
+ const outcome = result.outcomes[at];
1935
+ if (write === void 0 || outcome === void 0) break;
1936
+ if (outcome.accepted) {
1937
+ const covered = queue.coveredBy(write);
1938
+ queue.markUploaded(covered);
1939
+ state.pendingHold.push(...covered);
1940
+ progress.forgetDeferred(write.documentId);
1941
+ continue;
1942
+ }
1943
+ try {
1944
+ await refuse(write, outcome);
1945
+ } catch (error) {
1946
+ failure ??= error;
1947
+ break;
1948
+ }
1949
+ }
1950
+ return failure;
1951
+ }
1952
+ async function drain() {
1953
+ let failures = 0;
1954
+ while (!context.stopped()) {
1955
+ again = false;
1956
+ const batch = queue.latestAwaitingUpload().slice(0, UPLOAD_BATCH_WRITES);
1957
+ if (batch.length === 0) return;
1958
+ const upload = context.options.upload;
1959
+ const result = upload === void 0 ? await sendThroughServer(client, indexName, batch, context.requestOptions) : await sendThroughBackend(upload, batch);
1960
+ const failure = await settle(batch, result);
1961
+ session.startHold();
1962
+ context.changes.notify();
1963
+ if (failure === null || failure === void 0) {
1964
+ failures = 0;
1965
+ continue;
1966
+ }
1967
+ context.report(failure);
1968
+ await context.pause(backoffDelayMs(failures, UPLOAD_RETRY_DELAY_MS, RETRY_MAX_DELAY_MS));
1969
+ failures += 1;
1970
+ }
1971
+ }
1972
+ function kick() {
1973
+ if (context.stopped()) return;
1974
+ if (running !== null) {
1975
+ again = true;
1976
+ return;
1977
+ }
1978
+ running = drain().catch(context.report).finally(() => {
1979
+ running = null;
1980
+ if (again) kick();
1981
+ });
1982
+ }
1983
+ return {
1984
+ kick,
1985
+ idle: () => running ?? Promise.resolve()
1986
+ };
1987
+ }
1988
+
1989
+ // src/sync/device/index.ts
1990
+ function invalid(message) {
1991
+ return new NarsilError(ErrorCodes.CONFIG_INVALID, message);
1992
+ }
1993
+ function validated(options) {
1994
+ if (typeof options.indexName !== "string" || options.indexName.length === 0) {
1995
+ throw invalid("Device sync needs an index name");
1996
+ }
1997
+ const limit = options.replayLimitOfSnapshot;
1998
+ if (limit !== void 0 && (!Number.isFinite(limit) || limit < 0)) {
1999
+ throw invalid("replayLimitOfSnapshot must be a finite number at or above 0");
2000
+ }
2001
+ }
2002
+ function copyOf(document) {
2003
+ if (document === null || typeof document !== "object" || Array.isArray(document)) {
2004
+ throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, "A document must be an object");
2005
+ }
2006
+ return decode(encodeDocument(document));
2007
+ }
2008
+ function requireDocumentId(documentId) {
2009
+ if (typeof documentId !== "string" || documentId.length === 0) {
2010
+ throw new NarsilError(ErrorCodes.DOC_VALIDATION_FAILED, "A document ID must be a non-empty string");
2011
+ }
2012
+ }
2013
+ function createDeviceSync(options) {
2014
+ validated(options);
2015
+ const { engine, indexName, store } = options;
2016
+ const feedUrl = feedUrlOf(options.url, indexName);
2017
+ const client = createNarsilClient({ url: options.url });
2018
+ const changes = createChanges();
2019
+ let stopped = true;
2020
+ let recovered = null;
2021
+ let loop = null;
2022
+ let appChoseLoad = false;
2023
+ let snapshotDeferred = false;
2024
+ let aborts = new AbortController();
2025
+ async function credential() {
2026
+ return options.credential === void 0 ? null : await options.credential();
2027
+ }
2028
+ const context = {
2029
+ options,
2030
+ engine,
2031
+ indexName,
2032
+ store,
2033
+ client,
2034
+ work: createSerial(),
2035
+ queue: new QueueMirror(),
2036
+ changes,
2037
+ report(error) {
2038
+ try {
2039
+ options.onError?.(error);
2040
+ } catch {
2041
+ }
2042
+ },
2043
+ credential,
2044
+ async requestOptions() {
2045
+ const value = await credential();
2046
+ const signal = aborts.signal;
2047
+ return value === null ? { signal } : { signal, headers: { authorization: `Bearer ${value}` } };
2048
+ },
2049
+ makeDurable: options.makeDurable ?? (() => engine.checkpoint(indexName)),
2050
+ stopped: () => stopped,
2051
+ pause(delayMs) {
2052
+ return new Promise((resolve) => {
2053
+ if (stopped) {
2054
+ resolve();
2055
+ return;
2056
+ }
2057
+ let done = false;
2058
+ const finish = () => {
2059
+ if (done) return;
2060
+ done = true;
2061
+ clearTimeout(timer);
2062
+ resolve();
2063
+ };
2064
+ const timer = setTimeout(finish, delayMs);
2065
+ const watch = () => {
2066
+ if (done) return;
2067
+ if (stopped) finish();
2068
+ else changes.next().then(watch);
2069
+ };
2070
+ changes.next().then(watch);
2071
+ });
2072
+ }
2073
+ };
2074
+ const progress = createProgress(context);
2075
+ const state = {
2076
+ subscribed: false,
2077
+ needsSnapshot: null,
2078
+ replayAnyway: false,
2079
+ pendingHold: [],
2080
+ settings: null
2081
+ };
2082
+ const session = createSession(context, progress, state);
2083
+ const uploader = createUploader(context, progress, session, state);
2084
+ async function loadSnapshot() {
2085
+ const snapshotContext = {
2086
+ engine,
2087
+ indexName,
2088
+ client,
2089
+ store,
2090
+ requestOptions: context.requestOptions,
2091
+ chooseSnapshotLoad: options.chooseSnapshotLoad ?? (async () => "load"),
2092
+ settings: state.settings,
2093
+ appChoseLoad
2094
+ };
2095
+ const downloaded = await downloadPublishedSnapshot(snapshotContext);
2096
+ if (downloaded.kind === "kept") return "kept";
2097
+ await context.work.run(async () => {
2098
+ const position = await restoreDownloadedSnapshot(snapshotContext, downloaded);
2099
+ session.forgetAppliedSettings();
2100
+ await progress.adopt(position);
2101
+ });
2102
+ return "loaded";
2103
+ }
2104
+ async function snapshotStep(attempt) {
2105
+ if (snapshotDeferred && !appChoseLoad) {
2106
+ await changes.next();
2107
+ return attempt;
2108
+ }
2109
+ try {
2110
+ const outcome = await loadSnapshot();
2111
+ if (outcome === "loaded") {
2112
+ state.needsSnapshot = null;
2113
+ appChoseLoad = false;
2114
+ snapshotDeferred = false;
2115
+ } else if (state.needsSnapshot === "behind" && progress.position() !== null) {
2116
+ state.needsSnapshot = null;
2117
+ state.replayAnyway = true;
2118
+ } else {
2119
+ snapshotDeferred = true;
2120
+ }
2121
+ changes.notify();
2122
+ return 0;
2123
+ } catch (error) {
2124
+ context.report(error);
2125
+ await context.pause(backoffDelayMs(attempt, SNAPSHOT_RETRY_DELAY_MS, RETRY_MAX_DELAY_MS));
2126
+ return attempt + 1;
2127
+ }
2128
+ }
2129
+ async function run() {
2130
+ let attempt = 0;
2131
+ while (!stopped) {
2132
+ if (progress.position() === null || state.needsSnapshot !== null) {
2133
+ attempt = await snapshotStep(attempt);
2134
+ continue;
2135
+ }
2136
+ const { code, subscribed } = await session.connect(feedUrl);
2137
+ if (stopped) return;
2138
+ if (subscribed) attempt = 0;
2139
+ if (code === SYNC_CLOSE_RESYNC) state.needsSnapshot ??= "required";
2140
+ if (code === SYNC_CLOSE_CREDENTIAL_EXPIRED || state.needsSnapshot !== null) continue;
2141
+ await context.pause(backoffDelayMs(attempt, RECONNECT_MIN_DELAY_MS, RETRY_MAX_DELAY_MS));
2142
+ attempt += 1;
2143
+ }
2144
+ }
2145
+ async function waitUntil(condition) {
2146
+ while (!condition()) {
2147
+ if (stopped) throw invalid("Device sync stopped before it settled");
2148
+ await changes.next();
2149
+ }
2150
+ }
2151
+ function requireRecovered() {
2152
+ if (recovered === null) throw invalid("Call start before writing through device sync");
2153
+ return recovered;
2154
+ }
2155
+ async function write(documentId, document) {
2156
+ requireDocumentId(documentId);
2157
+ const copy = document === null ? null : copyOf(document);
2158
+ await requireRecovered();
2159
+ await context.work.run(async () => {
2160
+ const queued = await store.appendWrite({ documentId, document: copy });
2161
+ context.queue.add(queued);
2162
+ try {
2163
+ if (copy === null) await removeLocally(engine, indexName, documentId);
2164
+ else await putLocally(engine, indexName, documentId, copy);
2165
+ } catch (error) {
2166
+ await store.removeWrites([queued.sequence]);
2167
+ context.queue.remove([queued.sequence]);
2168
+ throw error;
2169
+ }
2170
+ });
2171
+ changes.notify();
2172
+ uploader.kick();
2173
+ }
2174
+ function quiet() {
2175
+ return state.subscribed && context.queue.size === 0 && state.pendingHold.length === 0 && !session.holding() && state.needsSnapshot === null;
2176
+ }
2177
+ return {
2178
+ put: (documentId, document) => write(documentId, document),
2179
+ remove: (documentId) => write(documentId, null),
2180
+ async start() {
2181
+ if (!stopped) return;
2182
+ stopped = false;
2183
+ aborts = new AbortController();
2184
+ recovered ??= progress.recover();
2185
+ try {
2186
+ await recovered;
2187
+ } catch (error) {
2188
+ recovered = null;
2189
+ stopped = true;
2190
+ throw error;
2191
+ }
2192
+ loop = run().catch(context.report);
2193
+ uploader.kick();
2194
+ },
2195
+ async stop() {
2196
+ if (stopped) return;
2197
+ stopped = true;
2198
+ aborts.abort();
2199
+ session.close("stopped");
2200
+ progress.cancelFlush();
2201
+ changes.notify();
2202
+ await Promise.allSettled([loop, uploader.idle()]);
2203
+ loop = null;
2204
+ if (progress.unsavedBytes() > 0) await progress.save().catch(context.report);
2205
+ },
2206
+ async loadSnapshot() {
2207
+ appChoseLoad = true;
2208
+ state.needsSnapshot ??= "required";
2209
+ session.close("snapshot");
2210
+ changes.notify();
2211
+ await waitUntil(() => !appChoseLoad && state.needsSnapshot === null);
2212
+ },
2213
+ async settled() {
2214
+ for (; ; ) {
2215
+ await waitUntil(quiet);
2216
+ const heads = await session.requestHeads();
2217
+ if (heads === null) continue;
2218
+ await waitUntil(() => progress.reached(heads) || !state.subscribed);
2219
+ if (!progress.reached(heads)) continue;
2220
+ await progress.save();
2221
+ if (quiet()) return;
2222
+ }
2223
+ },
2224
+ status() {
2225
+ const position = progress.position();
2226
+ return {
2227
+ connection: stopped ? "stopped" : state.subscribed ? "connected" : "connecting",
2228
+ queuedWrites: context.queue.size,
2229
+ position: position === null ? null : { epoch: position.epoch, seqNos: [...position.seqNos] },
2230
+ snapshotDeferred
2231
+ };
2232
+ }
2233
+ };
2234
+ }
2235
+
2236
+ export { createDeviceSync };