@multiplatform.one/frappe 9.17.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/dist/cjs/auth.cjs +34 -44
  2. package/dist/cjs/auth.native.cjs +97 -0
  3. package/dist/cjs/auth.native.js +77 -82
  4. package/dist/cjs/auth.native.js.map +1 -1
  5. package/dist/cjs/call.cjs +31 -35
  6. package/dist/cjs/call.native.cjs +92 -0
  7. package/dist/cjs/call.native.js +72 -71
  8. package/dist/cjs/call.native.js.map +1 -1
  9. package/dist/cjs/collection.cjs +243 -287
  10. package/dist/cjs/collection.native.cjs +461 -0
  11. package/dist/cjs/collection.native.js +436 -499
  12. package/dist/cjs/collection.native.js.map +1 -1
  13. package/dist/cjs/common/types.cjs +9 -11
  14. package/dist/cjs/common/types.native.cjs +18 -0
  15. package/dist/cjs/common/types.native.js +9 -10
  16. package/dist/cjs/common/types.native.js.map +1 -1
  17. package/dist/cjs/connectionKey.cjs +18 -22
  18. package/dist/cjs/connectionKey.native.cjs +32 -0
  19. package/dist/cjs/connectionKey.native.js +19 -22
  20. package/dist/cjs/connectionKey.native.js.map +1 -1
  21. package/dist/cjs/core/http.cjs +404 -407
  22. package/dist/cjs/core/http.native.cjs +659 -0
  23. package/dist/cjs/core/http.native.js +611 -615
  24. package/dist/cjs/core/http.native.js.map +1 -1
  25. package/dist/cjs/core/serverMessages.cjs +48 -43
  26. package/dist/cjs/core/serverMessages.native.cjs +89 -0
  27. package/dist/cjs/core/serverMessages.native.js +69 -70
  28. package/dist/cjs/core/serverMessages.native.js.map +1 -1
  29. package/dist/cjs/core/sessionGate.cjs +94 -97
  30. package/dist/cjs/core/sessionGate.native.cjs +270 -0
  31. package/dist/cjs/core/sessionGate.native.js +220 -232
  32. package/dist/cjs/core/sessionGate.native.js.map +1 -1
  33. package/dist/cjs/core/types.cjs +37 -39
  34. package/dist/cjs/core/types.native.cjs +169 -0
  35. package/dist/cjs/core/types.native.js +129 -136
  36. package/dist/cjs/core/types.native.js.map +1 -1
  37. package/dist/cjs/core/wire.cjs +28 -30
  38. package/dist/cjs/core/wire.native.cjs +53 -0
  39. package/dist/cjs/core/wire.native.js +28 -29
  40. package/dist/cjs/core/wire.native.js.map +1 -1
  41. package/dist/cjs/db.cjs +434 -449
  42. package/dist/cjs/db.native.cjs +625 -0
  43. package/dist/cjs/db.native.js +583 -590
  44. package/dist/cjs/db.native.js.map +1 -1
  45. package/dist/cjs/devtools/FrappeDevtoolsPanel.cjs +774 -799
  46. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.cjs +878 -0
  47. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.js +821 -862
  48. package/dist/cjs/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  49. package/dist/cjs/devtools/index.cjs +15 -17
  50. package/dist/cjs/devtools/index.native.cjs +30 -0
  51. package/dist/cjs/devtools/index.native.js +15 -16
  52. package/dist/cjs/devtools/index.native.js.map +1 -1
  53. package/dist/cjs/devtools/plugin.cjs +22 -26
  54. package/dist/cjs/devtools/plugin.native.cjs +46 -0
  55. package/dist/cjs/devtools/plugin.native.js +27 -35
  56. package/dist/cjs/devtools/plugin.native.js.map +1 -1
  57. package/dist/cjs/devtools/theme.cjs +40 -44
  58. package/dist/cjs/devtools/theme.native.cjs +53 -0
  59. package/dist/cjs/devtools/theme.native.js +40 -43
  60. package/dist/cjs/devtools/theme.native.js.map +1 -1
  61. package/dist/cjs/doctype.cjs +493 -440
  62. package/dist/cjs/doctype.native.cjs +631 -0
  63. package/dist/cjs/doctype.native.js +587 -563
  64. package/dist/cjs/doctype.native.js.map +1 -1
  65. package/dist/cjs/file.cjs +27 -31
  66. package/dist/cjs/file.native.cjs +78 -0
  67. package/dist/cjs/file.native.js +58 -62
  68. package/dist/cjs/file.native.js.map +1 -1
  69. package/dist/cjs/fixtureDb.cjs +187 -209
  70. package/dist/cjs/fixtureDb.native.cjs +313 -0
  71. package/dist/cjs/fixtureDb.native.js +291 -300
  72. package/dist/cjs/fixtureDb.native.js.map +1 -1
  73. package/dist/cjs/fixtures.cjs +173 -192
  74. package/dist/cjs/fixtures.native.cjs +379 -0
  75. package/dist/cjs/fixtures.native.js +359 -381
  76. package/dist/cjs/fixtures.native.js.map +1 -1
  77. package/dist/cjs/frappeApp.cjs +94 -101
  78. package/dist/cjs/frappeApp.native.cjs +181 -0
  79. package/dist/cjs/frappeApp.native.js +153 -152
  80. package/dist/cjs/frappeApp.native.js.map +1 -1
  81. package/dist/cjs/frappeReact.cjs +555 -528
  82. package/dist/cjs/frappeReact.native.cjs +710 -0
  83. package/dist/cjs/frappeReact.native.js +637 -632
  84. package/dist/cjs/frappeReact.native.js.map +1 -1
  85. package/dist/cjs/index.cjs +128 -135
  86. package/dist/cjs/index.gnome.cjs +61 -63
  87. package/dist/cjs/index.gnome.native.cjs +87 -0
  88. package/dist/cjs/index.gnome.native.js +61 -62
  89. package/dist/cjs/index.gnome.native.js.map +1 -1
  90. package/dist/cjs/index.native.cjs +171 -0
  91. package/dist/cjs/index.native.js +130 -136
  92. package/dist/cjs/index.native.js.map +1 -1
  93. package/dist/cjs/optimistic.cjs +35 -39
  94. package/dist/cjs/optimistic.native.cjs +59 -0
  95. package/dist/cjs/optimistic.native.js +38 -41
  96. package/dist/cjs/optimistic.native.js.map +1 -1
  97. package/dist/cjs/pacer.cjs +170 -176
  98. package/dist/cjs/pacer.native.cjs +263 -0
  99. package/dist/cjs/pacer.native.js +234 -245
  100. package/dist/cjs/pacer.native.js.map +1 -1
  101. package/dist/cjs/plugin/index.cjs +104 -112
  102. package/dist/cjs/plugin/index.native.cjs +178 -0
  103. package/dist/cjs/plugin/index.native.js +164 -177
  104. package/dist/cjs/plugin/index.native.js.map +1 -1
  105. package/dist/cjs/realtime.cjs +581 -610
  106. package/dist/cjs/realtime.native.cjs +945 -0
  107. package/dist/cjs/realtime.native.js +918 -928
  108. package/dist/cjs/realtime.native.js.map +1 -1
  109. package/dist/cjs/serverLoaders.cjs +60 -78
  110. package/dist/cjs/serverLoaders.native.cjs +103 -0
  111. package/dist/cjs/serverLoaders.native.js +73 -95
  112. package/dist/cjs/serverLoaders.native.js.map +1 -1
  113. package/dist/cjs/sync/backfill.cjs +281 -301
  114. package/dist/cjs/sync/backfill.native.cjs +475 -0
  115. package/dist/cjs/sync/backfill.native.js +449 -465
  116. package/dist/cjs/sync/backfill.native.js.map +1 -1
  117. package/dist/cjs/sync/filters.cjs +309 -267
  118. package/dist/cjs/sync/filters.native.cjs +472 -0
  119. package/dist/cjs/sync/filters.native.js +426 -398
  120. package/dist/cjs/sync/filters.native.js.map +1 -1
  121. package/dist/cjs/sync/index.cjs +476 -496
  122. package/dist/cjs/sync/index.native.cjs +771 -0
  123. package/dist/cjs/sync/index.native.js +738 -737
  124. package/dist/cjs/sync/index.native.js.map +1 -1
  125. package/dist/cjs/sync/merge.cjs +392 -393
  126. package/dist/cjs/sync/merge.native.cjs +681 -0
  127. package/dist/cjs/sync/merge.native.js +642 -673
  128. package/dist/cjs/sync/merge.native.js.map +1 -1
  129. package/dist/cjs/sync/mutationEngine.cjs +785 -829
  130. package/dist/cjs/sync/mutationEngine.native.cjs +1190 -0
  131. package/dist/cjs/sync/mutationEngine.native.js +1162 -1216
  132. package/dist/cjs/sync/mutationEngine.native.js.map +1 -1
  133. package/dist/cjs/sync/mutationJournal.cjs +147 -149
  134. package/dist/cjs/sync/mutationJournal.native.cjs +302 -0
  135. package/dist/cjs/sync/mutationJournal.native.js +278 -269
  136. package/dist/cjs/sync/mutationJournal.native.js.map +1 -1
  137. package/dist/cjs/sync/normalizedCache.cjs +127 -134
  138. package/dist/cjs/sync/normalizedCache.native.cjs +232 -0
  139. package/dist/cjs/sync/normalizedCache.native.js +212 -212
  140. package/dist/cjs/sync/normalizedCache.native.js.map +1 -1
  141. package/dist/cjs/sync/persistence.cjs +649 -661
  142. package/dist/cjs/sync/persistence.native.cjs +996 -0
  143. package/dist/cjs/sync/persistence.native.js +967 -965
  144. package/dist/cjs/sync/persistence.native.js.map +1 -1
  145. package/dist/cjs/sync/realtime.cjs +307 -315
  146. package/dist/cjs/sync/realtime.native.cjs +486 -0
  147. package/dist/cjs/sync/realtime.native.js +465 -461
  148. package/dist/cjs/sync/realtime.native.js.map +1 -1
  149. package/dist/cjs/sync/rehydration.cjs +279 -321
  150. package/dist/cjs/sync/rehydration.native.cjs +495 -0
  151. package/dist/cjs/sync/rehydration.native.js +473 -515
  152. package/dist/cjs/sync/rehydration.native.js.map +1 -1
  153. package/dist/cjs/sync/storage.cjs +127 -129
  154. package/dist/cjs/sync/storage.native.cjs +211 -0
  155. package/dist/cjs/sync/storage.native.js +188 -184
  156. package/dist/cjs/sync/storage.native.js.map +1 -1
  157. package/dist/cjs/sync/subscriptionManager.cjs +686 -708
  158. package/dist/cjs/sync/subscriptionManager.native.cjs +1205 -0
  159. package/dist/cjs/sync/subscriptionManager.native.js +1179 -1220
  160. package/dist/cjs/sync/subscriptionManager.native.js.map +1 -1
  161. package/dist/cjs/sync/types.cjs +79 -81
  162. package/dist/cjs/sync/types.native.cjs +103 -0
  163. package/dist/cjs/sync/types.native.js +89 -90
  164. package/dist/cjs/sync/types.native.js.map +1 -1
  165. package/dist/cjs/sync/virtualPageManager.cjs +762 -806
  166. package/dist/cjs/sync/virtualPageManager.native.cjs +1097 -0
  167. package/dist/cjs/sync/virtualPageManager.native.js +1072 -1097
  168. package/dist/cjs/sync/virtualPageManager.native.js.map +1 -1
  169. package/dist/cjs/syncOptionsKey.cjs +38 -45
  170. package/dist/cjs/syncOptionsKey.native.cjs +69 -0
  171. package/dist/cjs/syncOptionsKey.native.js +51 -63
  172. package/dist/cjs/syncOptionsKey.native.js.map +1 -1
  173. package/dist/cjs/useLiveQuery.cjs +14 -18
  174. package/dist/cjs/useLiveQuery.native.cjs +26 -0
  175. package/dist/cjs/useLiveQuery.native.js +14 -17
  176. package/dist/cjs/useLiveQuery.native.js.map +1 -1
  177. package/dist/cjs/util.cjs +22 -24
  178. package/dist/cjs/util.native.cjs +40 -0
  179. package/dist/cjs/util.native.js +22 -28
  180. package/dist/cjs/util.native.js.map +1 -1
  181. package/dist/esm/auth.mjs +22 -27
  182. package/dist/esm/auth.mjs.map +1 -1
  183. package/dist/esm/auth.native.js +64 -65
  184. package/dist/esm/auth.native.js.map +1 -1
  185. package/dist/esm/call.mjs +19 -18
  186. package/dist/esm/call.mjs.map +1 -1
  187. package/dist/esm/call.native.js +59 -54
  188. package/dist/esm/call.native.js.map +1 -1
  189. package/dist/esm/collection.mjs +228 -268
  190. package/dist/esm/collection.mjs.map +1 -1
  191. package/dist/esm/collection.native.js +421 -481
  192. package/dist/esm/collection.native.js.map +1 -1
  193. package/dist/esm/common/types.mjs +0 -2
  194. package/dist/esm/common/types.native.js +0 -2
  195. package/dist/esm/connectionKey.mjs +5 -4
  196. package/dist/esm/connectionKey.mjs.map +1 -1
  197. package/dist/esm/connectionKey.native.js +6 -5
  198. package/dist/esm/connectionKey.native.js.map +1 -1
  199. package/dist/esm/core/http.mjs +383 -382
  200. package/dist/esm/core/http.mjs.map +1 -1
  201. package/dist/esm/core/http.native.js +590 -591
  202. package/dist/esm/core/http.native.js.map +1 -1
  203. package/dist/esm/core/serverMessages.mjs +34 -26
  204. package/dist/esm/core/serverMessages.mjs.map +1 -1
  205. package/dist/esm/core/serverMessages.native.js +55 -54
  206. package/dist/esm/core/serverMessages.native.js.map +1 -1
  207. package/dist/esm/core/sessionGate.mjs +79 -79
  208. package/dist/esm/core/sessionGate.mjs.map +1 -1
  209. package/dist/esm/core/sessionGate.native.js +205 -215
  210. package/dist/esm/core/sessionGate.native.js.map +1 -1
  211. package/dist/esm/core/types.mjs +23 -22
  212. package/dist/esm/core/types.mjs.map +1 -1
  213. package/dist/esm/core/types.native.js +114 -119
  214. package/dist/esm/core/types.native.js.map +1 -1
  215. package/dist/esm/core/wire.mjs +10 -9
  216. package/dist/esm/core/wire.mjs.map +1 -1
  217. package/dist/esm/core/wire.native.js +10 -9
  218. package/dist/esm/core/wire.native.js.map +1 -1
  219. package/dist/esm/db.mjs +421 -432
  220. package/dist/esm/db.mjs.map +1 -1
  221. package/dist/esm/db.native.js +570 -574
  222. package/dist/esm/db.native.js.map +1 -1
  223. package/dist/esm/devtools/FrappeDevtoolsPanel.mjs +762 -781
  224. package/dist/esm/devtools/FrappeDevtoolsPanel.mjs.map +1 -1
  225. package/dist/esm/devtools/FrappeDevtoolsPanel.native.js +808 -839
  226. package/dist/esm/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  227. package/dist/esm/devtools/index.mjs +2 -2
  228. package/dist/esm/devtools/index.native.js +2 -2
  229. package/dist/esm/devtools/plugin.mjs +10 -8
  230. package/dist/esm/devtools/plugin.mjs.map +1 -1
  231. package/dist/esm/devtools/plugin.native.js +14 -12
  232. package/dist/esm/devtools/plugin.native.js.map +1 -1
  233. package/dist/esm/devtools/theme.mjs +27 -26
  234. package/dist/esm/devtools/theme.mjs.map +1 -1
  235. package/dist/esm/devtools/theme.native.js +27 -26
  236. package/dist/esm/devtools/theme.native.js.map +1 -1
  237. package/dist/esm/doctype.mjs +473 -416
  238. package/dist/esm/doctype.mjs.map +1 -1
  239. package/dist/esm/doctype.native.js +566 -539
  240. package/dist/esm/doctype.native.js.map +1 -1
  241. package/dist/esm/file.mjs +15 -14
  242. package/dist/esm/file.mjs.map +1 -1
  243. package/dist/esm/file.native.js +45 -45
  244. package/dist/esm/file.native.js.map +1 -1
  245. package/dist/esm/fixtureDb.mjs +175 -191
  246. package/dist/esm/fixtureDb.mjs.map +1 -1
  247. package/dist/esm/fixtureDb.native.js +279 -283
  248. package/dist/esm/fixtureDb.native.js.map +1 -1
  249. package/dist/esm/fixtures.mjs +161 -175
  250. package/dist/esm/fixtures.mjs.map +1 -1
  251. package/dist/esm/fixtures.native.js +346 -364
  252. package/dist/esm/fixtures.native.js.map +1 -1
  253. package/dist/esm/frappeApp.mjs +82 -83
  254. package/dist/esm/frappeApp.mjs.map +1 -1
  255. package/dist/esm/frappeApp.native.js +141 -135
  256. package/dist/esm/frappeApp.native.js.map +1 -1
  257. package/dist/esm/frappeReact.mjs +535 -504
  258. package/dist/esm/frappeReact.mjs.map +1 -1
  259. package/dist/esm/frappeReact.native.js +615 -607
  260. package/dist/esm/frappeReact.native.js.map +1 -1
  261. package/dist/esm/index.gnome.mjs +5 -5
  262. package/dist/esm/index.gnome.native.js +5 -5
  263. package/dist/esm/index.mjs +17 -18
  264. package/dist/esm/index.native.js +17 -18
  265. package/dist/esm/optimistic.mjs +19 -19
  266. package/dist/esm/optimistic.mjs.map +1 -1
  267. package/dist/esm/optimistic.native.js +22 -22
  268. package/dist/esm/optimistic.native.js.map +1 -1
  269. package/dist/esm/pacer.mjs +156 -158
  270. package/dist/esm/pacer.mjs.map +1 -1
  271. package/dist/esm/pacer.native.js +220 -228
  272. package/dist/esm/pacer.native.js.map +1 -1
  273. package/dist/esm/plugin/index.mjs +91 -94
  274. package/dist/esm/plugin/index.mjs.map +1 -1
  275. package/dist/esm/plugin/index.native.js +151 -160
  276. package/dist/esm/plugin/index.native.js.map +1 -1
  277. package/dist/esm/realtime.mjs +569 -594
  278. package/dist/esm/realtime.mjs.map +1 -1
  279. package/dist/esm/realtime.native.js +905 -912
  280. package/dist/esm/realtime.native.js.map +1 -1
  281. package/dist/esm/serverLoaders.mjs +47 -61
  282. package/dist/esm/serverLoaders.mjs.map +1 -1
  283. package/dist/esm/serverLoaders.native.js +56 -75
  284. package/dist/esm/serverLoaders.native.js.map +1 -1
  285. package/dist/esm/sync/backfill.mjs +268 -284
  286. package/dist/esm/sync/backfill.mjs.map +1 -1
  287. package/dist/esm/sync/backfill.native.js +435 -448
  288. package/dist/esm/sync/backfill.native.js.map +1 -1
  289. package/dist/esm/sync/filters.mjs +286 -241
  290. package/dist/esm/sync/filters.mjs.map +1 -1
  291. package/dist/esm/sync/filters.native.js +403 -373
  292. package/dist/esm/sync/filters.native.js.map +1 -1
  293. package/dist/esm/sync/index.mjs +465 -479
  294. package/dist/esm/sync/index.mjs.map +1 -1
  295. package/dist/esm/sync/index.native.js +726 -720
  296. package/dist/esm/sync/index.native.js.map +1 -1
  297. package/dist/esm/sync/merge.mjs +368 -366
  298. package/dist/esm/sync/merge.mjs.map +1 -1
  299. package/dist/esm/sync/merge.native.js +618 -647
  300. package/dist/esm/sync/merge.native.js.map +1 -1
  301. package/dist/esm/sync/mutationEngine.mjs +775 -814
  302. package/dist/esm/sync/mutationEngine.mjs.map +1 -1
  303. package/dist/esm/sync/mutationEngine.native.js +1152 -1202
  304. package/dist/esm/sync/mutationEngine.native.js.map +1 -1
  305. package/dist/esm/sync/mutationJournal.mjs +135 -133
  306. package/dist/esm/sync/mutationJournal.mjs.map +1 -1
  307. package/dist/esm/sync/mutationJournal.native.js +265 -253
  308. package/dist/esm/sync/mutationJournal.native.js.map +1 -1
  309. package/dist/esm/sync/normalizedCache.mjs +115 -117
  310. package/dist/esm/sync/normalizedCache.mjs.map +1 -1
  311. package/dist/esm/sync/normalizedCache.native.js +199 -195
  312. package/dist/esm/sync/normalizedCache.native.js.map +1 -1
  313. package/dist/esm/sync/persistence.mjs +637 -645
  314. package/dist/esm/sync/persistence.mjs.map +1 -1
  315. package/dist/esm/sync/persistence.native.js +954 -949
  316. package/dist/esm/sync/persistence.native.js.map +1 -1
  317. package/dist/esm/sync/realtime.mjs +296 -298
  318. package/dist/esm/sync/realtime.mjs.map +1 -1
  319. package/dist/esm/sync/realtime.native.js +453 -444
  320. package/dist/esm/sync/realtime.native.js.map +1 -1
  321. package/dist/esm/sync/rehydration.mjs +268 -304
  322. package/dist/esm/sync/rehydration.mjs.map +1 -1
  323. package/dist/esm/sync/rehydration.native.js +461 -498
  324. package/dist/esm/sync/rehydration.native.js.map +1 -1
  325. package/dist/esm/sync/storage.mjs +115 -113
  326. package/dist/esm/sync/storage.mjs.map +1 -1
  327. package/dist/esm/sync/storage.native.js +175 -168
  328. package/dist/esm/sync/storage.native.js.map +1 -1
  329. package/dist/esm/sync/subscriptionManager.mjs +675 -691
  330. package/dist/esm/sync/subscriptionManager.mjs.map +1 -1
  331. package/dist/esm/sync/subscriptionManager.native.js +1168 -1204
  332. package/dist/esm/sync/subscriptionManager.native.js.map +1 -1
  333. package/dist/esm/sync/types.mjs +56 -55
  334. package/dist/esm/sync/types.mjs.map +1 -1
  335. package/dist/esm/sync/types.native.js +66 -65
  336. package/dist/esm/sync/types.native.js.map +1 -1
  337. package/dist/esm/sync/virtualPageManager.mjs +749 -789
  338. package/dist/esm/sync/virtualPageManager.mjs.map +1 -1
  339. package/dist/esm/sync/virtualPageManager.native.js +1058 -1080
  340. package/dist/esm/sync/virtualPageManager.native.js.map +1 -1
  341. package/dist/esm/syncOptionsKey.mjs +25 -27
  342. package/dist/esm/syncOptionsKey.mjs.map +1 -1
  343. package/dist/esm/syncOptionsKey.native.js +38 -46
  344. package/dist/esm/syncOptionsKey.native.js.map +1 -1
  345. package/dist/esm/useLiveQuery.mjs +2 -2
  346. package/dist/esm/useLiveQuery.native.js +2 -2
  347. package/dist/esm/util.mjs +9 -7
  348. package/dist/esm/util.mjs.map +1 -1
  349. package/dist/esm/util.native.js +8 -11
  350. package/dist/esm/util.native.js.map +1 -1
  351. package/dist/jsx/auth.mjs +22 -27
  352. package/dist/jsx/auth.mjs.map +1 -1
  353. package/dist/jsx/auth.native.cjs +97 -0
  354. package/dist/jsx/auth.native.js +77 -82
  355. package/dist/jsx/auth.native.js.map +1 -1
  356. package/dist/jsx/call.mjs +19 -18
  357. package/dist/jsx/call.mjs.map +1 -1
  358. package/dist/jsx/call.native.cjs +92 -0
  359. package/dist/jsx/call.native.js +72 -71
  360. package/dist/jsx/call.native.js.map +1 -1
  361. package/dist/jsx/collection.mjs +228 -268
  362. package/dist/jsx/collection.mjs.map +1 -1
  363. package/dist/jsx/collection.native.cjs +461 -0
  364. package/dist/jsx/collection.native.js +436 -499
  365. package/dist/jsx/collection.native.js.map +1 -1
  366. package/dist/jsx/common/types.mjs +0 -2
  367. package/dist/jsx/common/types.native.cjs +18 -0
  368. package/dist/jsx/common/types.native.js +9 -10
  369. package/dist/jsx/common/types.native.js.map +1 -1
  370. package/dist/jsx/connectionKey.mjs +5 -4
  371. package/dist/jsx/connectionKey.mjs.map +1 -1
  372. package/dist/jsx/connectionKey.native.cjs +32 -0
  373. package/dist/jsx/connectionKey.native.js +19 -22
  374. package/dist/jsx/connectionKey.native.js.map +1 -1
  375. package/dist/jsx/core/http.mjs +383 -382
  376. package/dist/jsx/core/http.mjs.map +1 -1
  377. package/dist/jsx/core/http.native.cjs +659 -0
  378. package/dist/jsx/core/http.native.js +611 -615
  379. package/dist/jsx/core/http.native.js.map +1 -1
  380. package/dist/jsx/core/serverMessages.mjs +34 -26
  381. package/dist/jsx/core/serverMessages.mjs.map +1 -1
  382. package/dist/jsx/core/serverMessages.native.cjs +89 -0
  383. package/dist/jsx/core/serverMessages.native.js +69 -70
  384. package/dist/jsx/core/serverMessages.native.js.map +1 -1
  385. package/dist/jsx/core/sessionGate.mjs +79 -79
  386. package/dist/jsx/core/sessionGate.mjs.map +1 -1
  387. package/dist/jsx/core/sessionGate.native.cjs +270 -0
  388. package/dist/jsx/core/sessionGate.native.js +220 -232
  389. package/dist/jsx/core/sessionGate.native.js.map +1 -1
  390. package/dist/jsx/core/types.mjs +23 -22
  391. package/dist/jsx/core/types.mjs.map +1 -1
  392. package/dist/jsx/core/types.native.cjs +169 -0
  393. package/dist/jsx/core/types.native.js +129 -136
  394. package/dist/jsx/core/types.native.js.map +1 -1
  395. package/dist/jsx/core/wire.mjs +10 -9
  396. package/dist/jsx/core/wire.mjs.map +1 -1
  397. package/dist/jsx/core/wire.native.cjs +53 -0
  398. package/dist/jsx/core/wire.native.js +28 -29
  399. package/dist/jsx/core/wire.native.js.map +1 -1
  400. package/dist/jsx/db.mjs +421 -432
  401. package/dist/jsx/db.mjs.map +1 -1
  402. package/dist/jsx/db.native.cjs +625 -0
  403. package/dist/jsx/db.native.js +583 -590
  404. package/dist/jsx/db.native.js.map +1 -1
  405. package/dist/jsx/devtools/FrappeDevtoolsPanel.mjs +762 -781
  406. package/dist/jsx/devtools/FrappeDevtoolsPanel.mjs.map +1 -1
  407. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.cjs +878 -0
  408. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.js +821 -862
  409. package/dist/jsx/devtools/FrappeDevtoolsPanel.native.js.map +1 -1
  410. package/dist/jsx/devtools/index.mjs +2 -2
  411. package/dist/jsx/devtools/index.native.cjs +30 -0
  412. package/dist/jsx/devtools/index.native.js +15 -16
  413. package/dist/jsx/devtools/index.native.js.map +1 -1
  414. package/dist/jsx/devtools/plugin.mjs +10 -8
  415. package/dist/jsx/devtools/plugin.mjs.map +1 -1
  416. package/dist/jsx/devtools/plugin.native.cjs +46 -0
  417. package/dist/jsx/devtools/plugin.native.js +27 -35
  418. package/dist/jsx/devtools/plugin.native.js.map +1 -1
  419. package/dist/jsx/devtools/theme.mjs +27 -26
  420. package/dist/jsx/devtools/theme.mjs.map +1 -1
  421. package/dist/jsx/devtools/theme.native.cjs +53 -0
  422. package/dist/jsx/devtools/theme.native.js +40 -43
  423. package/dist/jsx/devtools/theme.native.js.map +1 -1
  424. package/dist/jsx/doctype.mjs +473 -416
  425. package/dist/jsx/doctype.mjs.map +1 -1
  426. package/dist/jsx/doctype.native.cjs +631 -0
  427. package/dist/jsx/doctype.native.js +587 -563
  428. package/dist/jsx/doctype.native.js.map +1 -1
  429. package/dist/jsx/file.mjs +15 -14
  430. package/dist/jsx/file.mjs.map +1 -1
  431. package/dist/jsx/file.native.cjs +78 -0
  432. package/dist/jsx/file.native.js +58 -62
  433. package/dist/jsx/file.native.js.map +1 -1
  434. package/dist/jsx/fixtureDb.mjs +175 -191
  435. package/dist/jsx/fixtureDb.mjs.map +1 -1
  436. package/dist/jsx/fixtureDb.native.cjs +313 -0
  437. package/dist/jsx/fixtureDb.native.js +291 -300
  438. package/dist/jsx/fixtureDb.native.js.map +1 -1
  439. package/dist/jsx/fixtures.mjs +161 -175
  440. package/dist/jsx/fixtures.mjs.map +1 -1
  441. package/dist/jsx/fixtures.native.cjs +379 -0
  442. package/dist/jsx/fixtures.native.js +359 -381
  443. package/dist/jsx/fixtures.native.js.map +1 -1
  444. package/dist/jsx/frappeApp.mjs +82 -83
  445. package/dist/jsx/frappeApp.mjs.map +1 -1
  446. package/dist/jsx/frappeApp.native.cjs +181 -0
  447. package/dist/jsx/frappeApp.native.js +153 -152
  448. package/dist/jsx/frappeApp.native.js.map +1 -1
  449. package/dist/jsx/frappeReact.mjs +535 -504
  450. package/dist/jsx/frappeReact.mjs.map +1 -1
  451. package/dist/jsx/frappeReact.native.cjs +710 -0
  452. package/dist/jsx/frappeReact.native.js +636 -631
  453. package/dist/jsx/frappeReact.native.js.map +1 -1
  454. package/dist/jsx/index.gnome.mjs +5 -5
  455. package/dist/jsx/index.gnome.native.cjs +87 -0
  456. package/dist/jsx/index.gnome.native.js +61 -62
  457. package/dist/jsx/index.gnome.native.js.map +1 -1
  458. package/dist/jsx/index.js +17 -18
  459. package/dist/jsx/index.mjs +17 -18
  460. package/dist/jsx/index.native.cjs +171 -0
  461. package/dist/jsx/index.native.js +128 -134
  462. package/dist/jsx/index.native.js.map +1 -1
  463. package/dist/jsx/optimistic.mjs +19 -19
  464. package/dist/jsx/optimistic.mjs.map +1 -1
  465. package/dist/jsx/optimistic.native.cjs +59 -0
  466. package/dist/jsx/optimistic.native.js +38 -41
  467. package/dist/jsx/optimistic.native.js.map +1 -1
  468. package/dist/jsx/pacer.mjs +156 -158
  469. package/dist/jsx/pacer.mjs.map +1 -1
  470. package/dist/jsx/pacer.native.cjs +263 -0
  471. package/dist/jsx/pacer.native.js +234 -245
  472. package/dist/jsx/pacer.native.js.map +1 -1
  473. package/dist/jsx/plugin/index.mjs +91 -94
  474. package/dist/jsx/plugin/index.mjs.map +1 -1
  475. package/dist/jsx/plugin/index.native.cjs +178 -0
  476. package/dist/jsx/plugin/index.native.js +164 -177
  477. package/dist/jsx/plugin/index.native.js.map +1 -1
  478. package/dist/jsx/realtime.mjs +569 -594
  479. package/dist/jsx/realtime.mjs.map +1 -1
  480. package/dist/jsx/realtime.native.cjs +945 -0
  481. package/dist/jsx/realtime.native.js +918 -928
  482. package/dist/jsx/realtime.native.js.map +1 -1
  483. package/dist/jsx/serverLoaders.mjs +47 -61
  484. package/dist/jsx/serverLoaders.mjs.map +1 -1
  485. package/dist/jsx/serverLoaders.native.cjs +103 -0
  486. package/dist/jsx/serverLoaders.native.js +73 -95
  487. package/dist/jsx/serverLoaders.native.js.map +1 -1
  488. package/dist/jsx/sync/backfill.mjs +268 -284
  489. package/dist/jsx/sync/backfill.mjs.map +1 -1
  490. package/dist/jsx/sync/backfill.native.cjs +475 -0
  491. package/dist/jsx/sync/backfill.native.js +449 -465
  492. package/dist/jsx/sync/backfill.native.js.map +1 -1
  493. package/dist/jsx/sync/filters.mjs +286 -241
  494. package/dist/jsx/sync/filters.mjs.map +1 -1
  495. package/dist/jsx/sync/filters.native.cjs +472 -0
  496. package/dist/jsx/sync/filters.native.js +426 -398
  497. package/dist/jsx/sync/filters.native.js.map +1 -1
  498. package/dist/jsx/sync/index.mjs +465 -479
  499. package/dist/jsx/sync/index.mjs.map +1 -1
  500. package/dist/jsx/sync/index.native.cjs +771 -0
  501. package/dist/jsx/sync/index.native.js +738 -737
  502. package/dist/jsx/sync/index.native.js.map +1 -1
  503. package/dist/jsx/sync/merge.mjs +368 -366
  504. package/dist/jsx/sync/merge.mjs.map +1 -1
  505. package/dist/jsx/sync/merge.native.cjs +681 -0
  506. package/dist/jsx/sync/merge.native.js +642 -673
  507. package/dist/jsx/sync/merge.native.js.map +1 -1
  508. package/dist/jsx/sync/mutationEngine.mjs +775 -814
  509. package/dist/jsx/sync/mutationEngine.mjs.map +1 -1
  510. package/dist/jsx/sync/mutationEngine.native.cjs +1190 -0
  511. package/dist/jsx/sync/mutationEngine.native.js +1162 -1216
  512. package/dist/jsx/sync/mutationEngine.native.js.map +1 -1
  513. package/dist/jsx/sync/mutationJournal.mjs +135 -133
  514. package/dist/jsx/sync/mutationJournal.mjs.map +1 -1
  515. package/dist/jsx/sync/mutationJournal.native.cjs +302 -0
  516. package/dist/jsx/sync/mutationJournal.native.js +278 -269
  517. package/dist/jsx/sync/mutationJournal.native.js.map +1 -1
  518. package/dist/jsx/sync/normalizedCache.mjs +115 -117
  519. package/dist/jsx/sync/normalizedCache.mjs.map +1 -1
  520. package/dist/jsx/sync/normalizedCache.native.cjs +232 -0
  521. package/dist/jsx/sync/normalizedCache.native.js +212 -212
  522. package/dist/jsx/sync/normalizedCache.native.js.map +1 -1
  523. package/dist/jsx/sync/persistence.mjs +637 -645
  524. package/dist/jsx/sync/persistence.mjs.map +1 -1
  525. package/dist/jsx/sync/persistence.native.cjs +996 -0
  526. package/dist/jsx/sync/persistence.native.js +967 -965
  527. package/dist/jsx/sync/persistence.native.js.map +1 -1
  528. package/dist/jsx/sync/realtime.mjs +296 -298
  529. package/dist/jsx/sync/realtime.mjs.map +1 -1
  530. package/dist/jsx/sync/realtime.native.cjs +486 -0
  531. package/dist/jsx/sync/realtime.native.js +465 -461
  532. package/dist/jsx/sync/realtime.native.js.map +1 -1
  533. package/dist/jsx/sync/rehydration.mjs +268 -304
  534. package/dist/jsx/sync/rehydration.mjs.map +1 -1
  535. package/dist/jsx/sync/rehydration.native.cjs +495 -0
  536. package/dist/jsx/sync/rehydration.native.js +473 -515
  537. package/dist/jsx/sync/rehydration.native.js.map +1 -1
  538. package/dist/jsx/sync/storage.mjs +115 -113
  539. package/dist/jsx/sync/storage.mjs.map +1 -1
  540. package/dist/jsx/sync/storage.native.cjs +211 -0
  541. package/dist/jsx/sync/storage.native.js +188 -184
  542. package/dist/jsx/sync/storage.native.js.map +1 -1
  543. package/dist/jsx/sync/subscriptionManager.mjs +675 -691
  544. package/dist/jsx/sync/subscriptionManager.mjs.map +1 -1
  545. package/dist/jsx/sync/subscriptionManager.native.cjs +1205 -0
  546. package/dist/jsx/sync/subscriptionManager.native.js +1179 -1220
  547. package/dist/jsx/sync/subscriptionManager.native.js.map +1 -1
  548. package/dist/jsx/sync/types.mjs +56 -55
  549. package/dist/jsx/sync/types.mjs.map +1 -1
  550. package/dist/jsx/sync/types.native.cjs +103 -0
  551. package/dist/jsx/sync/types.native.js +89 -90
  552. package/dist/jsx/sync/types.native.js.map +1 -1
  553. package/dist/jsx/sync/virtualPageManager.mjs +749 -789
  554. package/dist/jsx/sync/virtualPageManager.mjs.map +1 -1
  555. package/dist/jsx/sync/virtualPageManager.native.cjs +1097 -0
  556. package/dist/jsx/sync/virtualPageManager.native.js +1072 -1097
  557. package/dist/jsx/sync/virtualPageManager.native.js.map +1 -1
  558. package/dist/jsx/syncOptionsKey.mjs +25 -27
  559. package/dist/jsx/syncOptionsKey.mjs.map +1 -1
  560. package/dist/jsx/syncOptionsKey.native.cjs +69 -0
  561. package/dist/jsx/syncOptionsKey.native.js +51 -63
  562. package/dist/jsx/syncOptionsKey.native.js.map +1 -1
  563. package/dist/jsx/useLiveQuery.mjs +2 -2
  564. package/dist/jsx/useLiveQuery.native.cjs +26 -0
  565. package/dist/jsx/useLiveQuery.native.js +14 -17
  566. package/dist/jsx/useLiveQuery.native.js.map +1 -1
  567. package/dist/jsx/util.mjs +9 -7
  568. package/dist/jsx/util.mjs.map +1 -1
  569. package/dist/jsx/util.native.cjs +40 -0
  570. package/dist/jsx/util.native.js +22 -28
  571. package/dist/jsx/util.native.js.map +1 -1
  572. package/package.json +10 -10
  573. package/src/devtools/FrappeDevtoolsPanel.stories.tsx +16 -16
  574. package/src/devtools/plugin.stories.tsx +4 -4
  575. package/src/useFrappeCollection.stories.tsx +14 -14
  576. package/src/useFrappeInfiniteList.stories.tsx +11 -11
  577. package/src/useFrappePendingMutations.stories.tsx +12 -12
  578. package/types/devtools/FrappeDevtoolsPanel.d.ts +2 -1
  579. package/types/devtools/FrappeDevtoolsPanel.d.ts.map +1 -1
  580. package/types/devtools/plugin.d.ts +2 -1
  581. package/types/devtools/plugin.d.ts.map +1 -1
  582. package/dist/esm/common/types.mjs.map +0 -1
  583. package/dist/esm/common/types.native.js.map +0 -1
  584. package/dist/esm/devtools/index.mjs.map +0 -1
  585. package/dist/esm/devtools/index.native.js.map +0 -1
  586. package/dist/esm/index.gnome.mjs.map +0 -1
  587. package/dist/esm/index.gnome.native.js.map +0 -1
  588. package/dist/esm/index.mjs.map +0 -1
  589. package/dist/esm/index.native.js.map +0 -1
  590. package/dist/esm/useLiveQuery.mjs.map +0 -1
  591. package/dist/esm/useLiveQuery.native.js.map +0 -1
  592. package/dist/jsx/common/types.mjs.map +0 -1
  593. package/dist/jsx/devtools/index.mjs.map +0 -1
  594. package/dist/jsx/index.gnome.mjs.map +0 -1
  595. package/dist/jsx/index.js.map +0 -1
  596. package/dist/jsx/index.mjs.map +0 -1
  597. package/dist/jsx/useLiveQuery.mjs.map +0 -1
@@ -3,27 +3,25 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
5
  var __export = (target, all) => {
6
- for (var name in all) __defProp(target, name, {
7
- get: all[name],
8
- enumerable: true
9
- });
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
10
  };
11
11
  var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
- get: () => from[key],
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- return to;
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
19
  };
20
- var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
21
- value: true
22
- }), mod);
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
21
  var persistence_exports = {};
24
22
  __export(persistence_exports, {
25
- DEFAULT_STORAGE_READY_TIMEOUT_MS: () => DEFAULT_STORAGE_READY_TIMEOUT_MS,
26
- PersistenceManager: () => PersistenceManager
23
+ DEFAULT_STORAGE_READY_TIMEOUT_MS: () => DEFAULT_STORAGE_READY_TIMEOUT_MS,
24
+ PersistenceManager: () => PersistenceManager
27
25
  });
28
26
  module.exports = __toCommonJS(persistence_exports);
29
27
  var import_pacer = require("@tanstack/pacer");
@@ -32,649 +30,639 @@ var import_util = require("../util.cjs");
32
30
  var import_storage = require("./storage.cjs");
33
31
  const DEFAULT_STORAGE_READY_TIMEOUT_MS = 3e3;
34
32
  function getLocalStorage() {
35
- try {
36
- return typeof globalThis !== "undefined" && "localStorage" in globalThis ? globalThis.localStorage : void 0;
37
- } catch {
38
- return void 0;
39
- }
33
+ try {
34
+ return typeof globalThis !== "undefined" && "localStorage" in globalThis ? globalThis.localStorage : void 0;
35
+ } catch {
36
+ return void 0;
37
+ }
40
38
  }
41
- class PersistenceManager {
42
- persistenceStorage;
43
- saveDebouncer = new import_pacer.Debouncer(() => void this.save(), {
44
- wait: 50
45
- });
46
- broadcastChannel;
47
- // Active tab priority leadership state
48
- isLeader = false;
49
- tabId = this.generateTabId();
50
- leaderCheckInterval;
51
- visibilityState = "visible";
52
- lastVisibilityChange = Date.now();
53
- pendingOperations = /* @__PURE__ */new Set();
54
- acceptingNewWork = true;
55
- handoffInProgress = false;
56
- tabCoordinationConfig;
57
- leaderKey = "frappe-sync-leader";
58
- /** Cleanup function returned by the visibility change lifecycle subscription. */
59
- cleanupVisibilityChange;
60
- /** Active response timers that need cleanup. */
61
- activeResponseTimers = /* @__PURE__ */new Set();
62
- /** Flag to prevent operations after destroy. */
63
- isDestroyed = false;
64
- /**
65
- * Resolves once the persisted snapshot (if any) has been restored into
66
- * memory. Resolved immediately when persistence is disabled. Never rejects.
67
- */
68
- loadPromise = Promise.resolve();
69
- /** Set when the first read outlived its bound; a late answer is ignored. */
70
- loadAbandoned = false;
71
- loadTimer;
72
- normalizedCache;
73
- mutationJournal;
74
- subscriptionManager;
75
- mutationEngine;
76
- options;
77
- constructor(normalizedCache, mutationJournal, subscriptionManager, mutationEngine, options = {}) {
78
- this.normalizedCache = normalizedCache;
79
- this.mutationJournal = mutationJournal;
80
- this.subscriptionManager = subscriptionManager;
81
- this.mutationEngine = mutationEngine;
82
- this.options = options;
83
- this.tabCoordinationConfig = {
84
- activeTabPriority: options.tabCoordination?.activeTabPriority ?? true,
85
- leaderTimeout: options.tabCoordination?.leaderTimeout ?? 5e3,
86
- handoffGracePeriod: options.tabCoordination?.handoffGracePeriod ?? 2e3
87
- };
88
- if (import_platform.isNative || (0, import_util.isGjs)()) {
89
- this.setupPersistence();
90
- return;
91
- }
92
- if (typeof window === "undefined" || typeof document === "undefined") {
93
- return;
94
- }
95
- this.setupPersistence();
96
- this.setupBroadcastChannel();
97
- if (this.options.persistKey && this.tabCoordinationConfig.activeTabPriority) {
98
- this.setupTabCoordination();
99
- }
100
- }
101
- /**
102
- * Resolves when the initial snapshot restore has completed (immediately if
103
- * persistence is off). `SyncModule.subscribe` awaits this so a fresh mount
104
- * can re-adopt a restored subscription instead of racing the async load.
105
- */
106
- whenReady() {
107
- return this.loadPromise;
108
- }
109
- /**
110
- * Sets up persistence storage based on environment and options.
111
- */
112
- setupPersistence() {
113
- if (!this.options.persistKey) return;
114
- if (this.options.storage) {
115
- this.persistenceStorage = this.options.storage;
116
- } else if (typeof indexedDB !== "undefined") {
117
- this.persistenceStorage = new import_storage.IndexedDBKV();
118
- } else {
119
- if ((0, import_util.isGjs)()) {
120
- console.debug("[frappe-sync] persistKey set but no storage adapter on GJS \u2014 snapshots are in-memory only (pass SyncOptions.storage, e.g. a Gio file-backed KV, for real persistence)");
121
- }
122
- this.persistenceStorage = new import_storage.PlatformStorageKV();
123
- }
124
- this.loadPromise = this.loadWithin(this.options.storageReadyTimeout ?? DEFAULT_STORAGE_READY_TIMEOUT_MS);
125
- }
126
- loadWithin(timeoutMs) {
127
- const storage = this.persistenceStorage;
128
- const timedOut = new Promise(resolve => {
129
- this.loadTimer = setTimeout(() => resolve("timeout"), timeoutMs);
130
- });
131
- return Promise.race([this.load().then(() => "loaded"), timedOut]).then(outcome => {
132
- clearTimeout(this.loadTimer);
133
- this.loadTimer = void 0;
134
- if (outcome !== "timeout" || this.persistenceStorage !== storage) return;
135
- this.loadAbandoned = true;
136
- this.persistenceStorage = void 0;
137
- console.warn(`[frappe-sync] the storage for persistKey "${this.options.persistKey}" did not answer its first read within ${timeoutMs} ms; this session syncs in memory and persists nothing.`);
138
- });
139
- }
140
- /**
141
- * Sets up BroadcastChannel for cross-tab coordination.
142
- * Handles both simple string messages and structured TabMessage types.
143
- */
144
- setupBroadcastChannel() {
145
- if (!this.options.persistKey || typeof BroadcastChannel === "undefined") return;
146
- try {
147
- this.broadcastChannel = new BroadcastChannel(`frappe-sync:${this.options.persistKey}`);
148
- } catch {
149
- return;
150
- }
151
- this.broadcastChannel.onmessage = e => {
152
- if (typeof e?.data === "string") {
153
- if (e.data === "reset" && this.options.onResetCache) {
154
- this.options.onResetCache();
155
- }
156
- if (e.data === "backfill" && this.options.onBackfillAll) {
157
- this.options.onBackfillAll();
158
- }
159
- return;
160
- }
161
- const message = e?.data;
162
- if (!message || !message.type) return;
163
- switch (message.type) {
164
- case "visibility-check":
165
- if (message.fromTab !== this.tabId) {
166
- this.broadcastToTabs({
167
- type: "visibility-response",
168
- tabId: this.tabId,
169
- isVisible: this.visibilityState === "visible"
170
- });
171
- }
172
- break;
173
- case "leadership-request":
174
- if (this.isLeader && message.visibilityState === "visible" && this.visibilityState === "hidden") {
175
- this.initiateGracefulHandoff();
176
- }
177
- break;
178
- case "leadership-handoff":
179
- if (message.toTab === this.tabId) {
180
- if (message.state) {
181
- this.restoreStateFromHandoff(message.state);
182
- }
183
- this.becomeLeader();
184
- }
185
- break;
186
- case "mutation":
187
- if (!this.isLeader && message.mutation) {
188
- this.handleRemoteMutation(message.mutation);
189
- }
190
- break;
191
- case "sync-state":
192
- if (!this.isLeader && message.state) {
193
- this.restoreStateFromHandoff(message.state);
194
- }
195
- break;
196
- case "heartbeat":
197
- break;
198
- case "visibility-response":
199
- break;
200
- }
201
- };
202
- }
203
- /**
204
- * Handles a mutation relayed from another tab.
205
- * Updates local cache with the mutation's effects.
206
- */
207
- handleRemoteMutation(mutation) {
208
- if (mutation.doc) {
209
- if (mutation.operation === "delete") {
210
- this.normalizedCache.remove({
211
- doctype: mutation.doc.doctype,
212
- name: mutation.doc.name
213
- });
214
- } else {
215
- this.normalizedCache.upsert(mutation.doc);
216
- }
217
- }
218
- }
219
- /**
220
- * Broadcasts a mutation to other tabs.
221
- * Called by SyncModule after a successful mutation.
222
- */
223
- broadcastMutation(mutation) {
224
- if (!this.isLeader) return;
225
- this.broadcastToTabs({
226
- type: "mutation",
227
- mutation
228
- });
229
- }
230
- /**
231
- * Restores state received from a leadership handoff or sync-state message.
232
- */
233
- restoreStateFromHandoff(state) {
234
- if (!state || typeof state !== "object") return;
235
- const handoffState = state;
236
- if (handoffState.cache) {
237
- this.normalizedCache.state = handoffState.cache;
238
- }
239
- if (handoffState.subscriptions && Array.isArray(handoffState.subscriptions)) {
240
- const subscriptions = this.subscriptionManager.getAllSubscriptions();
241
- for (const subscription of handoffState.subscriptions) {
242
- if (subscription?.id) {
243
- subscriptions.set(subscription.id, subscription);
244
- }
245
- }
246
- }
247
- if (handoffState.tempMappings && Array.isArray(handoffState.tempMappings)) {
248
- const tempMap = this.mutationEngine.getTemporaryIdToRealNameMap();
249
- for (const [tempId, realId] of handoffState.tempMappings) {
250
- tempMap.set(tempId, realId);
251
- }
252
- }
253
- }
254
- /**
255
- * Schedules a debounced save operation.
256
- */
257
- scheduleSave() {
258
- if (!this.options.persistKey) return;
259
- this.saveDebouncer.maybeExecute();
260
- }
261
- /**
262
- * Persists a snapshot of subscriptions, cache, journal, and temp mappings.
263
- */
264
- async save() {
265
- if (!this.options.persistKey || !this.persistenceStorage) return;
266
- try {
267
- this.subscriptionManager.gcRestoredSubscriptions();
268
- const snapshot = {
269
- subs: [...this.subscriptionManager.getAllSubscriptions().values()].map(s => ({
270
- id: s.id,
271
- query: s.query,
272
- checkpoint: s.checkpoint,
273
- cursor: s.cursor,
274
- docIds: s.docIds
275
- })),
276
- cache: this.normalizedCache.state,
277
- journal: this.mutationJournal.listPending(),
278
- temp: [...this.mutationEngine.getTemporaryIdToRealNameMap().entries()]
279
- };
280
- await this.persistenceStorage.setItem(this.options.persistKey, JSON.stringify(snapshot));
281
- } catch (err) {
282
- console.warn("Failed to save sync state:", err);
283
- }
284
- }
285
- /**
286
- * Loads a previously persisted snapshot if present.
287
- */
288
- async load() {
289
- if (!this.options.persistKey || !this.persistenceStorage) return;
290
- try {
291
- const raw = await this.persistenceStorage.getItem(this.options.persistKey);
292
- if (!raw || this.loadAbandoned) return;
293
- const snap = JSON.parse(raw);
294
- if (snap?.cache && typeof snap.cache === "object") {
295
- for (const bucket of Object.values(snap.cache)) {
296
- const byId = bucket?.byId;
297
- if (!byId || typeof byId !== "object") continue;
298
- for (const doc of Object.values(byId)) {
299
- if (!doc?.doctype || !doc?.name) continue;
300
- if (this.normalizedCache.get(doc)) continue;
301
- this.normalizedCache.upsert(doc, {
302
- replace: true
303
- });
304
- }
305
- }
306
- }
307
- if (snap?.subs && Array.isArray(snap.subs)) {
308
- for (const subscription of snap.subs) {
309
- this.subscriptionManager.restoreSubscription(subscription);
310
- }
311
- }
312
- if (snap?.journal && Array.isArray(snap.journal)) {
313
- for (const {
314
- id,
315
- entry
316
- } of snap.journal) {
317
- this.mutationJournal.add(id, entry);
318
- }
319
- }
320
- if (snap?.temp && Array.isArray(snap.temp)) {
321
- const tempMap = this.mutationEngine.getTemporaryIdToRealNameMap();
322
- for (const [tempId, realId] of snap.temp) {
323
- tempMap.set(tempId, realId);
324
- }
325
- }
326
- } catch (err) {
327
- console.warn("Failed to load sync state:", err);
328
- }
329
- }
330
- /**
331
- * Broadcasts a reset message to other tabs.
332
- */
333
- broadcastReset() {
334
- if (this.broadcastChannel) {
335
- this.broadcastChannel.postMessage("reset");
336
- }
337
- }
338
- /**
339
- * Broadcasts a backfill message to other tabs.
340
- */
341
- broadcastBackfill() {
342
- if (this.broadcastChannel) {
343
- this.broadcastChannel.postMessage("backfill");
344
- }
345
- }
346
- /**
347
- * Broadcasts a generic change message to other tabs.
348
- */
349
- broadcastChange() {
350
- if (this.broadcastChannel) {
351
- this.broadcastChannel.postMessage("changed");
352
- }
353
- }
354
- /**
355
- * Sets up tab coordination with active tab priority.
356
- */
357
- setupTabCoordination() {
358
- this.visibilityState = typeof document !== "undefined" && document.hidden ? "hidden" : "visible";
359
- this.cleanupVisibilityChange = (0, import_platform.onVisibilityChange)(visible => {
360
- if (this.isDestroyed) return;
361
- const wasVisible = this.visibilityState === "visible";
362
- this.visibilityState = visible ? "visible" : "hidden";
363
- this.lastVisibilityChange = Date.now();
364
- if (!wasVisible && this.visibilityState === "visible") {
365
- this.evaluateLeadershipPriority();
366
- } else if (wasVisible && this.visibilityState === "hidden" && this.isLeader) {
367
- this.considerLeadershipHandoff();
368
- }
369
- });
370
- this.tryBecomeLeader();
371
- }
372
- /**
373
- * Attempts to become the leader tab.
374
- */
375
- tryBecomeLeader() {
376
- if (!getLocalStorage() || this.isDestroyed) return;
377
- const now = Date.now();
378
- const leaderData = this.getLeaderData();
379
- if (!leaderData || now - leaderData.timestamp > this.tabCoordinationConfig.leaderTimeout || this.visibilityState === "visible" && leaderData.visibilityState === "hidden") {
380
- this.becomeLeader();
381
- } else {
382
- if (this.leaderCheckInterval) {
383
- clearInterval(this.leaderCheckInterval);
384
- }
385
- this.leaderCheckInterval = setInterval(() => {
386
- if (!this.isDestroyed) {
387
- this.checkLeadership();
388
- }
389
- }, this.tabCoordinationConfig.leaderTimeout / 2);
390
- }
391
- }
392
- /**
393
- * Becomes the leader tab.
394
- */
395
- becomeLeader() {
396
- if (this.isDestroyed) return;
397
- this.isLeader = true;
398
- this.updateLeaderTimestamp();
399
- this.onBecomeLeader();
400
- if (this.leaderCheckInterval) {
401
- clearInterval(this.leaderCheckInterval);
402
- }
403
- this.leaderCheckInterval = setInterval(() => {
404
- if (!this.isDestroyed) {
405
- this.updateLeaderTimestamp();
406
- }
407
- }, this.tabCoordinationConfig.leaderTimeout / 2);
408
- }
409
- /**
410
- * Updates leader timestamp in localStorage.
411
- */
412
- updateLeaderTimestamp() {
413
- const ls = getLocalStorage();
414
- if (!ls) return;
415
- const leaderData = {
416
- tabId: this.tabId,
417
- timestamp: Date.now(),
418
- visibilityState: this.visibilityState,
419
- lastVisibilityChange: this.lastVisibilityChange
420
- };
421
- try {
422
- ls.setItem(this.leaderKey, JSON.stringify(leaderData));
423
- } catch (error) {
424
- console.warn("[PersistenceManager] Failed to update leader timestamp:", error);
425
- }
426
- }
427
- /**
428
- * Checks if this tab should remain leader.
429
- */
430
- checkLeadership() {
431
- const leaderData = this.getLeaderData();
432
- if (!leaderData) {
433
- this.tryBecomeLeader();
434
- return;
435
- }
436
- const now = Date.now();
437
- if (this.isLeader) {
438
- if (leaderData.tabId !== this.tabId) {
439
- this.isLeader = false;
440
- this.onLoseLeadership();
441
- }
442
- } else {
443
- if (now - leaderData.timestamp > this.tabCoordinationConfig.leaderTimeout || this.visibilityState === "visible" && leaderData.visibilityState === "hidden" && now - this.lastVisibilityChange > 1e3) {
444
- this.tryBecomeLeader();
445
- }
446
- }
447
- }
448
- /**
449
- * Gets current leader data from localStorage.
450
- */
451
- getLeaderData() {
452
- const ls = getLocalStorage();
453
- if (!ls) return null;
454
- try {
455
- const data = ls.getItem(this.leaderKey);
456
- return data ? JSON.parse(data) : null;
457
- } catch {
458
- return null;
459
- }
460
- }
461
- /**
462
- * Evaluates if this tab should take leadership based on visibility priority.
463
- */
464
- evaluateLeadershipPriority() {
465
- if (this.isLeader) return;
466
- const leaderData = this.getLeaderData();
467
- if (!leaderData) {
468
- this.tryBecomeLeader();
469
- return;
470
- }
471
- if (leaderData.visibilityState === "hidden" && this.visibilityState === "visible") {
472
- this.requestLeadershipHandoff();
473
- }
474
- }
475
- /**
476
- * Considers handing off leadership when tab becomes hidden.
477
- */
478
- considerLeadershipHandoff() {
479
- if (!this.isLeader) return;
480
- this.checkForActiveTabs(hasActiveTabs => {
481
- if (hasActiveTabs) {
482
- this.initiateGracefulHandoff();
483
- }
484
- });
485
- }
486
- /**
487
- * Requests leadership handoff from current leader.
488
- */
489
- requestLeadershipHandoff() {
490
- this.broadcastToTabs({
491
- type: "leadership-request",
492
- tabId: this.tabId,
493
- visibilityState: this.visibilityState
494
- });
495
- }
496
- /**
497
- * Initiates graceful handoff to another tab.
498
- */
499
- async initiateGracefulHandoff() {
500
- if (!this.isLeader || this.handoffInProgress) return;
501
- this.handoffInProgress = true;
502
- this.acceptingNewWork = false;
503
- await this.waitForPendingOperations();
504
- const successor = await this.findSuccessor();
505
- if (successor) {
506
- const state = await this.captureState();
507
- this.broadcastToTabs({
508
- type: "leadership-handoff",
509
- fromTab: this.tabId,
510
- toTab: successor,
511
- state
512
- });
513
- this.isLeader = false;
514
- this.onLoseLeadership();
515
- }
516
- this.handoffInProgress = false;
517
- this.acceptingNewWork = true;
518
- }
519
- /**
520
- * Waits for all pending operations to complete.
521
- */
522
- async waitForPendingOperations() {
523
- const timeout = new Promise(resolve => setTimeout(resolve, this.tabCoordinationConfig.handoffGracePeriod));
524
- const operations = Promise.all(this.pendingOperations);
525
- await Promise.race([operations, timeout]);
526
- }
527
- /**
528
- * Finds a suitable successor for leadership.
529
- */
530
- async findSuccessor() {
531
- return new Promise(resolve => {
532
- if (this.isDestroyed || typeof document === "undefined") {
533
- resolve(null);
534
- return;
535
- }
536
- const responses = [];
537
- const handleResponse = event => {
538
- if (event.data?.type === "visibility-response") {
539
- responses.push({
540
- tabId: event.data.tabId,
541
- isVisible: event.data.isVisible
542
- });
543
- }
544
- };
545
- window.addEventListener("message", handleResponse);
546
- this.broadcastToTabs({
547
- type: "visibility-check",
548
- fromTab: this.tabId
549
- });
550
- const responseTimer = setTimeout(() => {
551
- this.activeResponseTimers.delete(responseTimer);
552
- window.removeEventListener("message", handleResponse);
553
- const visibleTab = responses.find(r => r.isVisible);
554
- resolve(visibleTab ? visibleTab.tabId : responses[0]?.tabId || null);
555
- }, 500);
556
- this.activeResponseTimers.add(responseTimer);
557
- });
558
- }
559
- /**
560
- * Checks if there are other active tabs.
561
- */
562
- checkForActiveTabs(callback) {
563
- if (this.isDestroyed || typeof document === "undefined") {
564
- callback(false);
565
- return;
566
- }
567
- const responses = [];
568
- const handleResponse = event => {
569
- if (event.data?.type === "visibility-response") {
570
- responses.push(event.data.isVisible);
571
- }
572
- };
573
- window.addEventListener("message", handleResponse);
574
- this.broadcastToTabs({
575
- type: "visibility-check",
576
- fromTab: this.tabId
577
- });
578
- const responseTimer = setTimeout(() => {
579
- this.activeResponseTimers.delete(responseTimer);
580
- window.removeEventListener("message", handleResponse);
581
- callback(responses.some(isVisible => isVisible));
582
- }, 500);
583
- this.activeResponseTimers.add(responseTimer);
584
- }
585
- /**
586
- * Captures current state for handoff.
587
- */
588
- async captureState() {
589
- return {
590
- cache: this.normalizedCache.state,
591
- journal: this.mutationJournal.listPending(),
592
- subscriptions: [...this.subscriptionManager.getAllSubscriptions().values()],
593
- tempMappings: [...this.mutationEngine.getTemporaryIdToRealNameMap().entries()]
594
- };
595
- }
596
- /**
597
- * Broadcasts message to other tabs.
598
- */
599
- broadcastToTabs(message) {
600
- if (this.broadcastChannel) {
601
- this.broadcastChannel.postMessage(message);
602
- }
603
- const ls = getLocalStorage();
604
- if (ls) {
605
- try {
606
- const key = `frappe-sync-msg-${Date.now()}`;
607
- ls.setItem(key, JSON.stringify(message));
608
- setTimeout(() => ls.removeItem(key), 100);
609
- } catch {}
610
- }
611
- }
612
- /**
613
- * Handles becoming the leader.
614
- */
615
- onBecomeLeader() {
616
- console.debug(`[PersistenceManager] Tab ${this.tabId} became leader`);
617
- if (this.options.onBecomeLeader) {
618
- this.options.onBecomeLeader();
619
- }
620
- }
621
- /**
622
- * Handles losing leadership.
623
- */
624
- onLoseLeadership() {
625
- console.debug(`[PersistenceManager] Tab ${this.tabId} lost leadership`);
626
- if (this.leaderCheckInterval) {
627
- clearInterval(this.leaderCheckInterval);
628
- this.leaderCheckInterval = void 0;
629
- }
630
- if (this.options.onLoseLeadership) {
631
- this.options.onLoseLeadership();
632
- }
633
- }
634
- /**
635
- * Generates a unique tab ID.
636
- */
637
- generateTabId() {
638
- return `tab-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
639
- }
640
- /**
641
- * Tracks a pending operation.
642
- */
643
- trackOperation(operation) {
644
- this.pendingOperations.add(operation);
645
- operation.finally(() => {
646
- this.pendingOperations.delete(operation);
647
- }).catch(() => {});
648
- return operation;
649
- }
650
- /**
651
- * Gets whether this tab is the leader.
652
- */
653
- getIsLeader() {
654
- return this.isLeader;
655
- }
656
- /**
657
- * Cleans up timers, event listeners, and channels.
658
- */
659
- destroy() {
660
- this.isDestroyed = true;
661
- this.saveDebouncer.cancel();
662
- clearTimeout(this.loadTimer);
663
- this.loadTimer = void 0;
664
- if (this.leaderCheckInterval) {
665
- clearInterval(this.leaderCheckInterval);
666
- this.leaderCheckInterval = void 0;
667
- }
668
- for (const timer of this.activeResponseTimers) {
669
- clearTimeout(timer);
670
- }
671
- this.activeResponseTimers.clear();
672
- this.cleanupVisibilityChange?.();
673
- this.cleanupVisibilityChange = void 0;
674
- if (this.broadcastChannel) {
675
- this.broadcastChannel.close();
676
- this.broadcastChannel = void 0;
677
- }
678
- this.pendingOperations.clear();
679
- }
680
- }
39
+ var PersistenceManager = class {
40
+ persistenceStorage;
41
+ saveDebouncer = new import_pacer.Debouncer(() => void this.save(), { wait: 50 });
42
+ broadcastChannel;
43
+ isLeader = false;
44
+ tabId = this.generateTabId();
45
+ leaderCheckInterval;
46
+ visibilityState = "visible";
47
+ lastVisibilityChange = Date.now();
48
+ pendingOperations = /* @__PURE__ */ new Set();
49
+ acceptingNewWork = true;
50
+ handoffInProgress = false;
51
+ tabCoordinationConfig;
52
+ leaderKey = "frappe-sync-leader";
53
+ /** Cleanup function returned by the visibility change lifecycle subscription. */
54
+ cleanupVisibilityChange;
55
+ /** Active response timers that need cleanup. */
56
+ activeResponseTimers = /* @__PURE__ */ new Set();
57
+ /** Flag to prevent operations after destroy. */
58
+ isDestroyed = false;
59
+ /**
60
+ * Resolves once the persisted snapshot (if any) has been restored into
61
+ * memory. Resolved immediately when persistence is disabled. Never rejects.
62
+ */
63
+ loadPromise = Promise.resolve();
64
+ /** Set when the first read outlived its bound; a late answer is ignored. */
65
+ loadAbandoned = false;
66
+ loadTimer;
67
+ normalizedCache;
68
+ mutationJournal;
69
+ subscriptionManager;
70
+ mutationEngine;
71
+ options;
72
+ constructor(normalizedCache, mutationJournal, subscriptionManager, mutationEngine, options = {}) {
73
+ this.normalizedCache = normalizedCache;
74
+ this.mutationJournal = mutationJournal;
75
+ this.subscriptionManager = subscriptionManager;
76
+ this.mutationEngine = mutationEngine;
77
+ this.options = options;
78
+ this.tabCoordinationConfig = {
79
+ activeTabPriority: options.tabCoordination?.activeTabPriority ?? true,
80
+ leaderTimeout: options.tabCoordination?.leaderTimeout ?? 5e3,
81
+ handoffGracePeriod: options.tabCoordination?.handoffGracePeriod ?? 2e3
82
+ };
83
+ if (import_platform.isNative || (0, import_util.isGjs)()) {
84
+ this.setupPersistence();
85
+ return;
86
+ }
87
+ if (typeof window === "undefined" || typeof document === "undefined") {
88
+ return;
89
+ }
90
+ this.setupPersistence();
91
+ this.setupBroadcastChannel();
92
+ if (this.options.persistKey && this.tabCoordinationConfig.activeTabPriority) {
93
+ this.setupTabCoordination();
94
+ }
95
+ }
96
+ /**
97
+ * Resolves when the initial snapshot restore has completed (immediately if
98
+ * persistence is off). `SyncModule.subscribe` awaits this so a fresh mount
99
+ * can re-adopt a restored subscription instead of racing the async load.
100
+ */
101
+ whenReady() {
102
+ return this.loadPromise;
103
+ }
104
+ /**
105
+ * Sets up persistence storage based on environment and options.
106
+ */
107
+ setupPersistence() {
108
+ if (!this.options.persistKey) return;
109
+ if (this.options.storage) {
110
+ this.persistenceStorage = this.options.storage;
111
+ } else if (typeof indexedDB !== "undefined") {
112
+ this.persistenceStorage = new import_storage.IndexedDBKV();
113
+ } else {
114
+ if ((0, import_util.isGjs)()) {
115
+ console.debug("[frappe-sync] persistKey set but no storage adapter on GJS — snapshots are in-memory only (pass SyncOptions.storage, e.g. a Gio file-backed KV, for real persistence)");
116
+ }
117
+ this.persistenceStorage = new import_storage.PlatformStorageKV();
118
+ }
119
+ this.loadPromise = this.loadWithin(this.options.storageReadyTimeout ?? DEFAULT_STORAGE_READY_TIMEOUT_MS);
120
+ }
121
+ loadWithin(timeoutMs) {
122
+ const storage = this.persistenceStorage;
123
+ const timedOut = new Promise((resolve) => {
124
+ this.loadTimer = setTimeout(() => resolve("timeout"), timeoutMs);
125
+ });
126
+ return Promise.race([this.load().then(() => "loaded"), timedOut]).then((outcome) => {
127
+ clearTimeout(this.loadTimer);
128
+ this.loadTimer = void 0;
129
+ if (outcome !== "timeout" || this.persistenceStorage !== storage) return;
130
+ this.loadAbandoned = true;
131
+ this.persistenceStorage = void 0;
132
+ console.warn(`[frappe-sync] the storage for persistKey "${this.options.persistKey}" did not answer its first read within ${timeoutMs} ms; this session syncs in memory and persists nothing.`);
133
+ });
134
+ }
135
+ /**
136
+ * Sets up BroadcastChannel for cross-tab coordination.
137
+ * Handles both simple string messages and structured TabMessage types.
138
+ */
139
+ setupBroadcastChannel() {
140
+ if (!this.options.persistKey || typeof BroadcastChannel === "undefined") return;
141
+ try {
142
+ this.broadcastChannel = new BroadcastChannel(`frappe-sync:${this.options.persistKey}`);
143
+ } catch {
144
+ return;
145
+ }
146
+ this.broadcastChannel.onmessage = (e) => {
147
+ if (typeof e?.data === "string") {
148
+ if (e.data === "reset" && this.options.onResetCache) {
149
+ this.options.onResetCache();
150
+ }
151
+ if (e.data === "backfill" && this.options.onBackfillAll) {
152
+ this.options.onBackfillAll();
153
+ }
154
+ return;
155
+ }
156
+ const message = e?.data;
157
+ if (!message || !message.type) return;
158
+ switch (message.type) {
159
+ case "visibility-check":
160
+ if (message.fromTab !== this.tabId) {
161
+ this.broadcastToTabs({
162
+ type: "visibility-response",
163
+ tabId: this.tabId,
164
+ isVisible: this.visibilityState === "visible"
165
+ });
166
+ }
167
+ break;
168
+ case "leadership-request":
169
+ if (this.isLeader && message.visibilityState === "visible" && this.visibilityState === "hidden") {
170
+ this.initiateGracefulHandoff();
171
+ }
172
+ break;
173
+ case "leadership-handoff":
174
+ if (message.toTab === this.tabId) {
175
+ if (message.state) {
176
+ this.restoreStateFromHandoff(message.state);
177
+ }
178
+ this.becomeLeader();
179
+ }
180
+ break;
181
+ case "mutation":
182
+ if (!this.isLeader && message.mutation) {
183
+ this.handleRemoteMutation(message.mutation);
184
+ }
185
+ break;
186
+ case "sync-state":
187
+ if (!this.isLeader && message.state) {
188
+ this.restoreStateFromHandoff(message.state);
189
+ }
190
+ break;
191
+ case "heartbeat": break;
192
+ case "visibility-response": break;
193
+ }
194
+ };
195
+ }
196
+ /**
197
+ * Handles a mutation relayed from another tab.
198
+ * Updates local cache with the mutation's effects.
199
+ */
200
+ handleRemoteMutation(mutation) {
201
+ if (mutation.doc) {
202
+ if (mutation.operation === "delete") {
203
+ this.normalizedCache.remove({
204
+ doctype: mutation.doc.doctype,
205
+ name: mutation.doc.name
206
+ });
207
+ } else {
208
+ this.normalizedCache.upsert(mutation.doc);
209
+ }
210
+ }
211
+ }
212
+ /**
213
+ * Broadcasts a mutation to other tabs.
214
+ * Called by SyncModule after a successful mutation.
215
+ */
216
+ broadcastMutation(mutation) {
217
+ if (!this.isLeader) return;
218
+ this.broadcastToTabs({
219
+ type: "mutation",
220
+ mutation
221
+ });
222
+ }
223
+ /**
224
+ * Restores state received from a leadership handoff or sync-state message.
225
+ */
226
+ restoreStateFromHandoff(state) {
227
+ if (!state || typeof state !== "object") return;
228
+ const handoffState = state;
229
+ if (handoffState.cache) {
230
+ this.normalizedCache.state = handoffState.cache;
231
+ }
232
+ if (handoffState.subscriptions && Array.isArray(handoffState.subscriptions)) {
233
+ const subscriptions = this.subscriptionManager.getAllSubscriptions();
234
+ for (const subscription of handoffState.subscriptions) {
235
+ if (subscription?.id) {
236
+ subscriptions.set(subscription.id, subscription);
237
+ }
238
+ }
239
+ }
240
+ if (handoffState.tempMappings && Array.isArray(handoffState.tempMappings)) {
241
+ const tempMap = this.mutationEngine.getTemporaryIdToRealNameMap();
242
+ for (const [tempId, realId] of handoffState.tempMappings) {
243
+ tempMap.set(tempId, realId);
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * Schedules a debounced save operation.
249
+ */
250
+ scheduleSave() {
251
+ if (!this.options.persistKey) return;
252
+ this.saveDebouncer.maybeExecute();
253
+ }
254
+ /**
255
+ * Persists a snapshot of subscriptions, cache, journal, and temp mappings.
256
+ */
257
+ async save() {
258
+ if (!this.options.persistKey || !this.persistenceStorage) return;
259
+ try {
260
+ this.subscriptionManager.gcRestoredSubscriptions();
261
+ const snapshot = {
262
+ subs: [...this.subscriptionManager.getAllSubscriptions().values()].map((s) => ({
263
+ id: s.id,
264
+ query: s.query,
265
+ checkpoint: s.checkpoint,
266
+ cursor: s.cursor,
267
+ docIds: s.docIds
268
+ })),
269
+ cache: this.normalizedCache.state,
270
+ journal: this.mutationJournal.listPending(),
271
+ temp: [...this.mutationEngine.getTemporaryIdToRealNameMap().entries()]
272
+ };
273
+ await this.persistenceStorage.setItem(this.options.persistKey, JSON.stringify(snapshot));
274
+ } catch (err) {
275
+ console.warn("Failed to save sync state:", err);
276
+ }
277
+ }
278
+ /**
279
+ * Loads a previously persisted snapshot if present.
280
+ */
281
+ async load() {
282
+ if (!this.options.persistKey || !this.persistenceStorage) return;
283
+ try {
284
+ const raw = await this.persistenceStorage.getItem(this.options.persistKey);
285
+ if (!raw || this.loadAbandoned) return;
286
+ const snap = JSON.parse(raw);
287
+ if (snap?.cache && typeof snap.cache === "object") {
288
+ for (const bucket of Object.values(snap.cache)) {
289
+ const byId = bucket?.byId;
290
+ if (!byId || typeof byId !== "object") continue;
291
+ for (const doc of Object.values(byId)) {
292
+ if (!doc?.doctype || !doc?.name) continue;
293
+ if (this.normalizedCache.get(doc)) continue;
294
+ this.normalizedCache.upsert(doc, { replace: true });
295
+ }
296
+ }
297
+ }
298
+ if (snap?.subs && Array.isArray(snap.subs)) {
299
+ for (const subscription of snap.subs) {
300
+ this.subscriptionManager.restoreSubscription(subscription);
301
+ }
302
+ }
303
+ if (snap?.journal && Array.isArray(snap.journal)) {
304
+ for (const { id, entry } of snap.journal) {
305
+ this.mutationJournal.add(id, entry);
306
+ }
307
+ }
308
+ if (snap?.temp && Array.isArray(snap.temp)) {
309
+ const tempMap = this.mutationEngine.getTemporaryIdToRealNameMap();
310
+ for (const [tempId, realId] of snap.temp) {
311
+ tempMap.set(tempId, realId);
312
+ }
313
+ }
314
+ } catch (err) {
315
+ console.warn("Failed to load sync state:", err);
316
+ }
317
+ }
318
+ /**
319
+ * Broadcasts a reset message to other tabs.
320
+ */
321
+ broadcastReset() {
322
+ if (this.broadcastChannel) {
323
+ this.broadcastChannel.postMessage("reset");
324
+ }
325
+ }
326
+ /**
327
+ * Broadcasts a backfill message to other tabs.
328
+ */
329
+ broadcastBackfill() {
330
+ if (this.broadcastChannel) {
331
+ this.broadcastChannel.postMessage("backfill");
332
+ }
333
+ }
334
+ /**
335
+ * Broadcasts a generic change message to other tabs.
336
+ */
337
+ broadcastChange() {
338
+ if (this.broadcastChannel) {
339
+ this.broadcastChannel.postMessage("changed");
340
+ }
341
+ }
342
+ /**
343
+ * Sets up tab coordination with active tab priority.
344
+ */
345
+ setupTabCoordination() {
346
+ this.visibilityState = typeof document !== "undefined" && document.hidden ? "hidden" : "visible";
347
+ this.cleanupVisibilityChange = (0, import_platform.onVisibilityChange)((visible) => {
348
+ if (this.isDestroyed) return;
349
+ const wasVisible = this.visibilityState === "visible";
350
+ this.visibilityState = visible ? "visible" : "hidden";
351
+ this.lastVisibilityChange = Date.now();
352
+ if (!wasVisible && this.visibilityState === "visible") {
353
+ this.evaluateLeadershipPriority();
354
+ } else if (wasVisible && this.visibilityState === "hidden" && this.isLeader) {
355
+ this.considerLeadershipHandoff();
356
+ }
357
+ });
358
+ this.tryBecomeLeader();
359
+ }
360
+ /**
361
+ * Attempts to become the leader tab.
362
+ */
363
+ tryBecomeLeader() {
364
+ if (!getLocalStorage() || this.isDestroyed) return;
365
+ const now = Date.now();
366
+ const leaderData = this.getLeaderData();
367
+ if (!leaderData || now - leaderData.timestamp > this.tabCoordinationConfig.leaderTimeout || this.visibilityState === "visible" && leaderData.visibilityState === "hidden") {
368
+ this.becomeLeader();
369
+ } else {
370
+ if (this.leaderCheckInterval) {
371
+ clearInterval(this.leaderCheckInterval);
372
+ }
373
+ this.leaderCheckInterval = setInterval(() => {
374
+ if (!this.isDestroyed) {
375
+ this.checkLeadership();
376
+ }
377
+ }, this.tabCoordinationConfig.leaderTimeout / 2);
378
+ }
379
+ }
380
+ /**
381
+ * Becomes the leader tab.
382
+ */
383
+ becomeLeader() {
384
+ if (this.isDestroyed) return;
385
+ this.isLeader = true;
386
+ this.updateLeaderTimestamp();
387
+ this.onBecomeLeader();
388
+ if (this.leaderCheckInterval) {
389
+ clearInterval(this.leaderCheckInterval);
390
+ }
391
+ this.leaderCheckInterval = setInterval(() => {
392
+ if (!this.isDestroyed) {
393
+ this.updateLeaderTimestamp();
394
+ }
395
+ }, this.tabCoordinationConfig.leaderTimeout / 2);
396
+ }
397
+ /**
398
+ * Updates leader timestamp in localStorage.
399
+ */
400
+ updateLeaderTimestamp() {
401
+ const ls = getLocalStorage();
402
+ if (!ls) return;
403
+ const leaderData = {
404
+ tabId: this.tabId,
405
+ timestamp: Date.now(),
406
+ visibilityState: this.visibilityState,
407
+ lastVisibilityChange: this.lastVisibilityChange
408
+ };
409
+ try {
410
+ ls.setItem(this.leaderKey, JSON.stringify(leaderData));
411
+ } catch (error) {
412
+ console.warn("[PersistenceManager] Failed to update leader timestamp:", error);
413
+ }
414
+ }
415
+ /**
416
+ * Checks if this tab should remain leader.
417
+ */
418
+ checkLeadership() {
419
+ const leaderData = this.getLeaderData();
420
+ if (!leaderData) {
421
+ this.tryBecomeLeader();
422
+ return;
423
+ }
424
+ const now = Date.now();
425
+ if (this.isLeader) {
426
+ if (leaderData.tabId !== this.tabId) {
427
+ this.isLeader = false;
428
+ this.onLoseLeadership();
429
+ }
430
+ } else {
431
+ if (now - leaderData.timestamp > this.tabCoordinationConfig.leaderTimeout || this.visibilityState === "visible" && leaderData.visibilityState === "hidden" && now - this.lastVisibilityChange > 1e3) {
432
+ this.tryBecomeLeader();
433
+ }
434
+ }
435
+ }
436
+ /**
437
+ * Gets current leader data from localStorage.
438
+ */
439
+ getLeaderData() {
440
+ const ls = getLocalStorage();
441
+ if (!ls) return null;
442
+ try {
443
+ const data = ls.getItem(this.leaderKey);
444
+ return data ? JSON.parse(data) : null;
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
449
+ /**
450
+ * Evaluates if this tab should take leadership based on visibility priority.
451
+ */
452
+ evaluateLeadershipPriority() {
453
+ if (this.isLeader) return;
454
+ const leaderData = this.getLeaderData();
455
+ if (!leaderData) {
456
+ this.tryBecomeLeader();
457
+ return;
458
+ }
459
+ if (leaderData.visibilityState === "hidden" && this.visibilityState === "visible") {
460
+ this.requestLeadershipHandoff();
461
+ }
462
+ }
463
+ /**
464
+ * Considers handing off leadership when tab becomes hidden.
465
+ */
466
+ considerLeadershipHandoff() {
467
+ if (!this.isLeader) return;
468
+ this.checkForActiveTabs((hasActiveTabs) => {
469
+ if (hasActiveTabs) {
470
+ this.initiateGracefulHandoff();
471
+ }
472
+ });
473
+ }
474
+ /**
475
+ * Requests leadership handoff from current leader.
476
+ */
477
+ requestLeadershipHandoff() {
478
+ this.broadcastToTabs({
479
+ type: "leadership-request",
480
+ tabId: this.tabId,
481
+ visibilityState: this.visibilityState
482
+ });
483
+ }
484
+ /**
485
+ * Initiates graceful handoff to another tab.
486
+ */
487
+ async initiateGracefulHandoff() {
488
+ if (!this.isLeader || this.handoffInProgress) return;
489
+ this.handoffInProgress = true;
490
+ this.acceptingNewWork = false;
491
+ await this.waitForPendingOperations();
492
+ const successor = await this.findSuccessor();
493
+ if (successor) {
494
+ const state = await this.captureState();
495
+ this.broadcastToTabs({
496
+ type: "leadership-handoff",
497
+ fromTab: this.tabId,
498
+ toTab: successor,
499
+ state
500
+ });
501
+ this.isLeader = false;
502
+ this.onLoseLeadership();
503
+ }
504
+ this.handoffInProgress = false;
505
+ this.acceptingNewWork = true;
506
+ }
507
+ /**
508
+ * Waits for all pending operations to complete.
509
+ */
510
+ async waitForPendingOperations() {
511
+ const timeout = new Promise((resolve) => setTimeout(resolve, this.tabCoordinationConfig.handoffGracePeriod));
512
+ const operations = Promise.all(this.pendingOperations);
513
+ await Promise.race([operations, timeout]);
514
+ }
515
+ /**
516
+ * Finds a suitable successor for leadership.
517
+ */
518
+ async findSuccessor() {
519
+ return new Promise((resolve) => {
520
+ if (this.isDestroyed || typeof document === "undefined") {
521
+ resolve(null);
522
+ return;
523
+ }
524
+ const responses = [];
525
+ const handleResponse = (event) => {
526
+ if (event.data?.type === "visibility-response") {
527
+ responses.push({
528
+ tabId: event.data.tabId,
529
+ isVisible: event.data.isVisible
530
+ });
531
+ }
532
+ };
533
+ window.addEventListener("message", handleResponse);
534
+ this.broadcastToTabs({
535
+ type: "visibility-check",
536
+ fromTab: this.tabId
537
+ });
538
+ const responseTimer = setTimeout(() => {
539
+ this.activeResponseTimers.delete(responseTimer);
540
+ window.removeEventListener("message", handleResponse);
541
+ const visibleTab = responses.find((r) => r.isVisible);
542
+ resolve(visibleTab ? visibleTab.tabId : responses[0]?.tabId || null);
543
+ }, 500);
544
+ this.activeResponseTimers.add(responseTimer);
545
+ });
546
+ }
547
+ /**
548
+ * Checks if there are other active tabs.
549
+ */
550
+ checkForActiveTabs(callback) {
551
+ if (this.isDestroyed || typeof document === "undefined") {
552
+ callback(false);
553
+ return;
554
+ }
555
+ const responses = [];
556
+ const handleResponse = (event) => {
557
+ if (event.data?.type === "visibility-response") {
558
+ responses.push(event.data.isVisible);
559
+ }
560
+ };
561
+ window.addEventListener("message", handleResponse);
562
+ this.broadcastToTabs({
563
+ type: "visibility-check",
564
+ fromTab: this.tabId
565
+ });
566
+ const responseTimer = setTimeout(() => {
567
+ this.activeResponseTimers.delete(responseTimer);
568
+ window.removeEventListener("message", handleResponse);
569
+ callback(responses.some((isVisible) => isVisible));
570
+ }, 500);
571
+ this.activeResponseTimers.add(responseTimer);
572
+ }
573
+ /**
574
+ * Captures current state for handoff.
575
+ */
576
+ async captureState() {
577
+ return {
578
+ cache: this.normalizedCache.state,
579
+ journal: this.mutationJournal.listPending(),
580
+ subscriptions: [...this.subscriptionManager.getAllSubscriptions().values()],
581
+ tempMappings: [...this.mutationEngine.getTemporaryIdToRealNameMap().entries()]
582
+ };
583
+ }
584
+ /**
585
+ * Broadcasts message to other tabs.
586
+ */
587
+ broadcastToTabs(message) {
588
+ if (this.broadcastChannel) {
589
+ this.broadcastChannel.postMessage(message);
590
+ }
591
+ const ls = getLocalStorage();
592
+ if (ls) {
593
+ try {
594
+ const key = `frappe-sync-msg-${Date.now()}`;
595
+ ls.setItem(key, JSON.stringify(message));
596
+ setTimeout(() => ls.removeItem(key), 100);
597
+ } catch {}
598
+ }
599
+ }
600
+ /**
601
+ * Handles becoming the leader.
602
+ */
603
+ onBecomeLeader() {
604
+ console.debug(`[PersistenceManager] Tab ${this.tabId} became leader`);
605
+ if (this.options.onBecomeLeader) {
606
+ this.options.onBecomeLeader();
607
+ }
608
+ }
609
+ /**
610
+ * Handles losing leadership.
611
+ */
612
+ onLoseLeadership() {
613
+ console.debug(`[PersistenceManager] Tab ${this.tabId} lost leadership`);
614
+ if (this.leaderCheckInterval) {
615
+ clearInterval(this.leaderCheckInterval);
616
+ this.leaderCheckInterval = void 0;
617
+ }
618
+ if (this.options.onLoseLeadership) {
619
+ this.options.onLoseLeadership();
620
+ }
621
+ }
622
+ /**
623
+ * Generates a unique tab ID.
624
+ */
625
+ generateTabId() {
626
+ return `tab-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
627
+ }
628
+ /**
629
+ * Tracks a pending operation.
630
+ */
631
+ trackOperation(operation) {
632
+ this.pendingOperations.add(operation);
633
+ operation.finally(() => {
634
+ this.pendingOperations.delete(operation);
635
+ }).catch(() => {});
636
+ return operation;
637
+ }
638
+ /**
639
+ * Gets whether this tab is the leader.
640
+ */
641
+ getIsLeader() {
642
+ return this.isLeader;
643
+ }
644
+ /**
645
+ * Cleans up timers, event listeners, and channels.
646
+ */
647
+ destroy() {
648
+ this.isDestroyed = true;
649
+ this.saveDebouncer.cancel();
650
+ clearTimeout(this.loadTimer);
651
+ this.loadTimer = void 0;
652
+ if (this.leaderCheckInterval) {
653
+ clearInterval(this.leaderCheckInterval);
654
+ this.leaderCheckInterval = void 0;
655
+ }
656
+ for (const timer of this.activeResponseTimers) {
657
+ clearTimeout(timer);
658
+ }
659
+ this.activeResponseTimers.clear();
660
+ this.cleanupVisibilityChange?.();
661
+ this.cleanupVisibilityChange = void 0;
662
+ if (this.broadcastChannel) {
663
+ this.broadcastChannel.close();
664
+ this.broadcastChannel = void 0;
665
+ }
666
+ this.pendingOperations.clear();
667
+ }
668
+ };