@lunora/studio 1.0.0-alpha.361 → 1.0.0-alpha.363

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 (327) hide show
  1. package/dist/index.d.mts +4 -1
  2. package/dist/index.d.ts +4 -1
  3. package/dist/index.mjs +1 -1
  4. package/dist/mount.mjs +1 -1
  5. package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
  6. package/dist/packem_chunks/ApiTab.mjs +1 -1
  7. package/dist/packem_chunks/AuditPanel.mjs +1 -1
  8. package/dist/packem_chunks/ExportImportPanel.mjs +1 -1
  9. package/dist/packem_chunks/FileBrowser.mjs +1 -1
  10. package/dist/packem_chunks/FunctionRunner.mjs +1 -1
  11. package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
  12. package/dist/packem_chunks/HealthPanel.mjs +1 -1
  13. package/dist/packem_chunks/InsightsPanel.mjs +1 -1
  14. package/dist/packem_chunks/LogsPanel.mjs +1 -1
  15. package/dist/packem_chunks/MailPanel.mjs +1 -1
  16. package/dist/packem_chunks/MetricsPanel.mjs +1 -1
  17. package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
  18. package/dist/packem_chunks/PitrPanel.mjs +1 -1
  19. package/dist/packem_chunks/SchemaViewer.mjs +1 -1
  20. package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
  21. package/dist/packem_chunks/SettingsPanel.mjs +1 -1
  22. package/dist/packem_chunks/SqlEditorPanel.mjs +24 -9
  23. package/dist/packem_chunks/TableEditor.mjs +1 -1
  24. package/dist/packem_chunks/agents-panel.mjs +1 -1
  25. package/dist/packem_chunks/ai-knowledge.mjs +1 -0
  26. package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
  27. package/dist/packem_chunks/assistant-panel.mjs +3 -0
  28. package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
  29. package/dist/packem_chunks/containers-panel.mjs +1 -1
  30. package/dist/packem_chunks/dashboards-panel.mjs +1 -1
  31. package/dist/packem_chunks/evals-panel.mjs +1 -1
  32. package/dist/packem_chunks/fanout-panel.mjs +1 -1
  33. package/dist/packem_chunks/flags-panel.mjs +1 -1
  34. package/dist/packem_chunks/issues-panel.mjs +1 -1
  35. package/dist/packem_chunks/kv-browser.mjs +1 -1
  36. package/dist/packem_chunks/log-drains-panel.mjs +1 -1
  37. package/dist/packem_chunks/migrations-route.mjs +1 -1
  38. package/dist/packem_chunks/payments-panel.mjs +1 -1
  39. package/dist/packem_chunks/permissions-panel.mjs +1 -1
  40. package/dist/packem_chunks/privacy-requests-panel.mjs +1 -1
  41. package/dist/packem_chunks/queues-panel.mjs +1 -1
  42. package/dist/packem_chunks/reactors-panel.mjs +1 -1
  43. package/dist/packem_chunks/rls-panel.mjs +1 -1
  44. package/dist/packem_chunks/schedule-panel.mjs +1 -1
  45. package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
  46. package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
  47. package/dist/packem_chunks/traces-panel.mjs +1 -1
  48. package/dist/packem_chunks/workflows-panel.mjs +1 -1
  49. package/dist/packem_shared/ADMIN_FUNCTIONS-DUXsXId1.mjs +1 -0
  50. package/dist/packem_shared/{ApiDocsPanel-DD2Uns6b.mjs → ApiDocsPanel-B9S9l1Ce.mjs} +1 -1
  51. package/dist/packem_shared/{DataBrowser-CVRWnNWu.mjs → DataBrowser-Dm-jhIUP.mjs} +2 -2
  52. package/dist/packem_shared/{GlobalDataBrowser-DC47T6Zl.mjs → GlobalDataBrowser-C1Y8GUhe.mjs} +1 -1
  53. package/dist/packem_shared/{HomePanel-D12HxHQo.mjs → HomePanel-B5ytwPIo.mjs} +1 -1
  54. package/dist/packem_shared/{MigrationsPanel-DMkxSXNl.mjs → MigrationsPanel-CwLikxDT.mjs} +1 -1
  55. package/dist/packem_shared/Studio-B89ZNMOD.mjs +1 -0
  56. package/dist/packem_shared/{StudioApp-isdWpF9P.mjs → StudioApp-C9l1a3A8.mjs} +1 -1
  57. package/dist/packem_shared/advisor-view-CzieqKMe.mjs +5 -0
  58. package/dist/packem_shared/assistant-provider-Bp72uWsq.mjs +1 -0
  59. package/dist/packem_shared/assistant-reason-D6EwMCxT.mjs +1 -0
  60. package/dist/packem_shared/{cf-links-CBJ5SywP.mjs → cf-links-C4DVTr8A.mjs} +1 -1
  61. package/dist/packem_shared/error-alert-DKXm5h19.mjs +6 -0
  62. package/dist/packem_shared/{home-panel-CDVTuTF8.mjs → home-panel-5fGktYeD.mjs} +1 -1
  63. package/dist/packem_shared/recording-client-z4CBi0y8.mjs +1 -0
  64. package/dist/packem_shared/studio-gZfpz1wC.mjs +2 -0
  65. package/dist/packem_shared/{table-list-sidebar-CNadcIgG.mjs → table-list-sidebar-kpHaDWjy.mjs} +1 -1
  66. package/dist/packem_shared/use-assistant-rpc-GCUK2zPa.mjs +1 -0
  67. package/dist/standalone/chunk-2DT3QG6Q.js +1 -0
  68. package/dist/standalone/chunk-2EB7FN5S.js +1 -0
  69. package/dist/standalone/chunk-2H6VLY2M.js +1 -0
  70. package/dist/standalone/chunk-2NGKUO32.js +1 -0
  71. package/dist/standalone/chunk-2SNHKJXK.js +1 -0
  72. package/dist/standalone/chunk-2W4UO5BC.js +1 -0
  73. package/dist/standalone/chunk-32V7XGNC.js +1 -0
  74. package/dist/standalone/{chunk-SLIDAWNX.js → chunk-3D67ZJRW.js} +1 -1
  75. package/dist/standalone/chunk-3X3NXJBR.js +1 -0
  76. package/dist/standalone/chunk-4EPW63HS.js +1 -0
  77. package/dist/standalone/chunk-4L55URI5.js +2 -0
  78. package/dist/standalone/chunk-4N76XUNG.js +1 -0
  79. package/dist/standalone/{chunk-WS36BO4R.js → chunk-4NKJV7YX.js} +1 -1
  80. package/dist/standalone/chunk-4PI2OSSP.js +1 -0
  81. package/dist/standalone/chunk-53XKGQEE.js +1 -0
  82. package/dist/standalone/chunk-5GYHGDIF.js +8 -0
  83. package/dist/standalone/chunk-5PEAXTYQ.js +1 -0
  84. package/dist/standalone/chunk-5QUTVSHM.js +1 -0
  85. package/dist/standalone/{chunk-BYOGQ2IV.js → chunk-5RX5CQSU.js} +2 -2
  86. package/dist/standalone/{chunk-O2NMPIV2.js → chunk-5WNGRT7N.js} +1 -1
  87. package/dist/standalone/chunk-5Z2U4KBN.js +1 -0
  88. package/dist/standalone/chunk-66BMMNUR.js +1 -0
  89. package/dist/standalone/chunk-6FPV3EK2.js +1 -0
  90. package/dist/standalone/chunk-6G3E4PJ2.js +1 -0
  91. package/dist/standalone/chunk-75TRPM7O.js +1 -0
  92. package/dist/standalone/chunk-7MLX5CGD.js +1 -0
  93. package/dist/standalone/chunk-7QEZ2SFW.js +1 -0
  94. package/dist/standalone/chunk-7TQ7BZ67.js +1 -0
  95. package/dist/standalone/chunk-A2Q3TGIQ.js +1 -0
  96. package/dist/standalone/chunk-AD5J2ANS.js +1 -0
  97. package/dist/standalone/chunk-ALR4VAUE.js +1 -0
  98. package/dist/standalone/chunk-AXE2SDRU.js +1 -0
  99. package/dist/standalone/chunk-AZIKM5BA.js +1 -0
  100. package/dist/standalone/chunk-BAEIW3YS.js +1 -0
  101. package/dist/standalone/chunk-BBDTJG2K.js +1 -0
  102. package/dist/standalone/chunk-BCUOQNI2.js +1 -0
  103. package/dist/standalone/chunk-BG2CJOVS.js +1 -0
  104. package/dist/standalone/chunk-BI6MZHZJ.js +1 -0
  105. package/dist/standalone/chunk-BKI3JMXQ.js +1 -0
  106. package/dist/standalone/chunk-CKEQX655.js +1 -0
  107. package/dist/standalone/{chunk-DX55P3KZ.js → chunk-CL3JOU6F.js} +1 -1
  108. package/dist/standalone/chunk-CP7QNLR4.js +1 -0
  109. package/dist/standalone/chunk-CVSIFPI5.js +1 -0
  110. package/dist/standalone/chunk-D57B4MFK.js +1 -0
  111. package/dist/standalone/chunk-D65UVZIA.js +1 -0
  112. package/dist/standalone/{chunk-DBVJ5VLI.js → chunk-DA2CAFXI.js} +1 -1
  113. package/dist/standalone/chunk-DB6QX4X6.js +1 -0
  114. package/dist/standalone/chunk-DZFXH55R.js +1 -0
  115. package/dist/standalone/chunk-ELSQ4FVH.js +1 -0
  116. package/dist/standalone/chunk-EPWCW2DF.js +1 -0
  117. package/dist/standalone/chunk-FHLODLBC.js +1 -0
  118. package/dist/standalone/chunk-FJLRSFTE.js +1 -0
  119. package/dist/standalone/{chunk-3FS22LNI.js → chunk-FVCBNFQW.js} +3 -3
  120. package/dist/standalone/{chunk-VEWQWS3J.js → chunk-FWM5Z6CH.js} +1 -1
  121. package/dist/standalone/chunk-GJXCPZDN.js +1 -0
  122. package/dist/standalone/chunk-GNI37YCV.js +33 -0
  123. package/dist/standalone/chunk-GVQPNM3T.js +3 -0
  124. package/dist/standalone/chunk-GWNGVKLG.js +1 -0
  125. package/dist/standalone/chunk-GXTSE66Z.js +1 -0
  126. package/dist/standalone/chunk-H3EIPYRZ.js +1 -0
  127. package/dist/standalone/chunk-H5TMLWIS.js +1 -0
  128. package/dist/standalone/{chunk-XIRKBJPD.js → chunk-HBG6SSE2.js} +5 -5
  129. package/dist/standalone/chunk-HC2B7SXW.js +1 -0
  130. package/dist/standalone/chunk-HCOF7HOM.js +1 -0
  131. package/dist/standalone/chunk-HGCOTYPV.js +1 -0
  132. package/dist/standalone/chunk-HLHMHCXS.js +1 -0
  133. package/dist/standalone/chunk-HSF2DCJ2.js +30 -0
  134. package/dist/standalone/chunk-HZDLUAWS.js +1 -0
  135. package/dist/standalone/{chunk-3PAYDWHN.js → chunk-I3SSF2T6.js} +2 -2
  136. package/dist/standalone/chunk-I5QX75DE.js +1 -0
  137. package/dist/standalone/chunk-ICHZ2IBL.js +1 -0
  138. package/dist/standalone/{chunk-7ZIYHKLX.js → chunk-IG5VD7R7.js} +3 -3
  139. package/dist/standalone/{chunk-SU5DTRGK.js → chunk-IHGRWY3Y.js} +1 -1
  140. package/dist/standalone/chunk-J45HAKBU.js +1 -0
  141. package/dist/standalone/chunk-J4PQAVOF.js +1 -0
  142. package/dist/standalone/chunk-JD6PRRFO.js +1 -0
  143. package/dist/standalone/chunk-JOPNP4EO.js +1 -0
  144. package/dist/standalone/chunk-JVP3TR3A.js +1 -0
  145. package/dist/standalone/chunk-KGLIQIZU.js +1 -0
  146. package/dist/standalone/{chunk-ONWGX5Y4.js → chunk-KH6OXCG3.js} +1 -1
  147. package/dist/standalone/chunk-KKMQUBYH.js +1 -0
  148. package/dist/standalone/chunk-L2FYX4FN.js +1 -0
  149. package/dist/standalone/chunk-LDHJRHPZ.js +1 -0
  150. package/dist/standalone/chunk-LSEUUZN4.js +1 -0
  151. package/dist/standalone/chunk-MNYDT3RH.js +1 -0
  152. package/dist/standalone/chunk-MT4ICMXJ.js +1 -0
  153. package/dist/standalone/chunk-MXJTD2OX.js +1 -0
  154. package/dist/standalone/chunk-NGZNXNRD.js +1 -0
  155. package/dist/standalone/chunk-O3AZ7JKE.js +1 -0
  156. package/dist/standalone/chunk-OK2QU2EV.js +1 -0
  157. package/dist/standalone/{chunk-IH2CJZF2.js → chunk-ONTGYVAN.js} +1 -1
  158. package/dist/standalone/chunk-OWRKSQPE.js +1 -0
  159. package/dist/standalone/chunk-OZAOWE7T.js +1 -0
  160. package/dist/standalone/chunk-P5EVJEGC.js +1 -0
  161. package/dist/standalone/chunk-PDBW6GTJ.js +1 -0
  162. package/dist/standalone/chunk-PJUVJTDR.js +1 -0
  163. package/dist/standalone/chunk-Q3IA6HPX.js +1 -0
  164. package/dist/standalone/chunk-QAOZXPLU.js +1 -0
  165. package/dist/standalone/chunk-QKUVJIRX.js +1 -0
  166. package/dist/standalone/chunk-QNM2J7MG.js +1 -0
  167. package/dist/standalone/chunk-QRA7AKYO.js +1 -0
  168. package/dist/standalone/chunk-RBIVXSXT.js +1 -0
  169. package/dist/standalone/chunk-RCXNYW7P.js +1 -0
  170. package/dist/standalone/{chunk-TDVDZ7XQ.js → chunk-RIAOZECW.js} +1 -1
  171. package/dist/standalone/{chunk-LUHXNZI4.js → chunk-RTS5G3ET.js} +1 -1
  172. package/dist/standalone/chunk-S36FVTKK.js +1 -0
  173. package/dist/standalone/chunk-SDDEOSQB.js +1 -0
  174. package/dist/standalone/chunk-SHHGIT7M.js +7 -0
  175. package/dist/standalone/chunk-SR6CPTRT.js +1 -0
  176. package/dist/standalone/chunk-SVQWZPO4.js +1 -0
  177. package/dist/standalone/chunk-T3ZCW3RG.js +1 -0
  178. package/dist/standalone/chunk-TEMI7MVE.js +1 -0
  179. package/dist/standalone/chunk-TKBTZX4K.js +1 -0
  180. package/dist/standalone/chunk-TW4O2BA5.js +159 -0
  181. package/dist/standalone/chunk-U5MPNEM2.js +1 -0
  182. package/dist/standalone/chunk-UD5REVU2.js +1 -0
  183. package/dist/standalone/chunk-ULQNADMJ.js +1 -0
  184. package/dist/standalone/chunk-UPPNZ6MI.js +1 -0
  185. package/dist/standalone/{chunk-PQH2LSJX.js → chunk-UQA2AJGI.js} +1 -1
  186. package/dist/standalone/chunk-UTQLJKHH.js +1 -0
  187. package/dist/standalone/chunk-UVG3ZISC.js +1 -0
  188. package/dist/standalone/chunk-UXBNXITB.js +1 -0
  189. package/dist/standalone/chunk-UZ2ZXB74.js +1 -0
  190. package/dist/standalone/chunk-V3BE427M.js +1 -0
  191. package/dist/standalone/chunk-VQDTA4P6.js +1 -0
  192. package/dist/standalone/chunk-W4LJQYCI.js +1 -0
  193. package/dist/standalone/chunk-WLHQ4FKC.js +1 -0
  194. package/dist/standalone/chunk-XPFVUAPX.js +1 -0
  195. package/dist/standalone/{chunk-SYGCASPT.js → chunk-Y2YLTUMD.js} +1 -1
  196. package/dist/standalone/chunk-Y3IGTWUE.js +1 -0
  197. package/dist/standalone/chunk-Y64STA6O.js +1 -0
  198. package/dist/standalone/chunk-YEVTA35E.js +1 -0
  199. package/dist/standalone/chunk-YEXTJUKQ.js +6 -0
  200. package/dist/standalone/chunk-YFTPHGS2.js +1 -0
  201. package/dist/standalone/{chunk-R36QXQZX.js → chunk-YORPLSI5.js} +1 -1
  202. package/dist/standalone/chunk-Z64BZNPS.js +1 -0
  203. package/dist/standalone/chunk-Z6VILGGP.js +5 -0
  204. package/dist/standalone/chunk-ZBOB33BA.js +1 -0
  205. package/dist/standalone/{chunk-5R2YO7HF.js → chunk-ZOKSVUID.js} +4 -4
  206. package/dist/standalone/{chunk-H7HZ42JY.js → chunk-ZPQBVYNN.js} +1 -1
  207. package/dist/standalone/chunk-ZSWW2UGP.js +1 -0
  208. package/dist/standalone/studio.js +2 -2
  209. package/dist/styles.css +1 -1
  210. package/package.json +7 -6
  211. package/dist/packem_shared/ADMIN_FUNCTIONS-4aGsMs95.mjs +0 -1
  212. package/dist/packem_shared/Studio-MA8kKZLu.mjs +0 -1
  213. package/dist/packem_shared/advisor-view-tBumWci_.mjs +0 -1
  214. package/dist/packem_shared/error-alert-C0R39DO1.mjs +0 -1
  215. package/dist/packem_shared/recording-client-DAipTA_n.mjs +0 -1
  216. package/dist/packem_shared/studio-UhUrPz5J.mjs +0 -2
  217. package/dist/packem_shared/use-sql-assistant-rZPs3LC3.mjs +0 -1
  218. package/dist/standalone/chunk-2AH4ABE5.js +0 -1
  219. package/dist/standalone/chunk-2G57ENH5.js +0 -1
  220. package/dist/standalone/chunk-3GXPALXG.js +0 -1
  221. package/dist/standalone/chunk-3GYLOE4V.js +0 -1
  222. package/dist/standalone/chunk-473JK2PQ.js +0 -1
  223. package/dist/standalone/chunk-4C4THJUD.js +0 -1
  224. package/dist/standalone/chunk-4DAKKAK7.js +0 -1
  225. package/dist/standalone/chunk-4M57OYFX.js +0 -1
  226. package/dist/standalone/chunk-4SQBAPY6.js +0 -1
  227. package/dist/standalone/chunk-5DNGK3NT.js +0 -1
  228. package/dist/standalone/chunk-5GIQ6C5N.js +0 -1
  229. package/dist/standalone/chunk-5WJG7FMH.js +0 -1
  230. package/dist/standalone/chunk-63KDHS3H.js +0 -1
  231. package/dist/standalone/chunk-6B6ARRMI.js +0 -1
  232. package/dist/standalone/chunk-6LMO2D54.js +0 -1
  233. package/dist/standalone/chunk-6M7FLLMT.js +0 -1
  234. package/dist/standalone/chunk-6QEXGYWH.js +0 -1
  235. package/dist/standalone/chunk-6UTZXEW3.js +0 -1
  236. package/dist/standalone/chunk-6VAY6L4J.js +0 -1
  237. package/dist/standalone/chunk-7PADVGQX.js +0 -1
  238. package/dist/standalone/chunk-7RGYCU6F.js +0 -1
  239. package/dist/standalone/chunk-7UM5ROG6.js +0 -1
  240. package/dist/standalone/chunk-A566HCBX.js +0 -1
  241. package/dist/standalone/chunk-A5JISKHE.js +0 -1
  242. package/dist/standalone/chunk-ADNRFCMZ.js +0 -1
  243. package/dist/standalone/chunk-AP4PC2M4.js +0 -1
  244. package/dist/standalone/chunk-BFE2DRP6.js +0 -33
  245. package/dist/standalone/chunk-BPEB4KFE.js +0 -1
  246. package/dist/standalone/chunk-BVX45MU5.js +0 -7
  247. package/dist/standalone/chunk-C6GN7ZXJ.js +0 -1
  248. package/dist/standalone/chunk-CL2VZNDI.js +0 -1
  249. package/dist/standalone/chunk-CNA3TVUK.js +0 -1
  250. package/dist/standalone/chunk-CZ6HBDIL.js +0 -1
  251. package/dist/standalone/chunk-D6S7MXW4.js +0 -1
  252. package/dist/standalone/chunk-E26OT26O.js +0 -1
  253. package/dist/standalone/chunk-FCAXVYAX.js +0 -1
  254. package/dist/standalone/chunk-FXPAJDES.js +0 -1
  255. package/dist/standalone/chunk-HHRYM6UW.js +0 -1
  256. package/dist/standalone/chunk-HPRF5LMA.js +0 -1
  257. package/dist/standalone/chunk-IB22LETR.js +0 -1
  258. package/dist/standalone/chunk-IBJVVHV5.js +0 -1
  259. package/dist/standalone/chunk-IENQRRQT.js +0 -1
  260. package/dist/standalone/chunk-IQ4TTHQT.js +0 -1
  261. package/dist/standalone/chunk-ITH5LRWM.js +0 -1
  262. package/dist/standalone/chunk-J6VFG6M5.js +0 -1
  263. package/dist/standalone/chunk-JSDKOE4U.js +0 -1
  264. package/dist/standalone/chunk-JTGGWF7R.js +0 -1
  265. package/dist/standalone/chunk-JZD7ZN3F.js +0 -1
  266. package/dist/standalone/chunk-K3CWB3AM.js +0 -1
  267. package/dist/standalone/chunk-KNFB3FGW.js +0 -1
  268. package/dist/standalone/chunk-KNXWDE4N.js +0 -1
  269. package/dist/standalone/chunk-KRPXOSBL.js +0 -1
  270. package/dist/standalone/chunk-KRY7BYHT.js +0 -1
  271. package/dist/standalone/chunk-KYAG2YMF.js +0 -1
  272. package/dist/standalone/chunk-KZCEJFZF.js +0 -1
  273. package/dist/standalone/chunk-KZILJQX3.js +0 -8
  274. package/dist/standalone/chunk-LEYUH5TS.js +0 -1
  275. package/dist/standalone/chunk-LFM672WN.js +0 -1
  276. package/dist/standalone/chunk-LIGOLZND.js +0 -1
  277. package/dist/standalone/chunk-LPU6YTSU.js +0 -1
  278. package/dist/standalone/chunk-MWJC3S62.js +0 -1
  279. package/dist/standalone/chunk-NP2AQOLE.js +0 -1
  280. package/dist/standalone/chunk-NVKLYDOH.js +0 -1
  281. package/dist/standalone/chunk-O2X2XYCM.js +0 -1
  282. package/dist/standalone/chunk-O3MDWYXF.js +0 -1
  283. package/dist/standalone/chunk-ONG4JEZD.js +0 -1
  284. package/dist/standalone/chunk-OS26JXYA.js +0 -1
  285. package/dist/standalone/chunk-OXFKZ4BM.js +0 -1
  286. package/dist/standalone/chunk-PGTEGUAB.js +0 -1
  287. package/dist/standalone/chunk-PTBUWRBY.js +0 -1
  288. package/dist/standalone/chunk-Q6HA3L2H.js +0 -1
  289. package/dist/standalone/chunk-QGV5ARD2.js +0 -1
  290. package/dist/standalone/chunk-QWRK4ESB.js +0 -1
  291. package/dist/standalone/chunk-RL2ITK2N.js +0 -1
  292. package/dist/standalone/chunk-RTJO3AR4.js +0 -1
  293. package/dist/standalone/chunk-SFY646MC.js +0 -1
  294. package/dist/standalone/chunk-T5UMHPAB.js +0 -1
  295. package/dist/standalone/chunk-T6HV2FQP.js +0 -2
  296. package/dist/standalone/chunk-T7ZKNNGX.js +0 -1
  297. package/dist/standalone/chunk-TCYPNSTV.js +0 -1
  298. package/dist/standalone/chunk-TQM6XHBA.js +0 -1
  299. package/dist/standalone/chunk-TRMWBRRU.js +0 -1
  300. package/dist/standalone/chunk-TW7KJSMR.js +0 -15
  301. package/dist/standalone/chunk-TYD3V4NB.js +0 -1
  302. package/dist/standalone/chunk-TZKLK52W.js +0 -1
  303. package/dist/standalone/chunk-U4RXQSQ7.js +0 -1
  304. package/dist/standalone/chunk-UNZ2UBVL.js +0 -1
  305. package/dist/standalone/chunk-VJRNOSRY.js +0 -1
  306. package/dist/standalone/chunk-W2BCSK5S.js +0 -1
  307. package/dist/standalone/chunk-W7MRISE3.js +0 -1
  308. package/dist/standalone/chunk-WM72PRE3.js +0 -1
  309. package/dist/standalone/chunk-X4WHMCOZ.js +0 -1
  310. package/dist/standalone/chunk-X74GEPSG.js +0 -1
  311. package/dist/standalone/chunk-XKPD4SFN.js +0 -1
  312. package/dist/standalone/chunk-XMSNLMWU.js +0 -1
  313. package/dist/standalone/chunk-XOPFDWXX.js +0 -1
  314. package/dist/standalone/chunk-XQLOVFPP.js +0 -1
  315. package/dist/standalone/chunk-XSHYZPGF.js +0 -1
  316. package/dist/standalone/chunk-XST3UEHU.js +0 -1
  317. package/dist/standalone/chunk-XYR5NST4.js +0 -1
  318. package/dist/standalone/chunk-Y74LIFSL.js +0 -1
  319. package/dist/standalone/chunk-YHTHRYP5.js +0 -1
  320. package/dist/standalone/chunk-YMEKCV27.js +0 -1
  321. package/dist/standalone/chunk-Z5EV64KS.js +0 -1
  322. package/dist/standalone/chunk-ZBON5T5A.js +0 -1
  323. package/dist/standalone/chunk-ZGSL4DPP.js +0 -1
  324. package/dist/standalone/chunk-ZOQTXWPK.js +0 -1
  325. package/dist/standalone/chunk-ZTOREMGH.js +0 -1
  326. package/dist/standalone/chunk-ZZ5GICTF.js +0 -1
  327. /package/dist/standalone/{chunk-UYEZR3BI.js → chunk-P6VNMPWR.js} +0 -0
@@ -0,0 +1,7 @@
1
+ import{a as Es,b,c as Is,d as Rs}from"./chunk-GNI37YCV.js";import{a as As}from"./chunk-GWNGVKLG.js";import{a as ie,b as Tt}from"./chunk-6G3E4PJ2.js";import{a,d as D}from"./chunk-5PEAXTYQ.js";var de=a(t=>{try{return t(),!0}catch{return!1}},"o"),Mn=new Set([Object.prototype,Function.prototype]),Oe=a((t,e,s)=>{let r;for(let i=t;i!==null&&!Mn.has(i);i=Object.getPrototypeOf(i)){let n=Object.getOwnPropertyDescriptor(i,e)?.[s];typeof n=="function"&&(r=n)}return r},"y"),z=a((t,e)=>Oe(t,e,"get"),"r"),Ms=Oe(Date.prototype,"getTime","value"),Ln=z(Map.prototype,"size"),xn=z(Set.prototype,"size"),_n=z(ArrayBuffer.prototype,"byteLength"),Te=typeof URL=="function"?z(URL.prototype,"href"):void 0,Ot=typeof URL=="function"?URL.prototype:void 0,Qn=Te!==void 0&&Function.prototype.toString.call(Te).includes("[native code]"),Fs=Oe(Error,"isError","value"),Ps=Error.prototype,Dn=a((t,e)=>typeof Fs=="function"?Fs(t):e!==null&&(e===Ps||Ps.isPrototypeOf(e)),"L"),Un=Oe(Map.prototype,"forEach","value"),Hn=Oe(Set.prototype,"forEach","value"),Et=Object.getPrototypeOf(Uint8Array.prototype),It={data:{buffer:z(DataView.prototype,"buffer"),byteLength:z(DataView.prototype,"byteLength"),byteOffset:z(DataView.prototype,"byteOffset")},typed:{buffer:z(Et,"buffer"),byteLength:z(Et,"byteLength"),byteOffset:z(Et,"byteOffset")}},Ls=a(t=>Reflect.apply(Ms,t,[]),"S"),xs=a(t=>Reflect.apply(Te,t,[]),"m"),_s=a(t=>{let e=[];return Reflect.apply(Un,t,[(s,r)=>e.push([r,s])]),e},"A"),Qs=a(t=>{let e=[];return Reflect.apply(Hn,t,[s=>e.push(s)]),e},"w"),Ds=a(t=>{let e=de(()=>Reflect.apply(It.typed.buffer,t,[]))?It.typed:It.data;return new Uint8Array(Reflect.apply(e.buffer,t,[]),Reflect.apply(e.byteOffset,t,[]),Reflect.apply(e.byteLength,t,[]))},"j"),We=a(t=>{if(Array.isArray(t))return"array";let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype?"plain":de(()=>Reflect.apply(Ms,t,[]))?"builtin-date":de(()=>Reflect.apply(Ln,t,[]))?"builtin-map":de(()=>Reflect.apply(xn,t,[]))?"builtin-set":de(()=>Reflect.apply(_n,t,[]))?"builtin-array-buffer":ArrayBuffer.isView(t)?"builtin-view":Dn(t,e)?"builtin-error":Te!==void 0&&(Qn||Ot!==void 0&&e!==null&&(e===Ot||Ot.isPrototypeOf(e)))&&de(()=>Reflect.apply(Te,t,[]))?"builtin-url":"other"},"D");var Kn=2**32-1,Nn=/["\\\u0000-\u001F\uD800-\uDFFF]/,Us=a(t=>Nn.test(t)?JSON.stringify(t):`"${t}"`,"y"),jn=a(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"u"),qn=a((t,e)=>{let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=Us(o),i+=":",i+=e(c))}return`${i}}`},"g"),Wn=a(t=>{let{length:e}=t,s=Number.isInteger(e)?e:Math.trunc(e)||0;if(s>Kn)throw new RangeError("stable-key: array length exceeds 2**32 - 1");return s},"d"),Ee=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let s=jn(t);if(s!==void 0)return s}if(typeof t=="string")return Us(t);if(t===null||typeof t!="object")return JSON.stringify(t);let e=We(t);if(e==="array"){let s=Wn(t),r="[";for(let i=0;i<s;i+=1)i>0&&(r+=","),r+=Ee(t[i]);return`${r}]`}if(e!=="plain"){let s=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}return qn(t,Ee)},"c");var Rt=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Be=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"u"),Bn=a(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"R"),A="$lunora.wire$",$e=64,ze=1024,$n="__proto__",zn=/^-?\d+$/,Hs={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Ks={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},At=a((t,e,s)=>{e===$n?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"b");var Gn=a(t=>{let e=t.toString();if(e.length>ze)throw new RangeError(`wire-codec: over-long bigint (max ${String(ze)} digits)`);return[A,"bigint",e]},"B"),Vn=a(t=>Number.isNaN(t)?[A,"nan"]:t===1/0?[A,"inf"]:t===-1/0?[A,"-inf"]:t,"_"),Jn=a((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(n=>[n,t[n]]))),r=t,i=[A,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"P"),Yn=a(t=>{let e=t.constructor.name,s=Ds(t);return e==="Uint8Array"?[A,"bytes",Be(s)]:[A,"bytes",Be(s),e]},"$"),Xn=a((t,e,s)=>{switch(e){case"builtin-array-buffer":return[A,"bytes",Be(new Uint8Array(t)),"ArrayBuffer"];case"builtin-date":return[A,"date",s(Ls(t))];case"builtin-error":return Jn(t,s);case"builtin-map":return[A,"map",_s(t).map(([r,i])=>[s(r),s(i)])];case"builtin-set":return[A,"set",Qs(t).map(r=>s(r))];case"builtin-url":return[A,"url",xs(t)];case"builtin-view":return Yn(t);default:return}},"k"),Zn=a((t,e)=>{let s=t.map(r=>U(r,e));return s.length>0&&s[0]===A?[A,"arr",s]:s},"D"),ea=a((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&At(s,r,U(i,e))}return s},"C"),U=a((t,e=0)=>{if(e>$e)throw new RangeError(`wire-codec: value nesting exceeds the ${String($e)}-level limit`);if(t===void 0)return[A,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Gn(t);if(typeof t=="number")return Vn(t);if(typeof t!="object")return t;let s=We(t);if(s==="array")return Zn(t,e+1);if(s==="plain")return ea(t,e+1);let r=Xn(t,s,n=>U(n,e+1));if(r!==void 0)return r;let i=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${i} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)},"y"),ta=a(t=>{let e=t[2];if(typeof e!="string"||e.length>ze||!zn.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(ze)} digits)`);return BigInt(e)},"M"),sa=a((t,e)=>{let s=e(t[2]);if(typeof s!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(s)},"F"),ra=a((t,e)=>{let s=t[2];return new Map(s.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[e(r[0]),e(r[1])]}))},"G"),ia=a(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(e)},"L"),na=a((t,e)=>{let s=t[2],r=t[3];if(typeof s!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let i=(Object.hasOwn(Ks,s)?Ks[s]:void 0)??Error,n=new i(r);n.name!==s&&Object.defineProperty(n,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))At(n,c,u);return t.length>5&&Object.defineProperty(n,"cause",{configurable:!0,value:e(t[5]),writable:!0}),n},"W"),aa=a(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let s=Bn(e);if(Be(s)!==e)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let r=t[3]??"Uint8Array";if(r==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:new Uint8Array(s).buffer;let i=Object.hasOwn(Hs,r)?Hs[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"v"),oa=a((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return ta(t);case"bytes":return aa(t);case"date":return sa(t,e);case"error":return na(t,e);case"inf":return 1/0;case"map":return ra(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return ia(t);default:return t.map(s=>e(s))}},"Y"),ca=a((t,e)=>{let s={};for(let r of Object.keys(t))At(s,r,T(t[r],e));return s},"H"),T=a((t,e=0)=>{if(e>$e)throw new RangeError(`wire-codec: value nesting exceeds the ${String($e)}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){let s=t;return s[0]===A?oa(s,r=>T(r,e+1)):s.map(r=>T(r,e+1))}return ca(t,e+1)},"f"),Ns=a(t=>{let e=JSON.parse(t);return t.includes(A)||t.includes(String.raw`\u`)?T(e):e},"J"),ua=a(t=>{try{let e=Ns(t);return Rt(e)?e:void 0}catch{return}},"X");var q=a(t=>Ee(U(t)),"a");var le=D(ie(),1),js=D(Tt(),1);var Ie=le.createContext(void 0),Re=a(t=>{let e=le.useContext(Ie);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ft=a(({client:t,children:e})=>(le.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,js.jsx)(Ie.Provider,{value:t,children:e})),"QueryClientProvider");var j=class{static{a(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var ha=class extends j{static{a(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},pe=new ha;var da={setTimeout:a((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:a(t=>clearTimeout(t),"clearTimeout"),setInterval:a((t,e)=>setInterval(t,e),"setInterval"),clearInterval:a(t=>clearInterval(t),"clearInterval")},la=class{static{a(this,"TimeoutManager")}#e=da;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},G=new la;function qs(t){setTimeout(t,0)}a(qs,"systemSetTimeoutZero");var Mt=typeof window>"u"||"Deno"in globalThis;function O(){}a(O,"noop");function $s(t,e){return typeof t=="function"?t(e):t}a($s,"functionalUpdate");function Ae(t){return typeof t=="number"&&t>=0&&t!==1/0}a(Ae,"isValidTimeout");function Ge(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(Ge,"timeUntilStale");function W(t,e){return typeof t=="function"?t(e):t}a(W,"resolveStaleTime");function x(t,e){return typeof t=="function"?t(e):t}a(x,"resolveQueryBoolean");function Ve(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Fe(o,e.options))return!1}else if(!ne(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}a(Ve,"matchQuery");function Je(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(V(e.options.mutationKey)!==V(n))return!1}else if(!ne(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Je,"matchMutation");function Fe(t,e){return(e?.queryKeyHashFn||V)(t)}a(Fe,"hashQueryKeyByOptions");function V(t){return JSON.stringify(t,(e,s)=>Pt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(V,"hashKey");function ne(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!ne(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ne(t[r],e[r]))return!1;return!0}return!1}a(ne,"partialMatchKey");var pa=Object.prototype.hasOwnProperty;function Lt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Ws(t)&&Ws(e);if(!r&&!(Pt(t)&&Pt(e)))return e;let n=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},d=0;for(let h=0;h<c;h++){let l=r?h:o[h],p=t[l],f=e[l];if(p===f){u[l]=p,(r?h<n:pa.call(t,l))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=Lt(p,f,s+1);u[l]=y,y===p&&d++}return n===c&&d===n?t:u}a(Lt,"replaceEqualDeep");function fe(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}a(fe,"shallowEqualObjects");function Ws(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(Ws,"isPlainArray");function Pt(t){if(!Bs(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Bs(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(Pt,"isPlainObject");function Bs(t){return Object.prototype.toString.call(t)==="[object Object]"}a(Bs,"hasObjectPrototype");function zs(t){return new Promise(e=>{G.setTimeout(e,t)})}a(zs,"sleep");function Pe(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Lt(t,e):e}a(Pe,"replaceData");function fa(t){return t}a(fa,"keepPreviousData");function Gs(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(Gs,"addToEnd");function Vs(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(Vs,"addToStart");var me=Symbol();function Ye(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===me?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Ye,"ensureQueryFn");function ye(t,e){return typeof t=="function"?t(...e):!!t}a(ye,"shouldThrowError");function Js(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:a(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}a(Js,"addConsumeAwareSignal");var J=(()=>{let t=a(()=>Mt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Me(){let t,e,s=new Promise((i,n)=>{t=i,e=n});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return a(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}a(Me,"pendingThenable");var Ys=qs;function ma(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=Ys,n=a(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:a(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:a(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{r=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(ma,"createNotifyManager");var C=ma();var ya=class extends j{static{a(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(!0),"onlineListener"),s=a(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},be=new ya;function ba(t){return Math.min(1e3*2**t,3e4)}a(ba,"defaultRetryDelay");function xt(t){return(t??"online")==="online"?be.isOnline():!0}a(xt,"canFetch");var Xe=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ze(t){let e=!1,s=0,r,i=Me(),n=a(()=>i.status!=="pending","isResolved"),o=a(m=>{if(!n()){let g=new Xe(m);p(g),t.onCancel?.(g)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),d=a(()=>pe.isFocused()&&(t.networkMode==="always"||be.isOnline())&&t.canRun(),"canContinue"),h=a(()=>xt(t.networkMode)&&t.canRun(),"canStart"),l=a(m=>{n()||(r?.(),i.resolve(m))},"resolve"),p=a(m=>{n()||(r?.(),i.reject(m))},"reject"),f=a(()=>new Promise(m=>{r=a(g=>{(n()||d())&&m(g)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),y=a(()=>{if(n())return;let m,g=s===0?t.initialPromise:void 0;try{m=g??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(l).catch(S=>{if(n())return;let k=t.retry??(J.isServer()?0:3),E=t.retryDelay??ba,w=typeof E=="function"?E(s,S):E,I=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,S);if(e||!I){p(S);return}s++,t.onFail?.(s,S),zs(w).then(()=>d()?void 0:f()).then(()=>{e?p(S):y()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:a(()=>(h()?y():f().then(y),i),"start")}}a(Ze,"createRetryer");var et=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ae(this.gcTime)&&(this.#e=G.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(J.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(G.clearTimeout(this.#e),this.#e=void 0)}};function Zs(t){return{onFetch:a((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=a(async()=>{let h=!1,l=a(y=>{Js(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),p=Ye(e.options,e.fetchOptions),f=a(async(y,m,g)=>{if(h)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let k=a(()=>{let re={client:e.client,queryKey:e.queryKey,pageParam:m,direction:g?"backward":"forward",meta:e.options.meta};return l(re),re},"createQueryFnContext")(),E=await p(k),{maxPages:w}=e.options,I=g?Vs:Gs;return{pages:I(y.pages,E,w),pageParams:I(y.pageParams,m,w)}},"fetchPage");if(i&&n.length){let y=i==="backward",m=y?va:Xs,g={pages:n,pageParams:o},S=m(r,g);c=await f(g,S,y)}else{let y=t??n.length;do{let m=u===0?o[0]??r.initialPageParam:Xs(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=d},"onFetch")}}a(Zs,"infiniteQueryBehavior");function Xs(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}a(Xs,"getNextPageParam");function va(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(va,"getPreviousPageParam");var sr=class extends et{static{a(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=tr(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=tr(this.options);e.data!==void 0&&(this.setState(er(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Pe(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(O).catch(O):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>x(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===me||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>W(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Ge(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=a(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=a(()=>{let u=Ye(this.options,e),h=a(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"fetchFn"),o=a(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?Zs(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Ze({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof Xe&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:a((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"onFail"),onPause:a(()=>{this.#c({type:"pause"})},"onPause"),onContinue:a(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:a(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Xe){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=a(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,..._t(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...er(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),C.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function _t(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:xt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(_t,"fetchState");function er(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(er,"successState");function tr(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}a(tr,"getDefaultState");var Dt=class extends j{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Me(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#f;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),rr(this.#t,this.options)?this.#p():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Qt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Qt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof x(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#t.setOptions(this.options),e._defaulted&&!fe(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&ir(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||x(this.options.enabled,this.#t)!==x(e.enabled,this.#t)||W(this.options.staleTime,this.#t)!==W(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||x(this.options.enabled,this.#t)!==x(e.enabled,this.#t)||i!==this.#u)&&this.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Sa(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:a((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#p(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(O)),e}#y(){this.#S();let t=W(this.options.staleTime,this.#t);if(J.isServer()||this.#r.isStale||!Ae(t))return;let s=Ge(this.#r.dataUpdatedAt,t)+1;this.#d=G.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#w(),this.#u=t,!(J.isServer()||x(this.options.enabled,this.#t)===!1||!Ae(this.#u)||this.#u===0)&&(this.#l=G.setInterval(()=>{(this.options.refetchIntervalInBackground||pe.isFocused())&&this.#p()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#S(){this.#d!==void 0&&(G.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(G.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,n=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:d}=t,h={...d},l=!1,p;if(e._optimisticResults){let F=this.hasListeners(),R=!F&&rr(t,e),X=F&&ir(t,s,e,r);(R||X)&&(h={...h,..._t(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=h;p=h.data;let g=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let F;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(F=i.data,g=!0):F=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,F!==void 0&&(m="success",p=Pe(i?.data,F,e),l=!0)}if(e.select&&p!==void 0&&!g)if(i&&p===n?.data&&e.select===this.#h)p=this.#c;else try{this.#h=e.select,p=e.select(p),p=Pe(i?.data,p,e),this.#c=p,this.#a=null}catch(F){this.#a=F}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let S=h.fetchStatus==="fetching",k=m==="pending",E=m==="error",w=k&&S,I=p!==void 0,L={status:m,fetchStatus:h.fetchStatus,isPending:k,isSuccess:m==="success",isError:E,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!k,isLoadingError:E&&!I,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&I,isStale:Ut(t,e),refetch:this.refetch,promise:this.#o,isEnabled:x(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let F=L.data!==void 0,R=L.status==="error"&&!F,X=a(qe=>{R?qe.reject(L.error):F&&qe.resolve(L.data)},"finalizeThenableIfPossible"),Os=a(()=>{let qe=this.#o=L.promise=Me();X(qe)},"recreateThenable"),je=this.#o;switch(je.status){case"pending":t.queryHash===s.queryHash&&X(je);break;case"fulfilled":(R||L.data!==je.value)&&Os();break;case"rejected":(!R||L.error!==je.reason)&&Os();break}}return L}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#f=this.#t),fe(e,t))return;this.#r=e;let s=a(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:s()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#k(t){C.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ga(t,e){return x(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&x(e.retryOnMount,t)===!1)}a(ga,"shouldLoadOnMount");function rr(t,e){return ga(t,e)||t.state.data!==void 0&&Qt(t,e,e.refetchOnMount)}a(rr,"shouldFetchOnMount");function Qt(t,e,s){if(x(e.enabled,t)!==!1&&W(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&Ut(t,e)}return!1}a(Qt,"shouldFetchOn");function ir(t,e,s,r){return(t!==e||x(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&Ut(t,s)}a(ir,"shouldFetchOptionally");function Ut(t,e){return x(e.enabled,t)!==!1&&t.isStaleByTime(W(e.staleTime,t))}a(Ut,"isStale");function Sa(t,e){return!fe(t.getCurrentResult(),e)}a(Sa,"shouldAssignObserverCurrentProperties");var nr=class extends et{static{a(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Ht(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=a(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Ze({fn:a(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:a((n,o)=>{this.#n({type:"failed",failureCount:n,error:o})},"onFail"),onPause:a(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:a(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let n=await this.#r.start();return await this.#s.config.onSuccess?.(n,t,this.state.context,this,s),await this.options.onSuccess?.(n,t,this.state.context,s),await this.#s.config.onSettled?.(n,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(n,null,t,this.state.context,s),this.#n({type:"success",data:n}),n}catch(n){try{await this.#s.config.onError?.(n,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(n,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:n}),n}finally{this.#s.runNext(this)}}#n(t){let e=a(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),C.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function Ht(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Ht,"getDefaultState");var ar=class extends j{static{a(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new nr({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=tt(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=tt(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=tt(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=tt(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){C.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Je(e,s))}findAll(t={}){return this.getAll().filter(e=>Je(t,e))}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return C.batch(()=>Promise.all(t.map(e=>e.continue().catch(O))))}};function tt(t){return t.options.scope?.id}a(tt,"scopeFor");var Kt=class extends j{static{a(this,"MutationObserver")}#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#e.defaultMutationOptions(t),fe(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&V(e.mutationKey)!==V(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#n(),this.#i(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#n(),this.#i()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#n(){let t=this.#s?.state??Ht();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#i(t){C.batch(()=>{if(this.#r&&this.hasListeners()){let e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(t.data,null,e,s,r)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(void 0,t.error,e,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(e=>{e(this.#t)})})}};var or=class extends j{static{a(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??Fe(r,e),n=this.get(i);return n||(n=new sr({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(n)),n}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){C.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Ve(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ve(t,s)):e}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){C.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){C.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Nt=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new or,this.#t=t.mutationCache||new ar,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=pe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=be.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(W(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(r.queryHash)?.state.data,o=$s(e,n);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return C.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;C.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return C.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=C.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(O).catch(O)}invalidateQueries(t,e={}){return C.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=C.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,s);return s.throwOnError||(n=n.catch(O)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(O)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(W(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(O).catch(O)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(O).catch(O)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return be.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set(V(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ne(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(V(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ne(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Fe(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===me&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var ae=D(ie(),1);var Le=D(ie(),1),wa=D(Tt(),1);function Ca(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Ca,"createValue");var ka=Le.createContext(Ca()),cr=a(()=>Le.useContext(ka),"useQueryErrorResetBoundary");var ur=D(ie(),1);var hr=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?ye(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),dr=a(t=>{ur.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),lr=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||ye(s,[t.error,r])),"getHasError");var st=D(ie(),1);var pr=st.createContext(!1),fr=a(()=>st.useContext(pr),"useIsRestoring"),Ld=pr.Provider;var mr=a(t=>{if(t.suspense){let s=a(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),yr=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),br=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),jt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function vr(t,e,s){let r=fr(),i=cr(),n=Re(s),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,mr(o),hr(o,i,c),dr(i);let d=!n.getQueryCache().get(o.queryHash),[h]=ae.useState(()=>new e(n,o)),l=h.getOptimisticResult(o),p=!r&&u;if(ae.useSyncExternalStore(ae.useCallback(f=>{let y=p?h.subscribe(C.batchCalls(f)):O;return h.updateResult(),y},[h,p]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),ae.useEffect(()=>{h.setOptions(o)},[o,h]),br(o,l))throw jt(o,h,i);if(lr({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!J.isServer()&&yr(l,r)&&(d?jt(o,h,i):c?.promise)?.catch(O).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}a(vr,"useBaseQuery");function Ta(t,e){return vr(t,Dt,e)}a(Ta,"useQuery");var Z=D(ie(),1);function Oa(t,e){let s=Re(e),[r]=Z.useState(()=>new Kt(s,t));Z.useEffect(()=>{r.setOptions(t)},[r,t]);let i=Z.useSyncExternalStore(Z.useCallback(o=>r.subscribe(C.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=Z.useCallback((o,c)=>{r.mutate(o,c).catch(O)},[r]);if(i.error&&ye(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}a(Oa,"useMutation");var ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",qt=a(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let n=t[s]<<16|t[s+1]<<8|t[s+2];e+=ee.charAt(n>>18&63)+ee.charAt(n>>12&63)+ee.charAt(n>>6&63)+ee.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=ee.charAt(n>>18&63)+ee.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=ee.charAt(n>>18&63)+ee.charAt(n>>12&63)+ee.charAt(n>>6&63)}return e},"A");var Ea=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),Ia="_id",Wt="_creationTime",Bt="page",gr="pageDelta",Ra=a(t=>{if(Array.isArray(t))return t;if(Ea(t)&&Array.isArray(t[Bt]))return t[Bt]},"y"),Aa=a(t=>{let e;for(let s of t){let r=s[Wt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"g"),Fa=a((t,e)=>{let s=e[Wt];if(typeof s!="number")return t.length;let r=Aa(t);for(let[i,n]of t.entries()){let o=n[Wt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),Pa=a(t=>{if(typeof t!="object"||t===null)return;let e=t[Ia];return typeof e=="string"?e:void 0},"b"),Ma=a(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"D"),La=a((t,e)=>{let{key:s,op:r,row:i}=e,n=[],o=-1;for(let c of t){let u=Pa(c);if(u===void 0)return;if(u===s){if(r==="delete")continue;o===-1&&(o=n.length)}n.push(c)}if(r==="delete")return n;if(i!==void 0)return o===-1?n.splice(Fa(n,i),0,i):n[o]=i,n},"x"),xa=a((t,e)=>{let s=Ra(t);if(s===void 0)return;let r=La(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Bt]:r}},"E"),$t=Symbol("lunora.unmergeableDelta"),Sr=a((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return Ma(s)?e===void 0?s:xa(e,s)??$t:s},"m");var wr=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var fl=new Set(Object.keys(Es)),H=class extends b{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var rt=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),zt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),xe=a(t=>zt.has(t?.code??""),"u");var _e=a(t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")?{hint:t}:{},"n");var Gt=a(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"v"),_a=a((t,e)=>{let s=Gt(e);if(!(s===void 0||rt(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"p"),ve=a(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"y"),Vt=a(()=>new H("LunoraClient: batch slot carried no error envelope"),"E"),Cr=a((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"c"),kr=a(t=>{let{code:e,messageText:s}=Cr(t,"stream error"),r=t.error,i=r?.why,n=e===void 0?new Error(s):new b(e,s,_e(r?.hint));return typeof i=="string"&&(n.why=i),n},"D"),Jt=a(t=>{let{code:e,messageText:s}=Cr(t,"subscription error"),r=t.error,i=typeof r?.why=="string"?{why:r.why}:{};return{message:s,...e===void 0?{}:{code:e},..._e(r?.hint),...i}},"O"),Qa=Symbol.for("lunora.serverVerdict"),ge=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Qa]=!0,t.data!==void 0)try{e.data=T(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"d"),Da=a(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"b"),K=a((t,e)=>Object.defineProperty(t,"headers",{value:Da(e)}),"w"),Yt=a((t,e)=>{let s=ge(t),r=_a(s,e.get("retry-after"));return r!==void 0&&(s.data=r),K(s,e)},"j"),Xt=a(t=>{let e=ve(t);return e===void 0?Vt():ge(e)},"M"),Tr=new WeakSet,it=a(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return Tr.add(e),e},"N"),Qe=a(t=>t instanceof Error&&Tr.has(t),"T");var nt=class{static{a(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var at=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Zt=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),N=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),P=a((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),Ua="http://same-origin.invalid",De=a(t=>new URL(t,Ua),"p"),Ha=/^[a-z][a-z\d+.-]*:/iu,es=a((t,e)=>{if(Ha.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var ts=0,Se,Or=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"f"),Ka=a(t=>{let e=[...t.callbacks],s=t.lastValue;return()=>{for(let r of e){if(t.lastValue!==s)return;t.callbacks.has(r)&&Or([r],s)}}},"p"),Er=a(t=>{Se===void 0?t():Se.add(t)},"k"),Ir=a(()=>ts,"L"),Na=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"y"),Rr=a((t,e)=>{e!==t.lastValue&&(t.lastValue=e,Se===void 0?Or(t.callbacks,e):Se.add(t))},"d"),ot=a((t,e=()=>!0)=>{let s=new Set;Se=s;try{t()}finally{Se=void 0;let r=[...s].map(i=>typeof i=="function"?i:Ka(i));for(let i of r){if(!e())break;try{i()}catch{}}}},"v"),oe=a((t,e)=>{Rr(t,Na(e,t.optimisticLayers))},"m"),ct=a((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Rr(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"s"),o=a(()=>{oe(t,t.serverBase)},"a");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,ts+=1,r.acknowledgedAt=ts,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"b"),ut=a((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"h"),Ar=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"g"),ce=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"w");var Fr=0,ja="lunora-bridge",qa=1e3,Wa=3e3,ht=class{static{a(this,"u")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heldData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Fr+=1,this.tabId=`tab_${String(Fr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??qa,this.leaderTimeout=e.leaderTimeout??Wa,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??ja),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,n){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}}))}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,n,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!this.leader)return;let s,r=!0;for(let[i,n]of e.entries()){let o=i<e.length-1;try{this.bc?.postMessage(o?{...n,more:!0}:n),s=n,r=!o}catch{}}!r&&s!==void 0&&this.bc?.postMessage(s)}applySubscriptionData(e){let s=this.heldData.get(e.tabId)??[];if(s.push(e),e.more===!0){this.heldData.set(e.tabId,s);return}this.heldData.delete(e.tabId),ot(()=>{for(let r of s)this.onSubscriptionData?.(r.key,r.data,r.cursor,r.epoch,r.identity)},()=>this.running)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.applySubscriptionData(e);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.heldData.delete(e.tabId),this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.heldData.delete(this.knownLeader),this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var Ue=a((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(r,s*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var Ba=1024,dt=a(t=>{let e=t.maxBuffer??Ba,s=[],r=[],i=!1,n,o=!1,c=a(()=>{let h=r.shift();if(!h)return!1;if(n)return h.reject(n),!0;if(s.length>0){let l=s.shift();return h.resolve({done:!1,value:l}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(r.unshift(h),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(h){if(!(i||n)){for(n=h,s.length=0;c(););t.onFail?.()}},push(h){if(!(i||n||o)){if(s.length>=e){u.fail(new b("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(h),c()}}},d=a(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(s.length>0){let h=s.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,l)=>{r.push({reject:l,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var we=a(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ue=a(async(t,e,s,r=()=>new H(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw we(e);let i=new AbortController,n=[],o=new Promise((u,d)=>{if(t>0){let h=setTimeout(()=>{d(r()),i.abort()},t);n.push(()=>{clearTimeout(h)})}if(e){let h=a(()=>{i.abort(),d(we(e))},"a");e.addEventListener("abort",h,{once:!0}),n.push(()=>{e.removeEventListener("abort",h)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let u of n)u()}},"m"),ss=a(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),we(e);let s=a(()=>{},"o"),r=new Promise((i,n)=>{s=a(()=>{n(we(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),Pr=a(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ue(e,void 0,async()=>t.read(),()=>new b("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var lt=/^ /u,$a=/^\d+$/u,za=2147483647,Ga=10,Va=1e3,Mr=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"O"),Ja=a(t=>{let e="",s,r,i=[];for(let n of t.split(`
2
+ `))if(n.startsWith("event:"))e=n.slice(6).replace(lt,"");else if(n.startsWith("data:"))i.push(n.slice(5).replace(lt,""));else if(n.startsWith("id:")){let o=n.slice(3).replace(lt,"");o.includes("\0")||(s=o)}else if(n.startsWith("retry:")){let o=n.slice(6).replace(lt,"");$a.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),za))}return{data:i.join(`
3
+ `),event:e,id:s,retry:r}},"U"),Ya=a((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=r[u];if(d===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Mr(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Mr(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"Y"),Xa=a((t,e)=>{if(t.event==="complete")return e.complete(t.data),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR",n=new b(i,r,_e(s.hint));return typeof s.why=="string"&&(n.why=s.why),e.fail(n),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(T(JSON.parse(t.data)))}catch{return e.fail(new b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"J"),xr=a((t,e)=>{let s="",r=!1,i=a(o=>{let c=r?`\r${o}`:o;r=c.endsWith("\r"),r&&(c=c.slice(0,-1)),s+=c.replaceAll(`\r
4
+ `,`
5
+ `)},"s"),n=a(()=>{let o=s.indexOf(`
6
+
7
+ `);if(o===-1)return"empty";let c=Ja(s.slice(0,o));return s=s.slice(o+2),e.onFrame?.(),c.id!==void 0&&e.onId?.(c.id),c.retry!==void 0&&e.onRetry?.(c.retry),Xa(c,t)?"terminal":"dispatched"},"r");return{append:i,drain:a(()=>{for(;;){let o=n();if(o==="empty")return!1;if(o==="terminal")return!0}},"drain"),next:n}},"P"),rs=a(async(t,e,s,r,i=0)=>{let n=t.getReader(),o=new TextDecoder,c=xr(e,s),u=a(()=>n.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:d,value:h}=await Pr(n,i);if(d)break;if(c.append(o.decode(h,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(d){throw r.abort(),u().catch(()=>{}),d}},"q"),_r=a(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=a(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"N"),Za=a(async(t,e,s,r)=>{let i=xr(e,s);try{i.append(await t.text())}catch(n){throw r.abort(),n}for(;;){if(r.signal.aborted)return!1;let n=i.next();if(n==="empty")return!1;if(n==="terminal")return!0;await _r(0,r.signal)}},"K"),eo=a((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"X"),to=a(async(t,e)=>{let s,r=new Promise(n=>{s=setTimeout(()=>{n(void 0)},Va)}),i=t.json().catch(n=>{if(e.aborted)throw n});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"G"),so=a((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"z"),Lr=a(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"M"),Qr=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=Ya(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:d}=dt({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel"),onFail:a(()=>{n.abort()},"onFail")}),h=s.reconnect??!1,l=Ue(),{lastEventId:p}=s,f,y=0,m=a(()=>{l.reset(),y=0},"x"),g={},S=a(w=>{try{w()}catch(I){throw g.value={error:I},I}},"R"),k={onFrame:m,onId:a(w=>{S(()=>s.onEventId?.(w)),p=w},"onId"),onRetry:a(w=>{S(()=>s.onRetry?.(w)),f=w},"onRetry")},E=a(async()=>{let w=so(s.headers,p),I=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),re=a(R=>{if(n.signal.aborted){u.complete();return}return{completed:R,error:I}},"_"),L=new AbortController,F=a(()=>{L.abort()},"A");n.signal.addEventListener("abort",F,{once:!0});try{let R=await r(i,{headers:w,method:t.method,signal:L.signal});if(!R.ok){let X=await to(R,n.signal);u.fail(eo(X,R.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read",{hint:Rs}));return}return re(await Za(R,u,k,L))}return re(await rs(R.body,u,k,L,s.idleTimeoutMs))}catch(R){if(n.signal.aborted){u.complete();return}if(g.value){let{error:X}=g.value;u.fail(X instanceof Error?X:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:Lr(R)}}finally{n.signal.removeEventListener("abort",F)}},"H");return(async()=>{try{for(;;){if(n.signal.aborted){u.complete();return}let w=await E();if(!w)return;if(w.completed||!h||y>=Ga){w.completed||u.fail(w.error);return}y+=1,await _r(f??l.next(),n.signal)}}finally{c()}})().catch(w=>{if(n.signal.aborted){u.complete();return}u.fail(Lr(w))}),d},"ne");var M=class t{static{a(this,"y")}static key(e,s,r){return`${e}::${q(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}},Y=a((t,e)=>{t.ack=e},"s"),pt=a(t=>{t.ack==="inflight"&&Y(t,"idle")},"b");function ft(t){if(t!==void 0)return e=>{t(e)}}a(ft,"o");var te=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Dr=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(M.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let d=ct(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"g");var Ur=0,ro=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Ur+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${Ur.toString(36)}_${t}`},"d"),is=a((t,e)=>t!==void 0&&e!==t,"l"),yt=ro,Ce=a((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"h"),mt=class{static{a(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=yt();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{Ce(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw Ce(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(is(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{Ce(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of s)i.has(o)&&n.add(o.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(n=>{Ce(this.onPersistenceError,"replace",n,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);this.items.unshift(...e),this.notifySize()}}drainConflict(){let e=[],s=[];for(let r of this.items){let i=!0,n;if(r.precondition!==void 0)try{i=r.precondition()}catch(o){i=!1,n=o}if(i)s.push(r);else{let o=new Error("offline mutation skipped: precondition failed before replay",n===void 0?void 0:{cause:n});o.code="OFFLINE_PRECONDITION_FAILED",r.reject(o),e.push(r)}}return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=a(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"n"),n=this.appending.get(r);this.replayingIds.has(r)?i(!1):n===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):n.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),Ce(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){Ce(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var _=a(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),bt=a((t,e,s,r)=>{let i;return()=>{if(i)return i;let n=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=n,n.catch(()=>{i===n&&(i=void 0)}),n}},"E"),vt=a((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),n=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"u");var io="lunora-outbox",no="offline-mutations",ns="by_id",ao=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??io,r=t.storeName??no,i=bt(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(ns,"id",{unique:!0})}),n=vt(i,r);return{append:a(async o=>{await n("readwrite",c=>_(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>_(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>_(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await _(c.index(ns).getKey(o));u!==void 0&&await _(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await _(c.index(ns).getKey(o.id));u!==void 0&&await _(c.put(o,u))})},"replace")}},"w"),Hr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ao()}},"b");var he=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),oo=500,co=a((t,e)=>{if(!Number.isInteger(t)||t<1)throw new b("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var uo="lunora-query-cache",ho="query-cache",Kr="by_ts",lo=1,po=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??uo,r=t.storeName??ho,i=co(t.maxEntries??oo,"createIndexedDbQueryCache"),n=bt(e,s,lo,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Kr,"ts",{unique:!1})}),o=vt(n,r),c=a(async u=>{let d=await _(u.count())-i;d<=0||await new Promise((h,l)=>{let p=u.index(Kr).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||d<=0){h();return}f.delete(),d-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>_(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>_(u.getAll())),"load"),put:a(async(u,d)=>{await o("readwrite",async h=>{await _(h.put({...d,key:u})),await c(h)})},"put"),remove:a(async u=>{await o("readwrite",d=>_(d.delete(u)))},"remove")}},"N"),Nr=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return po()}},"L");var jr=new WeakMap,as=a((t,e)=>{jr.set(t,e)},"i"),os=a(t=>t===void 0?void 0:jr.get(t),"d"),qr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present&&i.answered?q(i.value):void 0,o=a(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:q(c.value)===n},"c");return n!==void 0&&as(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var Wr="/_lunora/rpc",cs="/_lunora/rpc-batch",us="/_lunora/ws",ti="/_lunora/admin/shard-traffic",yo="/_lunora/admin/scheduled",bo="/_lunora/admin/scheduled/status",vo="/_lunora/admin/scheduled/ws",go="/_lunora/admin/scheduled/cancel",Br="/_lunora/admin/scheduled/dead",So="/_lunora/admin/scheduled/dead/retry",wo="/_lunora/admin/scheduled/dead/cancel",Co="/_lunora/admin/workflows/instances",ko="/_lunora/admin/workflows/instance",To="/_lunora/admin/workflows/status",St="/_lunora/admin/storage",si="/_lunora/admin/storage/url",ri="/_lunora/admin/storage/buckets",ii="/_lunora/admin/functions",ni="/_lunora/admin/cron-jobs",ai="/_lunora/admin/cron-jobs/run",oi="/_lunora/admin/architecture",ci="/_lunora/admin/openapi",ui="/_lunora/admin/openrpc",hi="/_lunora/admin/global/tables",di="/_lunora/admin/global/table",li="/_lunora/admin/global/facet",pi="/_lunora/admin/vector/indexes",fi="/_lunora/admin/vector/query",mi="/_lunora/admin/logs/archive",yi="/_lunora/admin/kv/namespaces",bi="/_lunora/admin/kv/keys",wt="/_lunora/admin/kv/value",vi="/_lunora/admin/auth/users",gi="/_lunora/admin/auth/sessions",Si="/_lunora/admin/auth/users/create",wi="/_lunora/admin/auth/users/role",Ci="/_lunora/admin/auth/users/ban",ki="/_lunora/admin/auth/users/unban",Ti="/_lunora/admin/auth/users/password",Oi="/_lunora/admin/auth/users/remove",Ei="/_lunora/admin/auth/users/impersonate",Ii="/_lunora/admin/auth/sessions/revoke",Ri="/_lunora/admin/auth/sessions/revoke-all",Ai="/_lunora/admin/auth/capabilities",Fi="/_lunora/admin/auth/users/update",Pi="/_lunora/admin/auth/accounts",Mi="/_lunora/admin/auth/accounts/unlink",Li="/_lunora/admin/auth/passkeys",xi="/_lunora/admin/auth/passkeys/delete",_i="/_lunora/admin/auth/two-factor/disable",Qi="/_lunora/admin/auth/organizations",Di="/_lunora/admin/auth/organizations/members",Ui="/_lunora/admin/auth/organizations/invitations",Hi="/_lunora/admin/auth/organizations/members/remove",Ki="/_lunora/admin/auth/organizations/invitations/cancel",Ni="/_lunora/admin/auth/config",ji="/_lunora/admin/auth/sign-up-invitations",qi="/_lunora/admin/auth/sign-up-invitations/create",Wi="/_lunora/admin/auth/sign-up-invitations/revoke",Bi="/_lunora/admin/auth/organizations/create",$i="/_lunora/admin/auth/organizations/update",zi="/_lunora/admin/auth/organizations/remove",Gi="/_lunora/admin/auth/organizations/members/add",Vi="/_lunora/admin/auth/organizations/members/invite",Ji="/_lunora/admin/auth/organizations/members/role",Yi="/_lunora/admin/auth/organizations/teams",Xi="/_lunora/admin/auth/organizations/teams/create",Zi="/_lunora/admin/auth/organizations/teams/update",en="/_lunora/admin/auth/organizations/teams/remove",tn="/_lunora/admin/auth/organizations/teams/members",sn="/_lunora/admin/auth/organizations/teams/members/add",rn="/_lunora/admin/auth/organizations/teams/members/remove",nn="/_lunora/admin/auth/organizations/roles",an="/_lunora/admin/auth/organizations/roles/create",on="/_lunora/admin/auth/organizations/roles/update",cn="/_lunora/admin/auth/organizations/roles/remove",Oo="/api/auth",Eo="/get-session",Io="lunora-ping",hs=500,un=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Pe");new TextDecoder;var Ro=new TextEncoder,Ao=a(t=>qt(Ro.encode(t)),"Qt"),Fo=a(t=>Ao(JSON.stringify(t)),"xt"),Po="x-lunora-expect-subject",Mo=a(t=>Fo({subject:t}),"Kt"),Lo="refreshBatch",$r=Symbol.for("lunora:session-change"),xo="lunora:session-change",_o="better-auth.message",Qo="signout",hn=a(()=>{let t=globalThis,e=t[$r];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[$r]=e),e},"Me"),Do=a(()=>"document"in globalThis,"Jt"),Uo=a(async()=>{let t=[];for(let e of hn().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"zt"),Ho=a((t,e)=>{if(t!==_o||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Qo}catch{return!1}},"Yt"),Ko=a(t=>{let e=[],s=a(()=>{Uo().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(xo):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=a(o=>{Ho(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"Xt"),No=a(t=>{let e=hn();return e.listeners.add(t),e.detach===void 0&&Do()&&(e.detach=Ko(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Zt"),zr="/_lunora/ws/reauth",jo="lunora",qo="lunora.bearer.",Wo=a(t=>`${qo}${qt(new TextEncoder().encode(t))}`,"ss"),Bo=a(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"is"),vs=a(t=>"args"in t?{...t,args:T(t.args)}:t,"ae"),dn=a(async t=>(t.assertOpen(),((await t.adminFetch(yo,"GET")).records??[]).map(e=>vs(e))),"Tr"),ln=a(async t=>{t.assertOpen();let e=await t.adminFetch(bo,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Cr"),pn=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(go,"POST",{id:e})).cancelled===!0}),"kr"),fn=a(async t=>(t.assertOpen(),(await Bo(async e=>await t.adminFetch(e===void 0?Br:`${Br}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>vs(e))),"Ar"),mn=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(So,"POST",{id:e})).retried===!0}),"Er"),yn=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(wo,"POST",{id:e})).removed===!0}),"_r"),bn=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${Co}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Ir"),vn=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${ko}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"Rr"),gn=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(To,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Or"),B=a((t,e)=>{try{return U(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"C"),ps=a(t=>{try{return U(t),!0}catch{return!1}},"te"),Sn=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Fe"),$o=a((t,e,s)=>{let r=Array.from({length:e}),i=a(n=>({error:K(Xt(n),s),ok:!1}),"i");for(let n of t){if(typeof n.id!="number"||n.id<0||n.id>=e)continue;if(!Sn(n.body)){r[n.id]=i({});continue}let o=n.body;if("error"in o){r[n.id]=i(o);continue}try{r[n.id]={ok:!0,value:T(o.result)}}catch(c){r[n.id]={error:K(it(c),s),ok:!1}}}return r.map(n=>n??{error:K(new Error("batch call returned no result"),s),ok:!1})},"rs"),ds=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"X"),He=a(t=>t==="connected"||t==="polling","D"),v=a(t=>t??"","f"),$=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),zo=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)$(t,s)},"ns"),Go=new TextDecoder,Vo=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Go.decode(t)},"as"),se=class{static{a(this,"O")}listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},ke=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),Jo=a((t,e,s)=>{ke(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(Io)}catch{}},e))},"cs"),Gr=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let u=a(()=>{ke(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=a(h=>{u(),r.onClose(h)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},n)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}t.socket===c&&Jo(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"Ce"),Yo=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),p=a(y=>{if(u!==void 0){if(!y){l();return}d||(d=!0,i()),r()}},"l"),f=a(()=>{h||(h=!0,n().then(p).finally(()=>{h=!1}).catch(()=>{}))},"p");return{hasFailedOpen:a(()=>c>0,"hasFailedOpen"),isPolling:a(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"ds"),Xo=1e4,Vr=a(async t=>ue(Xo,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),wn=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Jr=a(t=>{if(t instanceof H)return!0;let e=t?.code;return e===void 0||wn.has(e)||zt.has(e)},"Ae"),Zo=1e3,Cn=6e4,ec={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ke=a((t,e,s)=>{let r=Gt(s.get("retry-after")),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`,o=t<400||t>=500||t===408?new H(n,i):new b(ec[t]??"BAD_REQUEST",n,{data:i});return K(o,s)},"W"),fs=a((t,e=Math.random)=>{let s=Math.min(Zo*2**Math.max(t-1,0),Cn);return Math.round(s*(.5+e()*.5))},"se"),tc=a(t=>{let e=t?.code;return t instanceof H||e===void 0||wn.has(e)},"fs"),sc=a((t,e,s)=>{let r=rt(t);return r!==void 0&&r>0?Math.min(r,Cn):tc(t)?fs(e,s):void 0},"ps"),rc=983040,ic=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"ys"),nc=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&Sn(s.body)&&e.set(s.id,s.body);return e},"Ss"),ac=a((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:K(Xt(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:K(it(s),e),kind:"undecodable"}}},"vs"),ls=a((t,e)=>`${v(t)}\0${e}`,"Z"),oc=a((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"bs"),ms=class{static{a(this,"gs")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){un(this.buffers,this.maxBuffers),this.buffers.set(ls(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(ls(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:T(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=ls(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},cc=a((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),n=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=n!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==n;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),oc(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"ws"),Yr=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Ee"),uc=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&te(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Ts"),ys=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"ie"),bs=a((t,e=!1)=>{let s=t.serverCursor,r=t.lastMutationId;Er(()=>{for(let i of t.checkpointCallbacks)i({checkpoint:s,mutationId:r,...e&&{rowsFollow:!0}})})},"re"),kn=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ne"),hc=a((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Cs"),dc=a(t=>t.type==="delta"&&t.more===!0,"ks"),Ct=a((t,e)=>t!==void 0&&t!==e,"j"),lc=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","As"),pc=a(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"Es"),fc=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())Y(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"_s"),mc=a((t,e,s)=>{if(Ct(s,t.identityFingerprint()))return;let r=t.leader,i=lc(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"Is"),yc=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Rs"),bc=a((t,e,s,r,i,n)=>{if(Ct(n,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,kn(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&ut(o,r),oe(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"Os"),vc=a((t,e,s,r)=>{if(Ct(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let n=!i.valueReceived;i.valueReceived=!0,te(i.errorCallbacks,s),n&&t.emitConnectionStatus(),t.settleAwaitedAnswer(i,!1)}},"Ls"),gc=a((t,e,s,r,i,n,o)=>{if(Ct(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&ys(c,i),bs(c))},"Ps"),Sc=a((t,e,s)=>t!==null||e&&s===null,"Ms"),wc=a(t=>t.sensitive===!0,"Fs"),Cc=a((t,e)=>{if(!wc(t))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"Hs"),kc=[gr,Lo],Tc=a(t=>t.type==="data"||t.type==="delta"||t.type==="settled"||t.type==="resume"||t.type==="error"&&typeof t.id=="string","Ns"),Oc=100,Tn=1e4,Ec=1e4,Ic=a((t,e)=>{let s,r=new Promise((n,o)=>{s=setTimeout(()=>{o(new Error("ws ticket mint timed out"))},e)}),i=(async()=>t())();return Promise.race([i,r]).finally(()=>{clearTimeout(s)})},"Bs"),Xr=a(async t=>typeof t=="function"?await t():t,"_e"),Zr=a(async(t,e,s,r)=>{let i=new AbortController,n=setTimeout(()=>{i.abort()},Tn);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return{status:o.status,text:await o.text()}}finally{clearTimeout(n)}},"Ie"),ei=a((t,e)=>new b("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Is}),"Re"),Rc=a((t,e)=>t instanceof TypeError&&ps(e),"Qs"),Ac=a((t,e,s,r)=>e||t===!0&&s&&!r,"xs"),Fc=Promise.resolve(),Pc=a(async(t,e,s)=>{let r,i,n=new AbortController,o=a(()=>{n.abort(e?.reason)},"a");e?.addEventListener("abort",o,{once:!0});try{await rs(t,{complete:a(c=>{e?.aborted!==!0&&(r=c)},"complete"),fail:a(c=>{i=c},"fail"),push:a(c=>{e?.aborted!==!0&&s?.(c)},"push")},{},n)}finally{e?.removeEventListener("abort",o)}if(e?.aborted===!0)throw e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError");return{failure:i,terminal:r}},"Ks"),gt=class t{static{a(this,"We")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new M;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new se;statusListeners=new se;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new se;identityChangeListeners=new se;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new se;pendingChangeListeners=new se;syncStatusListeners=new se;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new ms(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??N(Zt(e.url),us),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??Oo;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??wr(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=Hr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Nr(e.queryCache),this.clientQueryStore=new nt,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=Fc),this.offlineQueue=new mt(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:a(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${yt()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=No(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let d=this.identityFingerprint(),h=!r&&e!==null&&n,l=!r&&e===null&&i===null&&n&&!c,p=d!==i,f=!1;p&&(h?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,u,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(u,e,p)),p&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&He(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")})}catch(h){if(!Qe(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(un(this.clientWatermarks,8),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(N(this.url,`${this.authBasePath}${Eo}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=v(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=v(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=v(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&$(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:n,topic:o}=e;if(o.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=v(i),d=`/live/${n}/control`,h=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=a(()=>{let m=h;h=void 0,m?.()},"l"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:n,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),g=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let S=this.getConnection(i)?.connectionId;g&&S!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:S,stream:n,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,B(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,n=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=a(()=>{c.length=0},"c"),d=a(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),h=v(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:a(()=>{o=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),n()},"close"),send:a(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=B(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=Oc?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:a(()=>{},"close"),send:a(()=>{},"send")};let i=a(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),n,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:a(()=>{clearTimeout(n),i(s.onClose)},"onClose"),onMessage:a(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(T(u.data))}))},"onMessage"),onOpen:a(()=>{clearTimeout(n);let c=o.socket();n=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:a(()=>{clearTimeout(n),o.close()},"close"),send:a(c=>{let u=JSON.stringify(B(c,`socket message for '${e}'`)),d=o.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let n of this.subscriptions.all())(s||this.connectionGateState(n.shardKey).polling?n.valueReceived:n.ack==="acked")||(r+=1);for(let n of this.shapeSubscriptions.values())n.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:He(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let o=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.ack==="acked",functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.answered,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){let{WebSocketImpl:e}=this;if(e===void 0)return;let s=a(o=>o.protocol==="wss:"||o.protocol==="https:","t"),r=De(this.wsUrl),i=a(o=>{let c=De(String(o));return c.host===r.host&&s(c)===s(r)},"i"),n=e;return new Proxy(e,{construct:a((o,[c,u,...d])=>new n(c,u??(i(c)?this.upgradeProtocols():void 0),...d),"construct")})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){let s=this.getConnection(e.shardKey);return s===void 0||s.wsState==="open"?!0:s.polling.isPolling()||!s.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return qr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:ss(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,q(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=he(e,s,r),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=M.key(e,s,r),n=this.subscriptions.get(i);return{answered:n!==void 0&&(n.lastValue!==void 0||n.ack==="acked"||n.valueReceived),present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ue(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw we(r.signal);let{value:i}=await ss(this.runMutation(e,s,r),r.signal);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),p=d,{committed:f}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});d+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(N(Zt(this.url),vo),{onMessage:a(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(n=>vs(n))))},"onMessage")});return s.close}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let n=s??{},o=M.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=ft(r),d=ft(i.onError),h=ft(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=q(n),g=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={ack:"idle",args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:g?.value,optimisticLayers:[],serverBase:g?.value,serverCursor:g?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:B(n,`args for '${e.__lunoraRef}'`),...g?.serverEpoch===void 0?{}:{serverEpoch:g.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&He(this.computeStatus())&&this.awaitLeaderAnswer(c),g!==void 0&&this.cacheSeededQueries.set(o,g)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,p=!1,f=a(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(M.keyOf(l)),this.subscriptions.remove(l);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={answered:!1,args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:B(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey),this.emitSyncStatus()}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=dt({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:B(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:n};this.streams.set(i,l);let p=d?.wsState==="open"&&$(d,h);if(!p&&d===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=64;){let f=d.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Qr(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}async streamRpc(e,s={},r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i=e.__lunoraRef,n=await this.fetchImpl(N(this.url,Wr),{body:JSON.stringify({args:B(s,`args for '${i}'`),functionPath:i,shardKey:r.shardKey}),headers:{accept:"text/event-stream",...this.rpcRequestHeaders({},r.shardKey)},method:"POST",...r.signal?{signal:r.signal}:{}});if(!n.ok){let d=await n.json().catch(()=>{});if(d?.error)throw ge(d.error);let h=n.statusText?` ${n.statusText}`:"";throw new b("INTERNAL",`LunoraClient: request failed (status ${n.status.toString()}${h})`)}if(!n.body)throw new b("HTTP_STREAM_NO_BODY","LunoraClient: streaming response has no body");let{failure:o,terminal:c}=await Pc(n.body,r.signal,r.onFrame);if(o!==void 0)throw o;if(c===void 0)throw new b("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a complete frame");let u;try{u=JSON.parse(c)}catch{throw new b("HTTP_STREAM_BAD_CHUNK","LunoraClient: streaming result is not valid JSON")}if(typeof u!="object"||u===null||!("result"in u))throw new b("HTTP_STREAM_INTERRUPTED","LunoraClient: stream ended without a result");return T(u.result)}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(let e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,s,r,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(r,i),Sc(e,s,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,s,r){return!this.authTokenOnUpgrade||s===null||e===s?"none":r?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[jo,Wo(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=a(r=>v(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=v(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},5e3))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=v(e.shardKey);for(let[i,n]of this.streams)v(n.shardKey)===s&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,ke(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeShapes:a(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),awaitLeaderAnswers:a(()=>{this.awaitLeaderAnswers()},"awaitLeaderAnswers"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),settleAwaitedAnswer:a((r,i)=>{this.settleAwaitedAnswer(r,i)},"settleAwaitedAnswer"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new ht({channelName:e,onBecomeLeader:a(()=>{pc(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{fc(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{mc(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{bc(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{yc(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{vc(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{gc(s,r,i,n,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(N(this.url,cs),{body:JSON.stringify({calls:e.map((c,u)=>({args:B(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw K(new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`),r.headers)}let o=ve(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?K(ge(o),r.headers):K(new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return $o(n.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=Cc(e,r),n=s,o=i.mutationId??yt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,n,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,h);let p=i.onlineOnly?void 0:this.offlineFlushes.get(v(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:g}=this.writeQueueGate(i.shardKey),S=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),k=a(async(w=!1)=>this.enqueueOfflineMutation(e,n,i.shardKey,d,o,l,h,w?void 0:i.precondition,i.mutationId,u?.stamp,w,c),"b");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),g||y||S)return k();let E;try{let w=await this.rpc(e.__lunoraRef,n,i.shardKey,{baselineSeq:d,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:a(I=>{E=I},"onCommitCursor")});for(let I of h)I(E);return{committed:!0,value:w}}catch(w){let I=Rc(w,n),re=f&&m&&I,L=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof H)&&ps(n)){let F=k(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),F}throw this.settleFailedDirectWrite(w,E,h,l,u?.flags.authToken),Ac(i.onlineOnly,re,I,L)?ei(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ce(r),ei(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:n,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=n||c,d=this.WebSocketImpl!==void 0&&u,h=i||r;return{httpFirst:h,midReconnect:o==="connecting"&&u&&!h,shouldQueueOffline:d,socketDown:o!=="open"&&!s&&d&&!h,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Qe(e)){for(let o of r)o(s);return}ce(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h,l,p){let f=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let y=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:a(()=>{ce(o)},"onRejected")},shardKey:r})}catch(m){throw ce(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let g={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,issueSeq:p,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(u),onCommit:a(S=>{for(let k of c)k(S)},"onCommit"),reject:a(S=>{this.queuedIdentities.delete(n),Qe(S)||ce(o),m(S instanceof Error?S:new Error(String(S))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(g),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),g.id!==void 0&&this.queuedIdentities.set(g.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=v(e);return this.offlineQueue.hasPending(r=>v(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(he(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(is(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(he(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),oe(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,oe(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=he(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=he(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=he(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=a(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=a(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=v(e),r;for(let i of this.subscriptions.all())v(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=v(e),r=[];for(let c of this.subscriptions.all())v(c.shardKey)===s&&(ps(c.args)?r.push(c):(this.markQueryRejected(c,!0),te(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=Ir(),n=this.identityFingerprint(),o;try{o=await Vr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){this.markQueryRejected(u,!0),te(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:U(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await Vr(async s=>e(N(this.url,cs),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=M.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=ct(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,n){e&&this.applyOptimisticUpdate(e,s,r,i,n)}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Dr(this.subscriptions,r);try{e(u,s)}catch{ce(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(v(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!$(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(v(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=v(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Yo({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:a(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:a(()=>{this.emitConnectionStatus()},"onStateChange"),poll:a(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Ue(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:a(()=>{},"close"),resetBackoff:a(()=>{},"resetBackoff"),socket:a(()=>{},"socket")};let r=Ue(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(p,r.next()))},"o"),u=a(m=>{o||this.WebSocketImpl===void 0||Gr(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:a(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),d=0,h,l=a(async m=>{let g=this.wsCredentialGeneration;d+=1;let S=d,k;h=g;try{k=await Ic(m,Ec)}catch{S===d&&(h=void 0,c());return}if(S===d){if(h=void 0,g!==this.wsCredentialGeneration){p();return}u(k)}},"h"),p=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"l");p();let f=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ke(i);let{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}},"p");this.adminSocketTeardowns.add(f);let y=a(()=>{let{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ke(i);try{m.close()}catch{}s.onClose?.(),c()},"S");return this.supplementaryBounces.add(y),{close:a(()=>{f(),this.adminSocketTeardowns.delete(f),this.supplementaryBounces.delete(y)},"close"),resetBackoff:a(()=>{r.reset()},"resetBackoff"),socket:a(()=>i.socket,"socket")}}supplementaryUrl(e){let s=De(this.wsUrl),r=s.pathname.endsWith(us)?s.pathname.slice(0,-us.length):s.pathname;return s.pathname=N(r,e),es(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=De(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let n=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!n.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),es(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[Po]=Mo(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){let{fetchImpl:n}=this;if(!n)throw new H("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:B(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:d,response:h}=await ue(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await n(N(this.url,Wr),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=h.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(d===void 0)throw Ke(h.status,h.statusText,h.headers);let l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw Ke(h.status,h.statusText,h.headers);let p=ve(d);if(p!==void 0)throw Yt(p,h.headers);if(!h.ok)throw Ke(h.status,h.statusText,h.headers);i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(h,r),this.recordShardCursor(r,d.commitCursor);try{return T(d.result)}catch(f){throw K(it(f),h.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(N(this.url,e),{body:c,headers:n,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=ve(d);if(h!==void 0)throw ge({...h,message:h.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(v(e.shardKey));$(e,{caps:kc,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())v(s.shardKey)===v(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);s.wsState==="open"||s.wsState==="connecting"||(s.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(s,e).catch(()=>{this.handleDisconnect(s)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,s){let{wsToken:r,wsTicket:i}=this;if(typeof r=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,s);return}this.openSocket(e,s,{session:r,ticket:i})}async openSocketWithProvidedCredentials(e,s){let r=this.wsCredentialGeneration,i=Symbol("ws-token-attempt"),n;e.providerAttempt=i;try{n=await ue(this.connectTimeoutMs,void 0,async()=>({session:await Xr(this.wsToken),ticket:await Xr(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,n)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;Gr(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:a(n=>{n?.code===4003&&e.polling.noteFailedOpen(),n?.code===4001?this.notifyTokenExpired():n?.code===4003&&n.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:a(n=>{e.retired!==!0&&this.handleServerMessage(n.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.heldFrames=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.sendConnectEnvelope(e),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(let c of this.subscriptions.all())v(c.shardKey)===v(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:d}of c)$(e,{id:u,type:d});this.releaseIdleShard(s)}zo(e);let n=v(s),o=this.whisperHandlers.get(n);if(this.dropWhisperJoinWaiters(n),this.whisperJoins.set(n,new Map),o)for(let c of o.keys())this.sendWhisperJoin(e,n,c);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen"),protocols:this.upgradeProtocols()})}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),$(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),ke(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(v(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(v(n.shardKey)!==v(e.shardKey)||s.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e,s=!1){let r=v(e);for(let i of this.subscriptions.all())v(i.shardKey)===r&&(Y(i,"idle"),i.pendingDeltaRun=void 0,s&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(let i of this.shapeSubscriptions.values())v(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.ack==="acked"||!s&&e.ack==="inflight")return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,n=$(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return n&&Y(e,"inflight"),n&&!s&&this.armUnackedWatchdog(r,e),n}armUnackedWatchdog(e,s,r=!1){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{if(r){e.unackedWatchdogs.delete(s.id),pt(s),this.settleAwaitedAnswer(s,!1);return}let i=s.ack!=="acked"&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0);this.settleSubscribeWatchdog(e,s.id),i?this.armUnackedWatchdog(e,s,!0):pt(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&$(s,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=Vo(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}let n=this.getConnection(s);if(i.type!=="error"&&n?.reconnect.reset(),n&&typeof i.id=="string"&&this.settleSubscribeWatchdog(n,i.id),i.type==="batchStart")n&&(n.heldFrames=[]);else if(i.type==="batchEnd"){let o=n?.heldFrames;if(n&&o){let{socket:c}=n;n.heldFrames=void 0,ot(()=>{for(let u of o){if(n.retired===!0||n.socket!==c)break;this.dispatchServerMessage(u,s)}},()=>!this.closed)}}else n?.heldFrames&&Tc(i)?n.heldFrames.push(i):this.dispatchServerMessage(i,s)}dispatchServerMessage(e,s){switch(e.type){case"ack":{let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{let{data:r,generation:i,id:n,seq:o}=e,c=this.streams.get(n);c&&typeof o=="number"&&(c.lastSeq=o,typeof i=="number"&&(c.generation=i),c.durable=!0),c?.handle.push(T(r));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.handleDataMessage(e);return}case"error":{this.handleErrorMessage(e);break}case"identity":{this.handleIdentityFrame(e,s),this.adoptSocketConnectionId(e,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(e,s);break}case"pokeEnd":{this.handlePokeEnd(e,s);break}case"pokePart":{this.pokeAssembler.part(s,e);break}case"pokeStart":{this.pokeAssembler.start(s,e);break}case"resume":{this.handleResumeMessage(e);break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(v(s),e.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(kr(e)),this.forgetStream(r);return}let n=r===void 0?void 0:this.subscriptions.getById(r);if(n){pt(n);let c=Jt(e),u=this.identityFingerprint(),d=M.keyOf(n);this.markQueryRejected(n),te(n.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),te(o.errorCallbacks,Jt(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(s?e.valueReceived:e.ack==="acked")&&(s?e.valueReceived=!0:Y(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){uc(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,s,r){let i=e.answered,n=cc(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),Yr(e),n==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){Y(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&hc(i,e))return;let n,o=i.pendingDeltaRun;try{n=Sr(e,o===void 0?i.serverBase:o.payload)}catch(u){i.pendingDeltaRun=void 0,te(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${u instanceof Error?u.message:String(u)}`}),this.settleAwaitedAnswer(i,!1);return}if(n===$t){this.resnapshotSubscription(i);return}if(dc(e)){i.pendingDeltaRun={payload:n};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(M.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(kn(i,n,{cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(ys(i,e.lastMutationId),bs(i,!0)),this.persistQueryValue(i),ut(i,i.serverCursor),s!==void 0&&Ar(i,s),oe(i,n),this.tabCoordinator?.isLeader()){let u=M.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(u,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(M.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(s,!0))}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&ys(s,e.lastMutationId),bs(s),this.tabCoordinator?.isLeader())){let r=M.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=e.ack!=="acked";Y(e,"acked"),i&&this.emitSyncStatus(),(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),ut(e,e.serverCursor)&&oe(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(v(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=v(e),n=this.liveSocketGrants.get(i)?.get(s);if(n===void 0)return;let{stream:o,topic:c}=n,u=a(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,$(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let n of i.waiters.splice(0))clearTimeout(n.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let n={run:r,timer:void 0};n.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==n),r()},Tn),i.waiters.push(n)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let n=v(e),o=this.liveSocketGrants.get(n),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(n),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:n}=this;if(!n)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>Zr(n,N(this.url,e),o,c)).then(({status:u})=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(v(s));if(!r)return;let i=T(e.data);for(let n of r.values())if(!(n.stream!==e.stream||n.topic!==e.topic))try{n.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(v(s))?.get(e.topic);if(!r)return;let i=T(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(Y(r,"idle"),this.emitSyncStatus(),te(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&He(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),n=i!==void 0&&$(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),n}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(v(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}reconnectCold(){for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,Y(e,"idle"),e.valueReceived=!1,oe(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Yr(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){let{authToken:s,fetchImpl:r}=this;for(let i of this.connections.values()){let{connectionId:n}=i;e&&s!==null&&r!==void 0&&i.socket!==void 0&&n!==void 0&&i.retired!==!0?Zr(r,N(this.url,i.shardKey===void 0?zr:`${zr}?shard=${encodeURIComponent(i.shardKey)}`),JSON.stringify({connectionId:n}),{authorization:`Bearer ${s}`,"content-type":"application/json"}).then(({text:o})=>JSON.parse(o)?.ok===!0).catch(()=>!1).then(o=>{!o&&!this.closed&&this.authToken===s&&i.connectionId===n&&this.bounceShardSocket(i)}).catch(()=>{}):this.bounceShardSocket(i)}for(let i of this.supplementaryBounces)i()}bounceShardSocket(e){if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=v(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&He(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}snapshotAnswer(e){let s=os(e),r=s&&this.subscriptions.get(M.key(s.functionPath,s.args,s.shardKey));if(r!==void 0)return this.awaitingAnswer.has(r)?"awaiting":this.answeredUnreadable.has(r)?"unreadable":void 0}holdWhileUnanswered(e){let s=os(e);if(e===void 0||s===void 0)return e;let r=a(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return as(r,s),r}awaitLeaderAnswers(){for(let e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*1e4))}settleAwaitedAnswer(e,s){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),s&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(s||this.answeredUnreadable.add(e),this.answerHeldShards.delete(v(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,s){let r=s.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return r===-1?s:(this.offlineQueue.requeue(s.slice(r)),this.answerHeldShards.add(e),s.slice(0,r))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=v(e),n=this.holdUndecidedWrites(i,this.offlineQueue.drain(h=>v(h.shardKey)===i));if(n.length===0)return;let o=[],c=[];for(let h of n){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let d=[];for(let h=0;h<u.length;h+=hs){let l=u.slice(h,h+hs),p=await this.replayBatched(l,e,s);if(d.push(...p.requeue),p.stop||p.requeue.length>0){d.push(...u.slice(h+hs));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=v(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,fs(i))})}noteReplayRetryDelay(e,s,r){let i=v(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=sc(s,o)??(r===null&&xe(s)?fs(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?n?.delayMs:Math.max(n?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=v(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{B(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Jr(e)}noteReplayAuthRefusal(e,s){if(!xe(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...ds(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||xe(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!Jr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let o;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...ds(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Qe(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(n,c)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((d,h)=>({args:B(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&ic(i)>rc)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:n}=this,o,c;try{({payload:c,response:o}=await ue(this.rpcTimeoutMs,void 0,async d=>{let h=await n(N(this.url,cs),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...ds(e.find(l=>l.identity!==void 0)?.identity,r)}),method:"POST",signal:d});if(h.status===413&&e.length>1)return{payload:void 0,response:h};try{return{payload:await h.json(),response:h}}catch{return{payload:void 0,response:h}}}))}catch(d){return this.noteReplayRetryDelay(s,d,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,d),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,Ke(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let d=ve(c),h=d===void 0?Ke(o.status,o.statusText,o.headers):Yt(d,o.headers);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r,o.headers),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof H||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop||n.requeue.length>0)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i,n){let o=nc(s),c=[],u=!1,d=!1;for(let[h,l]of e.entries()){let p=ac(o.get(h),n);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{d||=xe(p.error),this.shouldRequeueReplayFailure(p.error,i)&&!this.spendsLastReplayAttempt(l,p.error)?(this.noteReplayRetryDelay(r,p.error,i),c.push(l)):this.settleReplayTerminal(l,p.error);break}case"unanswered":{let f=K(Vt(),n);if(this.spendsLastReplayAttempt(l,f)){this.settleReplayTerminal(l,f);break}this.noteReplayRetryDelay(r,f,i),c.push(l);break}default:u=!0,this.settleReplayUndecodable(l,p.error,p.commitCursor)}}return u&&!d&&this.noteCredentialAccepted(i),c}};var Mc=a(async t=>(t.assertOpen(),(await t.adminFetch(ii,"GET")).functions??[]),"Rt"),Lc=a(async t=>(t.assertOpen(),(await t.adminFetch(ni,"GET")).jobs??[]),"gt"),xc=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(ai,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Gt"),_c=a(async t=>(t.assertOpen(),await t.adminFetch(ci,"GET")),"Ct"),Qc=a(async t=>(t.assertOpen(),await t.adminFetch(oi,"GET")),"Nt"),Dc=a(async t=>(t.assertOpen(),await t.adminFetch(ui,"GET")),"Mt"),Uc=a(async t=>(t.assertOpen(),await t.adminFetch(hi,"GET")),"kt"),Hc=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(U(e.filters))),T(await t.adminFetch(`${di}?${s.toString()}`,"GET"))},"vt"),Kc=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(U(e.filters))),T(await t.adminFetch(`${li}?${s.toString()}`,"GET"))},"Lt"),Nc=a(async t=>(t.assertOpen(),(await t.adminFetch(yi,"GET")).namespaces??[]),"Vt"),jc=a(async(t,e)=>{t.assertOpen();let s=P(bi,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Kt"),qc=a(async(t,e)=>{t.assertOpen();let s=P(wt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Bt"),Wc=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(wt,"PUT",e)},"Dt"),Bc=a(async(t,e)=>{t.assertOpen();let s=P(wt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Jt"),$c=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(ti,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"xt"),zc=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(mi,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"$t"),Gc=a(async(t,e={})=>{t.assertOpen();let s=P(St,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"zt"),Vc=a(async(t,e,s)=>{t.assertOpen();let r=`${St}?key=${encodeURIComponent(e)}${at(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"jt"),Jc=a(async t=>(t.assertOpen(),(await t.adminFetch(ri,"GET")).buckets??[]),"Wt"),Yc=a(async(t,e)=>{t.assertOpen();let s=`${St}?key=${encodeURIComponent(e.key)}${at(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"qt"),Xc=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${si}?key=${encodeURIComponent(e)}${i}${at(s?.bucket)}`,o=await t.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Qt"),Zc=a(async t=>(t.assertOpen(),(await t.adminFetch(pi,"GET")).indexes??[]),"Yt"),eu=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(fi,"POST",e)).matches??[]),"Xt"),gs=class extends gt{static{a(this,"sa")}async shardTraffic(e){return $c(this.adminHost,e)}async listScheduledJobs(){return dn(this.adminHost)}async schedulerStatus(){return ln(this.adminHost)}async cancelScheduledJob(e){return pn(this.adminHost,e)}async listDeadJobs(){return fn(this.adminHost)}async retryDeadJob(e){return mn(this.adminHost,e)}async removeDeadJob(e){return yn(this.adminHost,e)}async listWorkflowInstances(e){return bn(this.adminHost,e)}async getWorkflowInstance(e){return vn(this.adminHost,e)}async setWorkflowInstanceStatus(e){return gn(this.adminHost,e)}async listFunctions(){return Mc(this.adminHost)}async getCronJobs(){return Lc(this.adminHost)}async runCronJob(e){return xc(this.adminHost,e)}async fetchOpenApi(){return _c(this.adminHost)}async fetchArchitecture(){return Qc(this.adminHost)}async fetchOpenRpc(){return Dc(this.adminHost)}async listStorageObjects(e={}){return Gc(this.adminHost,e)}async deleteStorageObject(e,s){return Vc(this.adminHost,e,s)}async listStorageBuckets(){return Jc(this.adminHost)}async uploadStorageObject(e){return Yc(this.adminHost,e)}async signedStorageUrl(e,s){return Xc(this.adminHost,e,s)}async listGlobalTables(){return Uc(this.adminHost)}async readGlobalTablePage(e){return Hc(this.adminHost,e)}async facetGlobalColumn(e){return Kc(this.adminHost,e)}async listVectorIndexes(){return Zc(this.adminHost)}async queryVectorIndex(e){return eu(this.adminHost,e)}async queryLogArchive(e={}){return zc(this.adminHost,e)}async listKvNamespaces(){return Nc(this.adminHost)}async listKvKeys(e){return jc(this.adminHost,e)}async getKvValue(e){return qc(this.adminHost,e)}async putKvValue(e){return Wc(this.adminHost,e)}async deleteKvKey(e){return Bc(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=P(vi,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminHost.adminFetch(s,"GET")}async createAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Si,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(wi,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ci,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ki,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ti,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Oi,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ei,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ii,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ri,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ai,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Fi,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(P(Pi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(P(Li,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(xi,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(P(Qi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=P(Di,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.adminHost.assertOpen();let s=P(Ui,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.adminHost.assertOpen();let s=P(ji,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(qi,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Wi,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Hi,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ki,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Bi,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch($i,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(zi,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Gi,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Vi,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ji,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=P(Yi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Xi,"POST",e)}async updateAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Zi,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(en,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=P(tn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(sn,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(rn,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=P(nn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(an,"POST",e)}async updateAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(on,"POST",e)}async deleteAuthOrgRole(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(cn,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=P(gi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},Ss=a(t=>"listAuthUsers"in t,"ea");var Rn=D(As(),1);var Q=D(ie(),1);var kt=D(Tt(),1);var ws=a(t=>q(t),"b");var On=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"E"),Cs={status:"idle"},En=a((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),tu=1e4,su=a(async(t,e,s)=>new Promise((r,i)=>{if(e.aborted){i(e.reason);return}let n,o,c=a(()=>{clearTimeout(n),o?.(),t.waiters.delete(d),e.removeEventListener("abort",u)},"l"),u=a(()=>{c(),i(e.reason)},"t"),d=a(h=>{c(),r(h)},"n");n=setTimeout(()=>{d(!1)},tu),t.waiters.add(d),e.addEventListener("abort",u,{once:!0}),o=s(()=>{d(!1)}),t.waiters.has(d)||o()}),"U"),Ts=class{static{a(this,"V")}constructor(e){this.client=e}client;entries=new Map;live=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(ws(e))}async liveValue(e,s,r,i){let{fetch:n,shardKey:o,waitForPush:c=!0}=i;if(!("window"in globalThis)||this.client.getWebSocketImpl()===void 0)return n();let u=ws(s),d=this.liveFor(u),h=d.state.status==="pushed"?e.getQueryData(s)??d.state.value:void 0;if(h!==void 0)return h;if(c&&d.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await su(d,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(u)}if(f)return this.liveValue(e,s,r,i)}let l=d.state,p;try{p=await n()}finally{this.forgetIdleLive(u)}if(d.state!==l&&d.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:d.state.value}return p}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=a(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))On(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=ws(s),u=this.entries.get(c);if(!u){u={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,u);let p=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=Cs;for(let m of p.clients.keys())On(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of p.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},En(y,!0)},{onError:a(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},En(y,!1));for(let m of p.errorCallbacks)m(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}u.clients.set(e,(u.clients.get(e)??0)+1);let d=this.live.get(c);d?.state.status==="pushed"&&e.setQueryData(s,d.state.value);let{onError:h}=o;h&&u.errorCallbacks.add(h);let l=!1;return()=>{if(l)return;l=!0;let p=this.entries.get(c);if(!p)return;let f=(p.clients.get(e)??1)-1;f>0?p.clients.set(e,f):p.clients.delete(e),h&&p.errorCallbacks.delete(h),p.clients.size===0&&(p.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}liveFor(e){let s=this.live.get(e);return s||(s={state:Cs,waiters:new Set},this.live.set(e,s)),s}forgetIdleLive(e){!this.entries.has(e)&&this.live.get(e)?.waiters.size===0&&this.live.delete(e)}dropLive(e){let s=this.live.get(e);s!==void 0&&(s.waiters.size===0?this.live.delete(e):s.state=Cs)}},In=new WeakMap,ks=a(t=>{let e=In.get(t);return e||(e=new Ts(t),In.set(t,e)),e},"L"),An=(0,Q.createContext)(null),ru=(0,Q.createContext)(!1),iu=a(()=>new Nt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),nu=a(t=>{let e=(0,Rn.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,Q.use)(Ie),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??iu(),"h"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,Q.useState)(o),u=i??n??c,d,h;e[3]!==r||e[4]!==u?(d=a(()=>{ks(r).clearOnIdentityChange(u)},"n"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,Q.useEffect)(d,h);let l=(0,Q.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=a(()=>{l.current!==r&&(ks(l.current).stopClearingOnIdentityChange(u),l.current=r,ks(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"a"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,Q.useEffect)(p,f);let[y]=(0,Q.useState)(r),m=r!==y,g;e[11]!==s||e[12]!==m?(g=(0,kt.jsx)(ru,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=g):g=e[13];let S;e[14]!==r||e[15]!==g?(S=(0,kt.jsx)(An,{value:r,children:g}),e[14]=r,e[15]=g,e[16]=S):S=e[16];let k=S;if(n===u)return k;let E;return e[17]!==k||e[18]!==u?(E=(0,kt.jsx)(Ft,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=E):E=e[19],E},"X");var Ne=a(()=>{let t=(0,Q.use)(An);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Fn=D(As(),1),Pn=D(ie(),1);var au=a(()=>{let t=(0,Fn.c)(4),e=Ne(),s,r,i;return t[0]!==e?(s=a(n=>e.onConnectionStatus(()=>{n()}),"o"),r=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,Pn.useSyncExternalStore)(s,r,i)},"S");var wf=a(()=>{let t=Ne();if(!Ss(t))throw new b("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{Ee as a,Rt as b,U as c,T as d,ua as e,gs as f,fa as g,Re as h,Ta as i,Oa as j,nu as k,au as l,wf as m};
@@ -0,0 +1 @@
1
+ import{a as f}from"./chunk-OK2QU2EV.js";import{a as h}from"./chunk-GWNGVKLG.js";import{b as N}from"./chunk-6G3E4PJ2.js";import{a as u,d as x}from"./chunk-5PEAXTYQ.js";var b=x(h(),1);var t=x(N(),1);var v=u(g=>{let e=(0,b.c)(16),{chart:c,footer:n,label:i,testId:m,value:p}=g,r;e[0]!==i?(r=(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:i}),e[0]=i,e[1]=r):r=e[1];let a;e[2]!==m||e[3]!==p?(a=(0,t.jsx)("span",{className:"truncate text-2xl font-semibold tabular-nums text-foreground","data-testid":m,children:p}),e[2]=m,e[3]=p,e[4]=a):a=e[4];let s;e[5]!==c||e[6]!==a?(s=(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[a,c]}),e[5]=c,e[6]=a,e[7]=s):s=e[7];let l;e[8]!==r||e[9]!==s?(l=(0,t.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[r,s]}),e[8]=r,e[9]=s,e[10]=l):l=e[10];let o;e[11]!==n?(o=n!=null&&(0,t.jsx)("div",{className:"border-t border-border bg-muted/50 px-4 py-2.5 text-[11px] text-muted-foreground",children:n}),e[11]=n,e[12]=o):o=e[12];let d;return e[13]!==l||e[14]!==o?(d=(0,t.jsxs)(f,{className:"justify-between gap-0 py-0",children:[l,o]}),e[13]=l,e[14]=o,e[15]=d):d=e[15],d},"j");export{v as a};
@@ -0,0 +1 @@
1
+ import{b as Me}from"./chunk-W4LJQYCI.js";import{a as ve}from"./chunk-YORPLSI5.js";import{b as ye,c as we}from"./chunk-ONTGYVAN.js";import{a as xe}from"./chunk-GJXCPZDN.js";import{a as Ne}from"./chunk-ELSQ4FVH.js";import"./chunk-NGVP66OH.js";import"./chunk-QAOZXPLU.js";import{a as be}from"./chunk-J45HAKBU.js";import{a as fe}from"./chunk-FHLODLBC.js";import{b as pe}from"./chunk-3D67ZJRW.js";import"./chunk-ZSWW2UGP.js";import{i as ue}from"./chunk-IHGRWY3Y.js";import"./chunk-OWRKSQPE.js";import"./chunk-4EPW63HS.js";import"./chunk-CKEQX655.js";import"./chunk-UD5REVU2.js";import{a as he}from"./chunk-RCXNYW7P.js";import{b as ce}from"./chunk-UQA2AJGI.js";import"./chunk-T3ZCW3RG.js";import{a as ge}from"./chunk-YEXTJUKQ.js";import"./chunk-LSEUUZN4.js";import"./chunk-OZAOWE7T.js";import"./chunk-BBDTJG2K.js";import"./chunk-4PI2OSSP.js";import{a as ie}from"./chunk-2W4UO5BC.js";import{c as de}from"./chunk-4N76XUNG.js";import"./chunk-SHHGIT7M.js";import"./chunk-ZPQBVYNN.js";import{B as U,p as me,w as oe,x as te}from"./chunk-GNI37YCV.js";import"./chunk-PDBW6GTJ.js";import{a as Le}from"./chunk-GWNGVKLG.js";import{a as Ce,b as Te}from"./chunk-6G3E4PJ2.js";import{a as m,d as le}from"./chunk-5PEAXTYQ.js";var O=le(Le(),1),A=le(Ce(),1);var s=le(Te(),1);var Pe=.5,Ie=4,Se=m(n=>Math.min(100,Math.max(0,n)),"ce"),Ke=m((n,e)=>{if(!Number.isFinite(e)||e<=0)return{leftPercent:0,widthPercent:100};let t=Se(n.offsetMs/e*100),a=n.durationMs/e*100,l=Math.max(Pe,Math.min(Se(a),100-t));return{leftPercent:t,widthPercent:l}},"Ce"),De=m((n,e,t=!1)=>{let a=e.trim().toLowerCase(),l=t?n.filter(r=>!r.ok):n;return a===""?[...l]:l.filter(r=>r.rootName.toLowerCase().includes(a)||r.functionPath.toLowerCase().includes(a)||r.traceId.toLowerCase().includes(a)||r.spans.some(o=>o.name.toLowerCase().includes(a)||o.spanId.toLowerCase().includes(a)))},"Ee"),G=m(n=>Number.isFinite(n)?n>0&&n<1?`${n.toFixed(2)}ms`:`${String(Math.round(n))}ms`:"\u2014","q"),Fe=m(n=>!Number.isFinite(n)||n<=0?[]:Array.from({length:Ie},(e,t)=>{let a=(t+1)/Ie;return{label:G(n*a),percent:a*100}}),"Pe"),ke=m(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n,me)}catch{return String(n)}},"ue"),ee=m(n=>{let e=(0,O.c)(7),{label:t,value:a}=n,l;e[0]!==t?(l=(0,s.jsx)("dt",{className:"w-40 shrink-0 text-muted-foreground",children:t}),e[0]=t,e[1]=l):l=e[1];let r;e[2]!==a?(r=(0,s.jsx)("dd",{className:"min-w-0 break-all",children:a}),e[2]=a,e[3]=r):r=e[3];let o;return e[4]!==l||e[5]!==r?(o=(0,s.jsxs)("div",{className:"flex gap-2",children:[l,r]}),e[4]=l,e[5]=r,e[6]=o):o=e[6],o},"Y"),je=m(n=>{let e=(0,O.c)(68),{span:t}=n,a=U(),l,r,o,d,i,u;if(e[0]!==t.attributes||e[1]!==t.durationMs||e[2]!==t.error||e[3]!==t.events||e[4]!==t.kind||e[5]!==t.offsetMs||e[6]!==t.parentSpanId||e[7]!==t.spanId||e[8]!==a){let $=Object.entries(t.attributes??{}),_;e[15]!==t.events?(_=t.events??[],e[15]=t.events,e[16]=_):_=e[16],l=_,r="border-t border-border bg-background/60 px-3 py-2 font-mono text-xs",o="tr-span-detail";let y;e[17]!==a?(y=a("Span ID"),e[17]=a,e[18]=y):y=e[18];let w;e[19]!==t.spanId||e[20]!==y?(w=(0,s.jsx)(ee,{label:y,value:t.spanId}),e[19]=t.spanId,e[20]=y,e[21]=w):w=e[21];let M;e[22]!==a?(M=a("Parent span ID"),e[22]=a,e[23]=M):M=e[23];let h;e[24]!==t.parentSpanId||e[25]!==a?(h=t.parentSpanId===""?a("\u2014 (trace root)"):t.parentSpanId,e[24]=t.parentSpanId,e[25]=a,e[26]=h):h=e[26];let p;e[27]!==h||e[28]!==M?(p=(0,s.jsx)(ee,{label:M,value:h}),e[27]=h,e[28]=M,e[29]=p):p=e[29];let b;e[30]!==a?(b=a("Kind"),e[30]=a,e[31]=b):b=e[31];let C=t.kind??"internal",S;e[32]!==b||e[33]!==C?(S=(0,s.jsx)(ee,{label:b,value:C}),e[32]=b,e[33]=C,e[34]=S):S=e[34];let I;e[35]!==a?(I=a("Started at"),e[35]=a,e[36]=I):I=e[36];let g;e[37]!==t.offsetMs||e[38]!==a?(g=a("+{offset}",{offset:G(t.offsetMs)}),e[37]=t.offsetMs,e[38]=a,e[39]=g):g=e[39];let x;e[40]!==I||e[41]!==g?(x=(0,s.jsx)(ee,{label:I,value:g}),e[40]=I,e[41]=g,e[42]=x):x=e[42];let k;e[43]!==a?(k=a("Duration"),e[43]=a,e[44]=k):k=e[44];let f;e[45]!==t.durationMs?(f=G(t.durationMs),e[45]=t.durationMs,e[46]=f):f=e[46];let N;e[47]!==k||e[48]!==f?(N=(0,s.jsx)(ee,{label:k,value:f}),e[47]=k,e[48]=f,e[49]=N):N=e[49],e[50]!==p||e[51]!==S||e[52]!==x||e[53]!==N||e[54]!==w?(d=(0,s.jsxs)("dl",{className:"flex flex-col gap-1",children:[w,p,S,x,N]}),e[50]=p,e[51]=S,e[52]=x,e[53]=N,e[54]=w,e[55]=d):d=e[55],e[56]!==t.error?(i=t.error!==void 0&&(0,s.jsxs)("div",{className:"mt-2 rounded-md border border-destructive/40 bg-destructive/10 px-2 py-1.5","data-testid":"tr-detail-error",children:[(0,s.jsx)("span",{className:"font-semibold text-destructive",children:t.error.type}),(0,s.jsx)("p",{className:"whitespace-pre-wrap break-all text-destructive",children:t.error.message})]}),e[56]=t.error,e[57]=i):i=e[57],u=$.length>0&&(0,s.jsxs)("div",{className:"mt-2","data-testid":"tr-detail-attributes",children:[(0,s.jsx)("p",{className:"mb-1 text-muted-foreground",children:a("Attributes")}),(0,s.jsx)("dl",{className:"flex flex-col gap-1",children:$.map(Ee)})]}),e[0]=t.attributes,e[1]=t.durationMs,e[2]=t.error,e[3]=t.events,e[4]=t.kind,e[5]=t.offsetMs,e[6]=t.parentSpanId,e[7]=t.spanId,e[8]=a,e[9]=l,e[10]=r,e[11]=o,e[12]=d,e[13]=i,e[14]=u}else l=e[9],r=e[10],o=e[11],d=e[12],i=e[13],u=e[14];let c;e[58]!==l||e[59]!==a?(c=l.length>0&&(0,s.jsxs)("div",{className:"mt-2","data-testid":"tr-detail-events",children:[(0,s.jsx)("p",{className:"mb-1 text-muted-foreground",children:a("Events")}),(0,s.jsx)("ul",{className:"flex flex-col gap-1",children:l.map(Oe)})]}),e[58]=l,e[59]=a,e[60]=c):c=e[60];let v;return e[61]!==r||e[62]!==o||e[63]!==d||e[64]!==i||e[65]!==u||e[66]!==c?(v=(0,s.jsxs)("div",{className:r,"data-testid":o,children:[d,i,u,c]}),e[61]=r,e[62]=o,e[63]=d,e[64]=i,e[65]=u,e[66]=c,e[67]=v):v=e[67],v},"Ke");function Ee(n){let[e,t]=n;return(0,s.jsx)(ee,{label:e,value:ke(t)},e)}m(Ee,"Fe");function Ae(n){let[e,t]=n;return`${e}=${ke(t)}`}m(Ae,"Re");function Oe(n){return(0,s.jsxs)("li",{className:"flex gap-2",children:[(0,s.jsx)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:oe(n.ts)}),(0,s.jsx)(ce,{variant:"secondary",children:n.name}),(0,s.jsx)("span",{className:"min-w-0 break-all text-muted-foreground",children:Object.entries(n.attributes??{}).map(Ae).join(" ")})]},`${n.name}:${String(n.ts)}`)}m(Oe,"Ae");var Be=14,_e="grid grid-cols-[14rem_1fr_4rem_16rem_16rem] items-center gap-2 px-3",We=m(n=>{let e=(0,O.c)(17),{traceDurationMs:t}=n,a,l,r,o,d,i;if(e[0]!==t){i=Symbol.for("react.early_return_sentinel");e:{let v=Fe(t);if(v.length===0){i=null;break e}e[7]===Symbol.for("react.memo_cache_sentinel")?(r=te(_e,"border-b border-border py-1 font-mono text-[10px] text-muted-foreground"),e[7]=r):r=e[7],o="tr-ruler",e[8]===Symbol.for("react.memo_cache_sentinel")?(d=(0,s.jsx)("span",{}),e[8]=d):d=e[8],a="relative h-3",l=v.map(Je)}e[0]=t,e[1]=a,e[2]=l,e[3]=r,e[4]=o,e[5]=d,e[6]=i}else a=e[1],l=e[2],r=e[3],o=e[4],d=e[5],i=e[6];if(i!==Symbol.for("react.early_return_sentinel"))return i;let u;e[9]!==a||e[10]!==l?(u=(0,s.jsx)("span",{className:a,children:l}),e[9]=a,e[10]=l,e[11]=u):u=e[11];let c;return e[12]!==r||e[13]!==o||e[14]!==d||e[15]!==u?(c=(0,s.jsxs)("div",{className:r,"data-testid":o,children:[d,u]}),e[12]=r,e[13]=o,e[14]=d,e[15]=u,e[16]=c):c=e[16],c},"je"),qe=m(n=>{let e=(0,O.c)(60),{span:t,traceDurationMs:a}=n,l=U(),[r,o]=(0,A.useState)(!1),d;e[0]!==t||e[1]!==a?(d=Ke(t,a),e[0]=t,e[1]=a,e[2]=d):d=e[2];let{leftPercent:i,widthPercent:u}=d,c;e[3]!==t.attributes?(c=ve(t.attributes),e[3]=t.attributes,e[4]=c):c=e[4];let v=c,$=t.depth*Be,_;e[5]!==$?(_={paddingLeft:$},e[5]=$,e[6]=_):_=e[6];let y=_,w=`${String(i)}%`,M=`${String(u)}%`,h;e[7]!==w||e[8]!==M?(h={left:w,width:M},e[7]=w,e[8]=M,e[9]=h):h=e[9];let p=h,b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b=m(()=>{o(Ue)},"h"),e[10]=b):b=e[10];let C=b,S=t.depth,I=`tr-span-detail-${t.spanId}`,g;e[11]!==t.durationMs||e[12]!==t.error||e[13]!==t.name||e[14]!==t.offsetMs||e[15]!==l?(g=l("{name}, {duration}, starts {offset} in{failure}",{duration:G(t.durationMs),failure:t.error===void 0?"":l(", failed: {message}",{message:t.error.message}),name:t.name,offset:G(t.offsetMs)}),e[11]=t.durationMs,e[12]=t.error,e[13]=t.name,e[14]=t.offsetMs,e[15]=l,e[16]=g):g=e[16];let x;e[17]===Symbol.for("react.memo_cache_sentinel")?(x=te(_e,"w-full border-b border-border py-1.5 text-left font-mono text-xs hover:bg-muted/50"),e[17]=x):x=e[17];let k=`tr-span-toggle-${t.spanId}`,f;e[18]!==t.ok?(f=t.ok?null:(0,s.jsx)("span",{"aria-hidden":"true",className:"mr-1 text-destructive","data-testid":"tr-span-error",children:"\u25CF"}),e[18]=t.ok,e[19]=f):f=e[19];let N;e[20]!==y||e[21]!==t.name||e[22]!==f?(N=(0,s.jsxs)("span",{className:"truncate",style:y,title:t.name,children:[f,t.name]}),e[20]=y,e[21]=t.name,e[22]=f,e[23]=N):N=e[23];let B=t.ok?"bg-primary/70":"bg-destructive",L;e[24]!==B?(L=te("absolute inset-y-0 rounded-sm",B),e[24]=B,e[25]=L):L=e[25];let E;e[26]!==p||e[27]!==i||e[28]!==L||e[29]!==u?(E=(0,s.jsx)("span",{"aria-hidden":"true",className:"relative h-3 overflow-hidden rounded-sm bg-muted",children:(0,s.jsx)("span",{className:L,"data-left":i,"data-testid":"tr-span-bar","data-width":u,style:p})}),e[26]=p,e[27]=i,e[28]=L,e[29]=u,e[30]=E):E=e[30];let W;e[31]!==t.durationMs?(W=G(t.durationMs),e[31]=t.durationMs,e[32]=W):W=e[32];let D;e[33]!==W?(D=(0,s.jsx)("span",{className:"text-right tabular-nums text-muted-foreground",children:W}),e[33]=W,e[34]=D):D=e[34];let q;e[35]!==t.error?(q=t.error===void 0?null:(0,s.jsx)("span",{className:"text-destructive","data-testid":"tr-span-error-message",title:t.error.message,children:`${t.error.type}: ${t.error.message}`}),e[35]=t.error,e[36]=q):q=e[36];let T;e[37]!==q?(T=(0,s.jsx)("span",{className:"truncate text-muted-foreground",children:q}),e[37]=q,e[38]=T):T=e[38];let z;e[39]!==v?(z=v===""?null:(0,s.jsx)("span",{"data-testid":"tr-span-attributes",title:v,children:v}),e[39]=v,e[40]=z):z=e[40];let P;e[41]!==z?(P=(0,s.jsx)("span",{className:"truncate text-muted-foreground",children:z}),e[41]=z,e[42]=P):P=e[42];let J;e[43]!==r||e[44]!==I||e[45]!==g||e[46]!==k||e[47]!==N||e[48]!==E||e[49]!==D||e[50]!==T||e[51]!==P?(J=(0,s.jsxs)("button",{"aria-controls":I,"aria-expanded":r,"aria-label":g,className:x,"data-testid":k,onClick:C,type:"button",children:[N,E,D,T,P]}),e[43]=r,e[44]=I,e[45]=g,e[46]=k,e[47]=N,e[48]=E,e[49]=D,e[50]=T,e[51]=P,e[52]=J):J=e[52];let F;e[53]!==r||e[54]!==t?(F=r&&(0,s.jsx)("div",{id:`tr-span-detail-${t.spanId}`,children:(0,s.jsx)(je,{span:t})}),e[53]=r,e[54]=t,e[55]=F):F=e[55];let K;return e[56]!==t.depth||e[57]!==J||e[58]!==F?(K=(0,s.jsxs)("li",{"data-depth":S,"data-testid":"tr-span-row",children:[J,F]}),e[56]=t.depth,e[57]=J,e[58]=F,e[59]=K):K=e[59],K},"Be"),ze=m(n=>{let e=(0,O.c)(15),{durationMs:t,spans:a}=n,l=U(),r;e[0]!==t?(r=(0,s.jsx)(We,{traceDurationMs:t}),e[0]=t,e[1]=r):r=e[1];let o;e[2]!==l?(o=l("Trace waterfall"),e[2]=l,e[3]=o):o=e[3];let d;if(e[4]!==t||e[5]!==a){let c;e[7]!==t?(c=m(v=>(0,s.jsx)(qe,{span:v,traceDurationMs:t},v.spanId),"c"),e[7]=t,e[8]=c):c=e[8],d=a.map(c),e[4]=t,e[5]=a,e[6]=d}else d=e[6];let i;e[9]!==o||e[10]!==d?(i=(0,s.jsx)("ul",{"aria-label":o,children:d}),e[9]=o,e[10]=d,e[11]=i):i=e[11];let u;return e[12]!==r||e[13]!==i?(u=(0,s.jsxs)(s.Fragment,{children:[r,i]}),e[12]=r,e[13]=i,e[14]=u):u=e[14],u},"Oe");function Je(n){return(0,s.jsx)("span",{className:te("absolute inset-y-0 border-l border-border/70",n.percent===100?"-translate-x-full pr-1":"pl-1"),style:{left:`${String(n.percent)}%`},children:n.label},n.percent)}m(Je,"We");function Ue(n){return!n}m(Ue,"Ue");var Ge=m(n=>Array.isArray(n?.traces)?n.traces:[],"qe"),He=m(n=>{let e=(0,O.c)(12),{entries:t}=n,a=U(),l;e[0]!==t.length||e[1]!==a?(l=a("Logs ({count})",{count:t.length}),e[0]=t.length,e[1]=a,e[2]=l):l=e[2];let r;e[3]!==l?(r=(0,s.jsx)("p",{className:"mb-1 font-mono text-xs text-muted-foreground",children:l}),e[3]=l,e[4]=r):r=e[4];let o;e[5]!==t?(o=t.map(Ve),e[5]=t,e[6]=o):o=e[6];let d;e[7]!==o?(d=(0,s.jsx)("div",{role:"grid",children:o}),e[7]=o,e[8]=d):d=e[8];let i;return e[9]!==r||e[10]!==d?(i=(0,s.jsxs)("div",{className:"border-t border-border px-3 py-2","data-testid":"tr-logs",children:[r,d]}),e[9]=r,e[10]=d,e[11]=i):i=e[11],i},"ze"),Qe=m(n=>{let e=(0,O.c)(50),{expanded:t,logs:a,onToggle:l,trace:r}=n,o=U(),d;e[0]!==l||e[1]!==r.traceId?(d=m(()=>{l(r.traceId)},"i"),e[0]=l,e[1]=r.traceId,e[2]=d):d=e[2];let i=d,u=`tr-row-${r.traceId}`,c=`tr-waterfall-${r.traceId}`,v=`tr-toggle-${r.traceId}`,$=t?"\u25BE":"\u25B8",_;e[3]!==$?(_=(0,s.jsx)("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-xs text-muted-foreground",children:$}),e[3]=$,e[4]=_):_=e[4];let y;e[5]!==r.rootName?(y=(0,s.jsx)("span",{className:"w-56 shrink-0 truncate text-sm font-medium",title:r.rootName,children:r.rootName}),e[5]=r.rootName,e[6]=y):y=e[6];let w;e[7]!==r.functionPath?(w=(0,s.jsx)("span",{className:"w-48 shrink-0 truncate font-mono text-xs text-muted-foreground",title:r.functionPath,children:r.functionPath}),e[7]=r.functionPath,e[8]=w):w=e[8];let M;e[9]!==r.durationMs?(M=G(r.durationMs),e[9]=r.durationMs,e[10]=M):M=e[10];let h;e[11]!==M?(h=(0,s.jsx)("span",{className:"w-20 shrink-0 text-right font-mono text-xs tabular-nums text-muted-foreground",children:M}),e[11]=M,e[12]=h):h=e[12];let p;e[13]!==o||e[14]!==r.spans.length?(p=o("{count} spans",{count:r.spans.length}),e[13]=o,e[14]=r.spans.length,e[15]=p):p=e[15];let b;e[16]!==p?(b=(0,s.jsx)("span",{className:"w-20 shrink-0 text-right font-mono text-xs tabular-nums text-muted-foreground",children:p}),e[16]=p,e[17]=b):b=e[17];let C=r.ok?"secondary":"destructive",S;e[18]!==o||e[19]!==r.ok?(S=r.ok?o("ok"):o("error"),e[18]=o,e[19]=r.ok,e[20]=S):S=e[20];let I;e[21]!==C||e[22]!==S?(I=(0,s.jsx)("span",{className:"shrink-0",children:(0,s.jsx)(ce,{variant:C,children:S})}),e[21]=C,e[22]=S,e[23]=I):I=e[23];let g;e[24]!==r.startTs?(g=oe(r.startTs),e[24]=r.startTs,e[25]=g):g=e[25];let x;e[26]!==g?(x=(0,s.jsx)("span",{className:"flex-1 truncate text-right font-mono text-xs tabular-nums text-muted-foreground",children:g}),e[26]=g,e[27]=x):x=e[27];let k;e[28]!==t||e[29]!==i||e[30]!==h||e[31]!==b||e[32]!==I||e[33]!==x||e[34]!==c||e[35]!==v||e[36]!==_||e[37]!==y||e[38]!==w?(k=(0,s.jsxs)("button",{"aria-controls":c,"aria-expanded":t,className:"flex w-full items-center gap-3 px-3 py-2 text-left hover:bg-muted/50","data-testid":v,onClick:i,type:"button",children:[_,y,w,h,b,I,x]}),e[28]=t,e[29]=i,e[30]=h,e[31]=b,e[32]=I,e[33]=x,e[34]=c,e[35]=v,e[36]=_,e[37]=y,e[38]=w,e[39]=k):k=e[39];let f;e[40]!==t||e[41]!==a||e[42]!==r.durationMs||e[43]!==r.spans||e[44]!==r.traceId?(f=t&&(0,s.jsxs)("div",{className:"bg-muted/20","data-testid":`tr-waterfall-${r.traceId}`,id:`tr-waterfall-${r.traceId}`,children:[(0,s.jsx)(ze,{durationMs:r.durationMs,spans:r.spans}),a.length>0&&(0,s.jsx)(He,{entries:a})]}),e[40]=t,e[41]=a,e[42]=r.durationMs,e[43]=r.spans,e[44]=r.traceId,e[45]=f):f=e[45];let N;return e[46]!==k||e[47]!==f||e[48]!==u?(N=(0,s.jsxs)("div",{className:"border-b border-border last:border-b-0","data-testid":u,children:[k,f]}),e[46]=k,e[47]=f,e[48]=u,e[49]=N):N=e[49],N},"Ge"),bt=m(n=>{let e=(0,O.c)(60),{initialShardKey:t}=n,a=U(),[l]=(0,A.useState)(ye),{queryShardKey:r,setShardKey:o,shardKey:d}=be(l?.shardKey!==void 0&&l.shardKey!==""?l.shardKey:t??""),[i,u]=(0,A.useState)(l?.traceId??""),[c,v]=(0,A.useState)(!1),[$,_]=(0,A.useState)(Xe),y;e[0]===Symbol.for("react.memo_cache_sentinel")?(y=[],e[0]=y):y=e[0],(0,A.useEffect)(Ye,y);let w;e[1]===Symbol.for("react.memo_cache_sentinel")?(w={},e[1]=w):w=e[1];let M;e[2]!==r?(M={live:!0,shardKey:r},e[2]=r,e[3]=M):M=e[3];let{data:h,error:p,errorSource:b,isLoading:C,liveError:S}=de(ie.getTraces,w,M),I;e[4]===Symbol.for("react.memo_cache_sentinel")?(I={},e[4]=I):I=e[4];let g=$.size>0,x;e[5]!==r||e[6]!==g?(x={enabled:g,live:!0,shardKey:r},e[5]=r,e[6]=g,e[7]=x):x=e[7];let{data:k}=de(ie.getLogs,I,x),f,N;e[8]!==h||e[9]!==r?(f=m(()=>{h!==void 0&&pe(r)},"p"),N=[h,r],e[8]=h,e[9]=r,e[10]=f,e[11]=N):(f=e[10],N=e[11]),(0,A.useEffect)(f,N);let B;if(e[12]!==h||e[13]!==p||e[14]!==b||e[15]!==$||e[16]!==C||e[17]!==S||e[18]!==k?.entries||e[19]!==c||e[20]!==r||e[21]!==i||e[22]!==o||e[23]!==d||e[24]!==a){let L=Ge(h),E=h?.total??L.length,W=E>L.length,D=De(L,i,c),q=Map.groupBy((k?.entries??[]).toReversed(),Ze),T;e[26]===Symbol.for("react.memo_cache_sentinel")?(T=m(j=>{u(j.target.value)},"C"),e[26]=T):T=e[26];let z=T,P;e[27]===Symbol.for("react.memo_cache_sentinel")?(P=m(j=>{_($e=>{let ne=new Set($e);return ne.has(j)?ne.delete(j):ne.add(j),ne})},"E"),e[27]=P):P=e[27];let J=P,F=p===null&&D.length===0&&!C,K;e[28]!==o||e[29]!==d?(K=(0,s.jsx)(fe,{onChange:o,testId:"tr-shard-input",value:d}),e[28]=o,e[29]=d,e[30]=K):K=e[30];let H;e[31]!==a?(H=a("Search traces"),e[31]=a,e[32]=H):H=e[32];let Q;e[33]!==a?(Q=a("search trace, span, or function"),e[33]=a,e[34]=Q):Q=e[34];let V;e[35]!==i||e[36]!==H||e[37]!==Q?(V=(0,s.jsx)(ue,{"aria-label":H,className:"h-8 w-56","data-testid":"tr-search",onChange:z,placeholder:Q,value:i}),e[35]=i,e[36]=H,e[37]=Q,e[38]=V):V=e[38];let X;e[39]!==c?(X=(0,s.jsx)(xe,{checked:c,"data-testid":"tr-only-errors",id:"tr-only-errors",onCheckedChange:v}),e[39]=c,e[40]=X):X=e[40];let Y;e[41]!==a?(Y=a("Errors only"),e[41]=a,e[42]=Y):Y=e[42];let Z;e[43]!==X||e[44]!==Y?(Z=(0,s.jsxs)("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",htmlFor:"tr-only-errors",children:[X,Y]}),e[43]=X,e[44]=Y,e[45]=Z):Z=e[45];let R;e[46]!==S?(R=(0,s.jsx)(Ne,{message:S,prefix:"tr"}),e[46]=S,e[47]=R):R=e[47];let re;e[48]!==K||e[49]!==V||e[50]!==Z||e[51]!==R?(re=(0,s.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[K,V,Z,R]}),e[48]=K,e[49]=V,e[50]=Z,e[51]=R,e[52]=re):re=e[52];let ae;e[53]!==p||e[54]!==b||e[55]!==r?(ae=p!==null&&(0,s.jsx)(ge,{error:b,shardKey:r,testId:"tr-error"}),e[53]=p,e[54]=b,e[55]=r,e[56]=ae):ae=e[56];let se;e[57]!==F||e[58]!==a?(se=F&&(0,s.jsx)(he,{description:a("Traces recorded with ctx.trace show up here as your app handles traffic. The span buffer resets when the shard hibernates."),icon:(0,s.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,s.jsx)("path",{d:"M4 6h10M7 12h13M10 18h7"})}),testId:"tr-empty",title:a("No traces")}),e[57]=F,e[58]=a,e[59]=se):se=e[59],B=(0,s.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-traces-panel",children:[re,ae,se,p===null&&W&&(0,s.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"tr-truncated",children:a("Showing the {shown} most recent of {total} traces in the buffer.",{shown:L.length,total:E})}),p===null&&D.length>0&&(0,s.jsx)("div",{"aria-label":a("Recent traces"),className:"overflow-hidden rounded-xl border border-border shadow-xs","data-testid":"tr-list",children:D.map(j=>(0,s.jsx)(Qe,{expanded:$.has(j.traceId),logs:q.get(j.traceId)??[],onToggle:J,trace:j},j.traceId))})]}),e[12]=h,e[13]=p,e[14]=b,e[15]=$,e[16]=C,e[17]=S,e[18]=k?.entries,e[19]=c,e[20]=r,e[21]=i,e[22]=o,e[23]=d,e[24]=a,e[25]=B}else B=e[25];return B},"bt");function Ve(n,e){return(0,s.jsx)("div",{className:"flex items-center border-b border-border py-1 font-mono text-xs last:border-b-0","data-testid":"tr-log-row",role:"row",children:(0,s.jsx)(Me,{entry:n})},`${String(e)}:${String(n.timestamp)}`)}m(Ve,"He");function Xe(){return new Set}m(Xe,"Je");function Ye(){we()}m(Ye,"Qe");function Ze(n){return n.traceId}m(Ze,"Ve");export{bt as default};
@@ -0,0 +1 @@
1
+ import{a as m}from"./chunk-6G3E4PJ2.js";import{a as r,d as p}from"./chunk-5PEAXTYQ.js";function d(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}r(d,"mergeObjects");var y={};function h(e,t,n,o,i){if(!n&&!o&&!i&&!e)return R(t);let c=R(e);return t&&(c=E(c,t)),n&&(c=E(c,n)),o&&(c=E(c,o)),i&&(c=E(c,i)),c}r(h,"mergeProps");function x(e){if(e.length===0)return y;if(e.length===1)return R(e[0]);let t=R(e[0]);for(let n=1;n<e.length;n+=1)t=E(t,e[n]);return t}r(x,"mergePropsN");function R(e){return b(e)?{...T(e,y)}:J(e)}r(R,"createInitialMergedProps");function E(e,t){return b(t)?T(t,e):q(e,t)}r(E,"mergeInto");function J(e){let t={...e};for(let n in t){let o=t[n];O(n,o)&&(t[n]=k(o))}return t}r(J,"copyInitialProps");function q(e,t){if(!t)return e;for(let n in t){let o=t[n];switch(n){case"style":{e[n]=d(e.style,o);break}case"className":{e[n]=g(e.className,o);break}default:O(n,o)?e[n]=K(e[n],o):e[n]=o}}return e}r(q,"mutablyMergeInto");function O(e,t){let n=e.charCodeAt(0),o=e.charCodeAt(1),i=e.charCodeAt(2);return n===111&&o===110&&i>=65&&i<=90&&(typeof t=="function"||typeof t>"u")}r(O,"isEventHandler");function b(e){return typeof e=="function"}r(b,"isPropsGetter");function T(e,t){return b(e)?e(t):e??y}r(T,"resolvePropsGetter");function K(e,t){return t?e?(...n)=>{let o=n[0];if(_(o)){let c=o;M(c);let s=t(...n);return c.baseUIHandlerPrevented||e?.(...n),s}let i=t(...n);return e?.(...n),i}:k(t):e}r(K,"mergeEventHandlers");function k(e){return e&&((...t)=>{let n=t[0];return _(n)&&M(n),e(...t)})}r(k,"wrapEventHandler");function M(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}r(M,"makeEventPreventable");function g(e,t){return t?e?t+" "+e:t:e}r(g,"mergeClassNames");function _(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}r(_,"isSyntheticEvent");function Q(e,t){return r(function(o,...i){let c=new URL(e);return c.searchParams.set("code",o.toString()),i.forEach(s=>c.searchParams.append("args[]",s)),`${t} error #${o}; visit ${c} for the full message.`},"formatErrorMessage")}r(Q,"createFormatErrorMessage");var X=Q("https://base-ui.com/production-error","Base UI"),L=X;var a=p(m(),1);var j=p(m(),1);var V={};function v(e,t){let n=j.useRef(V);return n.current===V&&(n.current=e(t)),n}r(v,"useRefWithInit");function A(e,t,n,o){let i=v(S).current;return ee(i,e,t,n,o)&&$(i,[e,t,n,o]),i.callback}r(A,"useMergedRefs");function U(e){let t=v(S).current;return te(t,e)&&$(t,e),t.callback}r(U,"useMergedRefsN");function S(){return{callback:null,cleanup:null,refs:[]}}r(S,"createForkRef");function ee(e,t,n,o,i){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==o||e.refs[3]!==i}r(ee,"didChange");function te(e,t){return e.refs.length!==t.length||e.refs.some((n,o)=>n!==t[o])}r(te,"didChangeN");function $(e,t){if(e.refs=t,t.every(n=>n==null)){e.callback=null;return}e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),n!=null){let o=Array(t.length).fill(null);for(let i=0;i<t.length;i+=1){let c=t[i];if(c!=null)switch(typeof c){case"function":{let s=c(n);typeof s=="function"&&(o[i]=s);break}case"object":{c.current=n;break}default:}}e.cleanup=()=>{for(let i=0;i<t.length;i+=1){let c=t[i];if(c!=null)switch(typeof c){case"function":{let s=o[i];typeof s=="function"?s():c(null);break}case"object":{c.current=null;break}default:}}}}}}r($,"update");var z=p(m(),1);var B=p(m(),1);var ne=parseInt(B.version,10);function Y(e){return ne>=e}r(Y,"isReactVersionAtLeast");function N(e){if(!z.isValidElement(e))return null;let t=e,n=t.props;return(Y(19)?n?.ref:t.ref)??null}r(N,"getReactElementRef");function we(){}r(we,"NOOP");var Ce=Object.freeze([]),l=Object.freeze({});function D(e,t){let n={};for(let o in e){let i=e[o];if(t?.hasOwnProperty(o)){let c=t[o](i);c!=null&&Object.assign(n,c);continue}i===!0?n[`data-${o.toLowerCase()}`]="":i&&(n[`data-${o.toLowerCase()}`]=i.toString())}return n}r(D,"getStateAttributesProps");function F(e,t){return typeof e=="function"?e(t):e}r(F,"resolveClassName");function W(e,t){return typeof e=="function"?e(t):e}r(W,"resolveStyle");var P=p(m(),1);function We(e,t,n={}){let o=t.render;n.enabled!==!1&&(o=ce(o));let i=re(t,n,o);if(n.enabled===!1)return null;let c=n.state??l;return se(e,o,i,c)}r(We,"useRenderElement");function re(e,t,n){let{className:o,style:i}=e,{state:c=l,ref:s,props:I,stateAttributesMapping:Z,enabled:f=!0}=t,w=f?F(o,c):void 0,C=f?W(i,c):void 0,G=f?D(c,Z):l,H=f&&I?oe(I):void 0,u=f?d(G,H)??{}:l;return typeof document<"u"&&(f?Array.isArray(s)?u.ref=U([u.ref,N(n),...s]):u.ref=A(u.ref,N(n),s):A(null,null)),f?(w!==void 0&&(u.className=g(u.className,w)),C!==void 0&&(u.style=d(u.style,C)),u):l}r(re,"useRenderElementProps");function oe(e){return Array.isArray(e)?x(e):h(void 0,e)}r(oe,"resolveRenderFunctionProps");var ie=Symbol.for("react.lazy");function ce(e){if(e?.$$typeof!==ie)return e;let t=a.Children.toArray(e)[0];return a.isValidElement(t)?t:e}r(ce,"unwrapLazyRenderProp");function se(e,t,n,o){if(t){if(typeof t=="function")return t(n,o);let i=h(n,t.props);return i.ref=n.ref,a.cloneElement(t,i)}if(e&&typeof e=="string")return ue(e,n);throw new Error(L(8))}r(se,"evaluateRenderProp");function ue(e,t){return e==="button"?(0,P.createElement)("button",{type:"button",...t,key:t.key}):e==="img"?(0,P.createElement)("img",{alt:"",...t,key:t.key}):a.createElement(e,t)}r(ue,"renderTag");export{h as a,M as b,L as c,v as d,A as e,Y as f,we as g,Ce as h,l as i,We as j};