@lunora/studio 1.0.0-alpha.29 → 1.0.0-alpha.291

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 (354) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/index.d.mts +1581 -0
  4. package/dist/index.d.ts +974 -806
  5. package/dist/index.mjs +1 -0
  6. package/dist/mount.d.mts +22 -0
  7. package/dist/mount.d.ts +11 -10
  8. package/dist/mount.mjs +1 -0
  9. package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -0
  10. package/dist/packem_chunks/ApiTab.mjs +1 -0
  11. package/dist/packem_chunks/AuditPanel.mjs +1 -0
  12. package/dist/packem_chunks/DeploymentHealthPanel.mjs +1 -0
  13. package/dist/packem_chunks/ExportImportPanel.mjs +3 -0
  14. package/dist/packem_chunks/FileBrowser.mjs +4 -0
  15. package/dist/packem_chunks/FunctionRunner.mjs +1 -0
  16. package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -0
  17. package/dist/packem_chunks/HealthPanel.mjs +1 -0
  18. package/dist/packem_chunks/InsightsPanel.mjs +1 -0
  19. package/dist/packem_chunks/LogsPanel.mjs +1 -0
  20. package/dist/packem_chunks/MailPanel.mjs +2 -0
  21. package/dist/packem_chunks/MetricsPanel.mjs +1 -0
  22. package/dist/packem_chunks/NotificationsPanel.mjs +1 -0
  23. package/dist/packem_chunks/PitrPanel.mjs +1 -0
  24. package/dist/packem_chunks/SchemaViewer.mjs +1 -0
  25. package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -0
  26. package/dist/packem_chunks/SettingsPanel.mjs +1 -0
  27. package/dist/packem_chunks/SqlEditorPanel.mjs +10 -0
  28. package/dist/packem_chunks/TableEditor.mjs +1 -0
  29. package/dist/packem_chunks/agents-panel.mjs +1 -0
  30. package/dist/packem_chunks/ai-usage-panel.mjs +1 -0
  31. package/dist/packem_chunks/analytics-panel.mjs +1 -0
  32. package/dist/packem_chunks/architecture-panel.mjs +1 -0
  33. package/dist/packem_chunks/auth-audit-panel.mjs +1 -0
  34. package/dist/packem_chunks/auth-config-panel.mjs +1 -0
  35. package/dist/packem_chunks/auth-sessions-panel.mjs +1 -0
  36. package/dist/packem_chunks/containers-panel.mjs +1 -0
  37. package/dist/packem_chunks/dashboards-panel.mjs +1 -0
  38. package/dist/packem_chunks/evals-panel.mjs +1 -0
  39. package/dist/packem_chunks/fanout-panel.mjs +1 -0
  40. package/dist/packem_chunks/flags-panel.mjs +1 -0
  41. package/dist/packem_chunks/issues-panel.mjs +1 -0
  42. package/dist/packem_chunks/kv-browser.mjs +1 -0
  43. package/dist/packem_chunks/log-drains-panel.mjs +4 -0
  44. package/dist/packem_chunks/migrations-route.mjs +1 -0
  45. package/dist/packem_chunks/organizations-panel.mjs +1 -0
  46. package/dist/packem_chunks/payments-panel.mjs +1 -0
  47. package/dist/packem_chunks/permissions-panel.mjs +1 -0
  48. package/dist/packem_chunks/privacy-requests-panel.mjs +1 -0
  49. package/dist/packem_chunks/queues-panel.mjs +1 -0
  50. package/dist/packem_chunks/reactors-panel.mjs +1 -0
  51. package/dist/packem_chunks/rls-panel.mjs +1 -0
  52. package/dist/packem_chunks/schedule-panel.mjs +1 -0
  53. package/dist/packem_chunks/sparkline.mjs +1 -0
  54. package/dist/packem_chunks/storage-rules-panel.mjs +1 -0
  55. package/dist/packem_chunks/subscriptions-panel.mjs +1 -0
  56. package/dist/packem_chunks/sync-client-panel.mjs +1 -0
  57. package/dist/packem_chunks/traces-panel.mjs +1 -0
  58. package/dist/packem_chunks/users-panel.mjs +1 -0
  59. package/dist/packem_chunks/vector-browser.mjs +1 -0
  60. package/dist/packem_chunks/workflows-panel.mjs +1 -0
  61. package/dist/packem_shared/ADMIN_FUNCTIONS-B8yyk5BX.mjs +1 -0
  62. package/dist/packem_shared/ApiDocsPanel-fhDlZGE4.mjs +2 -0
  63. package/dist/packem_shared/ApiReferencePanel-nAf8tNRr.mjs +1 -0
  64. package/dist/packem_shared/CommandPalette-D9ZY-qQd.mjs +1 -0
  65. package/dist/packem_shared/ConfirmButton-DU4p72Er.mjs +1 -0
  66. package/dist/packem_shared/ConnectionBadge-B8Hj5DaE.mjs +1 -0
  67. package/dist/packem_shared/DEFAULT_AUTO_REFRESH_MS-DuULO4XM.mjs +1 -0
  68. package/dist/packem_shared/DEFAULT_INSIGHT_THRESHOLDS-D5YMT0gM.mjs +1 -0
  69. package/dist/packem_shared/DEFAULT_LOCALE-A1Yg5ORA.mjs +1 -0
  70. package/dist/packem_shared/DataBrowser-C14aRmmR.mjs +4 -0
  71. package/dist/packem_shared/DataFilters-CYZFt2EK.mjs +1 -0
  72. package/dist/packem_shared/ErrorBoundary-BWNF98VF.mjs +1 -0
  73. package/dist/packem_shared/GlobalDataBrowser-DhObcZDY.mjs +1 -0
  74. package/dist/packem_shared/HomePanel-CUuYsApa.mjs +1 -0
  75. package/dist/packem_shared/MigrationsPanel-CkVIwAbK.mjs +1 -0
  76. package/dist/packem_shared/OpenRpcReferencePanel-BxEr49D9.mjs +1 -0
  77. package/dist/packem_shared/STUDIO_ROOT_CLASS-C6MccdVk.mjs +1 -0
  78. package/dist/packem_shared/ScheduledJobs-BZNcYWBP.mjs +1 -0
  79. package/dist/packem_shared/ShardInput-C6mjgAh4.mjs +1 -0
  80. package/dist/packem_shared/Studio-CZjQXFHC.mjs +1 -0
  81. package/dist/packem_shared/StudioApp-C9ENwcOH.mjs +1 -0
  82. package/dist/packem_shared/StudioI18nProvider-fVsCSs5L.mjs +1 -0
  83. package/dist/packem_shared/advisor-view-DzI2RQhY.mjs +1 -0
  84. package/dist/packem_shared/aggregateMetrics-DKFJc-o5.mjs +1 -0
  85. package/dist/packem_shared/alert-PB5W11MM.mjs +1 -0
  86. package/dist/packem_shared/app.d-D7vL0y8y.d.mts +349 -0
  87. package/dist/packem_shared/app.d-D7vL0y8y.d.ts +349 -0
  88. package/dist/packem_shared/auth-pager-DiDnXsfe.mjs +1 -0
  89. package/dist/packem_shared/badge-r_5B4LHP.mjs +1 -0
  90. package/dist/packem_shared/bar-chart-BCsEIQoQ.mjs +6 -0
  91. package/dist/packem_shared/browser-storage-BH1MxLZs.mjs +1 -0
  92. package/dist/packem_shared/button-q0UYSmrn.mjs +1 -0
  93. package/dist/packem_shared/card-By2O8ULa.mjs +1 -0
  94. package/dist/packem_shared/cf-links-CBJ5SywP.mjs +1 -0
  95. package/dist/packem_shared/checkbox-CnS9cyCz.mjs +1 -0
  96. package/dist/packem_shared/control-button-BOZ5K-FC.mjs +1 -0
  97. package/dist/packem_shared/data-grid-DIiNmDR9.mjs +1 -0
  98. package/dist/packem_shared/data-view-params-DhYmAkcj.mjs +1 -0
  99. package/dist/packem_shared/diagram-export-panel-D5CVNJkp.mjs +2 -0
  100. package/dist/packem_shared/dropdown-menu-jLZenfWH.mjs +2 -0
  101. package/dist/packem_shared/empty-state-D7jEML_T.mjs +1 -0
  102. package/dist/packem_shared/error-alert-DueSEkt-.mjs +1 -0
  103. package/dist/packem_shared/grid-features-OVIMIQan.mjs +6 -0
  104. package/dist/packem_shared/grid-pagination-DgzyzfBh.mjs +1 -0
  105. package/dist/packem_shared/home-panel-BcE8S2Nn.mjs +3 -0
  106. package/dist/packem_shared/input-CXhxesPC.mjs +1 -0
  107. package/dist/packem_shared/internal-Df43vQI0.mjs +2 -0
  108. package/dist/packem_shared/label-DKFzyHq6.mjs +1 -0
  109. package/dist/packem_shared/live-status-BuJdUZFU.mjs +1 -0
  110. package/dist/packem_shared/log-fields-BolUoZ9g.mjs +1 -0
  111. package/dist/packem_shared/log-line-CICyJ_kc.mjs +1 -0
  112. package/dist/packem_shared/metrics-format-1sNGG47R.mjs +1 -0
  113. package/dist/packem_shared/modal-shell-CDztwLnv.mjs +1 -0
  114. package/dist/packem_shared/operation-console-provider-DoloEvon.mjs +1 -0
  115. package/dist/packem_shared/recording-client-CyFiAE2l.mjs +1 -0
  116. package/dist/packem_shared/reference-view-CIHyURU6.mjs +13 -0
  117. package/dist/packem_shared/schema-diagram-C5oilX7l.mjs +2 -0
  118. package/dist/packem_shared/scroll-area-CXCQH7VT.mjs +2 -0
  119. package/dist/packem_shared/select-DPyS18Vy.mjs +2 -0
  120. package/dist/packem_shared/shard-history-CaO3C4KQ.mjs +1 -0
  121. package/dist/packem_shared/shortcuts-B9gDaXmw.mjs +1 -0
  122. package/dist/packem_shared/skeleton-DX1gfixl.mjs +1 -0
  123. package/dist/packem_shared/sparkline-B_sPPO_8.mjs +1 -0
  124. package/dist/packem_shared/sql-result-table-DyK762_A.mjs +1 -0
  125. package/dist/packem_shared/stat-card-BAv73QtB.mjs +1 -0
  126. package/dist/packem_shared/storage-tier-C2mKwYRj.mjs +1 -0
  127. package/dist/packem_shared/studio-fK2DTLde.mjs +2 -0
  128. package/dist/packem_shared/table-D0SBiDu-.mjs +2 -0
  129. package/dist/packem_shared/table-list-sidebar-DkPO_Qtz.mjs +1 -0
  130. package/dist/packem_shared/textarea--40GKAyz.mjs +1 -0
  131. package/dist/packem_shared/trace-handoff-BV3EWqy_.mjs +1 -0
  132. package/dist/packem_shared/use-admin-query-tlBof8Yg.mjs +1 -0
  133. package/dist/packem_shared/use-admin-spec-Bir7V68L.mjs +1 -0
  134. package/dist/packem_shared/use-async-submit-CZqCMTJ_.mjs +1 -0
  135. package/dist/packem_shared/use-auth-config-Z_n4ABCI.mjs +1 -0
  136. package/dist/packem_shared/use-mirrored-ref-CVDf2z1M.mjs +1 -0
  137. package/dist/packem_shared/use-open-trace-DMVhpnyG.mjs +1 -0
  138. package/dist/packem_shared/use-shard-key-BsP3o5wT.mjs +1 -0
  139. package/dist/packem_shared/use-sql-assistant-CZydTzd5.mjs +1 -0
  140. package/dist/packem_shared/useDebounced-DVeQ5-oW.mjs +1 -0
  141. package/dist/packem_shared/utils-bhneXptQ.mjs +1 -0
  142. package/dist/packem_shared/virtual-rect-D_j7aLxX.mjs +1 -0
  143. package/dist/packem_shared/wire-codec-B2DgCbKt.mjs +1 -0
  144. package/dist/standalone/chunk-253UHWDX.js +1 -0
  145. package/dist/standalone/chunk-2I4NHEKA.js +1 -0
  146. package/dist/standalone/chunk-2IKDEUCX.js +1 -0
  147. package/dist/standalone/chunk-2VA5S3IA.js +1 -0
  148. package/dist/standalone/chunk-37WYCOQ2.js +1 -0
  149. package/dist/standalone/chunk-3YXASVTP.js +1 -0
  150. package/dist/standalone/chunk-47EMK7A6.js +1 -0
  151. package/dist/standalone/chunk-4EFBLED2.js +1 -0
  152. package/dist/standalone/chunk-4ELKK7SE.js +1 -0
  153. package/dist/standalone/chunk-4GQJA35F.js +1 -0
  154. package/dist/standalone/chunk-4WD4XGC3.js +1 -0
  155. package/dist/standalone/chunk-4ZEL6BYL.js +1 -0
  156. package/dist/standalone/chunk-55UGUCQ6.js +1 -0
  157. package/dist/standalone/chunk-5B2RTXBS.js +1 -0
  158. package/dist/standalone/chunk-5O3OODSZ.js +1 -0
  159. package/dist/standalone/chunk-5QR2SQIS.js +1 -0
  160. package/dist/standalone/chunk-5QRUAQNY.js +1 -0
  161. package/dist/standalone/chunk-5UEMUPTW.js +1 -0
  162. package/dist/standalone/chunk-5XFBQCZ5.js +1 -0
  163. package/dist/standalone/chunk-627GZOJ7.js +1 -0
  164. package/dist/standalone/chunk-67YFV2GM.js +14 -0
  165. package/dist/standalone/chunk-6HLARDYO.js +1 -0
  166. package/dist/standalone/chunk-6QTAHSDD.js +1 -0
  167. package/dist/standalone/chunk-7G4Z6Q7X.js +1 -0
  168. package/dist/standalone/chunk-7GMSZEJR.js +4 -0
  169. package/dist/standalone/chunk-7HE4UK44.js +1 -0
  170. package/dist/standalone/chunk-7IU6DKN3.js +1 -0
  171. package/dist/standalone/chunk-7RKB5KS7.js +1 -0
  172. package/dist/standalone/chunk-7Y3SY37W.js +1 -0
  173. package/dist/standalone/chunk-AJEX5TMG.js +1 -0
  174. package/dist/standalone/chunk-AN4UDYUY.js +59 -0
  175. package/dist/standalone/chunk-AUAECCXB.js +1 -0
  176. package/dist/standalone/chunk-AUGKHAMQ.js +1 -0
  177. package/dist/standalone/chunk-BOMPSVRC.js +1 -0
  178. package/dist/standalone/chunk-C6SAOAML.js +1 -0
  179. package/dist/standalone/chunk-CCDX5RYT.js +1 -0
  180. package/dist/standalone/chunk-CGQMJYCW.js +1 -0
  181. package/dist/standalone/chunk-CVNG6XOK.js +1 -0
  182. package/dist/standalone/chunk-CVXNHIQW.js +1 -0
  183. package/dist/standalone/chunk-CX4FEQNT.js +1 -0
  184. package/dist/standalone/chunk-D7NNCIX4.js +1 -0
  185. package/dist/standalone/chunk-DB4FJSOK.js +1 -0
  186. package/dist/standalone/chunk-DGJMFHBV.js +9 -0
  187. package/dist/standalone/chunk-DY65YGY5.js +1 -0
  188. package/dist/standalone/chunk-DYLF2FA5.js +1 -0
  189. package/dist/standalone/chunk-E4PXACVL.js +3 -0
  190. package/dist/standalone/chunk-ECY2JC5F.js +1 -0
  191. package/dist/standalone/chunk-EK6VMAUN.js +1 -0
  192. package/dist/standalone/chunk-EQSFFE7F.js +2 -0
  193. package/dist/standalone/chunk-FJ4FPLVL.js +1 -0
  194. package/dist/standalone/chunk-FJF55TPZ.js +1 -0
  195. package/dist/standalone/chunk-FPI7AMQJ.js +1 -0
  196. package/dist/standalone/chunk-FUYEZFBP.js +1 -0
  197. package/dist/standalone/chunk-G5KWQMGT.js +1 -0
  198. package/dist/standalone/chunk-GCG65T2K.js +1 -0
  199. package/dist/standalone/chunk-GHQ2VDI2.js +1 -0
  200. package/dist/standalone/chunk-GN3LRVZ2.js +1 -0
  201. package/dist/standalone/chunk-HCTJKP5J.js +1 -0
  202. package/dist/standalone/chunk-HF4A3NUS.js +1 -0
  203. package/dist/standalone/chunk-HJHSQPHW.js +19 -0
  204. package/dist/standalone/chunk-I26MS5PJ.js +1 -0
  205. package/dist/standalone/chunk-IKKQNSLF.js +1 -0
  206. package/dist/standalone/chunk-IWZ7GVQO.js +1 -0
  207. package/dist/standalone/chunk-J6H3YTFH.js +1 -0
  208. package/dist/standalone/chunk-JHYNLMYA.js +1 -0
  209. package/dist/standalone/chunk-JQXA2OYK.js +1 -0
  210. package/dist/standalone/chunk-JZGTSH2C.js +4 -0
  211. package/dist/standalone/chunk-KGAUQL5T.js +1 -0
  212. package/dist/standalone/chunk-KVIBTEK5.js +1 -0
  213. package/dist/standalone/chunk-L56P33FH.js +1 -0
  214. package/dist/standalone/chunk-LFPYL6YU.js +1 -0
  215. package/dist/standalone/chunk-LW6ERMNX.js +1 -0
  216. package/dist/standalone/chunk-M6LSAR5C.js +1 -0
  217. package/dist/standalone/chunk-MEMHDCRE.js +1 -0
  218. package/dist/standalone/chunk-MTZ5UOQ5.js +3 -0
  219. package/dist/standalone/chunk-MVWZMWPD.js +1 -0
  220. package/dist/standalone/chunk-NCPW7WHO.js +1 -0
  221. package/dist/standalone/chunk-NDTQTKDX.js +6 -0
  222. package/dist/standalone/chunk-NGVP66OH.js +1 -0
  223. package/dist/standalone/chunk-NJGORSBO.js +1 -0
  224. package/dist/standalone/chunk-NQZALRU3.js +1 -0
  225. package/dist/standalone/chunk-NRP22GKC.js +1 -0
  226. package/dist/standalone/chunk-NXQW5E6W.js +1 -0
  227. package/dist/standalone/chunk-O5IUJQBJ.js +8 -0
  228. package/dist/standalone/chunk-OEKOZIPM.js +1 -0
  229. package/dist/standalone/chunk-OFZX4WXS.js +1 -0
  230. package/dist/standalone/chunk-OLQTBRWX.js +1 -0
  231. package/dist/standalone/chunk-OPM7ESDV.js +1 -0
  232. package/dist/standalone/chunk-OQ6I6OXT.js +2 -0
  233. package/dist/standalone/chunk-ORVHXDZV.js +1 -0
  234. package/dist/standalone/chunk-OSGXNEFA.js +1 -0
  235. package/dist/standalone/chunk-OYCUPD3Q.js +1 -0
  236. package/dist/standalone/chunk-PIMTWCRD.js +1 -0
  237. package/dist/standalone/chunk-Q6ED4KUL.js +1 -0
  238. package/dist/standalone/chunk-Q6IT6ZD7.js +1 -0
  239. package/dist/standalone/chunk-QAPKGURH.js +1 -0
  240. package/dist/standalone/chunk-QAQDMS6R.js +1 -0
  241. package/dist/standalone/chunk-QB55CQJC.js +1 -0
  242. package/dist/standalone/chunk-QJLHH3ET.js +1 -0
  243. package/dist/standalone/chunk-QLPEA5F7.js +5 -0
  244. package/dist/standalone/chunk-R6U22RSY.js +1 -0
  245. package/dist/standalone/chunk-RGMVGZV4.js +1 -0
  246. package/dist/standalone/chunk-RVZ2WOZ5.js +15 -0
  247. package/dist/standalone/chunk-RWVIV3U7.js +1 -0
  248. package/dist/standalone/chunk-RXZJYHAH.js +1 -0
  249. package/dist/standalone/chunk-S4Z7K55A.js +1 -0
  250. package/dist/standalone/chunk-SA2OGF3F.js +1 -0
  251. package/dist/standalone/chunk-SJ7BLQMI.js +1 -0
  252. package/dist/standalone/chunk-SJQERRSZ.js +1 -0
  253. package/dist/standalone/chunk-SMBKKLRX.js +1 -0
  254. package/dist/standalone/chunk-SV764LKQ.js +1 -0
  255. package/dist/standalone/chunk-UC7MNI2F.js +1 -0
  256. package/dist/standalone/chunk-UEKIUTCJ.js +1 -0
  257. package/dist/standalone/chunk-UYEZR3BI.js +1 -0
  258. package/dist/standalone/chunk-V2U4MITD.js +1 -0
  259. package/dist/standalone/chunk-VCFEO3RI.js +1 -0
  260. package/dist/standalone/chunk-VEK3S7MV.js +15 -0
  261. package/dist/standalone/chunk-VESGIGMQ.js +1 -0
  262. package/dist/standalone/chunk-W5TWX4V7.js +1 -0
  263. package/dist/standalone/chunk-WFICP5DT.js +1 -0
  264. package/dist/standalone/chunk-WJRYEML4.js +1 -0
  265. package/dist/standalone/chunk-WM6KXJGG.js +3 -0
  266. package/dist/standalone/chunk-WOPEVNW5.js +1 -0
  267. package/dist/standalone/chunk-WRQAHEWF.js +1 -0
  268. package/dist/standalone/chunk-WUJ3AOVG.js +1 -0
  269. package/dist/standalone/chunk-XGCIDUJF.js +1 -0
  270. package/dist/standalone/chunk-XHRKNCCI.js +1 -0
  271. package/dist/standalone/chunk-XQSJORIU.js +1 -0
  272. package/dist/standalone/chunk-Y3AYVFTK.js +1 -0
  273. package/dist/standalone/chunk-YRVZM2TB.js +1 -0
  274. package/dist/standalone/chunk-YVR4SEPU.js +1 -0
  275. package/dist/standalone/chunk-Z22BDS6N.js +1 -0
  276. package/dist/standalone/chunk-ZG4KF3SJ.js +1 -0
  277. package/dist/standalone/chunk-ZKJS6EBE.js +1 -0
  278. package/dist/standalone/studio.js +9 -378
  279. package/dist/styles.css +2 -2
  280. package/package.json +25 -21
  281. package/dist/index.js +0 -41
  282. package/dist/mount.js +0 -26
  283. package/dist/packem_shared/ADMIN_FUNCTIONS-CdaxLGkE.js +0 -48
  284. package/dist/packem_shared/ApiDocsPanel-BSSgtcVf.js +0 -842
  285. package/dist/packem_shared/ApiReferencePanel-D24xOjCw.js +0 -229
  286. package/dist/packem_shared/ApiTab-vo8uhE29.js +0 -251
  287. package/dist/packem_shared/AuditPanel-CBjYR6S5.js +0 -200
  288. package/dist/packem_shared/CommandPalette-L-CuSRUc.js +0 -373
  289. package/dist/packem_shared/ConfirmButton-C2eVi2Qv.js +0 -59
  290. package/dist/packem_shared/ConnectionBadge-B2DDM2Tn.js +0 -111
  291. package/dist/packem_shared/DEFAULT_AUTO_REFRESH_MS-Vxwaxx51.js +0 -50
  292. package/dist/packem_shared/DEFAULT_INSIGHT_THRESHOLDS-DjF0h-gA.js +0 -89
  293. package/dist/packem_shared/DEFAULT_LOCALE-CiX4W7Kr.js +0 -27
  294. package/dist/packem_shared/DataBrowser-DBKOIVKS.js +0 -4492
  295. package/dist/packem_shared/DataFilters-FNquMaiu.js +0 -249
  296. package/dist/packem_shared/ErrorBoundary-BzAApI7J.js +0 -66
  297. package/dist/packem_shared/ExportImportPanel-DtDEy4OD.js +0 -197
  298. package/dist/packem_shared/FileBrowser-DqLRjqsM.js +0 -2932
  299. package/dist/packem_shared/FunctionRunner-BmRkCvT4.js +0 -343
  300. package/dist/packem_shared/FunctionStatsPanel-Bi3kyQvu.js +0 -375
  301. package/dist/packem_shared/GlobalDataBrowser-DOjhvhKa.js +0 -289
  302. package/dist/packem_shared/HealthPanel-C7IPO6Ts.js +0 -648
  303. package/dist/packem_shared/HomePanel-dJIkHY_i.js +0 -14
  304. package/dist/packem_shared/InsightsPanel-BD29GXXd.js +0 -461
  305. package/dist/packem_shared/LogsPanel-2JhE1qep.js +0 -827
  306. package/dist/packem_shared/MailPanel-DwNsuFJC.js +0 -440
  307. package/dist/packem_shared/MetricsPanel-CRa4ITlq.js +0 -19
  308. package/dist/packem_shared/MigrationsPanel-Z1DmSSzf.js +0 -239
  309. package/dist/packem_shared/OpenRpcReferencePanel-Dq0yyVWz.js +0 -191
  310. package/dist/packem_shared/PitrPanel-3mec0LTF.js +0 -252
  311. package/dist/packem_shared/STUDIO_ROOT_CLASS-D12gX2dV.js +0 -3
  312. package/dist/packem_shared/ScheduledJobs--Z9GTmKb.js +0 -262
  313. package/dist/packem_shared/SchemaViewer-nxDV7dZJ.js +0 -2512
  314. package/dist/packem_shared/SecurityAdvisorPanel-5tYrJdvn.js +0 -92
  315. package/dist/packem_shared/SettingsPanel-SijRekVc.js +0 -390
  316. package/dist/packem_shared/ShardInput-gx_DZXXn.js +0 -107
  317. package/dist/packem_shared/SqlEditorPanel-DI4obotI.js +0 -13
  318. package/dist/packem_shared/Studio-B_L5Q2-X.js +0 -33
  319. package/dist/packem_shared/StudioApp-wxioPfiP.js +0 -657
  320. package/dist/packem_shared/StudioI18nProvider-B-tDCZIi.js +0 -48
  321. package/dist/packem_shared/TableEditor-1T-5KYtr.js +0 -11
  322. package/dist/packem_shared/advisor-view-DzqyvUU3.js +0 -159
  323. package/dist/packem_shared/aggregateMetrics-D4nUHEKU.js +0 -108
  324. package/dist/packem_shared/app.d-B6MyY_al.d.ts +0 -300
  325. package/dist/packem_shared/badge-B2PKA1-5.js +0 -49
  326. package/dist/packem_shared/bar-chart-CzJAgqkp.js +0 -3245
  327. package/dist/packem_shared/button-BhsN2uZH.js +0 -49
  328. package/dist/packem_shared/card-DURq3ElK.js +0 -175
  329. package/dist/packem_shared/cf-links-2cktDedA.js +0 -8
  330. package/dist/packem_shared/checkbox-UNkzAxl-.js +0 -63
  331. package/dist/packem_shared/data-grid-CrapHxR-.js +0 -183
  332. package/dist/packem_shared/dropdown-menu-WY4B_eJO.js +0 -280
  333. package/dist/packem_shared/empty-state-DY_oe0k6.js +0 -98
  334. package/dist/packem_shared/grid-features-DnTbXXNb.js +0 -840
  335. package/dist/packem_shared/home-panel-VdQI_8oX.js +0 -1700
  336. package/dist/packem_shared/input-XH4r1Pt1.js +0 -53
  337. package/dist/packem_shared/internal-CvMZCVd6.js +0 -68
  338. package/dist/packem_shared/label-D8ykjn5J.js +0 -46
  339. package/dist/packem_shared/live-status-FZ0psC1z.js +0 -44
  340. package/dist/packem_shared/metrics-panel-3FSfzgEX.js +0 -1611
  341. package/dist/packem_shared/reference-view-DVyk5kXj.js +0 -2180
  342. package/dist/packem_shared/shard-history-DyebH1R5.js +0 -38
  343. package/dist/packem_shared/sparkline-10dG-_f0.js +0 -93
  344. package/dist/packem_shared/sql-editor-panel-DBuIpCXk.js +0 -2562
  345. package/dist/packem_shared/storage-tier-CL98eOvn.js +0 -85
  346. package/dist/packem_shared/studio-Dm6H5DHS.js +0 -13388
  347. package/dist/packem_shared/table-DsCa9Qp9.js +0 -246
  348. package/dist/packem_shared/table-editor-7iSgi3te.js +0 -407
  349. package/dist/packem_shared/table-list-sidebar-BbSgfLJ2.js +0 -832
  350. package/dist/packem_shared/textarea-D3gaCU_-.js +0 -46
  351. package/dist/packem_shared/use-admin-query-CFl5GUg_.js +0 -105
  352. package/dist/packem_shared/useDebounced-Dxncpg6z.js +0 -32
  353. package/dist/packem_shared/utils-B05Dmz_H.js +0 -8
  354. package/dist/packem_shared/virtual-rect-CVMUskSm.js +0 -10
@@ -0,0 +1 @@
1
+ import{d as E}from"./chunk-BOMPSVRC.js";import{a as n,d as b,e as h}from"./chunk-I26MS5PJ.js";var y=b(h(),1);var T=n(()=>{},"noop"),K=typeof document<"u"?y.useLayoutEffect:T;var W=b(h(),1),l={...W};var a=l.useInsertionEffect,_=a&&a!==l.useLayoutEffect?a:t=>t();function q(t){let e=E(B).current;return e.next=t,_(e.effect),e.trampoline}n(q,"useStableCallback");function B(){let t={next:void 0,callback:O,trampoline:n((...e)=>t.callback?.(...e),"trampoline"),effect:n(()=>{t.callback=t.next},"effect")};return t}n(B,"createStableCallback");function O(){}n(O,"assertNotCalled");function s(){return typeof window<"u"}n(s,"hasWindow");function m(t){return N(t)?(t.nodeName||"").toLowerCase():"#document"}n(m,"getNodeName");function c(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}n(c,"getWindow");function V(t){var e;return(e=(N(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}n(V,"getDocumentElement");function N(t){return s()?t instanceof Node||t instanceof c(t).Node:!1}n(N,"isNode");function C(t){return s()?t instanceof Element||t instanceof c(t).Element:!1}n(C,"isElement");function L(t){return s()?t instanceof HTMLElement||t instanceof c(t).HTMLElement:!1}n(L,"isHTMLElement");function g(t){return!s()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof c(t).ShadowRoot}n(g,"isShadowRoot");function R(t){let{overflow:e,overflowX:i,overflowY:u,display:o}=v(t);return/auto|scroll|overlay|hidden|clip/.test(e+u+i)&&o!=="inline"&&o!=="contents"}n(R,"isOverflowElement");function J(t){return/^(table|td|th)$/.test(m(t))}n(J,"isTableElement");function $(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}n($,"isTopLayer");var A=/transform|translate|scale|rotate|perspective|filter/,H=/paint|layout|strict|content/,r=n(t=>!!t&&t!=="none","isNotNone"),d;function I(t){let e=C(t)?v(t):t;return r(e.transform)||r(e.translate)||r(e.scale)||r(e.rotate)||r(e.perspective)||!M()&&(r(e.backdropFilter)||r(e.filter))||A.test(e.willChange||"")||H.test(e.contain||"")}n(I,"isContainingBlock");function Q(t){let e=p(t);for(;L(e)&&!k(e);){if(I(e))return e;if($(e))return null;e=p(e)}return null}n(Q,"getContainingBlock");function M(){return d==null&&(d=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),d}n(M,"isWebKit");function k(t){return/^(html|body|#document)$/.test(m(t))}n(k,"isLastTraversableNode");function v(t){return c(t).getComputedStyle(t)}n(v,"getComputedStyle");function Z(t){return C(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}n(Z,"getNodeScroll");function p(t){if(m(t)==="html")return t;let e=t.assignedSlot||t.parentNode||g(t)&&t.host||V(t);return g(e)?e.host:e}n(p,"getParentNode");function D(t){let e=p(t);return k(e)?(t.ownerDocument||t).body:L(e)&&R(e)?e:D(e)}n(D,"getNearestOverflowAncestor");function S(t,e,i){var u;e===void 0&&(e=[]),i===void 0&&(i=!0);let o=D(t),x=o===((u=t.ownerDocument)==null?void 0:u.body),f=c(o);if(x){let w=F(f);return e.concat(f,f.visualViewport||[],R(o)?o:[],w&&i?S(w):[])}else return e.concat(o,S(o,[],i))}n(S,"getOverflowAncestors");function F(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}n(F,"getFrameElement");function nt(t){return t?.ownerDocument||document}n(nt,"ownerDocument");export{K as a,l as b,q as c,m as d,c as e,V as f,N as g,C as h,L as i,g as j,R as k,J as l,$ as m,I as n,Q as o,M as p,k as q,v as r,Z as s,p as t,S as u,F as v,nt as w};
@@ -0,0 +1 @@
1
+ import{a as f}from"./chunk-I26MS5PJ.js";function S(e,r,t){e.prototype=r.prototype=t,t.constructor=e}f(S,"default");function W(e,r){var t=Object.create(e.prototype);for(var n in r)t[n]=r[n];return t}f(W,"extend");function B(){}f(B,"Color");var C=.7,Y=1/C,R="\\s*([+-]?\\d+)\\s*",E="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",y="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Xe=/^#([0-9a-f]{3,8})$/,Se=new RegExp(`^rgb\\(${R},${R},${R}\\)$`),Ce=new RegExp(`^rgb\\(${y},${y},${y}\\)$`),Ee=new RegExp(`^rgba\\(${R},${R},${R},${E}\\)$`),Be=new RegExp(`^rgba\\(${y},${y},${y},${E}\\)$`),Ie=new RegExp(`^hsl\\(${E},${y},${y}\\)$`),_e=new RegExp(`^hsla\\(${E},${y},${y},${E}\\)$`),se={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};S(B,v,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:le,formatHex:le,formatHex8:je,formatHsl:Ye,formatRgb:ue,toString:ue});function le(){return this.rgb().formatHex()}f(le,"color_formatHex");function je(){return this.rgb().formatHex8()}f(je,"color_formatHex8");function Ye(){return ge(this).formatHsl()}f(Ye,"color_formatHsl");function ue(){return this.rgb().formatRgb()}f(ue,"color_formatRgb");function v(e){var r,t;return e=(e+"").trim().toLowerCase(),(r=Xe.exec(e))?(t=r[1].length,r=parseInt(r[1],16),t===6?xe(r):t===3?new d(r>>8&15|r>>4&240,r>>4&15|r&240,(r&15)<<4|r&15,1):t===8?_(r>>24&255,r>>16&255,r>>8&255,(r&255)/255):t===4?_(r>>12&15|r>>8&240,r>>8&15|r>>4&240,r>>4&15|r&240,((r&15)<<4|r&15)/255):null):(r=Se.exec(e))?new d(r[1],r[2],r[3],1):(r=Ce.exec(e))?new d(r[1]*255/100,r[2]*255/100,r[3]*255/100,1):(r=Ee.exec(e))?_(r[1],r[2],r[3],r[4]):(r=Be.exec(e))?_(r[1]*255/100,r[2]*255/100,r[3]*255/100,r[4]):(r=Ie.exec(e))?he(r[1],r[2]/100,r[3]/100,1):(r=_e.exec(e))?he(r[1],r[2]/100,r[3]/100,r[4]):se.hasOwnProperty(e)?xe(se[e]):e==="transparent"?new d(NaN,NaN,NaN,0):null}f(v,"color");function xe(e){return new d(e>>16&255,e>>8&255,e&255,1)}f(xe,"rgbn");function _(e,r,t,n){return n<=0&&(e=r=t=NaN),new d(e,r,t,n)}f(_,"rgba");function Le(e){return e instanceof B||(e=v(e)),e?(e=e.rgb(),new d(e.r,e.g,e.b,e.opacity)):new d}f(Le,"rgbConvert");function H(e,r,t,n){return arguments.length===1?Le(e):new d(e,r,t,n??1)}f(H,"rgb");function d(e,r,t,n){this.r=+e,this.g=+r,this.b=+t,this.opacity=+n}f(d,"Rgb");S(d,H,W(B,{brighter(e){return e=e==null?Y:Math.pow(Y,e),new d(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?C:Math.pow(C,e),new d(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new d(k(this.r),k(this.g),k(this.b),L(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:ce,formatHex:ce,formatHex8:Te,formatRgb:pe,toString:pe}));function ce(){return`#${N(this.r)}${N(this.g)}${N(this.b)}`}f(ce,"rgb_formatHex");function Te(){return`#${N(this.r)}${N(this.g)}${N(this.b)}${N((isNaN(this.opacity)?1:this.opacity)*255)}`}f(Te,"rgb_formatHex8");function pe(){let e=L(this.opacity);return`${e===1?"rgb(":"rgba("}${k(this.r)}, ${k(this.g)}, ${k(this.b)}${e===1?")":`, ${e})`}`}f(pe,"rgb_formatRgb");function L(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}f(L,"clampa");function k(e){return Math.max(0,Math.min(255,Math.round(e)||0))}f(k,"clampi");function N(e){return e=k(e),(e<16?"0":"")+e.toString(16)}f(N,"hex");function he(e,r,t,n){return n<=0?e=r=t=NaN:t<=0||t>=1?e=r=NaN:r<=0&&(e=NaN),new w(e,r,t,n)}f(he,"hsla");function ge(e){if(e instanceof w)return new w(e.h,e.s,e.l,e.opacity);if(e instanceof B||(e=v(e)),!e)return new w;if(e instanceof w)return e;e=e.rgb();var r=e.r/255,t=e.g/255,n=e.b/255,i=Math.min(r,t,n),o=Math.max(r,t,n),a=NaN,s=o-i,x=(o+i)/2;return s?(r===o?a=(t-n)/s+(t<n)*6:t===o?a=(n-r)/s+2:a=(r-t)/s+4,s/=x<.5?o+i:2-o-i,a*=60):s=x>0&&x<1?0:a,new w(a,s,x,e.opacity)}f(ge,"hslConvert");function me(e,r,t,n){return arguments.length===1?ge(e):new w(e,r,t,n??1)}f(me,"hsl");function w(e,r,t,n){this.h=+e,this.s=+r,this.l=+t,this.opacity=+n}f(w,"Hsl");S(w,me,W(B,{brighter(e){return e=e==null?Y:Math.pow(Y,e),new w(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?C:Math.pow(C,e),new w(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,r=isNaN(e)||isNaN(this.s)?0:this.s,t=this.l,n=t+(t<.5?t:1-t)*r,i=2*t-n;return new d(Z(e>=240?e-240:e+120,i,n),Z(e,i,n),Z(e<120?e+240:e-120,i,n),this.opacity)},clamp(){return new w(de(this.h),j(this.s),j(this.l),L(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=L(this.opacity);return`${e===1?"hsl(":"hsla("}${de(this.h)}, ${j(this.s)*100}%, ${j(this.l)*100}%${e===1?")":`, ${e})`}`}}));function de(e){return e=(e||0)%360,e<0?e+360:e}f(de,"clamph");function j(e){return Math.max(0,Math.min(1,e||0))}f(j,"clampt");function Z(e,r,t){return(e<60?r+(t-r)*e/60:e<180?t:e<240?r+(t-r)*(240-e)/60:r)*255}f(Z,"hsl2rgb");function F(e,r,t,n,i){var o=e*e,a=o*e;return((1-3*e+3*o-a)*r+(4-6*o+3*a)*t+(1+3*e+3*o-3*a)*n+a*i)/6}f(F,"basis");function J(e){var r=e.length-1;return function(t){var n=t<=0?t=0:t>=1?(t=1,r-1):Math.floor(t*r),i=e[n],o=e[n+1],a=n>0?e[n-1]:2*i-o,s=n<r-1?e[n+2]:2*o-i;return F((t-n/r)*r,a,i,o,s)}}f(J,"default");function U(e){var r=e.length;return function(t){var n=Math.floor(((t%=1)<0?++t:t)*r),i=e[(n+r-1)%r],o=e[n%r],a=e[(n+1)%r],s=e[(n+2)%r];return F((t-n/r)*r,i,o,a,s)}}f(U,"default");var I=f(e=>()=>e,"default");function De(e,r){return function(t){return e+t*r}}f(De,"linear");function Oe(e,r,t){return e=Math.pow(e,t),r=Math.pow(r,t)-e,t=1/t,function(n){return Math.pow(e+n*r,t)}}f(Oe,"exponential");function be(e){return(e=+e)==1?T:function(r,t){return t-r?Oe(r,t,e):I(isNaN(r)?t:r)}}f(be,"gamma");function T(e,r){var t=r-e;return t?De(e,t):I(isNaN(e)?r:e)}f(T,"nogamma");var D=f((function e(r){var t=be(r);function n(i,o){var a=t((i=H(i)).r,(o=H(o)).r),s=t(i.g,o.g),x=t(i.b,o.b),l=T(i.opacity,o.opacity);return function(u){return i.r=a(u),i.g=s(u),i.b=x(u),i.opacity=l(u),i+""}}return f(n,"rgb"),n.gamma=e,n}),"rgbGamma")(1);function we(e){return function(r){var t=r.length,n=new Array(t),i=new Array(t),o=new Array(t),a,s;for(a=0;a<t;++a)s=H(r[a]),n[a]=s.r||0,i[a]=s.g||0,o[a]=s.b||0;return n=e(n),i=e(i),o=e(o),s.opacity=1,function(x){return s.r=n(x),s.g=i(x),s.b=o(x),s+""}}}f(we,"rgbSpline");var ze=we(J),Pe=we(U);function ee(e,r){r||(r=[]);var t=e?Math.min(r.length,e.length):0,n=r.slice(),i;return function(o){for(i=0;i<t;++i)n[i]=e[i]*(1-o)+r[i]*o;return n}}f(ee,"default");function ye(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}f(ye,"isNumberArray");function ve(e,r){var t=r?r.length:0,n=e?Math.min(t,e.length):0,i=new Array(n),o=new Array(t),a;for(a=0;a<n;++a)i[a]=M(e[a],r[a]);for(;a<t;++a)o[a]=r[a];return function(s){for(a=0;a<n;++a)o[a]=i[a](s);return o}}f(ve,"genericArray");function re(e,r){var t=new Date;return e=+e,r=+r,function(n){return t.setTime(e*(1-n)+r*n),t}}f(re,"default");function g(e,r){return e=+e,r=+r,function(t){return e*(1-t)+r*t}}f(g,"default");function te(e,r){var t={},n={},i;(e===null||typeof e!="object")&&(e={}),(r===null||typeof r!="object")&&(r={});for(i in r)i in e?t[i]=M(e[i],r[i]):n[i]=r[i];return function(o){for(i in t)n[i]=t[i](o);return n}}f(te,"default");var fe=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ne=new RegExp(fe.source,"g");function Ve(e){return function(){return e}}f(Ve,"zero");function Qe(e){return function(r){return e(r)+""}}f(Qe,"one");function O(e,r){var t=fe.lastIndex=ne.lastIndex=0,n,i,o,a=-1,s=[],x=[];for(e=e+"",r=r+"";(n=fe.exec(e))&&(i=ne.exec(r));)(o=i.index)>t&&(o=r.slice(t,o),s[a]?s[a]+=o:s[++a]=o),(n=n[0])===(i=i[0])?s[a]?s[a]+=i:s[++a]=i:(s[++a]=null,x.push({i:a,x:g(n,i)})),t=ne.lastIndex;return t<r.length&&(o=r.slice(t),s[a]?s[a]+=o:s[++a]=o),s.length<2?x[0]?Qe(x[0].x):Ve(r):(r=x.length,function(l){for(var u=0,c;u<r;++u)s[(c=x[u]).i]=c.x(l);return s.join("")})}f(O,"default");function M(e,r){var t=typeof r,n;return r==null||t==="boolean"?I(r):(t==="number"?g:t==="string"?(n=v(r))?(r=n,D):O:r instanceof v?D:r instanceof Date?re:ye(r)?ee:Array.isArray(r)?ve:typeof r.valueOf!="function"&&typeof r.toString!="function"||isNaN(r)?te:g)(e,r)}f(M,"default");var Ge=1e-12;function Me(e){return((e=Math.exp(e))+1/e)/2}f(Me,"cosh");function Ke(e){return((e=Math.exp(e))-1/e)/2}f(Ke,"sinh");function We(e){return((e=Math.exp(2*e))-1)/(e+1)}f(We,"tanh");var Ze=f((function e(r,t,n){function i(o,a){var s=o[0],x=o[1],l=o[2],u=a[0],c=a[1],p=a[2],h=u-s,b=c-x,m=h*h+b*b,$,A;if(m<Ge)A=Math.log(p/l)/r,$=f(function(X){return[s+X*h,x+X*b,l*Math.exp(r*X*A)]},"i");else{var Q=Math.sqrt(m),G=(p*p-l*l+n*m)/(2*l*t*Q),K=(p*p-l*l-n*m)/(2*p*t*Q),q=Math.log(Math.sqrt(G*G+1)-G),qe=Math.log(Math.sqrt(K*K+1)-K);A=(qe-q)/r,$=f(function(X){var ie=X*A,ae=Me(q),oe=l/(t*Q)*(ae*We(r*ie+q)-Ke(q));return[s+oe*h,x+oe*b,l*ae/Me(r*ie+q)]},"i")}return $.duration=A*1e3*r/Math.SQRT2,$}return f(i,"zoom"),i.rho=function(o){var a=Math.max(.001,+o),s=a*a,x=s*s;return e(a,s,x)},i}),"zoomRho")(Math.SQRT2,2,4);function $e(e,r){return e=+e,r=+r,function(t){return Math.round(e*(1-t)+r*t)}}f($e,"default");var Ne=180/Math.PI,z={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function P(e,r,t,n,i,o){var a,s,x;return(a=Math.sqrt(e*e+r*r))&&(e/=a,r/=a),(x=e*t+r*n)&&(t-=e*x,n-=r*x),(s=Math.sqrt(t*t+n*n))&&(t/=s,n/=s,x/=s),e*n<r*t&&(e=-e,r=-r,x=-x,a=-a),{translateX:i,translateY:o,rotate:Math.atan2(r,e)*Ne,skewX:Math.atan(x)*Ne,scaleX:a,scaleY:s}}f(P,"default");var V;function ke(e){let r=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return r.isIdentity?z:P(r.a,r.b,r.c,r.d,r.e,r.f)}f(ke,"parseCss");function Re(e){return e==null?z:(V||(V=document.createElementNS("http://www.w3.org/2000/svg","g")),V.setAttribute("transform",e),(e=V.transform.baseVal.consolidate())?(e=e.matrix,P(e.a,e.b,e.c,e.d,e.e,e.f)):z)}f(Re,"parseSvg");function He(e,r,t,n){function i(l){return l.length?l.pop()+" ":""}f(i,"pop");function o(l,u,c,p,h,b){if(l!==c||u!==p){var m=h.push("translate(",null,r,null,t);b.push({i:m-4,x:g(l,c)},{i:m-2,x:g(u,p)})}else(c||p)&&h.push("translate("+c+r+p+t)}f(o,"translate");function a(l,u,c,p){l!==u?(l-u>180?u+=360:u-l>180&&(l+=360),p.push({i:c.push(i(c)+"rotate(",null,n)-2,x:g(l,u)})):u&&c.push(i(c)+"rotate("+u+n)}f(a,"rotate");function s(l,u,c,p){l!==u?p.push({i:c.push(i(c)+"skewX(",null,n)-2,x:g(l,u)}):u&&c.push(i(c)+"skewX("+u+n)}f(s,"skewX");function x(l,u,c,p,h,b){if(l!==c||u!==p){var m=h.push(i(h)+"scale(",null,",",null,")");b.push({i:m-4,x:g(l,c)},{i:m-2,x:g(u,p)})}else(c!==1||p!==1)&&h.push(i(h)+"scale("+c+","+p+")")}return f(x,"scale"),function(l,u){var c=[],p=[];return l=e(l),u=e(u),o(l.translateX,l.translateY,u.translateX,u.translateY,c,p),a(l.rotate,u.rotate,c,p),s(l.skewX,u.skewX,c,p),x(l.scaleX,l.scaleY,u.scaleX,u.scaleY,c,p),l=u=null,function(h){for(var b=-1,m=p.length,$;++b<m;)c[($=p[b]).i]=$.x(h);return c.join("")}}}f(He,"interpolateTransform");var Fe=He(ke,"px, ","px)","deg)"),Je=He(Re,", ",")",")");function Ae(e,r){r===void 0&&(r=e,e=M);for(var t=0,n=r.length-1,i=r[0],o=new Array(n<0?0:n);t<n;)o[t]=e(i,i=r[++t]);return function(a){var s=Math.max(0,Math.min(n-1,Math.floor(a*=n)));return o[s](a-s)}}f(Ae,"piecewise");export{v as a,D as b,g as c,O as d,M as e,$e as f,Fe as g,Je as h,Ze as i,Ae as j};
@@ -0,0 +1 @@
1
+ import{a as r,d as p,e as m}from"./chunk-I26MS5PJ.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};
@@ -0,0 +1 @@
1
+ import{a as H}from"./chunk-JQXA2OYK.js";import{b as x}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{b as z}from"./chunk-J6H3YTFH.js";import{g as O}from"./chunk-DGJMFHBV.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as _}from"./chunk-RWVIV3U7.js";import{a as q,b as B,c as E,d as S,e as i,f as s}from"./chunk-HCTJKP5J.js";import{a as A,e as L}from"./chunk-2IKDEUCX.js";import{d as W}from"./chunk-HJHSQPHW.js";import{a as R,d as M,f as $,g as D}from"./chunk-I26MS5PJ.js";var I=M($(),1);var n=M(D(),1);var F=2e3,G=new Set(["open"]),ie=R(Q=>{let e=(0,I.c)(41),{read:y}=Q,t=W(),j=O(),v;e[0]!==j||e[1]!==y?(v=R(()=>Promise.resolve(y?y():j.debug()),"T"),e[0]=j,e[1]=y,e[2]=v):v=e[2];let V=v,K=y?"injected":"live",b;e[3]!==K?(b=["lunora-studio","sync-client-debug",K],e[3]=K,e[4]=b):b=e[4];let{data:c,refetch:Y}=z(b,V);if(H(Y,!0,F),!c){let r;e[5]!==t?(r=t("Reading the sync client's state\u2026"),e[5]=t,e[6]=r):r=e[6];let g;e[7]!==t?(g=t("Sync client"),e[7]=t,e[8]=g):g=e[8];let T;return e[9]!==r||e[10]!==g?(T=(0,n.jsx)(A,{children:(0,n.jsx)(L,{children:(0,n.jsx)(_,{description:r,title:g})})}),e[9]=r,e[10]=g,e[11]=T):T=e[11],T}let{pendingWrites:k,shards:N,subscriptions:w}=c,a;e[12]!==t?(a=t("This Studio session's sync client"),e[12]=t,e[13]=a):a=e[13];let l;e[14]!==a?(l=(0,n.jsx)("span",{className:"text-sm font-medium",children:a}),e[14]=a,e[15]=l):l=e[15];let P=c.connectionStatus==="connected"?"default":"secondary",o;e[16]!==c.connectionStatus||e[17]!==P?(o=(0,n.jsx)(x,{variant:P,children:c.connectionStatus}),e[16]=c.connectionStatus,e[17]=P,e[18]=o):o=e[18];let d;e[19]!==k||e[20]!==t?(d=k>0?(0,n.jsx)(x,{variant:"secondary",children:t("{count} pending writes",{count:k})}):null,e[19]=k,e[20]=t,e[21]=d):d=e[21];let h;e[22]!==l||e[23]!==o||e[24]!==d?(h=(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[l,o,d]}),e[22]=l,e[23]=o,e[24]=d,e[25]=h):h=e[25];let u;e[26]!==t?(u=t("Reads client.debug() for the client running in this page \u2014 not your application's client. Call client.debug() in your app to diagnose a specific stuck overlay there."),e[26]=t,e[27]=u):u=e[27];let m;e[28]!==u?(m=(0,n.jsx)("p",{className:"text-muted-foreground text-xs",children:u}),e[28]=u,e[29]=m):m=e[29];let p;e[30]!==N||e[31]!==t?(p=N.length===0?(0,n.jsx)(_,{description:t("No shard connection has been opened yet."),title:t("No shards")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Shard")}),(0,n.jsx)(i,{children:t("Socket")}),(0,n.jsx)(i,{children:t("Confirmed watermark")})]})}),(0,n.jsx)(E,{children:N.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{children:r.shardKey??t("(default)")}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:G.has(r.wsState)?"default":"secondary",children:r.wsState})}),(0,n.jsx)(s,{children:r.confirmedMutationWatermark})]},r.shardKey??"__default__"))})]}),e[30]=N,e[31]=t,e[32]=p):p=e[32];let f;e[33]!==w||e[34]!==t?(f=w.length===0?(0,n.jsx)(_,{description:t("This client holds no live queries or shapes."),title:t("No subscriptions")}):(0,n.jsxs)(q,{children:[(0,n.jsx)(B,{children:(0,n.jsxs)(S,{children:[(0,n.jsx)(i,{children:t("Subscription")}),(0,n.jsx)(i,{children:t("Kind")}),(0,n.jsx)(i,{children:t("Acked")}),(0,n.jsx)(i,{children:t("Cursor")}),(0,n.jsx)(i,{children:t("Pending overlays")})]})}),(0,n.jsx)(E,{children:w.map(r=>(0,n.jsxs)(S,{children:[(0,n.jsx)(s,{className:"font-mono text-xs",children:r.functionPath}),(0,n.jsx)(s,{children:r.kind}),(0,n.jsx)(s,{children:(0,n.jsx)(x,{variant:r.acked?"default":"secondary",children:r.acked?t("yes"):t("no")})}),(0,n.jsx)(s,{children:r.serverCursor??"\u2014"}),(0,n.jsx)(s,{children:r.pendingOptimisticLayers})]},r.id))})]}),e[33]=w,e[34]=t,e[35]=f):f=e[35];let C;return e[36]!==m||e[37]!==p||e[38]!==f||e[39]!==h?(C=(0,n.jsx)(A,{children:(0,n.jsxs)(L,{className:"flex flex-col gap-4",children:[h,m,p,f]})}),e[36]=m,e[37]=p,e[38]=f,e[39]=h,e[40]=C):C=e[40],C},"ie");export{ie as default};
@@ -0,0 +1 @@
1
+ import{a as s}from"./chunk-I26MS5PJ.js";var u=new Set(["contains","eq","gt","gte","lt","lte","ne"]),a=s(r=>typeof r=="number"&&Number.isSafeInteger(r)?String(r):r,"i"),o=s(r=>{if(typeof r!="string")return;let e=r.trim();return e===""?void 0:e},"e"),v=s(r=>{if(r===null||typeof r!="object")return!1;let e=r;return typeof e.column=="string"&&typeof e.operator=="string"&&u.has(e.operator)},"p"),h=s(r=>{if(typeof r!="string"||r==="")return[];try{let e=JSON.parse(r);return Array.isArray(e)?e.filter(v):[]}catch{return[]}},"f"),g=s(r=>{if(typeof r!="string"||r==="")return;let e=r.lastIndexOf(":");if(e<=0)return;let i=r.slice(0,e),n=r.slice(e+1);if(!(n!=="asc"&&n!=="desc"))return{column:i,direction:n}},"u"),p=/^[\da-f]{16}$/u,b=s(r=>{let e={};if(typeof r.pins=="string"&&r.pins!==""){let c=r.pins.split(",").filter(f=>f!==""&&f.length<=64).slice(0,12);c.length>0&&(e.pins=c.join(","))}r.schema==="global"&&(e.schema="global");let i=o(r.table);i!==void 0&&(e.table=i);let n=o(a(r.shard));n!==void 0&&(e.shard=n);let d=o(a(r.search));d!==void 0&&(e.search=d);let t=o(r.order);t!==void 0&&g(t)!==void 0&&(e.order=t);let l=o(r.filters);return l!==void 0&&h(l).length>0&&(e.filters=l),e},"b"),y=s(r=>{let e=h(r.filters),i=g(r.order);return{filters:e.length>0?e:void 0,orderBy:i,search:o(a(r.search)),shard:o(a(r.shard)),table:o(r.table),tier:r.schema==="global"?"global":"shard"}},"v"),m=s(r=>{let e=r.filters??[];return{filters:e.length>0?JSON.stringify(e):void 0,order:r.orderBy===void 0?void 0:`${r.orderBy.column}:${r.orderBy.direction}`,schema:r.tier==="global"?"global":void 0,search:r.search!==void 0&&r.search!==""?r.search:void 0,shard:r.shard!==void 0&&r.shard!==""?r.shard:void 0,table:r.table!==void 0&&r.table!==""?r.table:void 0}},"y"),S=s(r=>{let{version:e}=r;return typeof e=="string"&&p.test(e)?{version:e}:{}},"S");export{b as a,y as b,m as c,S as d};
@@ -0,0 +1 @@
1
+ import{a as f,d as r,e as m,f as n}from"./chunk-I26MS5PJ.js";var u=r(n(),1),s=r(m(),1);function a(t){let e=(0,u.c)(2),c=(0,s.useRef)(t),o;return e[0]!==t?(o=f(()=>{c.current=t},"t"),e[0]=t,e[1]=o):o=e[1],(0,s.useEffect)(o),c}f(a,"m");export{a};
@@ -0,0 +1 @@
1
+ import{b as P}from"./chunk-5O3OODSZ.js";import{c as K,d as X,e as z,f as L,h as B,i as E,j as G,k as q,l as A,m as O,n as W,o as $,p as D}from"./chunk-AN4UDYUY.js";import{a as F,b as H,c as I,d as S,e as J,f as M}from"./chunk-HCTJKP5J.js";import{d as C,o as j}from"./chunk-HJHSQPHW.js";import{a as f,d as T,f as U,g as V}from"./chunk-I26MS5PJ.js";var N=T(U(),1);var t=T(V(),1);var _=50,R={value:{colors:{dark:["var(--chart-1)"],light:["var(--chart-1)"]},label:"value"}},Q=f(r=>{let a=r.columns.find(e=>r.rows.length>0&&r.rows.every(n=>typeof n[e]=="number"))??null;return{label:r.columns.find(e=>e!==a)??null,value:a}},"D"),Y=f(r=>{let a=(0,N.c)(3),{data:e,kind:n}=r,l;return a[0]!==e||a[1]!==n?(l=(0,t.jsx)(G,{className:"h-full w-full",config:R,children:n==="area"?(0,t.jsxs)(E,{data:e,children:[(0,t.jsx)(K,{vertical:!1}),(0,t.jsx)(L,{axisLine:!1,dataKey:"label",tickLine:!1}),(0,t.jsx)(A,{content:(0,t.jsx)(q,{})}),(0,t.jsx)(z,{dataKey:"value",fill:"var(--color-value-0)",fillOpacity:.2,stroke:"var(--color-value-0)",type:"monotone"})]}):(0,t.jsxs)(B,{data:e,children:[(0,t.jsx)(K,{vertical:!1}),(0,t.jsx)(L,{axisLine:!1,dataKey:"label",tickLine:!1}),(0,t.jsx)(A,{content:(0,t.jsx)(q,{})}),(0,t.jsx)(X,{dataKey:"value",dot:!1,stroke:"var(--color-value-0)",strokeWidth:2,type:"monotone"})]})}),a[0]=e,a[1]=n,a[2]=l):l=a[2],l},"J"),na=f(r=>{let a=(0,N.c)(21),{axes:e,kind:n,result:l}=r,u=C(),o;a[0]!==l?(o=Q(l),a[0]=l,a[1]=o):o=a[1];let d=o,m;a[2]!==l.columns?(m=new Set(l.columns),a[2]=l.columns,a[3]=m):m=a[3];let s=m,c=e!==void 0&&s.has(e.x)?e.x:d.label,p;a[4]!==e?.y||a[5]!==s?(p=e?.y.find(i=>s.has(i)),a[4]=e?.y,a[5]=s,a[6]=p):p=a[6];let x=p,y=x??d.value,b;a[7]!==c||a[8]!==l.rows||a[9]!==y?(b=y===null?[]:l.rows.slice(0,_).map((i,w)=>({label:c===null?`#${(w+1).toString()}`:j(i[c]),value:Number(i[y])||0})),a[7]=c,a[8]=l.rows,a[9]=y,a[10]=b):b=a[10];let k=b;if(y===null){let i;a[11]!==u?(i=u("No numeric column to chart."),a[11]=u,a[12]=i):i=a[12];let w;return a[13]!==i?(w=(0,t.jsx)("p",{className:"p-4 text-sm text-muted-foreground","data-testid":"sql-chart-empty",children:i}),a[13]=i,a[14]=w):w=a[14],w}let h=n??(e!==void 0&&x!==void 0?e.kind:"bar"),v;a[15]!==k||a[16]!==h?(v=h==="bar"?(0,t.jsxs)(O,{className:"h-full w-full",config:R,data:k,children:[(0,t.jsx)($,{dataKey:"label"}),(0,t.jsx)(W,{dataKey:"value"}),(0,t.jsx)(D,{})]}):(0,t.jsx)(Y,{data:k,kind:h}),a[15]=k,a[16]=h,a[17]=v):v=a[17];let g;return a[18]!==h||a[19]!==v?(g=(0,t.jsx)("div",{className:"h-80 w-full p-3","data-chart-kind":h,"data-testid":"sql-chart",children:v}),a[18]=h,a[19]=v,a[20]=g):g=a[20],g},"oe"),oa=f(r=>{let a=(0,N.c)(19),{result:e}=r,n=C();if(e.columns.length===0){let s;a[0]!==e.rowCount||a[1]!==n?(s=n("{count} rows",{count:e.rowCount}),a[0]=e.rowCount,a[1]=n,a[2]=s):s=a[2];let c;return a[3]!==s?(c=(0,t.jsx)("p",{className:"p-4 text-sm text-muted-foreground",children:s}),a[3]=s,a[4]=c):c=a[4],c}let l;a[5]!==e.columns?(l=e.columns.map(Z),a[5]=e.columns,a[6]=l):l=a[6];let u;a[7]!==l?(u=(0,t.jsx)(H,{className:"sticky top-0 z-10 bg-muted",children:(0,t.jsx)(S,{children:l})}),a[7]=l,a[8]=u):u=a[8];let o;if(a[9]!==e.columns||a[10]!==e.rows){let s;a[12]!==e.columns?(s=f((c,p)=>(0,t.jsx)(S,{"data-testid":"sql-row",children:e.columns.map(x=>(0,t.jsx)(M,{className:"max-w-md truncate font-mono text-xs",children:(0,t.jsx)(P,{value:c[x]})},x))},p),"s"),a[12]=e.columns,a[13]=s):s=a[13],o=e.rows.map(s),a[9]=e.columns,a[10]=e.rows,a[11]=o}else o=a[11];let d;a[14]!==o?(d=(0,t.jsx)(I,{children:o}),a[14]=o,a[15]=d):d=a[15];let m;return a[16]!==u||a[17]!==d?(m=(0,t.jsxs)(F,{"data-testid":"sql-rows",children:[u,d]}),a[16]=u,a[17]=d,a[18]=m):m=a[18],m},"ne");function Z(r){return(0,t.jsx)(J,{children:r},r)}f(Z,"P");export{na as a,oa as b};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-I26MS5PJ.js";var e=i(t=>{let r=Math.floor(t/1e3),o=Math.floor(r/3600),n=Math.floor(r%3600/60),a=r%60;return o>0?`${o.toString()}h ${n.toString()}m`:n>0?`${n.toString()}m ${a.toString()}s`:`${a.toString()}s`},"e"),m=i((t,r)=>{let o=t+r;return o===0?"\u2014":`${(t/o*100).toFixed(1)}%`},"a"),s=i(t=>t<=0?"\u2014":t<1?`${(t*1e3).toFixed(0)}\u03BCs`:t<1e3?`${t.toFixed(1)}ms`:`${(t/1e3).toFixed(2)}s`,"s"),c=i((t,r)=>new Intl.NumberFormat(r,t===0||Math.abs(t)>=1?{currency:"USD",maximumFractionDigits:2,minimumFractionDigits:2,style:"currency"}:{currency:"USD",maximumSignificantDigits:3,style:"currency"}).format(t),"c"),u=i((t,r)=>new Intl.NumberFormat(r,{maximumFractionDigits:0}).format(t),"m");export{e as a,m as b,s as c,c as d,u as e};
@@ -0,0 +1 @@
1
+ import{a as O,b as D}from"./chunk-5B2RTXBS.js";import{a as F}from"./chunk-SV764LKQ.js";import{a as V}from"./chunk-R6U22RSY.js";import{a as T}from"./chunk-YVR4SEPU.js";import"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import{i as L}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import"./chunk-AUAECCXB.js";import{b as C}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as z}from"./chunk-SJ7BLQMI.js";import"./chunk-NCPW7WHO.js";import"./chunk-WRQAHEWF.js";import"./chunk-55UGUCQ6.js";import{a as R}from"./chunk-4ZEL6BYL.js";import{c as M}from"./chunk-J6H3YTFH.js";import"./chunk-DGJMFHBV.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as K}from"./chunk-RWVIV3U7.js";import{a as A,b as q,c as B,d as p,e as d,f as n}from"./chunk-HCTJKP5J.js";import{a as I,e as E}from"./chunk-2IKDEUCX.js";import{d as b,m as j,t as k}from"./chunk-HJHSQPHW.js";import{a as i,d as y,e as ee,g as te}from"./chunk-I26MS5PJ.js";var s=y(ee(),1);var e=y(te(),1);var re=i(o=>o===void 0?"":JSON.stringify(o,j),"te"),ae=41,J=480,H=5,ie=i((o,t)=>O(o,l=>{t(l.height>0?l:{height:J,width:l.width})}),"ae"),Ne=i(({initialShardKey:o})=>{let t=b(),{queryShardKey:l,setShardKey:P,shardKey:U}=V(o),[h,W]=(0,s.useState)(""),{data:f,error:g,errorSource:Z,isLoading:_,liveError:G}=M(R.getAuditLog,{},{live:!0,shardKey:l}),c=(0,s.useMemo)(()=>f?.entries??[],[f]),m=(0,s.useMemo)(()=>{let a=h.trim().toLowerCase();return a===""?c:c.filter(r=>r.op.toLowerCase().includes(a)||(r.table??"").toLowerCase().includes(a)||(r.id??"").toLowerCase().includes(a))},[c,h]),x=(0,s.useRef)(null),v=D({count:m.length,estimateSize:i(()=>ae,"estimateSize"),getScrollElement:i(()=>x.current,"getScrollElement"),initialRect:{height:J,width:800},observeElementRect:ie,overscan:8}),u=v.getVirtualItems(),Q=v.getTotalSize(),N=u[0]?.start??0,w=Q-(u.at(-1)?.end??0),X={height:N},Y={height:w},$=i(a=>{W(a.target.value)},"z");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-audit",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)(T,{onChange:P,testId:"au-shard-input",value:U}),(0,e.jsx)(F,{message:G,prefix:"au"}),(0,e.jsx)(L,{"aria-label":t("Filter audit log"),className:"h-8 w-48","data-testid":"au-search",onChange:$,placeholder:t("filter op, table, id"),value:h})]}),g!==null&&(0,e.jsx)(z,{error:Z,testId:"au-error"}),g===null&&!_&&m.length===0&&(0,e.jsx)(K,{description:t("State-changing admin operations are recorded here."),icon:(0,e.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,e.jsx)("path",{d:"M8 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2h-2M9 3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1V3Zm-1 9h8m-8 4h5"})}),testId:"au-empty",title:t("No audit entries.")}),m.length>0&&(0,e.jsx)(I,{className:"overflow-hidden py-0",children:(0,e.jsx)(E,{className:"max-h-[30rem] overflow-auto px-0",ref:x,children:(0,e.jsxs)(A,{"data-testid":"au-table",children:[(0,e.jsx)(q,{children:(0,e.jsxs)(p,{children:[(0,e.jsx)(d,{children:t("time")}),(0,e.jsx)(d,{children:t("op")}),(0,e.jsx)(d,{children:t("table")}),(0,e.jsx)(d,{children:t("id")}),(0,e.jsx)(d,{children:t("detail")})]})}),(0,e.jsxs)(B,{children:[N>0&&(0,e.jsx)("tr",{"aria-hidden":"true",children:(0,e.jsx)("td",{colSpan:H,style:X})}),u.map(a=>{let r=m[a.index],S=re(r.detail);return(0,e.jsxs)(p,{"data-testid":"au-row",children:[(0,e.jsx)(n,{className:"text-muted-foreground tabular-nums",children:k(r.ts,"\u2014")}),(0,e.jsx)(n,{children:(0,e.jsx)(C,{variant:"secondary",children:r.op})}),(0,e.jsx)(n,{className:"font-medium",children:r.table??(0,e.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})}),(0,e.jsx)(n,{className:"max-w-[20ch] truncate font-mono text-xs",children:r.id??(0,e.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})}),(0,e.jsx)(n,{className:"max-w-[32ch] truncate font-mono text-xs text-muted-foreground",title:S||void 0,children:S||(0,e.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},r.seq)}),w>0&&(0,e.jsx)("tr",{"aria-hidden":"true",children:(0,e.jsx)("td",{colSpan:H,style:Y})})]})]})})})]})},"we");export{Ne as AuditPanel};
@@ -0,0 +1 @@
1
+ import{i as R}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as B}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as S}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as q}from"./chunk-SJ7BLQMI.js";import"./chunk-NCPW7WHO.js";import"./chunk-WRQAHEWF.js";import"./chunk-55UGUCQ6.js";import{a as U}from"./chunk-4ZEL6BYL.js";import{c as O}from"./chunk-J6H3YTFH.js";import"./chunk-DGJMFHBV.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as D}from"./chunk-RWVIV3U7.js";import{a as G,b as J,c as K,d as F,e as s,f as o}from"./chunk-HCTJKP5J.js";import{a as V,e as W}from"./chunk-2IKDEUCX.js";import{d as P,t as H}from"./chunk-HJHSQPHW.js";import{a as n,d as j,e as re,f as ae,g as ie}from"./chunk-I26MS5PJ.js";var X=j(ae(),1),M=j(re(),1);var t=j(ie(),1);var ne=n(e=>e==="ok"?"success":e==="failed"?"destructive":e==="expired"?"warning":"secondary","te"),Q=n(e=>e.endpoint??e.id,"M"),ve=n(()=>{let e=(0,X.c)(38),r=P(),[i,Y]=(0,M.useState)("all"),[l,Z]=(0,M.useState)(""),g;e[0]===Symbol.for("react.memo_cache_sentinel")?(g={},e[0]=g):g=e[0];let{data:I,error:d,errorSource:x,isLoading:_,refetch:v}=O(U.listPushSubscriptions,g),N;if(e[1]!==I?.subscriptions||e[2]!==d||e[3]!==x||e[4]!==_||e[5]!==i||e[6]!==v||e[7]!==l||e[8]!==r){let L=I?.subscriptions??[],T=l.trim().toLowerCase(),A=L.filter(a=>i!=="all"&&a.kind!==i?!1:T===""?!0:`${Q(a)} ${a.userId??""}`.toLowerCase().includes(T)),b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b=n(a=>{Z(a.target.value)},"w"),e[10]=b):b=e[10];let ee=b,w;e[11]!==v?(w=n(()=>{v()},"y"),e[11]=v,e[12]=w):w=e[12];let E=w,k;e[13]===Symbol.for("react.memo_cache_sentinel")?(k=["all","web-push","fcm"],e[13]=k):k=e[13];let te=k,c;e[14]!==i||e[15]!==r?(c=(0,t.jsx)("div",{className:"flex items-center gap-1","data-testid":"nt-kind-filter",role:"tablist",children:te.map(a=>(0,t.jsx)(B,{"aria-selected":i===a,"data-testid":`nt-kind-${a}`,onClick:n(()=>{Y(a)},"onClick"),role:"tab",size:"sm",type:"button",variant:i===a?"secondary":"ghost",children:a==="all"?r("All"):a},a))}),e[14]=i,e[15]=r,e[16]=c):c=e[16];let m;e[17]!==r?(m=r("Filter devices"),e[17]=r,e[18]=m):m=e[18];let h;e[19]!==r?(h=r("filter endpoint, user"),e[19]=r,e[20]=h):h=e[20];let u;e[21]!==l||e[22]!==m||e[23]!==h?(u=(0,t.jsx)(R,{"aria-label":m,className:"h-8 w-56","data-testid":"nt-search",onChange:ee,placeholder:h,value:l}),e[21]=l,e[22]=m,e[23]=h,e[24]=u):u=e[24];let f;e[25]!==r?(f=r("Refresh"),e[25]=r,e[26]=f):f=e[26];let p;e[27]!==E||e[28]!==f?(p=(0,t.jsx)(B,{className:"ml-auto","data-testid":"nt-refresh",onClick:E,size:"sm",type:"button",variant:"outline",children:f}),e[27]=E,e[28]=f,e[29]=p):p=e[29];let $=L.length>0&&(0,t.jsx)(S,{"data-testid":"nt-count",variant:"secondary",children:r("{count} devices",{count:L.length})}),y;e[30]!==p||e[31]!==$||e[32]!==c||e[33]!==u?(y=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,u,p,$]}),e[30]=p,e[31]=$,e[32]=c,e[33]=u,e[34]=y):y=e[34];let C;e[35]!==d||e[36]!==x?(C=d!==null&&(0,t.jsx)(q,{error:x,testId:"nt-error"}),e[35]=d,e[36]=x,e[37]=C):C=e[37],N=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-notifications",children:[y,C,d===null&&!_&&A.length===0&&(0,t.jsx)(D,{description:r("Registered Web Push / FCM devices appear here. Configure lunora/notify.ts with defineNotify({ store }) and register a device with ctx.push.register(...)."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M15 17h5l-1.4-1.4A2 2 0 0 1 18 14.2V11a6 6 0 0 0-4-5.7V5a2 2 0 1 0-4 0v.3A6 6 0 0 0 6 11v3.2a2 2 0 0 1-.6 1.4L4 17h5m6 0v1a3 3 0 1 1-6 0v-1m6 0H9"})}),testId:"nt-empty",title:r("No registered devices.")}),A.length>0&&(0,t.jsx)(V,{className:"overflow-hidden py-0",children:(0,t.jsx)(W,{className:"max-h-[30rem] overflow-auto px-0",children:(0,t.jsxs)(G,{"data-testid":"nt-table",children:[(0,t.jsx)(J,{children:(0,t.jsxs)(F,{children:[(0,t.jsx)(s,{children:r("kind")}),(0,t.jsx)(s,{children:r("endpoint")}),(0,t.jsx)(s,{children:r("user")}),(0,t.jsx)(s,{children:r("last seen")}),(0,t.jsx)(s,{children:r("status")}),(0,t.jsx)(s,{children:r("error")})]})}),(0,t.jsx)(K,{children:A.map(a=>{let z=Q(a);return(0,t.jsxs)(F,{"data-testid":"nt-row",children:[(0,t.jsx)(o,{children:(0,t.jsx)(S,{variant:"outline",children:a.kind})}),(0,t.jsx)(o,{className:"max-w-[28ch] truncate font-mono text-xs",title:z,children:z}),(0,t.jsx)(o,{className:"max-w-[16ch] truncate font-mono text-xs",children:a.userId??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})}),(0,t.jsx)(o,{className:"text-muted-foreground tabular-nums",children:H(a.lastSeenAt,"\u2014")}),(0,t.jsx)(o,{children:(0,t.jsx)(S,{"data-testid":`nt-status-${a.id}`,variant:ne(a.lastStatus),children:a.lastStatus??r("n/a")})}),(0,t.jsx)(o,{className:"max-w-[28ch] truncate font-mono text-xs text-muted-foreground",title:a.lastError??void 0,children:a.lastError??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},a.id)})})]})})})]}),e[1]=I?.subscriptions,e[2]=d,e[3]=x,e[4]=_,e[5]=i,e[6]=v,e[7]=l,e[8]=r,e[9]=N}else N=e[9];return N},"ge");export{ve as default};
@@ -0,0 +1 @@
1
+ import{d as D}from"./chunk-ZG4KF3SJ.js";import{a as C}from"./chunk-JQXA2OYK.js";import{a as j}from"./chunk-WM6KXJGG.js";import"./chunk-FUYEZFBP.js";import"./chunk-OQ6I6OXT.js";import"./chunk-SJQERRSZ.js";import"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as N}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as k}from"./chunk-SJ7BLQMI.js";import"./chunk-NCPW7WHO.js";import"./chunk-WRQAHEWF.js";import"./chunk-55UGUCQ6.js";import{a as u}from"./chunk-4ZEL6BYL.js";import{c as p}from"./chunk-J6H3YTFH.js";import"./chunk-DGJMFHBV.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as S}from"./chunk-RWVIV3U7.js";import{a as A,b as B,c as _,d as b,e as l,f as o}from"./chunk-HCTJKP5J.js";import{a as v,e as w}from"./chunk-2IKDEUCX.js";import{d as R,t as I}from"./chunk-HJHSQPHW.js";import{a as m,d as H,g as Q}from"./chunk-I26MS5PJ.js";var e=H(Q(),1);var P="payment_subscriptions",O="payment_events",V=[P,O],Y={},E=new Set(["active","trialing"]),z=new Set(["past_due","unpaid"]),s=m((a,t)=>{if(a[t]!==void 0)return a[t];let h=a.__doc__;return typeof h=="string"?D(h)?.[t]:void 0},"a"),n=m(a=>typeof a=="string"?a:typeof a=="number"||typeof a=="bigint"||typeof a=="boolean"?String(a):"","s"),J=m(a=>E.has(a)?"default":z.has(a)?"destructive":"outline","q"),ie=m(({limit:a=100})=>{let t=R(),h=j(),{data:x}=p(u.listTables,Y,{live:!0}),F=x!==void 0,L=Array.isArray(x)&&V.every(r=>x.some(d=>d.name===r)),c=h.payments&&L,i=p(u.readTablePage,{filters:[],limit:a,offset:0,orderBy:{column:"updatedAt",direction:"desc"},search:"",table:P},{enabled:c}),f=p(u.readTablePage,{filters:[],limit:25,offset:0,orderBy:{column:"processedAt",direction:"desc"},search:"",table:O},{enabled:c}),g=p(u.facetColumn,{column:"state",table:P},{enabled:c});C(()=>{c&&(i.refetch(),f.refetch(),g.refetch())},!0);let y=i.data?.rows??[],M=f.data?.rows??[],U=i.error??f.error,q=i.error===null?f.errorSource:i.errorSource,G=i.data?.total??y.length,T=g.data?.values===void 0?y.filter(r=>E.has(n(s(r,"state")))).length:g.data.values.reduce((r,d)=>r+(E.has(n(d.value))?d.count:0),0);return F&&!c?(0,e.jsx)("div",{className:"flex flex-col gap-4","data-testid":"payments-panel",children:(0,e.jsx)(S,{description:t("No @lunora/payment tables found in this deployment. Add `.extend(paymentExtension)` to lunora/schema.ts and wire `payment` on createShardDO() to sync customers and subscriptions."),testId:"payments-unconfigured",title:t("No payments configured")})}):(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"payments-panel",children:[(0,e.jsx)("div",{className:"flex items-center gap-2","data-testid":"payments-summary",children:(0,e.jsxs)(v,{className:"justify-between gap-0 py-0",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[(0,e.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:t("Subscriptions")}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-2xl font-semibold tabular-nums text-foreground",children:T}),(0,e.jsx)(N,{variant:"default",children:t("{count} active",{count:T})})]})]}),(0,e.jsx)("div",{className:"border-t border-border bg-muted/50 px-4 py-2.5 text-[11px] text-muted-foreground",children:t("{total} total",{total:G})})]})}),U===null?void 0:(0,e.jsx)(k,{error:q}),y.length===0&&!i.isLoading?(0,e.jsx)(S,{testId:"payments-empty",title:t("No subscriptions yet")}):(0,e.jsx)(v,{className:"overflow-hidden py-0",children:(0,e.jsx)(w,{className:"px-0",children:(0,e.jsxs)(A,{children:[(0,e.jsx)(B,{children:(0,e.jsxs)(b,{children:[(0,e.jsx)(l,{children:t("Provider")}),(0,e.jsx)(l,{children:t("Reference")}),(0,e.jsx)(l,{children:t("Plan")}),(0,e.jsx)(l,{children:t("State")}),(0,e.jsx)(l,{children:t("Renews")})]})}),(0,e.jsx)(_,{children:y.map(r=>{let d=n(s(r,"state"));return(0,e.jsxs)(b,{"data-testid":"payment-subscription-row",children:[(0,e.jsx)(o,{children:n(s(r,"provider"))}),(0,e.jsx)(o,{children:n(s(r,"referenceId"))}),(0,e.jsx)(o,{children:n(s(r,"priceId"))}),(0,e.jsx)(o,{children:(0,e.jsx)(N,{variant:J(d),children:d})}),(0,e.jsx)(o,{children:I(s(r,"currentPeriodEnd"))})]},n(s(r,"providerSubscriptionId")))})})]})})}),(0,e.jsxs)(v,{className:"overflow-hidden py-0",children:[(0,e.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,e.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:t("Recent webhook events")})}),(0,e.jsx)(w,{className:"px-0",children:(0,e.jsx)(A,{children:(0,e.jsx)(_,{children:M.map(r=>(0,e.jsxs)(b,{"data-testid":"payment-event-row",children:[(0,e.jsx)(o,{children:n(s(r,"provider"))}),(0,e.jsx)(o,{className:"font-medium",children:n(s(r,"type"))}),(0,e.jsx)(o,{className:"text-muted-foreground",children:n(s(r,"providerEventId"))}),(0,e.jsx)(o,{children:I(s(r,"processedAt"))})]},n(s(r,"providerEventId"))))})})})]})]})},"oe");export{ie as PaymentsPanel};
@@ -0,0 +1,9 @@
1
+ import{a as Yt,d as b}from"./chunk-VEK3S7MV.js";import{a,d as _,e as X,f as Xt,g as tt}from"./chunk-I26MS5PJ.js";var ce=_(X(),1),Zt=_(tt(),1);var be=ce.createContext(void 0),ge=a(t=>{let e=ce.useContext(be);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),st=a(({client:t,children:e})=>(ce.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Zt.jsx)(be.Provider,{value:t,children:e})),"QueryClientProvider");var L=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 Sr=class extends L{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"}},ue=new Sr;var wr={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")},Cr=class{static{a(this,"TimeoutManager")}#e=wr;#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)}},K=new Cr;function es(t){setTimeout(t,0)}a(es,"systemSetTimeoutZero");var it=typeof window>"u"||"Deno"in globalThis;function k(){}a(k,"noop");function rs(t,e){return typeof t=="function"?t(e):t}a(rs,"functionalUpdate");function ve(t){return typeof t=="number"&&t>=0&&t!==1/0}a(ve,"isValidTimeout");function Re(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(Re,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}a(q,"resolveStaleTime");function A(t,e){return typeof t=="function"?t(e):t}a(A,"resolveQueryBoolean");function Ae(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Se(o,e.options))return!1}else if(!Z(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(Ae,"matchQuery");function Fe(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(j(e.options.mutationKey)!==j(n))return!1}else if(!Z(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}a(Fe,"matchMutation");function Se(t,e){return(e?.queryKeyHashFn||j)(t)}a(Se,"hashQueryKeyByOptions");function j(t){return JSON.stringify(t,(e,s)=>rt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}a(j,"hashKey");function Z(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(!Z(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!Z(t[r],e[r]))return!1;return!0}return!1}a(Z,"partialMatchKey");var kr=Object.prototype.hasOwnProperty;function nt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=ts(t)&&ts(e);if(!r&&!(rt(t)&&rt(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],f=t[l],p=e[l];if(f===p){u[l]=f,(r?h<n:kr.call(t,l))&&d++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=nt(f,p,s+1);u[l]=m,m===f&&d++}return n===c&&d===n?t:u}a(nt,"replaceEqualDeep");function he(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(he,"shallowEqualObjects");function ts(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(ts,"isPlainArray");function rt(t){if(!ss(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!ss(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(rt,"isPlainObject");function ss(t){return Object.prototype.toString.call(t)==="[object Object]"}a(ss,"hasObjectPrototype");function is(t){return new Promise(e=>{K.setTimeout(e,t)})}a(is,"sleep");function we(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?nt(t,e):e}a(we,"replaceData");function Tr(t){return t}a(Tr,"keepPreviousData");function ns(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}a(ns,"addToEnd");function as(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}a(as,"addToStart");var de=Symbol();function Pe(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===de?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(Pe,"ensureQueryFn");function le(t,e){return typeof t=="function"?t(...e):!!t}a(le,"shouldThrowError");function os(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(os,"addConsumeAwareSignal");var B=(()=>{let t=a(()=>it,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Ce(){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(Ce,"pendingThenable");var cs=es;function Er(){let t=[],e=0,s=a(c=>{c()},"notifyFn"),r=a(c=>{c()},"batchNotifyFn"),i=cs,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(Er,"createNotifyManager");var v=Er();var Or=class extends L{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}},fe=new Or;function Ir(t){return Math.min(1e3*2**t,3e4)}a(Ir,"defaultRetryDelay");function at(t){return(t??"online")==="online"?fe.isOnline():!0}a(at,"canFetch");var Me=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function xe(t){let e=!1,s=0,r,i=Ce(),n=a(()=>i.status!=="pending","isResolved"),o=a(y=>{if(!n()){let S=new Me(y);f(S),t.onCancel?.(S)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),d=a(()=>ue.isFocused()&&(t.networkMode==="always"||fe.isOnline())&&t.canRun(),"canContinue"),h=a(()=>at(t.networkMode)&&t.canRun(),"canStart"),l=a(y=>{n()||(r?.(),i.resolve(y))},"resolve"),f=a(y=>{n()||(r?.(),i.reject(y))},"reject"),p=a(()=>new Promise(y=>{r=a(S=>{(n()||d())&&y(S)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),m=a(()=>{if(n())return;let y,S=s===0?t.initialPromise:void 0;try{y=S??t.fn()}catch(C){y=Promise.reject(C)}Promise.resolve(y).then(l).catch(C=>{if(n())return;let T=t.retry??(B.isServer()?0:3),E=t.retryDelay??Ir,H=typeof E=="function"?E(s,C):E,W=T===!0||typeof T=="number"&&s<T||typeof T=="function"&&T(s,C);if(e||!W){f(C);return}s++,t.onFail?.(s,C),is(H).then(()=>d()?void 0:p()).then(()=>{e?f(C):m()})})},"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()?m():p().then(m),i),"start")}}a(xe,"createRetryer");var Qe=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ve(this.gcTime)&&(this.#e=K.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(B.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(K.clearTimeout(this.#e),this.#e=void 0)}};function hs(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(m=>{os(m,()=>e.signal,()=>h=!0)},"addSignalProperty"),f=Pe(e.options,e.fetchOptions),p=a(async(m,y,S)=>{if(h)return Promise.reject(e.signal.reason);if(y==null&&m.pages.length)return Promise.resolve(m);let T=a(()=>{let ye={client:e.client,queryKey:e.queryKey,pageParam:y,direction:S?"backward":"forward",meta:e.options.meta};return l(ye),ye},"createQueryFnContext")(),E=await f(T),{maxPages:H}=e.options,W=S?as:ns;return{pages:W(m.pages,E,H),pageParams:W(m.pageParams,y,H)}},"fetchPage");if(i&&n.length){let m=i==="backward",y=m?Rr:us,S={pages:n,pageParams:o},C=y(r,S);c=await p(S,C,m)}else{let m=t??n.length;do{let y=u===0?o[0]??r.initialPageParam:us(r,c);if(u>0&&y==null)break;c=await p(c,y),u++}while(u<m)}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(hs,"infiniteQueryBehavior");function us(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(us,"getNextPageParam");function Rr(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}a(Rr,"getPreviousPageParam");var fs=class extends Qe{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=ls(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=ls(this.options);e.data!==void 0&&(this.setState(ds(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=we(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(k).catch(k):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=>A(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===de||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(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:!Re(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=Pe(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"?hs(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=xe({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof Me&&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 Me){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,...ot(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...ds(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),v.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function ot(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:at(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(ot,"fetchState");function ds(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(ds,"successState");function ls(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(ls,"getDefaultState");var ut=class extends L{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Ce(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ps(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ct(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ct(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 A(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&&!he(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&ms(this.#t,s,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#t!==s||A(this.options.enabled,this.#t)!==A(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||A(this.options.enabled,this.#t)!==A(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return Fr(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.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(k)),e}#y(){this.#S();let t=q(this.options.staleTime,this.#t);if(B.isServer()||this.#r.isStale||!ve(t))return;let s=Re(this.#r.dataUpdatedAt,t)+1;this.#d=K.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(B.isServer()||A(this.options.enabled,this.#t)===!1||!ve(this.#u)||this.#u===0)&&(this.#l=K.setInterval(()=>{(this.options.refetchIntervalInBackground||ue.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&(K.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(K.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,f;if(e._optimisticResults){let O=this.hasListeners(),N=!O&&ps(t,e),Y=O&&ms(t,s,e,r);(N||Y)&&(h={...h,...ot(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:y}=h;f=h.data;let S=!1;if(e.placeholderData!==void 0&&f===void 0&&y==="pending"){let O;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(O=i.data,S=!0):O=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,O!==void 0&&(y="success",f=we(i?.data,O,e),l=!0)}if(e.select&&f!==void 0&&!S)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=we(i?.data,f,e),this.#c=f,this.#a=null}catch(O){this.#a=O}this.#a&&(p=this.#a,f=this.#c,m=Date.now(),y="error");let C=h.fetchStatus==="fetching",T=y==="pending",E=y==="error",H=T&&C,W=f!==void 0,U={status:y,fetchStatus:h.fetchStatus,isPending:T,isSuccess:y==="success",isError:E,isInitialLoading:H,isLoading:H,data:f,dataUpdatedAt:h.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!T,isLoadingError:E&&!W,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:E&&W,isStale:ht(t,e),refetch:this.refetch,promise:this.#o,isEnabled:A(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=U.data!==void 0,N=U.status==="error"&&!O,Y=a(Ie=>{N?Ie.reject(U.error):O&&Ie.resolve(U.data)},"finalizeThenableIfPossible"),Jt=a(()=>{let Ie=this.#o=U.promise=Ce();Y(Ie)},"recreateThenable"),Oe=this.#o;switch(Oe.status){case"pending":t.queryHash===s.queryHash&&Y(Oe);break;case"fulfilled":(N||U.data!==Oe.value)&&Jt();break;case"rejected":(!N||U.error!==Oe.reason)&&Jt();break}}return U}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.#p=this.#t),he(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.#v()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Ar(t,e){return A(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&A(e.retryOnMount,t)===!1)}a(Ar,"shouldLoadOnMount");function ps(t,e){return Ar(t,e)||t.state.data!==void 0&&ct(t,e,e.refetchOnMount)}a(ps,"shouldFetchOnMount");function ct(t,e,s){if(A(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&ht(t,e)}return!1}a(ct,"shouldFetchOn");function ms(t,e,s,r){return(t!==e||A(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&ht(t,s)}a(ms,"shouldFetchOptionally");function ht(t,e){return A(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}a(ht,"isStale");function Fr(t,e){return!he(t.getCurrentResult(),e)}a(Fr,"shouldAssignObserverCurrentProperties");var ys=class extends Qe{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||dt(),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=xe({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),v.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function dt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(dt,"getDefaultState");var bs=class extends L{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 ys({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=_e(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=_e(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=_e(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=_e(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.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=>Fe(e,s))}findAll(t={}){return this.getAll().filter(e=>Fe(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(k))))}};function _e(t){return t.options.scope?.id}a(_e,"scopeFor");var lt=class extends L{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),he(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&j(e.mutationKey)!==j(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??dt();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){v.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 gs=class extends L{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??Se(r,e),n=this.get(i);return n||(n=new fs({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(){v.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=>Ae(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ae(t,s)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var ft=class{static{a(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new gs,this.#t=t.mutationCache||new bs,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=ue.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=fe.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(q(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=rs(e,n);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return v.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;v.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return v.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(k).catch(k)}invalidateQueries(t,e={}){return v.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=v.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(k)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(k)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(q(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(k).catch(k)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(k).catch(k)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return fe.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(j(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{Z(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(j(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{Z(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=Se(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===de&&(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 ee=_(X(),1);var ke=_(X(),1),Pr=_(tt(),1);function Mr(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Mr,"createValue");var xr=ke.createContext(Mr()),vs=a(()=>ke.useContext(xr),"useQueryErrorResetBoundary");var Ss=_(X(),1);var ws=a((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?le(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Cs=a(t=>{Ss.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),ks=a(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||le(s,[t.error,r])),"getHasError");var Le=_(X(),1);var Ts=Le.createContext(!1),Es=a(()=>Le.useContext(Ts),"useIsRestoring"),Eu=Ts.Provider;var Os=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"),Is=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Rs=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),pt=a((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function As(t,e,s){let r=Es(),i=vs(),n=ge(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,Os(o),ws(o,i,c),Cs(i);let d=!n.getQueryCache().get(o.queryHash),[h]=ee.useState(()=>new e(n,o)),l=h.getOptimisticResult(o),f=!r&&u;if(ee.useSyncExternalStore(ee.useCallback(p=>{let m=f?h.subscribe(v.batchCalls(p)):k;return h.updateResult(),m},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),ee.useEffect(()=>{h.setOptions(o)},[o,h]),Rs(o,l))throw pt(o,h,i);if(ks({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&&!B.isServer()&&Is(l,r)&&(d?pt(o,h,i):c?.promise)?.catch(k).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}a(As,"useBaseQuery");function Qr(t,e){return As(t,ut,e)}a(Qr,"useQuery");var z=_(X(),1);function _r(t,e){let s=ge(e),[r]=z.useState(()=>new lt(s,t));z.useEffect(()=>{r.setOptions(t)},[r,t]);let i=z.useSyncExternalStore(z.useCallback(o=>r.subscribe(v.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=z.useCallback((o,c)=>{r.mutate(o,c).catch(k)},[r]);if(i.error&&le(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}a(_r,"useMutation");var xs=_(Xt(),1);var M=_(X(),1);var Lr=/["\\\u0000-\u001F\uD800-\uDFFF]/,Fs=a(t=>Lr.test(t)?JSON.stringify(t):`"${t}"`,"g"),yt=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=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Fs(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=yt(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}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+=Fs(o),i+=":",i+=yt(c))}return i+"}"},"u"),mt=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"y"),F="$lunora.wire$",Dr="__proto__",Ur=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),V=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[F,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint"){let n=t.toString();if(n.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[F,"bigint",n]}if(s==="number"){let n=t;return Number.isNaN(n)?[F,"nan"]:n===1/0?[F,"inf"]:n===-1/0?[F,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[F,"date",V(t.getTime(),e+1)];if(t instanceof Error){let n=t,o=V(Object.fromEntries(Object.keys(n).map(u=>[u,n[u]])),e+1),c=[F,"error",String(n.name),String(n.message),o];return n.cause!==void 0&&c.push(V(n.cause,e+1)),c}if(t instanceof URL)return[F,"url",t.href];if(t instanceof Map)return[F,"map",[...t.entries()].map(([n,o])=>[V(n,e+1),V(o,e+1)])];if(t instanceof Set)return[F,"set",[...t].map(n=>V(n,e+1))];if(t instanceof ArrayBuffer)return[F,"bytes",mt(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,o=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return o==="Uint8Array"?[F,"bytes",mt(c)]:[F,"bytes",mt(c),o]}if(Array.isArray(t)){let n=t.map(o=>V(o,e+1));return n.length>0&&n[0]===F?[F,"arr",n]:n}if(!Ur(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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`)}let r=t,i={};for(let n of Object.keys(r)){let o=r[n];if(o===void 0)continue;let c=V(o,e+1);n===Dr?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"a"),Nr=a(t=>yt(V(t)),"p"),De=a(t=>Nr(t),"w");var Ue=_(tt(),1);var Ps=a(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"Q"),gt=class{static{a(this,"A")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(De(e))}openSnapshotSample(e){let s=De(e);return this.samples.set(s,(this.samples.get(s)??0)+1),{key:s,pushes:this.pushes.get(s)??0}}closeSnapshotSample(e){let s=(this.samples.get(e.key)??1)-1,r=(this.pushes.get(e.key)??0)===e.pushes;return s>0?(this.samples.set(e.key,s),r):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),r)}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"]}))Ps(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,n,o={}){let c=De(s),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){Ps(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,f)},{onError:a(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:d}=o;d&&u.errorCallbacks.add(d);let h=!1;return()=>{if(h)return;h=!0;let l=this.entries.get(c);l&&(l.refCount-=1,d&&l.errorCallbacks.delete(d),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},Ms=new WeakMap,bt=a(t=>{let e=Ms.get(t);return e||(e=new gt(t),Ms.set(t,e)),e},"I"),Qs=(0,M.createContext)(null),qr=(0,M.createContext)(!1),Kr=a(()=>new ft({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),jr=a(t=>{let e=(0,xs.c)(20),{children:s,client:r,queryClient:i}=t,n=(0,M.use)(be),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??Kr(),"d"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,M.useState)(o),u=i??n??c,d,h;e[3]!==r||e[4]!==u?(d=a(()=>{bt(r).clearOnIdentityChange(u)},"u"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,M.useEffect)(d,h);let l=(0,M.useRef)(r),f,p;e[7]!==r||e[8]!==u?(f=a(()=>{l.current!==r&&(bt(l.current).stopClearingOnIdentityChange(u),l.current=r,bt(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"o"),p=[r,u],e[7]=r,e[8]=u,e[9]=f,e[10]=p):(f=e[9],p=e[10]),(0,M.useEffect)(f,p);let[m]=(0,M.useState)(r),y=r!==m,S;e[11]!==s||e[12]!==y?(S=(0,Ue.jsx)(qr,{value:y,children:s}),e[11]=s,e[12]=y,e[13]=S):S=e[13];let C;e[14]!==r||e[15]!==S?(C=(0,Ue.jsx)(Qs,{value:r,children:S}),e[14]=r,e[15]=S,e[16]=C):C=e[16];let T=C;if(n===u)return T;let E;return e[17]!==T||e[18]!==u?(E=(0,Ue.jsx)(st,{client:u,children:T}),e[17]=T,e[18]=u,e[19]=E):E=e[19],E},"V");var vt=a(()=>{let t=(0,M.use)(Qs);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var Ne=a(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"g"),Br=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},"p"),G="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Ds=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+=G.charAt(n>>18&63)+G.charAt(n>>12&63)+G.charAt(n>>6&63)+G.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=G.charAt(n>>18&63)+G.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=G.charAt(n>>18&63)+G.charAt(n>>12&63)+G.charAt(n>>6&63)}return e},"h"),I="$lunora.wire$",St="__proto__",_s={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Ls={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},wt=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"E"),R=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[I,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint"){let n=t.toString();if(n.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[I,"bigint",n]}if(s==="number"){let n=t;return Number.isNaN(n)?[I,"nan"]:n===1/0?[I,"inf"]:n===-1/0?[I,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[I,"date",R(t.getTime(),e+1)];if(t instanceof Error){let n=t,o=R(Object.fromEntries(Object.keys(n).map(u=>[u,n[u]])),e+1),c=[I,"error",String(n.name),String(n.message),o];return n.cause!==void 0&&c.push(R(n.cause,e+1)),c}if(t instanceof URL)return[I,"url",t.href];if(t instanceof Map)return[I,"map",[...t.entries()].map(([n,o])=>[R(n,e+1),R(o,e+1)])];if(t instanceof Set)return[I,"set",[...t].map(n=>R(n,e+1))];if(t instanceof ArrayBuffer)return[I,"bytes",Ne(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,o=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return o==="Uint8Array"?[I,"bytes",Ne(c)]:[I,"bytes",Ne(c),o]}if(Array.isArray(t)){let n=t.map(o=>R(o,e+1));return n.length>0&&n[0]===I?[I,"arr",n]:n}if(!wt(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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`)}let r=t,i={};for(let n of Object.keys(r)){let o=r[n];if(o===void 0)continue;let c=R(o,e+1);n===St?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"b"),w=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===I)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>w(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=w(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[w(n[0],e+1),w(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>w(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let o=(Object.hasOwn(Ls,i)?Ls[i]:void 0)??Error,c=new o(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=w(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let d of Object.keys(u))d===St?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:w(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Br(i);if(Ne(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let o=t[3]??"Uint8Array";if(o==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(_s,o)?_s[o]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>w(i,e+1))}return t.map(i=>w(i,e+1))}let s=t,r={};for(let i of Object.keys(s)){let n=w(s[i],e+1);i===St?Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):r[i]=n}return r},"y");var x=a(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),qe=a((t,e,s,r)=>{let i;return()=>i||(i=new Promise((n,o)=>{let c=t.open(e,s);c.addEventListener("upgradeneeded",()=>{r(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{o(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Ke=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 oe=a((t,e,s)=>`${t}::${e}::${s??""}`,"T"),$r=500,Hr=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 Wr="lunora-query-cache",zr="query-cache",Us="by_ts",Vr=1,Gr=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??Wr,r=t.storeName??zr,i=Hr(t.maxEntries??$r,"createIndexedDbQueryCache"),n=qe(e,s,Vr,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Us,"ts",{unique:!1})}),o=Ke(n,r),c=a(async u=>{let d=await x(u.count())-i;d<=0||await new Promise((h,l)=>{let f=u.index(Us).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||d<=0){h();return}p.delete(),d-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>x(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>x(u.getAll())),"load"),put:a(async(u,d)=>{await o("readwrite",async h=>{await x(h.put({...d,key:u})),await c(h)})},"put"),remove:a(async u=>{await o("readwrite",d=>x(d.delete(u)))},"remove")}},"N"),Ns=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Gr()}},"L");var qs=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"r");var je=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 Ks=0,Jr="lunora-bridge",Yr=1e3,Xr=3e3,Be=class{static{a(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Ks+=1,this.tabId=`tab_${String(Ks)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Yr,this.leaderTimeout=e.leaderTimeout??Xr,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??Jr),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.broadcast({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.bc?.postMessage(e)}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.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);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.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.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 Ct="_id",kt="_creationTime",Tt="page",js="pageDelta",Zr=a(t=>{if(Array.isArray(t))return t;if(wt(t)&&Array.isArray(t[Tt]))return t[Tt]},"g"),ei=a(t=>{let e;for(let s of t){let r=s[kt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"A"),ti=a((t,e)=>{let s=e[kt];if(typeof s!="number")return t.length;let r=ei(t);for(let[i,n]of t.entries()){let o=n[kt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"x"),si=a(t=>{if(typeof t!="object"||t===null)return;let e=t[Ct];return typeof e=="string"?e:void 0},"D"),ri=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")},"E"),ii=a((t,e)=>{let s=[];for(let u of t){if(si(u)===void 0)return;s.push(u)}let{key:r,op:i,row:n}=e;if(i==="delete"){let u=s.filter(d=>d[Ct]!==r);return u.length===s.length?[...s]:u}if(n===void 0)return;let o=[...s],c=s.findIndex(u=>u[Ct]===r);return c===-1?o.splice(ti(s,n),0,n):o[c]=n,o},"I"),ni=a((t,e)=>{let s=Zr(t);if(s===void 0)return;let r=ii(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Tt]:r}},"b"),Et=Symbol("lunora.unmergeableDelta"),Bs=a((t,e)=>{if("data"in t&&t.data!==void 0)return w(t.data);let s=w(t.delta);return ri(s)?e===void 0?s:ni(e,s)??Et:s},"m");var kh=new Set(Object.keys(Yt)),$=class extends b{static{a(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var $e=a(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Ot=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),He=a(t=>Ot.has(t?.code??""),"u");var ai=1024,We=a(t=>{let e=t.maxBuffer??ai,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(););},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 $s=/^ /u,Hs=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),oi=a(t=>{let e="",s=[];for(let r of t.split(`
2
+ `))r.startsWith("event:")?e=r.slice(6).replace($s,""):r.startsWith("data:")&&s.push(r.slice(5).replace($s,""));return{data:s.join(`
3
+ `),event:e}},"S"),ci=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(Hs(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Hs(u));let o=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"T"),ui=a((t,e)=>{if(t.event==="complete")return e.complete(),!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";return e.fail(new b(i,r)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(w(JSON.parse(t.data)))}catch{return e.fail(new b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),hi=a(async(t,e)=>{let s=t.getReader(),r=new TextDecoder,i="",n=!1,o=a(u=>{let d=n?`\r${u}`:u;n=d.endsWith("\r"),n&&(d=d.slice(0,-1)),i+=d.replaceAll(`\r
4
+ `,`
5
+ `)},"l"),c=a(()=>{let u=i.indexOf(`
6
+
7
+ `);for(;u!==-1;){let d=oi(i.slice(0,u));if(i=i.slice(u+2),ui(d,e))return!0;u=i.indexOf(`
8
+
9
+ `)}return!1},"d");for(;;){let{done:u,value:d}=await s.read();if(u)break;if(o(r.decode(d,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}o(r.decode()),c()||e.fail(new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),Ws=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=ci(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"l"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:d}=We({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await hi(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new b("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"_");var di=/["\\\u0000-\u001F\uD800-\uDFFF]/,zs=a(t=>di.test(t)?JSON.stringify(t):`"${t}"`,"y"),It=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=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return zs(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=It(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}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+=zs(o),i+=":",i+=It(c))}return i+"}"},"i"),te=a(t=>It(R(t)),"u");var Q=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${te(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()}};function ze(t){if(t!==void 0)return e=>{t(e)}}a(ze,"b");var J=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Rt=0,Vs=a(()=>Rt,"h"),li=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Gs=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),se=a((t,e)=>{Gs(t,li(e,t.optimisticLayers))},"y"),At=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),Gs(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)},"l"),o=a(()=>{se(t,t.serverBase)},"s");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,Rt+=1,r.acknowledgedAt=Rt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"g"),Ve=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},"k"),Js=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),pe=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Ys=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(Q.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=At(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ft=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},"f"),fi=a((t,e)=>{let s=Ft(e);if(!(s===void 0||$e(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},"v"),me=a(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),pi=a(()=>new $("LunoraClient: batch slot carried no error envelope"),"m"),Xs=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}},"s"),Zs=a(t=>{let{code:e,messageText:s}=Xs(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),Pt=a(t=>{let{code:e,messageText:s}=Xs(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),Ge=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=w(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"n"),Mt=a((t,e)=>{let s=Ge(t),r=fi(s,e);return r!==void 0&&(s.data=r),s},"y"),Je=a(t=>{let e=me(t);return e===void 0?pi():Ge(e)},"h");var er=0,mi=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();er+=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)}_${er.toString(36)}_${t}`},"d"),xt=a((t,e)=>t!==void 0&&e!==t,"f"),Xe=mi,re=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)},"o"),Ye=class{static{a(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];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.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=Xe(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{re(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw re(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(xt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{re(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;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(o=>{re(this.onPersistenceError,"replace",o,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,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.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){re(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{re(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var yi="lunora-outbox",bi="offline-mutations",Qt="by_id",gi=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??yi,r=t.storeName??bi,i=qe(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Qt,"id",{unique:!0})}),n=Ke(i,r);return{append:a(async o=>{await n("readwrite",c=>x(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>x(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>x(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o));u!==void 0&&await x(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o.id));u!==void 0&&await x(c.put(o,u))})},"replace")}},"w"),tr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return gi()}},"b");var _t=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 sr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?te(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:te(o.value)===n}},"c");var Lt=500,hr=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Se");new TextDecoder;var vi=new TextEncoder,Si=a(t=>Ds(vi.encode(JSON.stringify(t))),"tt"),wi="x-lunora-expect-subject",Ci=a(t=>Si({subject:t}),"rt"),rr=Symbol.for("lunora:session-change"),ki="lunora:session-change",Ti="better-auth.message",Ei="signout",dr=a(()=>{let t=globalThis,e=t[rr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[rr]=e),e},"ge"),Oi=a(()=>"document"in globalThis,"ot"),Ii=a(async()=>{let t=[];for(let e of dr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"ct"),Ri=a((t,e)=>{if(t!==Ti||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Ei}catch{return!1}},"dt"),Ai=a(t=>{let e=[],s=a(()=>{Ii().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(ki):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=>{Ri(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"ut"),Fi=a(t=>{let e=dr();return e.listeners.add(t),e.detach===void 0&&Oi()&&(e.detach=Ai(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ht"),Pi="/_lunora/rpc",Dt="/_lunora/rpc-batch",Mi="/_lunora/ws",xi="/_lunora/admin/shard-traffic",Qi="/_lunora/admin/scheduled",_i="/_lunora/admin/scheduled/status",Li="/_lunora/admin/scheduled/ws",Di="/_lunora/admin/scheduled/cancel",ir="/_lunora/admin/scheduled/dead",Ui="/_lunora/admin/scheduled/dead/retry",Ni="/_lunora/admin/scheduled/dead/cancel",qi="/_lunora/admin/workflows/instances",Ki="/_lunora/admin/workflows/instance",ji="/_lunora/admin/workflows/status",Wt="/_lunora/admin/storage",Bi="/_lunora/admin/storage/url",$i="/_lunora/admin/storage/buckets",Hi="/_lunora/admin/functions",Wi="/_lunora/admin/cron-jobs",zi="/_lunora/admin/cron-jobs/run",Vi="/_lunora/admin/architecture",Gi="/_lunora/admin/openapi",Ji="/_lunora/admin/openrpc",Yi="/_lunora/admin/global/tables",Xi="/_lunora/admin/global/table",Zi="/_lunora/admin/global/facet",en="/_lunora/admin/vector/indexes",tn="/_lunora/admin/vector/query",sn="/_lunora/admin/logs/archive",rn="/_lunora/admin/kv/namespaces",nn="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",an="/_lunora/admin/auth/users",on="/_lunora/admin/auth/sessions",cn="/_lunora/admin/auth/users/create",un="/_lunora/admin/auth/users/role",hn="/_lunora/admin/auth/users/ban",dn="/_lunora/admin/auth/users/unban",ln="/_lunora/admin/auth/users/password",fn="/_lunora/admin/auth/users/remove",pn="/_lunora/admin/auth/users/impersonate",mn="/_lunora/admin/auth/sessions/revoke",yn="/_lunora/admin/auth/sessions/revoke-all",bn="/_lunora/admin/auth/capabilities",gn="/_lunora/admin/auth/users/update",vn="/_lunora/admin/auth/accounts",Sn="/_lunora/admin/auth/accounts/unlink",wn="/_lunora/admin/auth/passkeys",Cn="/_lunora/admin/auth/passkeys/delete",kn="/_lunora/admin/auth/two-factor/disable",Tn="/_lunora/admin/auth/organizations",En="/_lunora/admin/auth/organizations/members",On="/_lunora/admin/auth/organizations/invitations",In="/_lunora/admin/auth/organizations/members/remove",Rn="/_lunora/admin/auth/organizations/invitations/cancel",An="/_lunora/admin/auth/config",Fn="/_lunora/admin/auth/sign-up-invitations",Pn="/_lunora/admin/auth/sign-up-invitations/create",Mn="/_lunora/admin/auth/sign-up-invitations/revoke",xn="/_lunora/admin/auth/organizations/create",Qn="/_lunora/admin/auth/organizations/update",_n="/_lunora/admin/auth/organizations/remove",Ln="/_lunora/admin/auth/organizations/members/add",Dn="/_lunora/admin/auth/organizations/members/invite",Un="/_lunora/admin/auth/organizations/members/role",Nn="/_lunora/admin/auth/organizations/teams",qn="/_lunora/admin/auth/organizations/teams/create",Kn="/_lunora/admin/auth/organizations/teams/update",jn="/_lunora/admin/auth/organizations/teams/remove",Bn="/_lunora/admin/auth/organizations/teams/members",$n="/_lunora/admin/auth/organizations/teams/members/add",Hn="/_lunora/admin/auth/organizations/teams/members/remove",Wn="/_lunora/admin/auth/organizations/roles",zn="/_lunora/admin/auth/organizations/roles/create",Vn="/_lunora/admin/auth/organizations/roles/update",Gn="/_lunora/admin/auth/organizations/roles/remove",Jn="/api/auth",Yn="/get-session",Xn="lunora-ping",Zn=a(async t=>(t.assertOpen(),(await t.adminFetch(Hi,"GET")).functions??[]),"Hs"),ea=a(async t=>(t.assertOpen(),(await t.adminFetch(Wi,"GET")).jobs??[]),"Ls"),ta=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(zi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Ms"),sa=a(async t=>(t.assertOpen(),await t.adminFetch(Gi,"GET")),"Us"),ra=a(async t=>(t.assertOpen(),await t.adminFetch(Vi,"GET")),"Ns"),ia=a(async t=>(t.assertOpen(),await t.adminFetch(Ji,"GET")),"xs"),na=a(async t=>(t.assertOpen(),await t.adminFetch(Yi,"GET")),"Ds"),aa=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(R(e.filters))),w(await t.adminFetch(`${Xi}?${s.toString()}`,"GET"))},"Bs"),oa=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(R(e.filters))),w(await t.adminFetch(`${Zi}?${s.toString()}`,"GET"))},"Qs"),Vt=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"re"),nr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"fe"),ie=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),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}`},"b"),ca=a(async t=>(t.assertOpen(),(await t.adminFetch(rn,"GET")).namespaces??[]),"Ks"),ua=a(async(t,e)=>{t.assertOpen();let s=P(nn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"qs"),ha=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Ws"),da=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(zt,"PUT",e)},"js"),la=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"$s"),fa=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(xi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Gs"),pa=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(sn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"Vs"),ma=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}},"zs"),Gt=a(t=>"args"in t?{...t,args:w(t.args)}:t,"ie"),ya=a(async t=>(t.assertOpen(),((await t.adminFetch(Qi,"GET")).records??[]).map(e=>Gt(e))),"Js"),ba=a(async t=>{t.assertOpen();let e=await t.adminFetch(_i,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Ys"),ga=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Di,"POST",{id:e})).cancelled===!0}),"Xs"),va=a(async t=>(t.assertOpen(),(await ma(async e=>await t.adminFetch(e===void 0?ir:`${ir}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Gt(e))),"Zs"),Sa=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Ui,"POST",{id:e})).retried===!0}),"er"),wa=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Ni,"POST",{id:e})).removed===!0}),"tr"),Ca=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(`${qi}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"sr"),ka=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Ki}?${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"),Ta=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(ji,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"ir"),Ea=a(async(t,e={})=>{t.assertOpen();let s=P(Wt,{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??[]}},"nr"),Oa=a(async(t,e,s)=>{t.assertOpen();let r=`${Wt}?key=${encodeURIComponent(e)}${Vt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"ar"),Ia=a(async t=>(t.assertOpen(),(await t.adminFetch($i,"GET")).buckets??[]),"or"),Ra=a(async(t,e)=>{t.assertOpen();let s=`${Wt}?key=${encodeURIComponent(e.key)}${Vt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"cr"),Aa=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${Bi}?key=${encodeURIComponent(e)}${i}${Vt(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},"dr"),Fa=a(async t=>(t.assertOpen(),(await t.adminFetch(en,"GET")).indexes??[]),"ur"),Pa=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(tn,"POST",e)).matches??[]),"hr"),ne=a((t,e)=>{try{return R(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)}},"w"),ar=a(t=>{try{return R(t),!0}catch{return!1}},"pe"),lr=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Te"),Ma=a((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!lr(r.body)){s[r.id]={error:Je({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Je(i),ok:!1}:{ok:!0,value:w(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"lr"),Ut=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),xa=3e4,Qa=1e4,_a=5e3,La=3,Da=250,Ua=5e3,Na=5e3,qa=64,Ka=3,ja=1e4,Ba=8,Nt=a(t=>t==="connected"||t==="polling","V"),g=a(t=>t??"","l"),D=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),$a=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)D(t,s)},"wr"),Ha=new TextDecoder,Wa=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Ha.decode(t)},"Ar"),ae=class{static{a(this,"_")}listeners=new Set;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()}},Ee=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"F"),za=a((t,e,s)=>{Ee(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(Xn)}catch{}},e))},"_r"),or=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=new i(e);t.socket=c;let u=a(()=>{Ee(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)}za(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()})},"me"),Va=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"),f=a(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),p=a(()=>{h||(h=!0,n().then(f).finally(()=>{h=!1}).catch(()=>{}))},"m");return{isPolling:a(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"Ir"),Ga=1e4,cr=a(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Ga)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ye"),fr=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ja=a(t=>{if(t instanceof $)return!0;let e=t?.code;return e===void 0||fr.has(e)||Ot.has(e)},"Rr"),pr=6e4,Ya=1e3,Xa={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Te=a((t,e,s)=>{let r=Ft(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new $(n,i):new b(Xa[t]??"BAD_REQUEST",n,{data:i})},"P"),Kt=a((t,e=Math.random)=>{let s=Math.min(Ya*2**Math.max(t-1,0),pr);return Math.round(s*(.5+e()*.5))},"X"),Za=a(t=>t instanceof $||fr.has(t?.code??""),"Hr"),eo=a((t,e,s)=>{let r=$e(t);return r!==void 0&&r>0?Math.min(r,pr):Za(t)?Kt(e,s):void 0},"Lr"),to=983040,so=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ur"),mr=new WeakSet,yr=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 mr.add(e),e},"we"),Ze=a(t=>t instanceof Error&&mr.has(t),"N"),ro=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&lr(s.body)&&e.set(s.id,s.body);return e},"Nr"),io=a(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Je(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:w(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:yr(e),kind:"undecodable"}}},"xr"),qt=a((t,e)=>`${g(t)}\0${e}`,"z"),no=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)},"Dr"),jt=class{static{a(this,"Br")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){hr(this.buffers,this.maxBuffers),this.buffers.set(qt(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(qt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:w(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=qt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},ao=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,"reseed";i&&t.rows.clear(),no(t.rows,r),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"},"Qr"),ur=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"be"),oo=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Kr"),Bt=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"Z"),$t=a((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ee"),br=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ee"),et=a((t,e)=>t!==void 0&&t!==e,"x"),co=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","qr"),uo=a(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Wr"),ho=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"jr"),lo=a((t,e,s)=>{if(et(s,t.identityFingerprint()))return;let r=t.leader,i=co(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"$r"),fo=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Gr"),po=a((t,e,s,r,i,n)=>{if(et(n,t.identityFingerprint()))return;let o=t.subscription(e);o&&(t.dropCacheSeed(e),br(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&Ve(o,r),se(o,s))},"Vr"),mo=a((t,e,s,r)=>{if(et(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&J(i.errorCallbacks,s)},"zr"),yo=a((t,e,s,r,i,n,o)=>{if(et(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&Bt(c,i),$t(c))},"Jr"),bo=a((t,e,s)=>t!==null||e&&s===null,"Yr"),go=[js],vo=Promise.resolve(),Ht=class t{static{a(this,"Ae")}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;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new Q;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;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 ae;statusListeners=new ae;tokenExpiredListeners=new ae;identityChangeListeners=new ae;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ae;pendingChangeListeners=new ae;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new jt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ie(nr(e.url),Mi),this.wsToken=e.wsToken;let s=e.authBasePath??Jn;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??qs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??xa,this.connectTimeoutMs=e.connectTimeoutMs??Qa,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??_a,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??La,this.defaultConnectionContext=e.connectionContext,this.persistence=tr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ns(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,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=vo),this.offlineQueue=new Ye(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Xe()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Fi(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,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),bo(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Nt(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(!Ze(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&&(hr(this.clientWatermarks,Ba),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(ie(this.url,`${this.authBasePath}${Yn}`),{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.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(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=g(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=g(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&&D(u,{topic:e,type:"whisper_subscribe"})}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&&D(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(r.shardKey)}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&D(i,{data:ne(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(r.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),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.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.serverCursor!==void 0,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(){return this.WebSocketImpl}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 sr(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=te(s),n=oe(e,i,r),o=this.hydratedQueryCache.get(n);if(o!==void 0)return this.cachedQueryMatchesIdentity(o)?o.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=Q.key(e,s,r),n=this.subscriptions.get(i);return{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})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);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})}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),f=d,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return fa(this.adminHost,e)}async listScheduledJobs(){return ya(this.adminHost)}async schedulerStatus(){return ba(this.adminHost)}async cancelScheduledJob(e){return ga(this.adminHost,e)}async listDeadJobs(){return va(this.adminHost)}async retryDeadJob(e){return Sa(this.adminHost,e)}async removeDeadJob(e){return wa(this.adminHost,e)}async listWorkflowInstances(e){return Ca(this.adminHost,e)}async getWorkflowInstance(e){return ka(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ta(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ie(nr(this.url),Li),r=_t(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(h,r.next()))},"a"),u=a(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;or(i,p,this.managedSocketOptions,{onClose:a(()=>{c()},"onClose"),onMessage:a(m=>{let y;try{y=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}y.type==="jobs"&&Array.isArray(y.records)&&(r.reset(),e(y.records.map(S=>Gt(S))))},"onMessage")})},"c"),d=a(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"d"),h=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");h();let l=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Ee(i),i.socket?.close(),i.socket=void 0},"h");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return Zn(this.adminHost)}async getCronJobs(){return ea(this.adminHost)}async runCronJob(e){return ta(this.adminHost,e)}async fetchOpenApi(){return sa(this.adminHost)}async fetchArchitecture(){return ra(this.adminHost)}async fetchOpenRpc(){return ia(this.adminHost)}async listStorageObjects(e={}){return Ea(this.adminHost,e)}async deleteStorageObject(e,s){return Oa(this.adminHost,e,s)}async listStorageBuckets(){return Ia(this.adminHost)}async uploadStorageObject(e){return Ra(this.adminHost,e)}async signedStorageUrl(e,s){return Aa(this.adminHost,e,s)}async listGlobalTables(){return na(this.adminHost)}async readGlobalTablePage(e){return aa(this.adminHost,e)}async facetGlobalColumn(e){return oa(this.adminHost,e)}async listVectorIndexes(){return Fa(this.adminHost)}async queryVectorIndex(e){return Pa(this.adminHost,e)}async queryLogArchive(e={}){return pa(this.adminHost,e)}async listKvNamespaces(){return ca(this.adminHost)}async listKvKeys(e){return ua(this.adminHost,e)}async getKvValue(e){return ha(this.adminHost,e)}async putKvValue(e){return da(this.adminHost,e)}async deleteKvKey(e){return la(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P(an,{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.adminFetch(s,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(cn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(un,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(hn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(dn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(ln,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(fn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(pn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(mn,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(yn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(bn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(gn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(vn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Sn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(wn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Cn,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(kn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(Tn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(En,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(On,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(Fn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Pn,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Mn,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(In,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Rn,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(An,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(xn,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Qn,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(_n,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ln,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Dn,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Un,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Nn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(qn,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Kn,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(Bn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Wn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(on,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},o=Q.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=ze(r),d=ze(i.onError),h=ze(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=te(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:ne(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(o,m)}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;return()=>{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(Q.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}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={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:ne(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}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}=We({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:ne(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 f=d?.wsState==="open"&&D(d,h);if(!f&&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(!f){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=qa;){let p=d.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}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 Ws(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=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();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.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.whisperHandlers.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}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=>g(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=g(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())},Na))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,n]of this.streams)g(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.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Ee(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={activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),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"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new Be({channelName:e,onBecomeLeader:a(()=>{uo(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{ho(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{lo(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{po(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{fo(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{mo(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{yo(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(ie(this.url,Dt),{body:JSON.stringify({calls:e.map((c,u)=>({args:ne(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 new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=me(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?Ge(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);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 Ma(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??Xe(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:S}=this.offlineQueue,C=m||S,T=this.WebSocketImpl!==void 0&&C,E=p||f,H=y==="connecting"&&C&&!E,W=y!=="open"&&!l&&T&&!E,ye=T&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),U=a(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,n,d,u,r.precondition,r.mutationId,o?.stamp),"ne");if(W||H||ye)return U();let O;try{let N=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:a(Y=>{O=Y},"onCommitCursor")});for(let Y of u)Y(O);return{committed:!0,value:N}}catch(N){if(E&&T&&N instanceof TypeError&&ar(i))return U();throw this.settleFailedDirectWrite(N,O,u,d,o?.flags.authToken),N}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Ze(e)){for(let o of r)o(s);return}pe(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:a(()=>{pe(o)},"onRejected")},shardKey:r})}catch(p){throw pe(o),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:l,precondition:u,onCommit:a(y=>{for(let S of c)S(y)},"onCommit"),reject:a(y=>{this.queuedIdentities.delete(n),Ze(y)||pe(o),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(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(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(xt(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(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),se(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,se(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(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=oe(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=oe(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(()=>{})},Da))}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)))}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=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(ar(c.args)?r.push(c):J(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=Vs(),n=this.identityFingerprint(),o;try{o=await cr(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){J(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:R(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await cr(async s=>e(ie(this.url,Dt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();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=Q.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=At(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Ys(this.subscriptions,r);try{e(u,s)}catch{pe(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!D(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(g(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=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Va({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:_t(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[wi]=Ci(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={}){if(!this.fetchImpl)throw new $("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),o=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(ie(this.url,Pi),{body:JSON.stringify({args:ne(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw Te(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw Te(c.status,c.statusText,c.headers.get("retry-after"));let h=me(u);if(h!==void 0)throw Mt(h,c.headers.get("retry-after"));if(!c.ok)throw Te(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return w(u.result)}catch(l){throw yr(l)}}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(ie(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=me(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw l.code=h.code,l}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(g(e.shardKey));D(e,{caps:go,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,or(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Ua),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of n)D(e,{id:o,type:c});this.releaseIdleShard(s)}$a(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())D(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),D(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(),Ee(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(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){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Ka;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},ja))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return D(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&D(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=Wa(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:o,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(w(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Zs(e)),this.forgetStream(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let o=Pt(e),c=this.identityFingerprint(),u=Q.keyOf(i);J(i.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,o,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&J(n.errorCallbacks,Pt(e))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){oo(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=ao(e,s,r);if(ur(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,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)return;let n;try{n=Bs(e,i.serverBase)}catch(o){J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${o instanceof Error?o.message:String(o)}`});return}if(n===Et){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(Q.keyOf(i)),br(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(Bt(i,e.lastMutationId),$t(i,!0)),this.persistQueryValue(i),Ve(i,i.serverCursor),s!==void 0&&Js(i,s),se(i,n),this.tabCoordinator?.isLeader()){let o=Q.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Bt(s,e.lastMutationId),$t(s),this.tabCoordinator?.isLeader())){let r=Q.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(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),Ve(e,e.serverCursor)&&se(e,e.serverBase))}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=w(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&&(r.acked=!1,J(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{re(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}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&&Nt(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)}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.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,se(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,ur(e);this.bounceShardSockets(),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()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(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&&Nt(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))}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=g(e),n=this.offlineQueue.drain(h=>g(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+=Lt){let l=u.slice(h,h+Lt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+Lt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Kt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=eo(s,o)??(r===null&&He(s)?Kt(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=g(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{ne(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)||Ja(e)}noteReplayAuthRefusal(e,s){if(!He(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,...Ut(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)}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,...Ut(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Ze(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)){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:ne(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&&so(i)>to)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ie(this.url,Dt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Ut(e.find(d=>d.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,Te(n.status,n.statusText,u),s,r)}if(!c.results){let d=me(c),h=d===void 0?Te(n.status,n.statusText,u):Mt(d,u);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof $||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,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)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){let n=ro(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=io(n.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=He(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var gr=_(Xt(),1),vr=_(X(),1);var So=a(()=>{let t=(0,gr.c)(4),e=vt(),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,vr.useSyncExternalStore)(s,r,i)},"S");export{Ht as a,Tr as b,ge as c,Qr as d,_r as e,jr as f,vt as g,So as h};