@happyvertical/smrt-planner 0.57.40 → 0.57.42

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 (530) hide show
  1. package/app/404.html +18 -18
  2. package/app/_app/immutable/chunks/{Bikltb61.js → 6xbjrI4d.js} +1 -1
  3. package/app/_app/immutable/chunks/{Ds81oecv.js → 9lQKFJ6L.js} +1 -1
  4. package/app/_app/immutable/chunks/{cXr3doj-.js → B65vMbFu.js} +1 -1
  5. package/app/_app/immutable/chunks/{D00XWXiM.js → BCqX5USC.js} +1 -1
  6. package/app/_app/immutable/chunks/{BytZpJV4.js → BCqjz7ZK.js} +1 -1
  7. package/app/_app/immutable/chunks/BKCcmB-M.js +1 -0
  8. package/app/_app/immutable/chunks/{BAwEK5g5.js → Bcu83dbj.js} +1 -1
  9. package/app/_app/immutable/chunks/{CUNj1yy1.js → BloyF-no.js} +1 -1
  10. package/app/_app/immutable/chunks/{CrCEAfXG.js → C82D5CfG.js} +1 -1
  11. package/app/_app/immutable/chunks/{CGy-IxPQ.js → CJbuGsJr.js} +1 -1
  12. package/app/_app/immutable/chunks/{DVHELJ71.js → CNpxWKbe.js} +1 -1
  13. package/app/_app/immutable/chunks/{f1wD15Gj.js → CYUgSPpT.js} +33 -33
  14. package/app/_app/immutable/chunks/CeWqQy-q.js +1 -0
  15. package/app/_app/immutable/chunks/{DV-QPPmm.js → CfTx8qDx.js} +1 -1
  16. package/app/_app/immutable/chunks/{BBzpxK-8.js → CgfZMunu.js} +2 -2
  17. package/app/_app/immutable/chunks/{DwJwsALF.js → CkNMgX14.js} +1 -1
  18. package/app/_app/immutable/chunks/{DvjvjwnR.js → CtW58PwZ.js} +1 -1
  19. package/app/_app/immutable/chunks/{CF92oapa.js → D-Emmhyt.js} +1 -1
  20. package/app/_app/immutable/chunks/{Bz6UsD_f.js → D4ttNCNo.js} +1 -1
  21. package/app/_app/immutable/chunks/{CaTJsbff.js → DKXNCCIs.js} +1 -1
  22. package/app/_app/immutable/chunks/{DmNUwu-S.js → DYBRXDw_.js} +1 -1
  23. package/app/_app/immutable/chunks/{BoItyfDx.js → DYH94YAS.js} +1 -1
  24. package/app/_app/immutable/chunks/{CijPG3jg.js → DbsNF_dU.js} +1 -1
  25. package/app/_app/immutable/chunks/{mQ6O0Tem.js → DgkGuZjQ.js} +1 -1
  26. package/app/_app/immutable/chunks/{D4QMl-tN.js → DiUrXCtt.js} +1 -1
  27. package/app/_app/immutable/chunks/{DPhUHp9B.js → DrfRpn0x.js} +1 -1
  28. package/app/_app/immutable/chunks/DuXHA11S.js +2 -0
  29. package/app/_app/immutable/chunks/{D75d6u7q.js → GLzea02G.js} +1 -1
  30. package/app/_app/immutable/chunks/{CX6N0Q6b.js → bsILmYkY.js} +1 -1
  31. package/app/_app/immutable/chunks/{CgeTxqIE.js → r6pCtoyG.js} +3 -3
  32. package/app/_app/immutable/entry/{app.Ci1kI5es.js → app.3G9_sgKZ.js} +2 -2
  33. package/app/_app/immutable/entry/start.BWQZK3OR.js +1 -0
  34. package/app/_app/immutable/nodes/{0.Z902gPeD.js → 0.CvH5MY_6.js} +1 -1
  35. package/app/_app/immutable/nodes/{1.Ccdu2St_.js → 1.B4JoGBuJ.js} +1 -1
  36. package/app/_app/immutable/nodes/{10.Dyma18OU.js → 10.DTPWlI3p.js} +1 -1
  37. package/app/_app/immutable/nodes/{11.Cu6DiI7h.js → 11.CYsyeNXN.js} +1 -1
  38. package/app/_app/immutable/nodes/{12.FH2vqMr8.js → 12.BYr59dUL.js} +1 -1
  39. package/app/_app/immutable/nodes/{13.Be1MlzbM.js → 13.BT5TWODa.js} +1 -1
  40. package/app/_app/immutable/nodes/{14.DM_cZGhH.js → 14.BLYMIfYZ.js} +1 -1
  41. package/app/_app/immutable/nodes/{2.CjNkW-UL.js → 2.qweVUpzT.js} +3 -3
  42. package/app/_app/immutable/nodes/{3.TF7PiZW5.js → 3.CbE-U-8h.js} +1 -1
  43. package/app/_app/immutable/nodes/{4.YRTy9VBr.js → 4.Q9WS3oPO.js} +1 -1
  44. package/app/_app/immutable/nodes/{5.BgL37Avs.js → 5.CJefJ9Zd.js} +1 -1
  45. package/app/_app/immutable/nodes/{6.C57oZZy1.js → 6.CQaywI4p.js} +1 -1
  46. package/app/_app/immutable/nodes/{7.CvchC13t.js → 7.DapIHeju.js} +1 -1
  47. package/app/_app/immutable/nodes/{8.CTFwoCm2.js → 8.CL4GIGCh.js} +1 -1
  48. package/app/_app/immutable/nodes/{9.CZeQtlqV.js → 9.dAsLJHo1.js} +1 -1
  49. package/app/_app/version.json +1 -1
  50. package/app/advanced-styles/index.html +21 -21
  51. package/app/ai/index.html +24 -24
  52. package/app/blueprint/index.html +19 -19
  53. package/app/cookbook/index.html +19 -19
  54. package/app/index.html +27 -27
  55. package/app/m/ads/AdDeliveryTier/index.html +23 -23
  56. package/app/m/ads/AdEvent/index.html +23 -23
  57. package/app/m/ads/AdFormat/index.html +23 -23
  58. package/app/m/ads/AdGroup/index.html +23 -23
  59. package/app/m/ads/AdVariation/index.html +23 -23
  60. package/app/m/analytics/AnalyticsDataStream/index.html +23 -23
  61. package/app/m/analytics/AnalyticsEvent/index.html +23 -23
  62. package/app/m/analytics/AnalyticsProperty/index.html +23 -23
  63. package/app/m/analytics/AnalyticsReport/index.html +23 -23
  64. package/app/m/approvals/ApprovalEvent/index.html +23 -23
  65. package/app/m/approvals/ApprovalPolicy/index.html +23 -23
  66. package/app/m/approvals/ApprovalRequest/index.html +23 -23
  67. package/app/m/assets/Asset/attachments/index.html +24 -24
  68. package/app/m/assets/Asset/index.html +23 -23
  69. package/app/m/assets/AssetAssociation/index.html +23 -23
  70. package/app/m/assets/AssetMetafield/index.html +23 -23
  71. package/app/m/assets/AssetStatus/index.html +23 -23
  72. package/app/m/assets/AssetType/index.html +23 -23
  73. package/app/m/assets/Folder/index.html +23 -23
  74. package/app/m/chat/AgentSession/index.html +23 -23
  75. package/app/m/chat/ChatMessage/index.html +23 -23
  76. package/app/m/chat/ChatParticipant/index.html +23 -23
  77. package/app/m/chat/ChatReaction/index.html +23 -23
  78. package/app/m/chat/ChatRoom/index.html +23 -23
  79. package/app/m/chat/ChatThread/index.html +23 -23
  80. package/app/m/chat/VoiceGatewayTurn/index.html +23 -23
  81. package/app/m/chat/VoiceSession/index.html +23 -23
  82. package/app/m/commerce/Agreement/index.html +23 -23
  83. package/app/m/commerce/Cart/index.html +23 -23
  84. package/app/m/commerce/Contract/index.html +23 -23
  85. package/app/m/commerce/ContractLineItem/index.html +23 -23
  86. package/app/m/commerce/Customer/index.html +23 -23
  87. package/app/m/commerce/DocumentTax/index.html +23 -23
  88. package/app/m/commerce/Estimate/index.html +23 -23
  89. package/app/m/commerce/Fulfillment/index.html +23 -23
  90. package/app/m/commerce/FulfillmentLineItem/index.html +23 -23
  91. package/app/m/commerce/HistoricalCustomerFunds/index.html +23 -23
  92. package/app/m/commerce/HistoricalCustomerFundsAllocation/index.html +23 -23
  93. package/app/m/commerce/HistoricalSalesLine/index.html +23 -23
  94. package/app/m/commerce/Invoice/index.html +23 -23
  95. package/app/m/commerce/InvoiceLineItem/index.html +23 -23
  96. package/app/m/commerce/Lease/index.html +23 -23
  97. package/app/m/commerce/LicenseSale/index.html +23 -23
  98. package/app/m/commerce/Order/index.html +23 -23
  99. package/app/m/commerce/Payment/index.html +23 -23
  100. package/app/m/commerce/PaymentAllocation/index.html +23 -23
  101. package/app/m/commerce/PaymentInstrument/index.html +23 -23
  102. package/app/m/commerce/PaymentIntent/index.html +23 -23
  103. package/app/m/commerce/Payout/index.html +23 -23
  104. package/app/m/commerce/ProductionOrder/index.html +23 -23
  105. package/app/m/commerce/PurchaseContract/index.html +23 -23
  106. package/app/m/commerce/PurchaseOrder/index.html +23 -23
  107. package/app/m/commerce/SalesContract/index.html +23 -23
  108. package/app/m/commerce/SupplierQuote/index.html +23 -23
  109. package/app/m/commerce/TaxCode/index.html +23 -23
  110. package/app/m/commerce/TaxComponent/index.html +23 -23
  111. package/app/m/commerce/TaxSettings/index.html +23 -23
  112. package/app/m/commerce/TaxSummaryReport/index.html +23 -23
  113. package/app/m/commerce/TenantPaymentAccount/index.html +23 -23
  114. package/app/m/commerce/Vendor/index.html +23 -23
  115. package/app/m/commerce/WholesaleOrder/index.html +23 -23
  116. package/app/m/content/Content/articles/index.html +24 -24
  117. package/app/m/content/Content/index.html +23 -23
  118. package/app/m/content/ContentContribution/index.html +23 -23
  119. package/app/m/content/ContentContributionAttachment/index.html +23 -23
  120. package/app/m/content/ContentContributionRevision/index.html +23 -23
  121. package/app/m/content/ContentContributionType/index.html +23 -23
  122. package/app/m/content/ContentContributor/index.html +23 -23
  123. package/app/m/content/ContentCorrection/index.html +23 -23
  124. package/app/m/content/ContentFeedSource/index.html +23 -23
  125. package/app/m/content/ContentGovernanceAssignment/index.html +23 -23
  126. package/app/m/content/ContentGovernancePolicy/index.html +23 -23
  127. package/app/m/content/ContentGovernanceProfile/index.html +23 -23
  128. package/app/m/content/ContentReference/index.html +23 -23
  129. package/app/m/content/ContentReview/index.html +23 -23
  130. package/app/m/content/ContentVersion/index.html +23 -23
  131. package/app/m/events/Event/index.html +23 -23
  132. package/app/m/events/EventParticipant/index.html +23 -23
  133. package/app/m/events/EventSeries/index.html +23 -23
  134. package/app/m/events/EventType/index.html +23 -23
  135. package/app/m/expenses/Expense/index.html +23 -23
  136. package/app/m/facts/Fact/index.html +23 -23
  137. package/app/m/facts/FactContent/index.html +23 -23
  138. package/app/m/facts/FactEvidence/index.html +23 -23
  139. package/app/m/facts/FactSource/index.html +23 -23
  140. package/app/m/facts/FactSubject/index.html +23 -23
  141. package/app/m/facts/FactTag/index.html +23 -23
  142. package/app/m/fields/FieldPolicy/index.html +23 -23
  143. package/app/m/fields/FieldPolicySuggestion/index.html +23 -23
  144. package/app/m/fields/FieldUsageCounter/index.html +23 -23
  145. package/app/m/human-resources/Employment/index.html +23 -23
  146. package/app/m/human-resources/EmploymentTerm/index.html +23 -23
  147. package/app/m/human-resources/HeldQualification/index.html +23 -23
  148. package/app/m/human-resources/Qualification/index.html +23 -23
  149. package/app/m/images/Image/index.html +23 -23
  150. package/app/m/inventory/InventoryLocation/index.html +23 -23
  151. package/app/m/inventory/Lot/index.html +23 -23
  152. package/app/m/inventory/LotCorrection/index.html +23 -23
  153. package/app/m/inventory/LotDocument/index.html +23 -23
  154. package/app/m/inventory/LotStockLevel/index.html +23 -23
  155. package/app/m/inventory/LotUsage/index.html +23 -23
  156. package/app/m/inventory/StockLevel/index.html +23 -23
  157. package/app/m/inventory/StockMovement/index.html +23 -23
  158. package/app/m/ledgers/Account/index.html +23 -23
  159. package/app/m/ledgers/Journal/index.html +23 -23
  160. package/app/m/ledgers/JournalEntry/index.html +23 -23
  161. package/app/m/ledgers/Ledger/index.html +23 -23
  162. package/app/m/manufacturing/Assembly/index.html +23 -23
  163. package/app/m/manufacturing/BillOfMaterials/index.html +23 -23
  164. package/app/m/manufacturing/BomLine/index.html +23 -23
  165. package/app/m/manufacturing/Operation/index.html +23 -23
  166. package/app/m/manufacturing/ProductionRun/index.html +23 -23
  167. package/app/m/manufacturing/ProductionRunCompletion/index.html +23 -23
  168. package/app/m/manufacturing/RoutingStep/index.html +23 -23
  169. package/app/m/marketing/Campaign/index.html +23 -23
  170. package/app/m/marketing/CampaignChannel/index.html +23 -23
  171. package/app/m/marketing/CampaignMetricSnapshot/index.html +23 -23
  172. package/app/m/messages/Account/index.html +23 -23
  173. package/app/m/messages/Attachment/index.html +23 -23
  174. package/app/m/messages/Blacklist/index.html +23 -23
  175. package/app/m/messages/Email/failed-sends/index.html +24 -24
  176. package/app/m/messages/Email/index.html +23 -23
  177. package/app/m/messages/Email/mailbox/index.html +24 -24
  178. package/app/m/messages/EmailAccount/index.html +23 -23
  179. package/app/m/messages/EmailAttachment/index.html +23 -23
  180. package/app/m/messages/EmailFolder/index.html +23 -23
  181. package/app/m/messages/Message/index.html +23 -23
  182. package/app/m/messages/MessagingEndpoint/index.html +23 -23
  183. package/app/m/messages/PersonaMessageRoute/index.html +23 -23
  184. package/app/m/messages/SlackAccount/index.html +23 -23
  185. package/app/m/messages/SlackMessage/index.html +23 -23
  186. package/app/m/messages/SlackMessage/slack-messages/index.html +24 -24
  187. package/app/m/messages/TelegramAccount/index.html +23 -23
  188. package/app/m/messages/Tweet/index.html +23 -23
  189. package/app/m/messages/TwitterAccount/index.html +23 -23
  190. package/app/m/messages/Whitelist/index.html +23 -23
  191. package/app/m/messages/ZulipAccount/index.html +23 -23
  192. package/app/m/places/Place/index.html +23 -23
  193. package/app/m/places/PlaceType/index.html +23 -23
  194. package/app/m/products/Category/index.html +23 -23
  195. package/app/m/products/Material/index.html +23 -23
  196. package/app/m/products/Product/index.html +23 -23
  197. package/app/m/products/Product/ingredients/index.html +24 -24
  198. package/app/m/products/ProductVariant/index.html +23 -23
  199. package/app/m/products/Sku/index.html +23 -23
  200. package/app/m/profiles/ApiKey/index.html +23 -23
  201. package/app/m/profiles/Bot/index.html +23 -23
  202. package/app/m/profiles/MagicLinkToken/index.html +23 -23
  203. package/app/m/profiles/NostrIdentity/index.html +23 -23
  204. package/app/m/profiles/OidcIdentity/index.html +23 -23
  205. package/app/m/profiles/Organization/index.html +23 -23
  206. package/app/m/profiles/Person/index.html +23 -23
  207. package/app/m/profiles/Profile/index.html +23 -23
  208. package/app/m/profiles/ProfileMetadata/index.html +23 -23
  209. package/app/m/profiles/ProfileMetafield/index.html +23 -23
  210. package/app/m/profiles/ProfileRelationship/index.html +23 -23
  211. package/app/m/profiles/ProfileRelationshipTerm/index.html +23 -23
  212. package/app/m/profiles/ProfileRelationshipType/index.html +23 -23
  213. package/app/m/profiles/ProfileType/index.html +23 -23
  214. package/app/m/projects/Comment/index.html +23 -23
  215. package/app/m/projects/Issue/index.html +23 -23
  216. package/app/m/projects/Label/index.html +23 -23
  217. package/app/m/projects/Project/index.html +23 -23
  218. package/app/m/projects/ProjectIntegration/index.html +23 -23
  219. package/app/m/projects/PullRequest/index.html +23 -23
  220. package/app/m/projects/Repository/index.html +23 -23
  221. package/app/m/properties/Property/index.html +23 -23
  222. package/app/m/properties/Zone/index.html +23 -23
  223. package/app/m/reports/RuntimeReport/index.html +23 -23
  224. package/app/m/reports/SmrtPrincipalReportRefreshTask/index.html +23 -23
  225. package/app/m/reports/SmrtReportLock/index.html +23 -23
  226. package/app/m/reports/SmrtReportRefreshTask/index.html +23 -23
  227. package/app/m/reports/SmrtReportRun/index.html +23 -23
  228. package/app/m/reports/SmrtReportSchedule/index.html +23 -23
  229. package/app/m/reports/SmrtReportWatermark/index.html +23 -23
  230. package/app/m/sales/Agreement/index.html +23 -23
  231. package/app/m/sales/AttributionException/index.html +23 -23
  232. package/app/m/sales/AttributionPolicy/index.html +23 -23
  233. package/app/m/sales/Commission/index.html +23 -23
  234. package/app/m/sales/CommissionAdjustment/index.html +23 -23
  235. package/app/m/sales/CommissionPayout/index.html +23 -23
  236. package/app/m/sales/CommissionPlan/index.html +23 -23
  237. package/app/m/sales/Earner/index.html +23 -23
  238. package/app/m/sales/EarnerSourceAttribution/index.html +23 -23
  239. package/app/m/sales/EarningEvent/index.html +23 -23
  240. package/app/m/sales/ExecutedAgreement/index.html +23 -23
  241. package/app/m/sales/Lead/index.html +23 -23
  242. package/app/m/sales/Opportunity/index.html +23 -23
  243. package/app/m/sales/OpportunityConversion/index.html +23 -23
  244. package/app/m/sales/PipelineDefinition/index.html +23 -23
  245. package/app/m/sales/PipelineStage/index.html +23 -23
  246. package/app/m/sales/Referral/index.html +23 -23
  247. package/app/m/sales/ReferralAgreement/index.html +23 -23
  248. package/app/m/sales/ReferralLink/index.html +23 -23
  249. package/app/m/sales/ReferralProgram/index.html +23 -23
  250. package/app/m/sales/ReferralTermSnapshot/index.html +23 -23
  251. package/app/m/sales/ReferralTouch/index.html +23 -23
  252. package/app/m/sales/Referrer/index.html +23 -23
  253. package/app/m/sales/SalesActivity/index.html +23 -23
  254. package/app/m/sales/SalesRepresentative/index.html +23 -23
  255. package/app/m/sites/Site/index.html +23 -23
  256. package/app/m/sites/SiteAgentBinding/index.html +23 -23
  257. package/app/m/social/OAuthState/index.html +23 -23
  258. package/app/m/social/SocialAccount/index.html +23 -23
  259. package/app/m/social/SocialPost/index.html +23 -23
  260. package/app/m/social/SocialPostAnalyticsSnapshot/index.html +23 -23
  261. package/app/m/subscriptions/BillingAdjustment/index.html +23 -23
  262. package/app/m/subscriptions/ClientCharge/index.html +23 -23
  263. package/app/m/subscriptions/CreditGrant/index.html +23 -23
  264. package/app/m/subscriptions/PricingRule/index.html +23 -23
  265. package/app/m/subscriptions/RetailCharge/index.html +23 -23
  266. package/app/m/subscriptions/SpendingPolicy/index.html +23 -23
  267. package/app/m/subscriptions/SubscriptionPlan/index.html +23 -23
  268. package/app/m/subscriptions/SubscriptionPlanVersion/index.html +23 -23
  269. package/app/m/subscriptions/TenantSubscription/index.html +23 -23
  270. package/app/m/subscriptions/TenantUsageMetric/index.html +23 -23
  271. package/app/m/support/ServiceTimeEntry/index.html +23 -23
  272. package/app/m/support/SupportAiRun/index.html +23 -23
  273. package/app/m/support/SupportAvailability/index.html +23 -23
  274. package/app/m/support/SupportCase/index.html +23 -23
  275. package/app/m/support/SupportCaseEvent/index.html +23 -23
  276. package/app/m/support/SupportChannelBinding/index.html +23 -23
  277. package/app/m/support/SupportCharge/index.html +23 -23
  278. package/app/m/support/SupportCompensation/index.html +23 -23
  279. package/app/m/support/SupportCompensationPlan/index.html +23 -23
  280. package/app/m/support/SupportEscalation/index.html +23 -23
  281. package/app/m/support/SupportInteraction/index.html +23 -23
  282. package/app/m/support/SupportPlan/index.html +23 -23
  283. package/app/m/support/SupportPolicy/index.html +23 -23
  284. package/app/m/support/SupportQualification/index.html +23 -23
  285. package/app/m/support/SupportServiceTarget/index.html +23 -23
  286. package/app/m/support/SupportSpecialist/index.html +23 -23
  287. package/app/m/support/SupportWorkLink/index.html +23 -23
  288. package/app/m/tags/Tag/index.html +23 -23
  289. package/app/m/tags/TagAlias/index.html +23 -23
  290. package/app/m/timesheets/AttendanceBreak/index.html +23 -23
  291. package/app/m/timesheets/AttendancePunch/index.html +23 -23
  292. package/app/m/timesheets/AttendanceSegment/index.html +23 -23
  293. package/app/m/timesheets/ServiceChargeSnapshot/index.html +23 -23
  294. package/app/m/timesheets/ServiceCompensationSnapshot/index.html +23 -23
  295. package/app/m/timesheets/ServiceTimeEntry/index.html +23 -23
  296. package/app/m/users/Group/index.html +23 -23
  297. package/app/m/users/GroupMember/index.html +23 -23
  298. package/app/m/users/GroupRole/index.html +23 -23
  299. package/app/m/users/Membership/index.html +23 -23
  300. package/app/m/users/MembershipOverride/index.html +23 -23
  301. package/app/m/users/Permission/index.html +23 -23
  302. package/app/m/users/Role/index.html +23 -23
  303. package/app/m/users/RolePermission/index.html +23 -23
  304. package/app/m/users/Session/index.html +23 -23
  305. package/app/m/users/Tenant/index.html +23 -23
  306. package/app/m/users/TenantIntegration/index.html +23 -23
  307. package/app/m/users/TenantPermissionOverride/index.html +23 -23
  308. package/app/m/users/User/index.html +23 -23
  309. package/app/m/video/Character/index.html +23 -23
  310. package/app/m/video/CharacterAsset/index.html +23 -23
  311. package/app/m/video/CompositeJob/index.html +23 -23
  312. package/app/m/video/Performer/index.html +23 -23
  313. package/app/m/video/PerformerAsset/index.html +23 -23
  314. package/app/m/video/Scene/index.html +23 -23
  315. package/app/m/video/SceneAsset/index.html +23 -23
  316. package/app/m/video/VideoComposition/index.html +23 -23
  317. package/app/m/video/VideoCompositionAsset/index.html +23 -23
  318. package/app/m/video/VideoSequence/index.html +23 -23
  319. package/app/m/video/VideoSequenceAsset/index.html +23 -23
  320. package/app/m/video/VideoShot/index.html +23 -23
  321. package/app/m/video/VideoShotAsset/index.html +23 -23
  322. package/app/m/video/VideoShotCharacter/index.html +23 -23
  323. package/app/m/video/VideoWorkflow/index.html +23 -23
  324. package/app/m/voice/VoiceOutput/index.html +23 -23
  325. package/app/m/voice/VoiceProfile/index.html +23 -23
  326. package/app/m/voice/VoiceSample/index.html +23 -23
  327. package/app/mcp.html +2 -2
  328. package/app/packages/ads/index.html +21 -21
  329. package/app/packages/analytics/index.html +21 -21
  330. package/app/packages/approvals/index.html +21 -21
  331. package/app/packages/assets/index.html +21 -21
  332. package/app/packages/chat/index.html +21 -21
  333. package/app/packages/comments/index.html +21 -21
  334. package/app/packages/commerce/index.html +21 -21
  335. package/app/packages/content/index.html +21 -21
  336. package/app/packages/events/index.html +21 -21
  337. package/app/packages/expenses/index.html +21 -21
  338. package/app/packages/facts/index.html +21 -21
  339. package/app/packages/fields/index.html +21 -21
  340. package/app/packages/human-resources/index.html +21 -21
  341. package/app/packages/images/index.html +21 -21
  342. package/app/packages/index.html +20 -20
  343. package/app/packages/ingestion/index.html +21 -21
  344. package/app/packages/inventory/index.html +21 -21
  345. package/app/packages/ledgers/index.html +21 -21
  346. package/app/packages/manufacturing/index.html +21 -21
  347. package/app/packages/marketing/index.html +21 -21
  348. package/app/packages/messages/index.html +21 -21
  349. package/app/packages/places/index.html +21 -21
  350. package/app/packages/preferences/index.html +21 -21
  351. package/app/packages/products/index.html +21 -21
  352. package/app/packages/profiles/index.html +21 -21
  353. package/app/packages/projects/index.html +21 -21
  354. package/app/packages/properties/index.html +21 -21
  355. package/app/packages/reactions/index.html +21 -21
  356. package/app/packages/reports/index.html +21 -21
  357. package/app/packages/sales/index.html +21 -21
  358. package/app/packages/sites/index.html +21 -21
  359. package/app/packages/social/index.html +21 -21
  360. package/app/packages/subscriptions/index.html +21 -21
  361. package/app/packages/support/index.html +21 -21
  362. package/app/packages/tags/index.html +21 -21
  363. package/app/packages/timesheets/index.html +21 -21
  364. package/app/packages/users/index.html +22 -22
  365. package/app/packages/video/index.html +21 -21
  366. package/app/packages/voice/index.html +21 -21
  367. package/app/packages/webhooks/index.html +21 -21
  368. package/app/recipes/account-access/help/index.html +22 -22
  369. package/app/recipes/account-access/index.html +23 -23
  370. package/app/recipes/activity/help/index.html +21 -21
  371. package/app/recipes/activity/index.html +23 -23
  372. package/app/recipes/ads.campaigns/help/index.html +21 -21
  373. package/app/recipes/ads.campaigns/index.html +23 -23
  374. package/app/recipes/affiliates.referrals/help/index.html +21 -21
  375. package/app/recipes/affiliates.referrals/index.html +23 -23
  376. package/app/recipes/agreements/help/index.html +21 -21
  377. package/app/recipes/agreements/index.html +23 -23
  378. package/app/recipes/analytics.reports/help/index.html +21 -21
  379. package/app/recipes/analytics.reports/index.html +23 -23
  380. package/app/recipes/approvals.requests/help/index.html +21 -21
  381. package/app/recipes/approvals.requests/index.html +23 -23
  382. package/app/recipes/assets/help/index.html +21 -21
  383. package/app/recipes/assets/index.html +23 -23
  384. package/app/recipes/billing/help/index.html +21 -21
  385. package/app/recipes/billing/index.html +23 -23
  386. package/app/recipes/chat.assistant/help/index.html +21 -21
  387. package/app/recipes/chat.assistant/index.html +23 -23
  388. package/app/recipes/comments/help/index.html +21 -21
  389. package/app/recipes/comments/index.html +23 -23
  390. package/app/recipes/commerce.customers/help/index.html +21 -21
  391. package/app/recipes/commerce.customers/index.html +23 -23
  392. package/app/recipes/commerce.estimates/help/index.html +21 -21
  393. package/app/recipes/commerce.estimates/index.html +23 -23
  394. package/app/recipes/commerce.purchases/help/index.html +21 -21
  395. package/app/recipes/commerce.purchases/index.html +23 -23
  396. package/app/recipes/commerce.sales/help/index.html +21 -21
  397. package/app/recipes/commerce.sales/index.html +23 -23
  398. package/app/recipes/commerce.vendors/help/index.html +21 -21
  399. package/app/recipes/commerce.vendors/index.html +23 -23
  400. package/app/recipes/commerce.wholesale/help/index.html +21 -21
  401. package/app/recipes/commerce.wholesale/index.html +23 -23
  402. package/app/recipes/content.articles/help/index.html +21 -21
  403. package/app/recipes/content.articles/index.html +23 -23
  404. package/app/recipes/events.calendar/help/index.html +21 -21
  405. package/app/recipes/events.calendar/index.html +23 -23
  406. package/app/recipes/expenses.tracking/help/index.html +21 -21
  407. package/app/recipes/expenses.tracking/index.html +23 -23
  408. package/app/recipes/fields.form-customization/help/index.html +21 -21
  409. package/app/recipes/fields.form-customization/index.html +23 -23
  410. package/app/recipes/human-resources.people/help/index.html +21 -21
  411. package/app/recipes/human-resources.people/index.html +23 -23
  412. package/app/recipes/human-resources.qualifications/help/index.html +21 -21
  413. package/app/recipes/human-resources.qualifications/index.html +23 -23
  414. package/app/recipes/ingestion/help/index.html +21 -21
  415. package/app/recipes/ingestion/index.html +23 -23
  416. package/app/recipes/integrations/help/index.html +21 -21
  417. package/app/recipes/integrations/index.html +23 -23
  418. package/app/recipes/inventory.stock/help/index.html +21 -21
  419. package/app/recipes/inventory.stock/index.html +23 -23
  420. package/app/recipes/ledgers.bookkeeping/help/index.html +21 -21
  421. package/app/recipes/ledgers.bookkeeping/index.html +23 -23
  422. package/app/recipes/manufacturing.assemblies/help/index.html +21 -21
  423. package/app/recipes/manufacturing.assemblies/index.html +23 -23
  424. package/app/recipes/manufacturing.production/help/index.html +21 -21
  425. package/app/recipes/manufacturing.production/index.html +23 -23
  426. package/app/recipes/marketing.campaigns/help/index.html +21 -21
  427. package/app/recipes/marketing.campaigns/index.html +23 -23
  428. package/app/recipes/messages/help/index.html +21 -21
  429. package/app/recipes/messages/index.html +23 -23
  430. package/app/recipes/places.locations/help/index.html +21 -21
  431. package/app/recipes/places.locations/index.html +23 -23
  432. package/app/recipes/products/help/index.html +21 -21
  433. package/app/recipes/products/index.html +23 -23
  434. package/app/recipes/projects.tracker/help/index.html +21 -21
  435. package/app/recipes/projects.tracker/index.html +23 -23
  436. package/app/recipes/reports.materialized/help/index.html +21 -21
  437. package/app/recipes/reports.materialized/index.html +23 -23
  438. package/app/recipes/reports.runtime/help/index.html +21 -21
  439. package/app/recipes/reports.runtime/index.html +23 -23
  440. package/app/recipes/sales.pipeline/help/index.html +21 -21
  441. package/app/recipes/sales.pipeline/index.html +23 -23
  442. package/app/recipes/social.posts/help/index.html +21 -21
  443. package/app/recipes/social.posts/index.html +23 -23
  444. package/app/recipes/subscriptions.plans/help/index.html +21 -21
  445. package/app/recipes/subscriptions.plans/index.html +23 -23
  446. package/app/recipes/support.tickets/help/index.html +21 -21
  447. package/app/recipes/support.tickets/index.html +23 -23
  448. package/app/recipes/tags.taxonomy/help/index.html +21 -21
  449. package/app/recipes/tags.taxonomy/index.html +23 -23
  450. package/app/recipes/team-collaboration/help/index.html +21 -21
  451. package/app/recipes/team-collaboration/index.html +23 -23
  452. package/app/recipes/timesheets.time-entries/help/index.html +21 -21
  453. package/app/recipes/timesheets.time-entries/index.html +23 -23
  454. package/app/recipes/video.library/help/index.html +21 -21
  455. package/app/recipes/video.library/index.html +23 -23
  456. package/app/recipes/voice.profiles/help/index.html +21 -21
  457. package/app/recipes/voice.profiles/index.html +23 -23
  458. package/app/s/custom-accounts/index.html +19 -19
  459. package/app/s/custom-appointments/index.html +19 -19
  460. package/app/s/custom-billing/index.html +19 -19
  461. package/app/s/custom-bookings/index.html +19 -19
  462. package/app/s/custom-buying/index.html +19 -19
  463. package/app/s/custom-checkout/index.html +19 -19
  464. package/app/s/custom-classes/index.html +19 -19
  465. package/app/s/custom-clients/index.html +19 -19
  466. package/app/s/custom-events/index.html +19 -19
  467. package/app/s/custom-fleet/index.html +19 -19
  468. package/app/s/custom-gigs/index.html +19 -19
  469. package/app/s/custom-giving/index.html +19 -19
  470. package/app/s/custom-instruments/index.html +19 -19
  471. package/app/s/custom-jobs/index.html +19 -19
  472. package/app/s/custom-kitchen/index.html +19 -19
  473. package/app/s/custom-lessons/index.html +19 -19
  474. package/app/s/custom-material/index.html +19 -19
  475. package/app/s/custom-meetings/index.html +19 -19
  476. package/app/s/custom-members/index.html +19 -19
  477. package/app/s/custom-merch/index.html +19 -19
  478. package/app/s/custom-money/index.html +19 -19
  479. package/app/s/custom-paint/index.html +19 -19
  480. package/app/s/custom-parts/index.html +19 -19
  481. package/app/s/custom-rentals/index.html +19 -19
  482. package/app/s/custom-roastery/index.html +19 -19
  483. package/app/s/custom-schedule/index.html +19 -19
  484. package/app/s/custom-shelf/index.html +19 -19
  485. package/app/s/custom-shop/index.html +19 -19
  486. package/app/s/custom-students/index.html +19 -19
  487. package/app/s/custom-wholesale/index.html +19 -19
  488. package/app/s/custom-work/index.html +19 -19
  489. package/app/s/custom-yard/index.html +19 -19
  490. package/app/s/section-access-control/index.html +19 -19
  491. package/app/s/section-account-security/index.html +19 -19
  492. package/app/s/section-accounting/index.html +19 -19
  493. package/app/s/section-activity/index.html +19 -19
  494. package/app/s/section-agreements/index.html +19 -19
  495. package/app/s/section-analytics/index.html +19 -19
  496. package/app/s/section-approvals/index.html +19 -19
  497. package/app/s/section-assets/index.html +19 -19
  498. package/app/s/section-billing/index.html +19 -19
  499. package/app/s/section-calendar/index.html +19 -19
  500. package/app/s/section-catalog/index.html +19 -19
  501. package/app/s/section-chat.assistant/index.html +19 -19
  502. package/app/s/section-comments/index.html +19 -19
  503. package/app/s/section-fields.form-customization/index.html +19 -19
  504. package/app/s/section-grow/index.html +19 -19
  505. package/app/s/section-ingestion/index.html +19 -19
  506. package/app/s/section-integrations/index.html +19 -19
  507. package/app/s/section-make/index.html +19 -19
  508. package/app/s/section-messages/index.html +19 -19
  509. package/app/s/section-more/index.html +19 -19
  510. package/app/s/section-operations/index.html +19 -19
  511. package/app/s/section-places/index.html +19 -19
  512. package/app/s/section-projects/index.html +19 -19
  513. package/app/s/section-publish/index.html +19 -19
  514. package/app/s/section-purchasing/index.html +19 -19
  515. package/app/s/section-reports.materialized/index.html +19 -19
  516. package/app/s/section-reports.runtime/index.html +19 -19
  517. package/app/s/section-sales/index.html +19 -19
  518. package/app/s/section-staff/index.html +19 -19
  519. package/app/s/section-support/index.html +19 -19
  520. package/app/s/section-taxonomy/index.html +19 -19
  521. package/app/s/section-team/index.html +19 -19
  522. package/app/s/section-work/index.html +19 -19
  523. package/dist/catalog/catalog.json +49 -39
  524. package/dist/smrt-version.d.ts +1 -1
  525. package/dist/smrt-version.js +1 -1
  526. package/package.json +55 -55
  527. package/app/_app/immutable/chunks/BNB4IwPy.js +0 -9
  528. package/app/_app/immutable/chunks/CBHn82fo.js +0 -1
  529. package/app/_app/immutable/chunks/yk0CbPfJ.js +0 -1
  530. package/app/_app/immutable/entry/start.6TiI-_oR.js +0 -1
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./COiEfhsA.js";import{a as t,i as n,n as r,o as i,r as a,t as o}from"./BYcBM-fh.js";var s=[`read`,`write`,`destructive`];function c(e){let t=s.includes(e.effect)?e.effect:`destructive`;return{effect:t,destructive:t!==`read`,idempotent:e.idempotent??!1,openWorld:e.openWorld??!0}}function l(e){return{readOnlyHint:e.effect===`read`,destructiveHint:e.destructive,idempotentHint:e.idempotent,openWorldHint:e.openWorld,untrustedContentHint:!0}}function u(e){return{readOnlyHint:e.effect===`read`,destructiveHint:e.effect===`destructive`,idempotentHint:e.idempotent,openWorldHint:e.openWorld,untrustedContentHint:!0}}function d(e){throw Error(`[smrt-web] invalid view intent declaration: ${e}`)}function f(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function p(e,t,n=0){if(n>32&&d(`${t} nests deeper than 32 levels`),e===null)return null;if(typeof e==`function`&&d(`${t} is a function. A view intent declaration carries no code: its execute is constructed by the registry from 'target', so an intent has no path to REST.`),typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)||d(`${t} must be a finite number`),e;if(Array.isArray(e))return e.map((e,r)=>p(e,`${t}[${r}]`,n+1));if(f(e)){let r={};for(let[i,a]of Object.entries(e)){let e=p(a,`${t}.${i}`,n+1);Object.defineProperty(r,i,{value:e,enumerable:!0,writable:!0,configurable:!0})}return r}d(`${t} must be JSON data (got ${Object.prototype.toString.call(e)})`)}function m(e){return e.replace(/[.-]/g,`_`)}var h=new Set([`not_found`,`unsupported`,`consent_required`,`human_confirmation_required`,`sensitive_control`,`control_not_writable`,`control_not_editable`,`nothing_to_undo`,`stale_revision`,`idempotency_conflict`,`non_monotonic_revision`,`invalid_request`,`denied`]);function g(e){return typeof e==`string`&&h.has(e)?e:`denied`}function _(e){return JSON.stringify({ok:!0,...e})}function v(e){return JSON.stringify({ok:!1,reason:e})}function y(e){return f(e)?e:{}}var b=0;function x(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():(b+=1,`intent-${Date.now().toString(36)}-${b}`)}var S=class extends Error{};function C(e,t){try{return p(e[t],t)}catch{throw new S(t)}}function w(e){let t=e.revision;return typeof t==`number`&&Number.isFinite(t)?{revision:t}:{}}function T(e){return e instanceof S?`invalid_request`:`denied`}function E(e,t,n){let r={action:e.action,identity:t};switch(e.action){case`highlight`:{let e=n.durationMs;if(e!==void 0){if(typeof e!=`number`||!Number.isFinite(e))throw new S(`durationMs`);return{...r,durationMs:e}}return r}case`stage`:if(!(`value`in n))throw new S(`value`);return{...r,value:C(n,`value`)};case`apply`:return{...r,...`value`in n?{value:C(n,`value`)}:{},...w(n)};case`discard`:return{...r,...w(n)};default:return r}}function ee(e,t){if(t.registry!==e.target.registry)throw Error(`[smrt-web] intent '${e.id}' targets the ${e.target.registry} registry but was bound to ${t.registry}`);let r={name:m(e.id),description:e.description,inputSchema:e.inputSchema,annotations:u(e.classification)};if(t.registry===`control`&&e.target.registry===`control`){let i=e.target,a=t.identity;D(e.id,`formId`,i.formId,a.formId),D(e.id,`controlId`,i.controlId,a.controlId);let o=t.registryPort;return{...r,execute:n(async e=>{try{let t=E(i,a,y(e)),n=await o.execute(t,{source:`agent`});return n.ok?_({action:i.action,identity:a}):v(g(n.reason))}catch(e){return v(T(e))}})}}if(t.registry===`dataSurface`&&e.target.registry===`dataSurface`){let i=e.target,a=t.identity;D(e.id,`surfaceId`,i.surfaceId,a.surfaceId),D(e.id,`kind`,i.kind,a.kind);let o=t.registryPort;return{...r,execute:n(async e=>{try{let t=y(e),n=`payload`in t?C(t,`payload`):void 0,r=o.inspect(a);if(!r)return v(`not_found`);let s=await o.execute({version:1,commandId:x(),identity:a,expectedRevision:r.revision,controlId:i.controlId,...n===void 0?{}:{payload:n}});return s.ok?_({controlId:i.controlId,identity:a,...s.revision===void 0?{}:{revision:s.revision}}):v(g(s.reason))}catch(e){return v(T(e))}})}}throw Error(`[smrt-web] intent '${e.id}' could not be compiled for its binding`)}function D(e,t,n,r){if(n!==void 0&&n!==r)throw Error(`[smrt-web] intent '${e}' declares ${t} '${n}' but was bound to '${r}'`)}function te(){try{return!1}catch{return!1}}function O(e,t){return Array.isArray(e)?`[${e.map(e=>O(e,!0)??`"[object]"`).join(`,`)}]`:e instanceof Error?t?void 0:JSON.stringify(e.message):typeof e==`symbol`||typeof e==`bigint`||t&&(e===void 0||typeof e==`number`&&!Number.isFinite(e))?JSON.stringify(String(e)):e===void 0||typeof e==`number`&&!Number.isFinite(e)?String(e):typeof e!=`object`||!e?JSON.stringify(e):void 0}function k(e,t={},n=`error`){let r=Object.entries(t).flatMap(([e,t])=>{try{let n=O(t,!1);return n===void 0?[]:[`${e}=${n}`]}catch{return[]}}).join(`, `).replace(/[\u2028\u2029]/g,e=>`\\u${e.charCodeAt(0).toString(16)}`);return`TanStack DB ${n} ${e}${r&&` (${r})`}: https://tanstack.com/db/latest/docs/errors#${n}-${e}`}function ne(e,t){return k(e,t,`warning`)}var re=Symbol(`refProxy`);function ie(e){if(e&&typeof e==`object`)try{let t=e[re];return t===!0||Array.isArray(t)?t:void 0}catch{return}}function ae(e){return e&&typeof e==`object`&&ie(e)!==void 0}var A=class{},j=class extends A{constructor(e,t,n){super(),this.path=e,this.type=`ref`,t!==void 0&&(this.sourceAlias=t),n!==void 0&&Object.defineProperty(this,"bindingId",{value:n,enumerable:!1})}};function oe(e){return e.sourceAlias!==void 0&&e.path[0]===e.sourceAlias?e.sourceAlias:void 0}function M(e){return oe(e)===void 0?e.path:e.path.slice(1)}var N=class extends A{constructor(e){super(),this.value=e,this.type=`val`}},P=class extends A{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},se=class extends A{constructor(e,t,n){super(),this.name=e,this.args=t,this.grouping=n,this.type=`agg`}};function ce(e){return e instanceof se||e instanceof P||e instanceof j||e instanceof N}function F(e,t){if(typeof e==typeof t){if(typeof e==`number`&&typeof t==`number`){let n=Number.isNaN(e),r=Number.isNaN(t);if(n||r)return n&&r?0:n?1:-1}return e<t?-1:+(e>t)}return typeof e==`string`?-1:1}I(),I(),I(),I(),I(),le();function le(){let e=new WeakMap,t=Symbol();try{if(e.set(t,0),e.get(t)===0)return e}catch{}return new Map}function I(){return Math.random()*(2**31-1)>>>0}I(),I(),I(),I(),I();var ue=I();I(),I(),I(),I(),I(),I(),I(),I();var de=new WeakMap,L=new WeakSet;function fe(e){R(e)}var pe=1;function R(e){let t=de.get(e);return t===void 0&&(t=pe^ue,pe++,de.set(e,t),L.add(e)),t}function z(){let e=typeof globalThis<`u`?globalThis.crypto:void 0;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[];for(let e=0;e<16;e++)n.push(t[e].toString(16).padStart(2,`0`));return n.slice(0,4).join(``)+`-`+n.slice(4,6).join(``)+`-`+n.slice(6,8).join(``)+`-`+n.slice(8,10).join(``)+`-`+n.slice(10,16).join(``)}throw Error(k(171))}var me=Symbol.for(`@tanstack/db.collectionOptions.claim`),B=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},he=class extends B{constructor(e,t,n){let r=`${e===`insert`?`Insert`:`Update`} validation failed: ${t.map(e=>`
2
+ - ${e.message} - path: ${e.path}`).join(``)}`;super(n||r),this.name=`SchemaValidationError`,this.type=e,this.issues=t}},V=class extends B{constructor(e){super(e),this.name=`CollectionConfigurationError`}},H=class extends V{constructor(e){super(k(3,{reason:e})),this.name=`InvalidSyncPersistenceCapabilityError`}},ge=class extends V{constructor(){super(k(4))}},_e=class extends V{constructor(){super(k(5))}},ve=class extends V{constructor(){super(k(6))}},ye=class extends V{constructor(){super(k(7))}},be=class extends B{constructor(e){super(e),this.name=`CollectionStateError`}},U=class extends be{constructor(e,t){super(k(8,{operation:e,collectionId:t}))}},xe=class extends be{constructor(e,t){super(k(254,{collectionId:e,dependents:t}))}},Se=class extends be{constructor(e){super(k(255,{collectionId:e}))}},Ce=class extends be{constructor(e){super(k(256,{collectionId:e}))}},we=class extends be{constructor(e,t,n){super(k(9,{from:e,to:t,collectionId:n}))}},Te=class extends be{constructor(){super(k(10))}},Ee=class extends be{constructor(){super(k(11))}},De=class extends B{constructor(e){super(e),this.name=`CollectionOperationError`}},Oe=class extends De{constructor(e){super(k(14,{item:e}))}},ke=class extends De{constructor(e,t){super(k(15,{key:e,type:e===null?`null`:typeof e}))}},Ae=class extends De{constructor(e){super(k(16,{key:e}))}},je=class extends De{constructor(e,t,n){super(k(17,{key:e,collectionId:t,...n}))}},Me=class extends De{constructor(){super(k(18))}},Ne=class extends De{constructor(){super(k(19))}},Pe=class extends De{constructor(e){super(k(20,{key:e}))}},Fe=class extends De{constructor(e,t){super(k(21,{originalKey:e,newKey:t}))}},Ie=class extends De{constructor(){super(k(22))}},Le=class extends De{constructor(e){super(k(23,{key:e}))}},Re=class extends B{constructor(e){super(e),this.name=`MissingHandlerError`}},ze=class extends Re{constructor(){super(k(24))}},Be=class extends Re{constructor(){super(k(25))}},Ve=class extends Re{constructor(){super(k(26))}},He=class extends B{constructor(e){super(e),this.name=`TransactionError`}},Ue=class extends He{constructor(){super(k(31))}},We=class extends He{constructor(){super(k(33))}},Ge=class extends He{constructor(){super(k(34))}},Ke=class extends He{constructor(e){super(k(233,{id:e}))}},qe=class extends He{constructor(){super(k(35))}},Je=class extends He{constructor(){super(k(36))}},Ye=class extends He{constructor(){super(k(37))}},Xe=class extends He{constructor(e){super(k(38,{key:e}))}},Ze=class extends He{constructor(){super(k(39))}},Qe=class extends He{constructor(){super(k(40))}},$e=class extends He{constructor(e){super(k(41,{detail:e}))}},et=class extends B{constructor(e){super(e),this.name=`QueryCompilationError`}},tt=class extends et{constructor(e){super(k(59,{type:e}))}},nt=class extends et{constructor(){super(k(60))}},rt=class extends et{constructor(e){super(k(61,{functionName:e}))}},it=class extends B{constructor(e,t){super(k(78,{collectionId:e,error:t})),this.name=`SyncCleanupError`}},at=class extends Error{constructor(){super(k(79)),this.name=`AbortError`}},ot=class extends Error{constructor(){super(k(80)),this.name=`AbortError`}},st=class extends Error{constructor(){super(k(81)),this.name=`AbortError`}},ct=class extends Error{constructor(e,t){super(k(87,{path:e,reason:t})),this.path=e,this.reason=t,this.name=`UnhashableQueryIRError`}},lt=Symbol(`liveQueryInternal`),ut=new WeakMap;function dt(e){return e.utils?.[lt]?.getBuilder?.()}function ft(e){return ut.get(e)}var pt=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`];function mt(e,t){return _t(e,t,void 0)}function ht(e){return e===null||Object.getPrototypeOf(e)===null}function gt(e){let t=Object.keys(e);for(let n of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,n)&&t.push(n);return t}function _t(e,t,n,r=!1,i=!1){if(e===t||Object.is(e,t))return!0;if(e==null||t==null||typeof e!=typeof t||i&&typeof e==`object`&&Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date)return t instanceof Date&&Object.is(e.getTime(),t.getTime());if(t instanceof Date)return!1;if(e instanceof RegExp)return t instanceof RegExp&&e.source===t.source&&e.flags===t.flags&&(!r||e.lastIndex===t.lastIndex);if(t instanceof RegExp)return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;if(n?.has(e))return n.get(e)===t;n??=new Map,n.set(e,t);let a=r&&Array.from(t.entries()),o=Array.from(e.entries()).every(([e,o],s)=>a?Object.is(e,a[s][0])&&_t(o,a[s][1],n,!0,i):t.has(e)&&_t(o,t.get(e),n,r,i));return n.delete(e),o}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;if(n?.has(e))return n.get(e)===t;n??=new Map,n.set(e,t);let a=Array.from(e),o=Array.from(t);if(r){let t=a.every((e,t)=>_t(e,o[t],n,r,i));return n.delete(e),t}if(a.every(e=>typeof e!=`object`))return n.delete(e),a.every(e=>t.has(e));let s=(e,t,n)=>{if(e===a.length)return!0;let c=a[e];for(let[a,l]of t.entries()){let u=new Map(n);if(_t(c,o[l],u,r,i)&&s(e+1,t.filter((e,t)=>t!==a),u))return!0}return!1},c=s(0,o.map((e,t)=>t),n);return n.delete(e),c}if(t instanceof Set)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)&&!(e instanceof DataView)&&!(t instanceof DataView)){let n=e,i=t;if(r&&Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)||n.length!==i.length)return!1;for(let e=0;e<n.length;e++){let t=n[e],r=i[e];if(t!==r&&(t===t||r===r))return!1}return!0}if(ArrayBuffer.isView(t)&&!(t instanceof DataView)&&!ArrayBuffer.isView(e))return!1;if(yt(e)&&yt(t)){let n=e[Symbol.toStringTag];if(n!==t[Symbol.toStringTag])return!1;if(n===`Temporal.Duration`){let n=e,r=t;return pt.every(e=>n[e]===r[e])}return typeof e.equals==`function`?e.equals(t):e.toString()===t.toString()}if(yt(t)||Array.isArray(e)!==Array.isArray(t)||Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&!r){if(n?.has(e))return n.get(e)===t;n??=new Map,n.set(e,t);let a=e.every((e,a)=>_t(e,t[a],n,r,i));return n.delete(e),a}if(typeof e==`object`){let a=Object.getPrototypeOf(e),o=Object.getPrototypeOf(t),s=ht(a),c=ht(o);if(a!==o&&!s&&!c)return!1;if(n?.has(e))return n.get(e)===t;let l=gt(e),u=gt(t);if(l.length!==u.length)return!1;if(l.length===0&&!Array.isArray(e)&&!(s&&c))return e instanceof URL&&e.href===t.href;let d=!1,f=!0;for(let a of l){let o=e[a];if(!d&&typeof o==`object`&&o&&(n??=new Map,n.set(e,t),d=!0),!Object.prototype.propertyIsEnumerable.call(t,a)||!_t(o,t[a],n,r,i)){f=!1;break}}return d&&n.delete(e),f}return!1}var vt=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function yt(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&vt.has(t)}var bt={direction:`asc`,nulls:`first`,stringSort:`locale`};function xt(e,t){if(typeof e!=`string`&&typeof e!=`number`)throw e===void 0?new Oe(t):new ke(e,t)}function St(){let e=new WeakMap,t,n,r,i=0,a=(e,t)=>{let n=e.get(t);return n===void 0&&(n=++i,e.set(t,n)),n};return i=>{r??=Dt();let o;if(typeof i==`symbol`){let e=Symbol.keyFor(i);e===void 0?(t??=Ct(),o=a(t,i)):(n??=new Map,o=a(n,e))}else o=a(e,i);return[`runtimeReference`,r,o]}}function Ct(){let e=new WeakMap,t=Symbol();try{if(e.set(t,0),e.get(t)===0)return e}catch{}return new Map}var wt;function Tt(e){return wt??=St(),wt(e)}function Et(e){return e?.stringSort===`custom`?{...e,compare:Tt(e.compare)}:e}function Dt(){let e=new Uint32Array(4),t=Reflect.get(globalThis,`crypto`);return typeof t?.getRandomValues==`function`?(t.getRandomValues(e),Array.from(e,e=>e.toString(36)).join(`-`)):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}function W(e){return typeof e==`number`&&Number.isNaN(e)||e instanceof Date&&Number.isNaN(e.getTime())}var Ot=(e,t,n)=>{let{nulls:r}=n;if(e==null&&t==null)return 0;if(e==null)return r===`first`?-1:1;if(t==null)return r===`first`?1:-1;let i=W(e),a=W(t);if(i&&a)return 0;if(i)return 1;if(a)return-1;if(typeof e==`string`&&typeof t==`string`){if(n.stringSort===`custom`)return n.compare(e,t);if(n.stringSort===`locale`)return e.localeCompare(t,n.locale,n.localeOptions)}if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<Math.min(e.length,t.length);r++){let i=Ot(e[r],t[r],n);if(i!==0)return i}return e.length-t.length}if(e instanceof Date&&t instanceof Date)return e.getTime()-t.getTime();if(yt(e)&&yt(t))return zt(e,t);let o=typeof e==`symbol`,s=typeof t==`symbol`;if(o&&s)return e===t?0:Tt(e)[2]-Tt(t)[2];if(o)return 1;if(s)return-1;let c=typeof e==`object`,l=typeof t==`object`;if(c||l){if(c&&l)return Tt(e)[2]-Tt(t)[2];if(c)return 1;if(l)return-1}return e<t?-1:+(e>t)},kt=(e,t,n)=>e==null||t==null?Ot(e,t,n):Ot(t,e,n);function At(e){if(Mt(e))return`Binary`;if(yt(e)){let t=e[Symbol.toStringTag],n=e;return t===`Temporal.Duration`&&(n.years||n.months||n.weeks)?`Temporal.Duration.calendar`:t}return Array.isArray(e)?`Array`:`Object`}function jt(e,t=`values`){let n=e.direction===`asc`?Ot:kt;if(t!==`index`)return(t,r)=>n(t,r,e);let r=e.direction===`asc`?1:-1;return(t,i)=>{if(t!=null&&i!=null){t instanceof Date&&(t=t.getTime()),i instanceof Date&&(i=i.getTime());let e=typeof t,n=typeof i;if(e!==n)return(e<n?-1:1)*r;if(e===`object`){let e=At(t),n=At(i);if(e!==n)return(e<n?-1:1)*r;if(e===`Binary`||e===`Temporal.Duration.calendar`||e===`Temporal.PlainMonthDay`){let e=Rt(t),n=Rt(i);return(e<n?-1:+(e>n))*r}}}return n(t,i,e)}}jt({direction:`asc`,nulls:`first`,stringSort:`locale`});function Mt(e){return e instanceof Uint8Array||typeof Buffer<`u`&&e instanceof Buffer}function Nt(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}var Pt=`\0tanstack-db:`;function Ft(e,t){return`${Pt}${e}:${t}`}var It=new WeakMap;function Lt(e){let t=It.get(e);if(t)return t;let n;if(e.byteLength<=8192)n=String.fromCharCode.apply(null,e);else{let t=[];for(let n=0;n<e.byteLength;n+=8192)t.push(String.fromCharCode.apply(null,e.subarray(n,n+8192)));n=t.join(``)}let r=Ft(`binary`,n);return It.set(e,r),r}function Rt(e){if(typeof e==`string`)return e.startsWith(Pt)?Ft(`string`,e):e;if(typeof e!=`object`||!e)return e;if(e instanceof Date)return e.getTime();if(yt(e)){let t=e[Symbol.toStringTag];if(t===`Temporal.Duration`){let n=e;return Ft(t,pt.map(e=>n[e]).join(`,`))}return Ft(t,e.toString())}return Mt(e)?Lt(e):e}function zt(e,t){let n=e[Symbol.toStringTag],r=t[Symbol.toStringTag];if(n!==r)throw TypeError(k(167,{aTag:n,bTag:r}));let i=e.constructor.compare;if(typeof i!=`function`)throw TypeError(k(168,{aTag:n}));return i(e,t)}function Bt(e,t){return yt(e)&&yt(t)?zt(e,t):e<t?-1:+(e>t)}function Vt(e,t){return e===t?!0:Mt(e)&&Mt(t)?Nt(e,t):!1}var Ht=Symbol(`tanstack_db_parent_context`),Ut=Symbol(`tanstack_db_parent_projection_not_found`);function Wt(e){return Kt(e)?e.projectedBindings:void 0}function Gt(e,t){let n=Wt(e);return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:Ut}function Kt(e){return typeof e==`object`&&!!e&&Ht in e}function qt(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jt(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Yt=Symbol(`tanstack_db_route_metadata`);[...new Set([Yt,Symbol(`includesPublicKey`)])];function Xt(e){if(typeof e==`object`&&e&&Yt in e)return e[Yt]}function Zt(e,t){return Xt(e)??(typeof e==`object`&&e?Xt(e[t]):void 0)}function G(e){return e==null}function Qt(e){return Mt(e)?e:Rt(e)}function $t(e,t){return W(e)||W(t)?W(e)&&W(t):Vt(e,t)}function en(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function tn(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function nn(e){return e===!0}function rn(e,t=!1){return on(e,t)}function an(e){return on(e,!0)}function on(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?cn(e):sn(e);case`func`:return ln(e,t);default:throw new tt(e.type)}}function sn(e){let t=oe(e),[n,...r]=e.path,i=t??n,a=t===void 0?r:M(e);if(!i)throw new nt;let o=e.bindingId?JSON.stringify([e.bindingId,a]):void 0,s=o?e=>Gt(Zt(e,i)?.parentContext,o):void 0;if(i===`$selected`){if(a.length===0)return e=>e.$selected;if(a.length===1){let e=a[0];return t=>t.$selected?.[e]}return e=>{let t=e.$selected;if(t===void 0)return;let n=t;for(let e of a){if(n==null)return n;n=n[e]}return n}}let c=i;if(a.length===0)return e=>{let t=s?.(e);return s&&t!==Ut?t:e[c]};if(a.length===1){let e=a[0];return t=>{let n=s?.(t);return s&&n!==Ut?n:t[c]?.[e]}}return e=>{let t=s?.(e);if(s&&t!==Ut)return t;let n=e[c];if(n===void 0)return;let r=n;for(let e of a){if(r==null)return r;r=r[e]}return r}}function cn(e){let t=M(e);return e=>{let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}}function ln(e,t){let n=e.args.map(e=>on(e,t));switch(e.name){case`array`:return e=>n.map(t=>t(e));case`eq`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n),a=typeof r;if(a===typeof i&&(a===`string`||a===`boolean`))return r===i;let o=Qt(r),s=Qt(i);return G(o)||G(s)?null:$t(o,s)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:W(r)||W(i)?W(r)&&!W(i):Bt(r,i)>0}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:W(r)||W(i)?W(r):Bt(r,i)>=0}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:W(r)||W(i)?W(i)&&!W(r):Bt(r,i)<0}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:W(r)||W(i)?W(i):Bt(r,i)<=0}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;G(n)&&(t=!0)}return!t||null};case`or`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!0)return!0;G(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return G(n)?null:!n}}case`in`:{let t=n[0],r=n[1],i=e.args[1];if(i.type===`val`&&Array.isArray(i.value)){let e=i.value.filter(e=>!G(e)),n=e.filter(Mt),r=new Set(e.filter(e=>!Mt(e)).map(Rt));return e=>{let i=t(e);return G(i)?null:Mt(i)?n.some(e=>Vt(e,i)):r.has(Rt(i))}}return e=>{let n=Qt(t(e)),i=r(e);return G(n)?null:Array.isArray(i)?i.some(e=>$t(Qt(e),n)):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:dn(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return G(r)||G(i)?null:dn(r,i,!0)}}case`upper`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toUpperCase():n}}case`lower`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toLowerCase():n}}case`length`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`||Array.isArray(n)?n.length:0}}case`concat`:return e=>n.map(t=>{let n=t(e);try{return String(n??``)}catch{try{return JSON.stringify(n)||``}catch{return`[object]`}}}).join(``);case`coalesce`:return e=>{for(let t of n){let n=t(e);if(n!=null)return n}return null};case`caseWhen`:{let e=n.length%2==1,t=Math.floor(n.length/2);if(n.length<2)throw Error(k(127));return r=>{for(let e=0;e<t;e++){let t=n[e*2];if(un(t(r))){let t=n[e*2+1];return t(r)}}return e?n[n.length-1](r):null}}case`add`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)+(i??0)}}case`subtract`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)-(i??0)}}case`multiply`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)*(i??0)}}case`divide`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n)??0;return i===0?null:(r??0)/i}}case`date`:{let e=n[0];return t=>{let n=en(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=en(e(t));return n?n.toISOString():null}}case`strftime`:{let e=n[0],t=n[1];return n=>{let r=e(n);if(typeof r!=`string`)return null;let i=en(t(n));return i?tn(r,i):null}}case`isUndefined`:{let e=n[0];return t=>e(t)===void 0}case`isNull`:{let e=n[0];return t=>e(t)===null}default:throw new rt(e.name)}}function un(e){return e==null||e===!1?!1:e===!0?!0:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:!!e}function dn(e,t,n){if(typeof e!=`string`||typeof t!=`string`)return!1;let r=n?e.toLowerCase():e,i=n?t.toLowerCase():t,a=0,o=0,s=-1,c=0;for(;a<r.length;){let e=o<i.length?i[o]:void 0;if(e===`%`)s=o,c=a,o++;else if(e===`_`||e===r[a])a++,o++;else if(s!==-1)c++,a=c,o=s+1;else return!1}for(;i[o]===`%`;)o++;return o===i.length}var fn=class{constructor(e,t){this.gu=t,this.bl=e}lookup(e,t){let n=e===`gt`?`lt`:e===`gte`?`lte`:e===`lt`?`gt`:e===`lte`?`gte`:e;return this.bl.lookup(n,t)}rangeQuery(e={}){return this.bl.rangeQueryReversed(e)}take(e,t,n){return this.gu===void 0?this.bl.takeReversed(e,t,n):this.read(e,n,t??null)}takeFromStart(e,t){return this.gu===void 0?this.bl.takeReversedFromEnd(e,t):this.read(e,t)}read(e,t,n){let r=new Set([...this.bl.equalityLookup(null),...this.bl.equalityLookup(void 0)]),i=e=>t?.(e)??!0,a=e=>!r.has(e)&&i(e),o=e=>e<=0?[]:n==null?this.bl.takeReversedFromEnd(e,a):this.bl.takeReversed(e,n,a),s=e=>e<=0?[]:[...r].sort(F).filter(i).slice(0,e);if(n===null)return this.gu?o(e):[];if(this.gu&&n===void 0){let t=s(e);return[...t,...o(e-t.length)]}let c=o(e);return this.gu?c:[...c,...s(e-c.length)]}supports(e){return this.bl.supports(e)}get supportsRangeOptimization(){return this.bl.supportsRangeOptimization}get supportsOrderOptimization(){return this.bl.supportsOrderOptimization===!0}canOptimizeRangeFor(e){return this.bl.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.bl.keyCount}};function pn(e,t,n,r,i){let a=e,o=a.$hasPendingWrites??r();return{...e,$hasPendingWrites:o,$origin:a.$origin??i(),$key:a.$key??t,$collectionId:a.$collectionId??n}}var mn=[`$hasPendingWrites`,`$origin`,`$key`,`$collectionId`];function hn(e){return mn.includes(e)}function gn(e){return e.some(e=>hn(e))}function _n(e){return e.supports(`gt`)&&e.supportsRangeOptimization}function vn(e){return _n(e)&&!!e.supportsOrderOptimization}function yn(e,t,n,r){if(gn(t))return;let i=n??{...bt,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(i)){let e=n.matchesDirection(i.direction)?n:new fn(n,i.nulls===`first`);if(!r||r(e))return e}}function bn(e){if(e.length===0)return new Set;if(e.length===1)return new Set(e[0]);let t=new Set(e[0]);for(let n=1;n<e.length;n++){let r=new Set;for(let i of t)e[n].has(i)&&r.add(i);t=r}return t}function xn(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function Sn(e){return e!=null}function Cn(e){return{...bt,...e.compareOptions}.stringSort!==`lexical`}function wn(e,t){switch(typeof e){case`number`:case`bigint`:case`boolean`:return!1;case`string`:return Cn(t);case`symbol`:return!0;case`object`:return e!==null&&!(e instanceof Date);default:return!1}}function Tn(e,t,n){return!wn(e,n)&&t.supportsRangeOptimization&&(t.canOptimizeRangeFor?.(e)??!0)}function En(e,t){return Dn(e,t)}function Dn(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return kn(e,t);case`and`:return An(e,t);case`or`:return jn(e,t);case`in`:return Mn(e,t)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function On(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};let n=new Map;for(let[t,r]of e.args.entries())if(r.type===`func`&&[`gt`,`gte`,`lt`,`lte`].includes(r.name)){let e=r;if(e.args.length===2){let r=e.args[0],i=e.args[1],a=null,o=null,s=e.name;if(r.type===`ref`&&i.type===`val`)a=r,o=i;else if(r.type===`val`&&i.type===`ref`)switch(a=i,o=r,s){case`gt`:s=`lt`;break;case`gte`:s=`lte`;break;case`lt`:s=`gt`;break;case`lte`:s=`gte`}if(a&&o){let e=a.path,r=JSON.stringify(e),i=o.value;n.has(r)||n.set(r,[]),n.get(r).push({operation:s,value:i,argIndex:t})}}}for(let[e,r]of n)if(r.length>=2){let n=yn(t,JSON.parse(e));if(n&&r.some(e=>!Tn(e.value,n,t)))continue;if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e=jt({...bt,...t.compareOptions,direction:`asc`}),i,a,o=!1,s=!1,c=!0,l=!0,u=!1;for(let{operation:t,value:n}of r)if(!Sn(n))u=!0;else switch(t){case`gt`:case`gte`:{let r=o?e(n,i):1;r>0?(i=n,o=!0,c=t===`gte`):r===0&&t===`gt`&&(c=!1);break}case`lt`:case`lte`:{let r=s?e(n,a):-1;r<0?(a=n,s=!0,l=t===`lte`):r===0&&t===`lt`&&(l=!1);break}}let d={};return o&&(d.from=i,d.fromInclusive=c),s&&(d.to=a,d.toInclusive=l),{canOptimize:!0,matchingKeys:n.rangeQuery(d),isExact:o&&!u,coveredArgIndices:new Set(r.map(e=>e.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function kn(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(n.type===`ref`&&r.type===`val`)i=n,a=r;else if(n.type===`val`&&r.type===`ref`)switch(i=r,a=n,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`}if(i&&a){let e=i.path,n=yn(t,e);if(n){let e=a.value,r=o;return!n.supports(r)||(o===`gt`||o===`gte`||o===`lt`||o===`lte`)&&!Tn(e,n,t)?{canOptimize:!1,matchingKeys:new Set,isExact:!1}:{canOptimize:!0,matchingKeys:n.lookup(r,e),isExact:o===`lt`||o===`lte`?!1:Sn(e)}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function An(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=On(e,t),r=n.canOptimize?n.coveredArgIndices:new Set,i=[];n.canOptimize&&i.push(n);let a=!n.canOptimize||n.isExact;for(let[n,o]of e.args.entries()){if(r.has(n))continue;let e=Dn(o,t);e.canOptimize?(i.push(e),e.isExact||(a=!1)):a=!1}return i.length>0?{canOptimize:!0,matchingKeys:bn(i.map(e=>e.matchingKeys)),isExact:a}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function jn(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=[];for(let r of e.args){let e=Dn(r,t);if(!e.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};n.push(e)}return{canOptimize:!0,matchingKeys:xn(n.map(e=>e.matchingKeys)),isExact:n.every(e=>e.isExact)}}function Mn(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=e.args[0],r=e.args[1];if(n.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){let e=n.path,i=r.value,a=yn(t,e),o=i.every(e=>Sn(e));if(a){if(a.supports(`in`))return{canOptimize:!0,matchingKeys:a.lookup(`in`,i),isExact:o};if(a.supports(`eq`)){let e=new Set;for(let t of i){let n=a.lookup(`eq`,t);for(let t of n)e.add(t)}return{canOptimize:!0,matchingKeys:e,isExact:o}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}var Nn=new WeakMap;function Pn(e){return typeof e==`object`&&e?Nn.get(e):void 0}function Fn(){let e=new Map;function t(n){let r=JSON.stringify(n);if(e.has(r))return e.get(r);let i=new Proxy({},{get(e,r,i){if(r===`__refProxy`)return!0;if(r===`__path`)return n;if(r!==`__sourceAlias`&&r!==`__bindingId`&&r!==`__type`)return r===re?!0:typeof r==`symbol`?Reflect.get(e,r,i):t([...n,String(r)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__sourceAlias`||t===`__bindingId`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return e.set(r,i),i}return t([])}function K(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)return new N(e);let t=ie(e);if(t!==void 0)return Array.isArray(t)?new j(t,t[0],e.__bindingId):new j(e.__path,e.__sourceAlias,e.__bindingId);let n=Pn(e);if(n)throw Error(k(126,{name:n}));return ce(e)?e:new N(e)}function In(e,t){return new P(`eq`,[K(e),K(t)])}function Ln(e,t){return new P(`gt`,[K(e),K(t)])}function Rn(e,t){return new P(`gte`,[K(e),K(t)])}function zn(e,t){return new P(`lt`,[K(e),K(t)])}function Bn(e,t,...n){return new P(`and`,[e,t,...n].map(e=>K(e)))}function Vn(e,t,...n){return new P(`or`,[e,t,...n].map(e=>K(e)))}function Hn(e){return new P(`not`,[K(e)])}function Un(e){return new P(`isUndefined`,[K(e)])}function Wn(e){return new P(`isNull`,[K(e)])}var Gn=[`eq`,`gt`,`gte`,`lt`,`lte`,`in`];function Kn(){return te()&&!1}function qn(e){return e.config.autoIndex===`eager`}function Jn(e,t,n,r,i){if(gn(t))return;let a=qn(n);if(!a&&!Kn())return;let o=r??{...bt,...n.compareOptions};if(!yn(n,t,o,i)){if(!a)n.id,n.size;else try{n.createIndex(e=>{let n=e;for(let e of t)n=n[e];return n},{name:`auto:${t.join(`.`)}`,options:{compareOptions:o}})}catch(e){console.warn(ne(215,{id:n.id,value:t.join(`.`)}),e)}}}function Yn(e,t){if(!qn(t)&&!Kn())return;let n=Xn(e);for(let{fieldName:e,fieldPath:r}of n)Jn(e,r,t)}function Xn(e){let t=[];function n(e){if(e.type!==`func`)return;let r=e;if(r.name===`and`){for(let e of r.args)n(e);return}if(!Gn.includes(r.name)||r.args.length<1||r.args[0].type!==`ref`)return;let i=r.args[0].path;if(i.length===0)return;let a=i.join(`_`);t.push({fieldName:a,fieldPath:i})}return n(e),t}function Zn(e){let t=Rt(e),n=typeof t;return n===`string`||n===`number`||n===`boolean`?`${n}:${String(t)}`:void 0}function Qn(e,t){try{let n=e;for(let e of t)n=n?.[e];return n}catch{return}}function $n(e,t){if(e.type!==`func`||e.name!==`eq`)return;let n=e.args;if(n.length!==2)return;let r=n[0],i=n[1],a=r.type===`ref`?r:i,o=r.type===`val`?r:i;if(a.type!==`ref`||o.type!==`val`)return;let s=t(a);if(!s?.length||hn(s[0]))return;let c=Zn(o.value);return c===void 0?void 0:{path:s,literalKey:c}}function er(e,t){return tr(e,t.compareOptions)}function tr(e,t){return e.compareOptions.stringSort===void 0?{...t,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function nr(e){let t=e.type===`func`&&e.name===`and`?e.args:[e];for(let e of t){let t=$n(e,M);if(t)return e=>Zn(Qn(e,t.path))===t.literalKey}}function rr(e,t={},n){let r=r=>{let i=[],a=r&&n&&t.where?nr(t.where):void 0,o=a?n(a):e.entries();for(let[e,t]of o)(r?.(t)??!0)&&i.push({type:`insert`,key:e,value:t});return i};if(t.limit!==void 0&&!t.orderBy)throw Error(k(94));if(t.orderBy){let n=t.where?ir(t.where):void 0,r=or(e,t.orderBy,t.limit,n,t.optimizedOnly);if(r===void 0)return;let i=[];for(let t of r){let n=e.get(t);n!==void 0&&i.push({type:`insert`,key:t,value:n})}return i}if(!t.where)return r();try{let n=t.where,i=En(n,e);if(i.canOptimize){let t=i.isExact?void 0:ir(n),r=[];for(let n of i.matchingKeys){let i=e.get(n);i!==void 0&&(t?.(i)??!0)&&r.push({type:`insert`,key:n,value:i})}return r}return t.optimizedOnly?void 0:r(ir(n))}catch(n){console.warn(ne(213,{id:e.id}),n);let i=ir(t.where);return t.optimizedOnly?void 0:r(i)}}function ir(e){let t=an(e);return e=>{try{return nn(t(e))}catch{return!1}}}function ar(e,t){let n=ir(t.whereExpression);return t=>{let r=[];for(let e of t)if(e.type===`insert`)n(e.value)&&r.push(e);else if(e.type===`update`){let t=n(e.value),i=e.previousValue?n(e.previousValue):!1;t&&i?r.push(e):t&&!i?r.push({...e,type:`insert`}):!t&&i&&r.push({...e,type:`delete`,value:e.previousValue})}else n(e.value)&&r.push(e);return r.length>0||t.length===0?(e(r),!0):!1}}function or(e,t,n,r,i){if(t.length===1){let i=t[0],a=i.expression;if(a.type===`ref`){let t=a.path,o=er(i,e);Jn(t[0],t,e,o,_n);let s=yn(e,t,o,vn);if(s)return s.takeFromStart(n??s.keyCount,t=>{let n=e.get(t);return n===void 0?!1:r?.(n)??!0})}}if(i)return;let a=[];for(let[t,n]of e.entries())(r?.(n)??!0)&&a.push({key:t,value:n});let o=t.map(t=>({expression:t.expression,compare:jt(er(t,e))}));a.sort((e,t)=>{for(let n of o){let r=sr(e.value,n.expression),i=sr(t.value,n.expression),a=n.compare(r,i);if(a!==0)return a}return 0});let s=a.map(e=>e.key);return n===void 0?s:s.slice(0,n)}function sr(e,t){if(t.type===`ref`){let n=t,r=e;for(let e of n.path)r=r?.[e];return r}return t.type===`val`?t.value:an(t)(e)}var cr=class{constructor(e){this.bT=new Set,this.map=new Map,this.am=[],this.comparator=e}indexOf(e,t,n=this.am){let r=0,i=n.length;if(!this.comparator){for(;r<i;){let t=Math.floor((r+i)/2),a=n[t],o=F(e,a);if(o<0)i=t;else if(o>0)r=t+1;else return t}return r}for(;r<i;){let a=Math.floor((r+i)/2),o=n[a],s=this.map.get(o),c=this.comparator(t,s);if(c<0)i=a;else if(c>0)r=a+1;else{let t=F(e,o);if(t<0)i=a;else if(t>0)r=a+1;else return a}}return r}restoreOrder(){if(this.bT.size===0)return;let e=this.am,t=e.filter(e=>!this.bT.has(e)),n=[...this.bT].filter(e=>this.map.has(e)).sort((e,t)=>(this.comparator?.(this.map.get(e),this.map.get(t))??0)||F(e,t));e.length=0;let r=0;for(let i of n){let n=this.indexOf(i,this.map.get(i),t);for(;r<n;)e.push(t[r++]);e.push(i)}for(;r<t.length;)e.push(t[r++]);this.bT.clear()}cz(e){let t=t=>t===e||t!==t&&e!==e,n=this.indexOf(e,this.map.get(e));t(this.am[n])||(n=this.am.findIndex(t)),this.am.splice(n,1)}set(e,t,n=!1){return!this.comparator&&this.map.has(e)?(this.map.set(e,t),this):n?(this.map.set(e,t),this.bT.add(e),this):(this.restoreOrder(),this.map.has(e)&&this.cz(e),this.am.splice(this.indexOf(e,t),0,e),this.map.set(e,t),this)}get(e){return this.map.get(e)}delete(e,t=!1){if(t){let t=this.map.delete(e);return t&&this.bT.add(e),t}return this.restoreOrder(),this.map.has(e)&&this.cz(e),this.map.delete(e)}has(e){return this.map.has(e)}clear(){this.map.clear(),this.am=[],this.bT.clear()}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.keys())yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.restoreOrder(),this.am[Symbol.iterator]()}*values(){for(let e of this.keys())yield this.map.get(e)}};function lr(e,t){let n=e.preserveHydrationSeedKeys;return e.truncate===!0&&(!n||e.sourceTruncate===!0&&!n.has(t))}function ur(e){return e.metadata!==void 0&&e.type!==`delete`?{type:`set`,value:e.metadata}:e.type===`update`?void 0:{type:`delete`}}var dr=class{constructor(e){this.pendingSyncedTransactions=[],this.a7={states:new Map,truncated:!1,sourceKeys:new Set},this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,this.hasAppliedAdapterTruncate=!1,this.adapterTruncateKeptKeys=new Set,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.bf=()=>!1,this.getStagedSyncTransactions=()=>[],this.heldOptimisticRows=new Map,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.dE=new Map,this.size=0,this.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.bU=!1,this.syncRunGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.bU)return;this.bU=!0;let e=!1,t;try{let n;do n=this.dG(),n.failure&&!e&&(e=!0,t=n.failure.error);while(n.processed)}finally{this.bU=!1}if(e)throw t},this.config=e,this.transactions=new cr((e,t)=>e.compareCreatedAt(t)),this.syncedData=new cr(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this.a3=e.events}ak(e,t=this){let n=!this.isLocalOnly&&(t.optimisticUpserts.has(e)||t.optimisticDeletes.has(e));return{$hasPendingWrites:n,$origin:this.isLocalOnly||n?`local`:t.rowOrigins.get(e)??`remote`,$key:e,$collectionId:this.collection.id}}et(e){let t=new Map;for(let n of e){let e=this.rowOrigins.get(n);e!==void 0&&t.set(n,e)}return t}aW(e,t){let n=e,r=n.$hasPendingWrites??t.$hasPendingWrites,i=n.$origin??t.$origin,a=n.$key??t.$key,o=n.$collectionId??t.$collectionId,s=this.dE.get(a);if(s&&s.row===e&&s.hasPendingWrites===r&&s.origin===i&&s.collectionId===o)return s.enriched;let c={...e,$hasPendingWrites:r,$origin:i,$key:a,$collectionId:o};return this.dE.set(a,{row:e,hasPendingWrites:r,origin:i,collectionId:o,enriched:c}),c}dh(){this.dE.clear(),this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.aW(e,this.ak(t))}*entriesPassing(e){let t=this.optimisticUpserts.size===0&&this.optimisticDeletes.size===0?this.syncedData:this.entries();for(let[n,r]of t)e(r)&&(yield[n,this.enrichWithVirtualProps(r,n)])}enrichChangeMessage(e){let{__virtualProps:t}=e,n=e.previousValue?this.aW(e.previousValue,t?.previousValue??this.ak(e.key)):void 0,r=this.aW(e.value,t?.value??this.ak(e.key));return e.type===`delete`&&this.dE.delete(e.key),{key:e.key,type:e.type,value:r,previousValue:n,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e,t=this.optimisticUpserts,n=this.optimisticDeletes){if(!n.has(e))return t.get(e)??this.syncedData.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)||r.has(e)}*keys(){let{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(let n of e.keys())t.has(n)||(yield n);for(let r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}[Symbol.iterator](){return this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}setDeferredSyncKeys(e,t=()=>[]){this.bf=e,this.getStagedSyncTransactions=t}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),r=this.rowOrigins,i=new Set;for(let e of this.pendingSyncedTransactions)if(e.committed)for(let t of e.operations)i.add(t.key);let a=e=>i.has(e)||this.bf(e);for(let e of this.transactions.values())if(e.state===`completed`)for(let t of e.mutations){if(t.collection!==this.collection||!a(t.key)||(this.pendingLocalOrigins.add(t.key),!t.optimistic))continue;let n=this.heldOptimisticRows.get(t.key);n&&n.owner.compareCreatedAt(e)>0||this.heldOptimisticRows.set(t.key,{owner:e,row:t.type===`delete`?void 0:t.modified})}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear(),this.c7(a),this.size=this.e1();let o=[];this.ey(t,n,r,o);let s=e?o:o.filter(e=>!this.recentlySyncedKeys.has(e.key));s.length>0&&this.indexes.updateIndexes(s),this.changes.emitEvents(s,e)}trackTransaction(e){let t=this.transactions.get(e.id);if(t===e)return!1;if(t&&t.state!==`completed`&&t.state!==`failed`)throw new Ke(e.id);return this.transactions.set(e.id,e),e.collections.add(this.collection),!0}c7(e){if(e){for(let t of this.heldOptimisticRows.keys())e(t)||this.heldOptimisticRows.delete(t);for(let t of this.pendingLocalOrigins)e(t)||this.pendingLocalOrigins.delete(t)}for(let[e,{row:t}]of this.heldOptimisticRows)t===void 0?this.optimisticDeletes.add(e):this.optimisticUpserts.set(e,t);this.gl()}gl(){for(let[e,t]of this.transactions)if(t.state===`completed`||t.state===`failed`)this.transactions.delete(e,!0);else if(!this.lifecycle.hasStartedCleanup())for(let e of t.mutations)e.collection===this.collection&&(this.pendingLocalChanges.add(e.key),e.optimistic&&(e.type===`delete`?(this.optimisticUpserts.delete(e.key),this.optimisticDeletes.add(e.key)):(this.optimisticUpserts.set(e.key,e.modified),this.optimisticDeletes.delete(e.key))))}e1(){let e=this.syncedData.size;for(let t of this.optimisticDeletes)this.syncedData.has(t)&&!this.optimisticUpserts.has(t)&&e--;for(let t of this.optimisticUpserts.keys())this.syncedData.has(t)||e++;return e}ey(e,t,n,r){let i=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(let a of i){let i=this.get(a),o=this.get(a,e,t),s=this.ak(a,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),c=this.ak(a);o!==void 0&&i===void 0?r.push({type:`delete`,key:a,value:o,__virtualProps:{value:s}}):o===void 0&&i!==void 0?r.push({type:`insert`,key:a,value:i,__virtualProps:{value:c}}):o!==void 0&&i!==void 0&&(!mt(o,i)||s.$origin!==c.$origin||s.$hasPendingWrites!==c.$hasPendingWrites)&&r.push({type:`update`,key:a,value:i,previousValue:o,__virtualProps:{value:c,previousValue:s}})}}createSyncedKeyLookup(){if(this.pendingSyncedTransactions.length===0)return e=>this.syncedData.has(e);let e=new Map,t=!1;for(let n of this.pendingSyncedTransactions)if(n.committed){n.truncate&&(e.clear(),t=!0);for(let t of n.operations)e.set(t.key,t.type!==`delete`)}return n=>e.get(n)??(!t&&this.syncedData.has(n))}enableHydrationAuthorityTracking(){this.appliedAdapterKeys??=new Map}bj(e,t){let n=e.states.get(t);return n===void 0?e.truncated?{exists:!1,value:void 0}:{exists:this.syncedData.has(t),value:this.syncedData.get(t)}:n}getAcceptedSyncedRow(e){return this.bj(this.a7,e).value}acceptSyncTransaction(e){let t=this.pendingSyncedTransactions,n=t.indexOf(e);n!==-1&&t.splice(n,1);let r=t.findIndex(e=>!e.committed),i=r===-1?t.length:r;t.splice(i,0,e),i!==n&&this.refreshPendingSyncedProjection(),this.commitPendingTransactions()}discardOpenSyncTransactions(){let e=this.pendingSyncedTransactions.filter(e=>e.committed);e.length!==this.pendingSyncedTransactions.length&&(this.pendingSyncedTransactions=e,this.refreshPendingSyncedProjection())}hasOpenSyncTransaction(){return this.pendingSyncedTransactions.at(-1)?.committed===!1}hasHeldSyncTransaction(){return this.pendingSyncedTransactions.some(e=>e.committed)}*acceptedSyncedEntries(){let{states:e,truncated:t}=this.a7;if(!t)for(let t of this.syncedData.entries())e.has(t[0])||(yield t);for(let[t,n]of e)n.exists&&(yield[t,n.value])}dt(e,t,n){let r=this.bj(e,t);return!r.exists||this.hydrationSeedKeys.has(t)&&!e.sourceKeys.has(t)?`insert`:r.value!==void 0&&mt(r.value,n)?`update`:`duplicate`}b_(e){return e.type===`update`&&e.originalSyncType!==`insert`&&(this.config.sync.rowUpdateMode||`partial`)===`partial`}classifyPendingSyncedInsert(e,t){return this.dt(this.a7,e,t)}c1(e,t){let n=t.key;if(t.type===`delete`)e.states.set(n,{exists:!1,value:void 0});else if(this.b_(t)){let r=this.bj(e,n);e.states.set(n,{exists:!0,value:{...r.value,...t.value}})}else e.states.set(n,{exists:!0,value:t.value})}stagePendingSyncOperation(e,t){this.c1(this.a7,e),t||this.a7.sourceKeys.add(e.key)}dJ(e){let t=e.explicitRowMetadataWrites,n=e.rowMetadataWrites;for(let t of e.operations)n.delete(t.key);for(let[e,r]of t)n.set(e,r.write);e.operations.forEach((e,r)=>{let i=e.key;if(r<(t.get(i)?.position??0))return;let a=ur(e);a&&n.set(i,a)})}bA(){let e={states:new Map,truncated:!1,sourceKeys:new Set},t=new Set;for(let n of this.pendingSyncedTransactions){if(n.invalidationError!==void 0)continue;let r=n.committed?void 0:{states:new Map(e.states),truncated:e.truncated,sourceKeys:new Set(e.sourceKeys)};n.truncate&&(e.states=new Map,e.truncated=!0);let i;for(let r of n.operations){let a=r.key;if(!n.committed&&r.originalSyncType===`insert`&&r.type!==`delete`&&!(this.hydrationSeedKeys.has(a)&&e.sourceKeys.has(a)&&!t.has(a))){let t=this.dt(e,a,r.value);if(t===`duplicate`){i=a;break}r.type=t}this.c1(e,r),n.preserveHydrationSeedKeys?.has(a)||(e.sourceKeys.add(a),n.committed&&t.add(a))}i===void 0?n.committed||this.dJ(n):(Object.assign(e,r),n.invalidationError=n.duplicateKeyError?.(i)??new at)}this.a7=e}refreshPendingSyncedProjection(){this.bA()}hasPersistingTransaction(){for(let e of this.transactions.values())if(e.state===`persisting`)return!0;return!1}dG(){let e=this.syncRunGeneration,t=this.hasPersistingTransaction(),n=[],r=[],i=!1,a=!1,o=!1;for(let e of this.pendingSyncedTransactions)e.committed?(n.push(e),o||=e.layoutChanged,e.truncate&&(i=!0,a=e.truncateMarkReady!==!1)):r.push(e);if(n.length===0)return{processed:!1};if(!t||i){let t=o?[...this.keys()]:void 0;this.pendingSyncedTransactions=r;let s=n.reduce((e,t)=>e+t.operations.length,0)>=512;for(let e of n)e.applicationStarted=!0;this.isCommittingSyncTransactions=!0;let c=new Set,l=new Map;for(let e of n){for(let t of e.operations){let e=t.key;c.add(e),l.has(e)||l.set(e,t)}for(let[t]of e.rowMetadataWrites)c.add(t)}let u=this.et(c),d=new Map(this.optimisticUpserts),f=new Set(this.optimisticDeletes),p=this.preSyncVisibleState;if(p.size===0){p=new Map;for(let e of c){let t=this.get(e);t!==void 0&&p.set(e,t)}}let m=[],h;if(i)for(let[e,t]of this.entries())m.push({type:`delete`,key:e,value:this.aW(t,this.ak(e))});for(let e of n){if(e.truncate){this.syncedData.clear();let t=e.sourceTruncate?e.preserveHydrationSeedKeys:void 0;if(!e.preserveHydrationSeedKeys||t){for(let e of[this.syncedMetadata,this.hydrationSeedKeys,this.hydratedKeys,this.appliedAdapterKeys??new Set])for(let n of e.keys())t?.has(n)||e.delete(n);this.appliedAdapterKeys&&(this.hasAppliedAdapterTruncate=!0,this.adapterTruncateKeptKeys=new Set(t))}this.dE.clear(),this.rowOrigins.clear(),this.pendingLocalOrigins.clear();for(let e of c)p.delete(e);this.a3.emit(`truncate`,{type:`truncate`,collection:this.collection})}let t=new Set;for(let n of e.operations){let r=n.key,i=this.isLocalOnly||this.pendingLocalChanges.has(r)||this.pendingLocalOrigins.has(r)||t.has(r)?`local`:`remote`;i===`local`&&t.add(r),this.dE.delete(r),n.type===`delete`?(this.syncedData.delete(r,s),this.syncedMetadata.delete(r),this.rowOrigins.delete(r)):(this.syncedData.set(r,this.b_(n)?{...this.syncedData.get(r),...n.value}:n.value,s),this.rowOrigins.set(r,i)),this.pendingLocalChanges.delete(r),this.pendingLocalOrigins.delete(r),this.bf(r)||this.heldOptimisticRows.delete(r),e.preserveHydrationSeedKeys?.has(r)||(this.hydrationSeedKeys.delete(r),this.hydratedKeys.delete(r),n.type===`delete`?this.appliedAdapterKeys?.set(r,!0):this.appliedAdapterKeys?.get(r)&&this.appliedAdapterKeys.set(r,!1))}for(let[t,n]of e.rowMetadataWrites)!e.preserveHydrationSeedKeys?.has(t)&&!this.appliedAdapterKeys?.has(t)&&this.appliedAdapterKeys?.set(t,!1),n.type===`delete`?this.syncedMetadata.delete(t):this.syncedMetadata.set(t,n.value);for(let[t,n]of e.collectionMetadataWrites)n.type===`delete`?this.syncedCollectionMetadata.delete(t):this.syncedCollectionMetadata.set(t,n.value)}if(this.syncedData.restoreOrder(),this.refreshPendingSyncedProjection(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,this.c7(),i){for(let[e,t]of this.optimisticUpserts)m.push({type:`insert`,key:e,value:t});h=new Set(this.optimisticUpserts.keys())}for(let e of c){if(h?.has(e))continue;let t=l.get(e),n=t?.type===`update`&&p.get(e)===t.value?t.previousValue:void 0,r=!i&&!d.has(e)&&!f.has(e)&&n!==void 0?n:p.get(e),a=this.get(e);if(r===void 0){if(a===void 0)continue;m.push({type:`insert`,key:e,value:a});continue}let o=this.preSyncVirtualState.get(e)??this.ak(e,{rowOrigins:u,optimisticUpserts:d,optimisticDeletes:f}),s=t=>pn(t,e,this.collection.id,()=>o.$hasPendingWrites,()=>o.$origin);if(a===void 0){m.push({type:`delete`,key:e,value:s(r)});continue}let c=this.ak(e);(o.$hasPendingWrites!==c.$hasPendingWrites||o.$origin!==c.$origin||!mt(r,a))&&m.push({type:`update`,key:e,value:a,previousValue:s(r)})}this.size=this.e1(),m.length>0&&this.indexes.updateIndexes(m);let g,_=e=>{try{e()}catch(e){g??={error:e}}},v=t!==void 0&&(t.length!==this.size||[...this.keys()].some((e,n)=>e!==t[n])),y=!1,b=()=>{y=!0,_(()=>this.changes.emitEvents(m,!0,v))};a&&this.lifecycle.status!==`ready`&&_(()=>this.lifecycle.markReady(b)),y||b(),i&&this.lifecycle.status===`ready`&&_(()=>this.lifecycle.completeReload()),this.syncRunGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncRunGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit=!0);for(let e of n)e.applied.resolve();return{processed:!0,failure:g}}return{processed:!1}}cancelPendingSyncedTransaction(e,t=new at){if(e.committed||this.pendingSyncedTransactions.at(-1)!==e)throw new $e(`only the open last sync transaction can be canceled`);this.pendingSyncedTransactions.pop();let n=new Set;for(let t of e.operations)n.add(t.key);e.applied.reject(t),this.bA();let r=new Set;for(let e of this.pendingSyncedTransactions)if(e.invalidationError===void 0)for(let t of e.operations)r.add(t.key);for(let e of n)r.has(e)||(this.recentlySyncedKeys.delete(e),this.preSyncVisibleState.delete(e),this.preSyncVirtualState.delete(e));this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;let e=new Set;for(let t of this.pendingSyncedTransactions)if(t.committed){for(let n of t.operations)e.add(n.key);for(let n of t.rowMetadataWrites.keys())e.add(n)}for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);this.preSyncVisibleState.set(t,e),e!==void 0&&this.preSyncVirtualState.set(t,this.ak(t))}}onTransactionStateChange(){let e=this.hasPersistingTransaction();this.changes.shouldBatchEvents=this.pendingSyncedTransactions.some(t=>t.committed&&(!e||t.truncate)),this.changes.shouldBatchEvents&&this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncRunGeneration++;for(let e of this.pendingSyncedTransactions)e.applied.reject(new at);this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.heldOptimisticRows.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.appliedAdapterKeys?.clear(),this.hasAppliedAdapterTruncate=!1,this.adapterTruncateKeptKeys.clear(),this.dh(),this.isLocalOnly=!1,this.localOnlyDirectWrite=void 0,this.size=0,this.pendingSyncedTransactions=[],this.refreshPendingSyncedProjection(),this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}},fr=new class{constructor(){this.fW=new Map}fg(e){let t=this.fW.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map},this.fW.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(e===void 0){r();return}let i=this.fg(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){let e=new Set(n);e.delete(t),i.dependencies.set(t,e)}else i.dependencies.has(t)||i.dependencies.set(t,new Set)}flush(e){let t=this.fW.get(e);if(!t)return;let{queue:n,jobs:r,dependencies:i}=t;for(;n.length>0;){let t=!1,a=n.length;for(let e=0;e<a;e++){let e=n.shift(),a=r.get(e);if(!a){i.delete(e);continue}let o=i.get(e),s=!o;if(o){s=!0;for(let t of o)if(t!==e&&r.has(t)){s=!1;break}}s?(r.delete(e),i.delete(e),a(),t=!0):n.push(e)}if(!t)throw Error(k(161,{contextId:e}))}this.fW.delete(e)}clear(e){this.fW.delete(e)}},pr,mr;function hr(){return mr}function gr(e){if(pr===void 0)throw e;mr??={error:e}}function _r(e){if(pr!==void 0)return e();let t=Symbol(`collection-publication`);pr=t,mr=void 0;let n,r;try{n=e(),fr.flush(t),r=hr()}catch(e){try{fr.clear(t)}catch{}let n=hr();throw n?n.error:e}finally{pr=void 0,mr=void 0}if(r)throw r.error;return n}function vr(e){let t;for(let n of e)try{n()}catch(e){t??={error:e}}if(t)throw t.error}function yr(e){queueMicrotask(()=>{throw e})}var br=class{constructor(){this.listeners=new Map,this.e4=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);let n=this.listeners.get(e),r=t,i=n.get(r);return i||(i={},n.set(r,i)),()=>{let t=this.listeners.get(e);t?.get(r)===i&&t.delete(r)}}once(e,t){let n=()=>{},r=e=>{n(),t(e)};return this.e4.set(r,t),n=this.on(e,r),n}off(e,t){let n=this.listeners.get(e);if(n)for(let e of n.keys())(e===t||this.e4.get(e)===t)&&n.delete(e)}waitFor(e,t){return new Promise((n,r)=>{let i,a=this.on(e,e=>{i&&=(clearTimeout(i),void 0),n(e),a()});t&&(i=setTimeout(()=>{i=void 0,a(),r(Error(k(98,{event:e})))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){let r=this.listeners.get(e);if(r)for(let[i,a]of[...r]){if(!n())break;if(this.listeners.get(e)?.get(i)===a)try{i(t)}catch(e){queueMicrotask(()=>{throw e})}}}clearListeners(){this.listeners.clear()}};function xr(e){return Vn(Wn(e),Un(e))}function Sr(e,t){let n=xr(e.expression);if(t==null)return e.compareOptions.nulls===`first`?Hn(n):new N(!1);let r=(e.compareOptions.direction===`asc`?Ln:zn)(e.expression,new N(t));return e.compareOptions.nulls===`last`?Vn(r,n):r}function Cr(e,t){if(t.length!==0){if(e.length===0||t.length!==1)throw Error(k(169));return Sr(e[0],t[0])}}function wr(e,t){let{expression:n}=e[0]??{};if(!n||t.length===0)return;let r=t[0];if(r==null)return xr(n);if(r instanceof Date)return Number.isFinite(r.getTime())?Bn(Rn(n,new N(r)),zn(n,new N(new Date(r.getTime()+1)))):void 0;if(typeof r!=`object`)return In(n,new N(r))}var Tr=e=>{try{return e instanceof Error?e:Error(String(e))}catch{return Error(k(170))}};function Er(){let e,t,n=!0;return{promise:new Promise((r,i)=>{e=e=>{n=!1,r(e)},t=e=>{n=!1,i(e)}}),resolve:e,reject:t,isPending:()=>n}}function Dr(e){return e===`error`||e===`crashed`}function Or(){let e=Er();return e.promise.catch(()=>{}),e}function kr(e){e.abortController?.abort(),e.removeRequestAbortListener?.()}function Ar(e,t,n){e?.addEventListener(`abort`,n,{once:!0});let r=()=>e?.removeEventListener(`abort`,n);t.then(r,r)}var jr=class extends br{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.ej=!1,this.snapshotSent=!1,this.C=[],this.d8=new WeakMap,this.aC=new Set,this.ac=new Map,this.ad=new Map,this.fk=`ready`,this.aV=0,this.aq=new Set,this.dx=new WeakMap,this.aR=!1,this.unsubscribed=!1,this.c_=n.deferAcquisition===!0,n.onUnsubscribe&&this.on(`unsubscribed`,n.onUnsubscribe),n.onLoadSubsetError&&this.on(`loadSubset:error`,n.onLoadSubsetError),n.whereExpression&&Yn(n.whereExpression,this.collection);let r=e=>{this.fj(e),this.e9(e),t(e)};this.callback=r,this.dN=n.whereExpression?ar(this.callback,n):e=>(this.callback(e),!0),this.ec=this.collection.on(`truncate`,()=>this.fC()),this.dB=this.collection._onCleanupStart(()=>{this.eE()}),this.cb=this.collection.on(`status:change`,({status:e})=>{if(e!==`loading`&&e!==`ready`)return;let t=this.collection._sync.getSyncRunGeneration(),n=this.o;this.C.some(e=>e.acquisitionState===`detached`)&&this.setStatus(`loadingSubset`),queueMicrotask(()=>{this.o===n&&this.eM(t)})})}get owner(){return this.options.owner}get status(){return this.fk}get lastError(){return this.fu}isDeferringAcquisition(){return this.c_}resumeDeferredAcquisition(){if(!this.c_||this.unsubscribed)return;let e=this.options.onResumeAcquisition?.();this.unsubscribed||(this.c_=!1,e?.(),this.collection.status!==`idle`&&this.eM(this.collection._sync.getSyncRunGeneration()))}retireSyncRun(){let e=this.g3()&&this.C.length>0;this.eE(!0,e),e&&this.fC(!0)}g3(){return this.collection.config.syncMode===`on-demand`&&!this.c_}eE(e=!1,t=!1){this.bP(),this.aR=t,e||(this.ad=new Map(this.ac)),this.aq.clear();for(let t of[...this.C])if((!e||t.acquisitionState===`starting`)&&t.initialResult?.reject(new st),kr(t.acquisition),t.acquisitionState===`starting`){let e=this.C.indexOf(t);e!==-1&&this.C.splice(e,1)}else t.acquisitionState=`detached`,t.acquisition={options:t.requestOptions,syncRunGeneration:t.acquisition.syncRunGeneration};this.b9()}eM(e){if(this.unsubscribed||this.c_||!this.Z(e))return;if(Dr(this.collection.status)||this.collection.config.syncMode===`on-demand`&&this.collection._sync.syncLoadSubsetFn===null){this.b9();return}let t=this.C.filter(e=>e.acquisitionState===`detached`&&!e.requestOptions.signal?.aborted);if(t.length===0){this.b9();return}if(this.collection.config.syncMode!==`on-demand`&&this.collection.status!==`ready`)return;let n=this.o,r=n?.syncRunGeneration===e,i=r?n:this.c4(e,()=>{let e=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((e??[]).filter(e=>e.type!==`delete`).map(e=>[e.key,e.value]))});r&&(n.pendingSetups++,n.failed&&(n.completion.isPending()||(n.completion=Or()),n.currentAttempt={pendingCount:0,setupComplete:!1}));let a=i.currentAttempt;this.o=i,this.setStatus(`loadingSubset`),this.o===i&&this.cX(i,a,t)}fC(e=!1){let t=this.g3()?[...this.C]:[];if(t.length===0&&this.ad.size===0){this.dU();return}let n=this.o;n?(n.completion.isPending()||(n.completion=Or()),n.pendingSetups++,n.failures.clear(),n.unloaded.clear(),n.failed=!1,n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.c4(this.collection._sync.getSyncRunGeneration(),()=>new Map(this.ac)),this.o=n);let r=n.currentAttempt;if(this.setStatus(`loadingSubset`),this.o===n){this.options.truncateReplayPublication&&(this.aR=!0,this.options.truncateReplayPublication.start(e));for(let e of t)e.acquisition.abortController?.abort();this.dU(),queueMicrotask(()=>{this.o===n&&(this.Z(n.syncRunGeneration)?this.cX(n,r,n.currentAttempt===r?t:[]):this.c8(n))})}}eu(e,t,n){let r=()=>this.o===e&&e.currentAttempt===t,i=()=>r()&&this.Z(e.syncRunGeneration)&&this.a4(n),a=n.initialResult,o=n.parkedParticipant;n.parkedParticipant=void 0,o&&e.pending.delete(o)&&o.attempt.pendingCount--,a&&e.completion.promise.then(a.resolve,e=>{e instanceof st||a.reject(e)});let s=n.acquisition,c=n.acquisitionState===`active`;if(n.acquisitionState=`detached`,c&&this.releaseAcquisition(s),!i()||n.requestOptions.signal?.aborted)return;let l=this.cF(n);l.attempt=t,n.acquisition=l,n.acquisitionState=`starting`;let u=this.collection._sync.loadSubset(l.options);i()?(n.acquisitionState=`active`,this.co(u,n,l.options,!0,()=>i()&&!l.options.signal?.aborted),this.cB(e,t,n,u,l.options.signal)):(n.acquisition===l&&(n.acquisitionState=`detached`),this.releaseAcquisition(l))}ea(e,t){try{if(this.o!==e)return;if(!this.Z(e.syncRunGeneration)){this.c8(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.bJ(e)}catch(e){queueMicrotask(()=>{throw e})}}cB(e,t,n,r,i){if(this.o!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(r instanceof Promise))return;let a={demand:n,attempt:t};t.pendingCount++,e.pending.add(a);let o=()=>this.ea(e,a);return Ar(i,r,()=>{e.currentAttempt===t&&e.unloaded.add(n),queueMicrotask(o)}),r.then(o,a=>{if(!i?.aborted&&this.o===e&&e.currentAttempt===t&&this.Z(e.syncRunGeneration)&&this.C.includes(n)){let t=this.cl(r,a);e.failures.set(n,t),e.failed=!0}o()}),a}dX(e){let t=this.o;if(t){t.failures.delete(e);for(let n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}bJ(e){if(this.o!==e||e.pendingSetups>0||e.pending.size>0)return;let t=[...e.failures].filter(([t])=>this.C.includes(t)&&!this.C.some(n=>n.replaces?.includes(t)&&!e.failures.has(n)&&!e.unloaded.has(n))).map(([,e])=>e);try{if(t.length>0)this.eP(e,t);else{if(this.gN(e,()=>this.bJ(e)))return;this.fb(e)}}finally{this.b9()}}eP(e,t){if(this.o!==e)return;let n=e.completion.isPending();if(e.completion.reject(t[0]),n&&this.options.truncateReplayPublication?.fail?.(t),!e.privateRows)return;let r=e.publicationState;this.loadedInitialState=r.loadedInitialState,this.snapshotSent=r.snapshotSent}fb(e){if(this.o===e){this.o=void 0,this.aR=!1;try{this.gy(e.privateRows)}finally{e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}}gy(e){for(let t of this.ad.keys())e?.delete(t);this.ad.clear();try{if(e){let t=this.fx(this.ac,e);t.length>0&&this.dN(t)}}finally{this.cg()}}cg(){this.aC=new Set(this.ac.keys())}eG(e){let t=this.o?.privateRows;if(!t)return!1;for(let n of e)n.type===`delete`?t.delete(n.key):t.set(n.key,n.value);return!0}fx(e,t){let n=[];for(let[r,i]of e){let e=t.get(r);e===void 0?n.push({type:`delete`,key:r,value:i}):mt(e,i)||n.push({type:`update`,key:r,value:e,previousValue:i})}for(let[r,i]of t)e.has(r)||n.push({type:`insert`,key:r,value:i});return n}get fS(){return this.o!==void 0}b9(){this.aq.size===0&&!this.hasTruncateReplayWork&&this.setStatus(`ready`)}Z(e){return e===this.collection._sync.getSyncRunGeneration()}c8(e){this.o===e&&(this.bP(),this.ad.clear())}failReplacement(e){if(this.o)return;let t=this.c4(this.collection._sync.getSyncRunGeneration(),()=>new Map);t.pendingSetups=0,t.failed=!0,t.completion.reject(e),this.o=t,this.aR=!0}gN(e,t){let n=this.options.truncateReplayPublication?.siblingReplays();return n?.then(()=>{this.o===e&&t()}),n!==void 0}get hasTruncateReplayWork(){let e=this.o;return e!==void 0&&(e.pendingSetups>0||e.pending.size>0)}bP(){let e=this.o;e?.completion.isPending()&&e.completion.reject(new st),this.o=void 0,this.aR=!1}dU(){this.snapshotSent=!1,this.loadedInitialState=!1}c4(e,t){return{syncRunGeneration:e,publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent},privateRows:this.options.truncateReplayPublication?void 0:t(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,unloaded:new Set,failed:!1,completion:Or()}}cX(e,t,n){for(let r of n)if(this.C.includes(r)&&r.acquisition.attempt!==t&&(this.eu(e,t,r),this.o!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.bJ(e)}get hasPendingTruncateReplacement(){return this.aR}get hasHeldSyncTransaction(){return this.collection._hasHeldSyncTransaction()}get pendingTruncateReplacement(){let e=this.o?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){let e=this.o?.completion;return this.aR&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this.fk===e)return;let t=this.fk;this.fk=e;let n=++this.aV;if(this.emitInnerWhile(`status:change`,{type:`status:change`,subscription:this,previousStatus:t,status:e},()=>this.aV===n),this.aV!==n)return;let r=`status:${e}`;this.emitInnerWhile(r,{type:r,subscription:this,previousStatus:t,status:e},()=>this.aV===n)}co(e,t,n,r,i=()=>!0){if(!(e instanceof Promise))return;let a=this.collection._sync.getSyncRunGeneration(),o={demand:t,promise:e};r&&(this.aq.add(o),this.setStatus(`loadingSubset`));let s=()=>{r&&(this.aq.delete(o),this.Z(a)&&this.b9())};r&&Ar(n.signal,e,()=>queueMicrotask(s)),e.then(s,t=>{this.Z(a)&&i()&&this.bR(n,this.cl(e,t)),s()})}cl(e,t){let n=this.dx.get(e);if(n)return n;let r=Tr(t);return this.dx.set(e,r),r}cO(e){for(let t of this.aq)t.demand===e&&this.aq.delete(t);this.b9()}cF(e){if(this.collection.config.syncMode!==`on-demand`)return{options:e.requestOptions,syncRunGeneration:this.collection._sync.getSyncRunGeneration()};let t=new AbortController,n=e.requestOptions.signal,r;if(n?.aborted)t.abort(n.reason);else if(n){let e=()=>t.abort(n.reason);n.addEventListener(`abort`,e,{once:!0}),r=()=>n.removeEventListener(`abort`,e)}return{options:{...e.requestOptions,signal:t.signal},syncRunGeneration:this.collection._sync.getSyncRunGeneration(),abortController:t,removeRequestAbortListener:r}}releaseAcquisition(e){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.Z(e.syncRunGeneration)&&this.collection._sync.unloadSubset(e.options)}catch(e){yr(e)}finally{e.removeRequestAbortListener?.()}}}dD(e){let t={requestOptions:e,acquisition:{options:e,syncRunGeneration:this.collection._sync.getSyncRunGeneration()},acquisitionState:`starting`},n=this.o,r=n?.currentAttempt;if(this.collection.status===`cleaned-up`||this.c_&&this.collection.config.syncMode===`on-demand`||this.collection.config.syncMode===`on-demand`&&(Dr(this.collection.status)||this.collection.status!==`idle`&&this.collection._sync.syncLoadSubsetFn===null)){t.acquisitionState=`detached`,this.C.push(t);let i=Er();t.initialResult=i;let a=()=>i.reject(new st);e.signal?.addEventListener(`abort`,a,{once:!0});let o=()=>{e.signal?.removeEventListener(`abort`,a),t.initialResult=void 0};return i.promise.then(o,o),n&&r&&(t.parkedParticipant=this.cB(n,r,t,i.promise,e.signal)),{demand:t,result:i.promise,started:!1}}let i=this.cF(t);t.acquisition=i;let a=this.collection._sync.getSyncRunGeneration();this.C.push(t);let o=this.collection._sync.loadSubset(i.options);if(!this.Z(a)){let e=this.C.indexOf(t);return e!==-1&&this.C.splice(e,1),kr(i),{demand:t,result:o,started:!0}}return t.acquisitionState=`active`,this.C.includes(t)?(n&&r&&this.cB(n,r,t,o,i.options.signal),{demand:t,result:o,started:!0}):(this.releaseAcquisition(i),{demand:t,result:o,started:!0})}a4(e){return!this.unsubscribed&&this.C.includes(e)}bR(e,t,n=!1){let r=Tr(t);return e.signal?.aborted&&!n||(this.fu=r,this.emitInner(`loadSubset:error`,{type:`loadSubset:error`,subscription:this,options:e,error:r})),r}emitEvents(e){if(this.unsubscribed)return!1;let t=this.d0(e);return e.length>0&&t.length===0||this.eG(t)?!1:this.dN(t)}eH(e){this.eG(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;let t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if(`where`in e){let n=e.where;if(t.where){let e=t.where;t.where=Bn(e,n)}else t.where=n}e.boundedPrefix&&(t.orderBy=e.orderBy,t.limit=e.limit)}else this.loadedInitialState=!0;let n={...e?.refetch?{refetch:!0}:{},where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit===void 0?void 0:e.limit+this.collection._optimisticOverlaySize()};e?.where&&this.d8.set(n,e.where);let{demand:r,result:i,started:a}=this.dD(n);if(!this.a4(r)||(e?.onLoadSubsetResult?.(i,r.acquisition.options,e=>this.e6(r,e)),!this.a4(r))||(a&&this.co(i,r,r.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.a4(r)))return!1;let o;if(e?.onUnoptimized){if(o=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),o===void 0){if(e.onUnoptimized(),!this.a4(r))return!1;o=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else o=this.collection.currentStateAsChanges(t);if(!this.a4(r)||o===void 0)return!1;let s=this.o?.privateRows??this.ac,c=o.filter(e=>!this.fS&&this.ad.has(e.key)||!this.aC.has(e.key)&&!s.has(e.key));for(let e of c)this.aC.add(e.key);return this.snapshotSent=!0,this.eH(this.fS?c:this.cy(c)),!0}releaseSnapshot(...e){let t=[];for(let n of e){let e=this.C.find(e=>!t.includes(e)&&this.d7(e,n));e&&t.push(e)}t.length>0&&this.g$(t)}replaceSnapshots(e,t){let n=this.C.find(t=>this.d7(t,e));n&&(n.replaces=this.C.filter(e=>t.some(t=>this.d7(e,t))))}d7(e,t){return e.requestOptions.where===t||this.d8.get(e.requestOptions)===t}e6(e,t){try{t&&this.bR(e.acquisition.options,t.error,!0)}finally{this.C.includes(e)&&this.g$([e])}}g$(e){let t=this.o,n=[];for(let t of e){let e=t.acquisition;this.C.splice(this.C.indexOf(t),1),t.initialResult?.reject(new st),n.push(()=>this.dX(t)),t.acquisitionState===`active`&&n.push(()=>this.releaseAcquisition(e))}vr([...n,()=>this.fm(),()=>{t&&this.bJ(t)},...e.map(e=>()=>this.cO(e))])}fm(){let e=this.o;this.C.length===0&&e&&(e.privateRows&&!e.failed?this.fb(e):this.gN(e,()=>this.fm())||(this.bP(),this.ad=new Map(this.ac),this.cg(),this.options.truncateReplayPublication?.succeed()))}readOrderedSnapshot(e){let t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(e=>e!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((e,t)=>Bn(e,t)):void 0});return Array.isArray(n)?n.filter(({key:e})=>!this.collection._hasOptimisticOverlay(e)):[]}requestLimitedSnapshot({refetch:e,orderBy:t,limit:n,minValues:r,offset:i,trackLoadSubsetPromise:a=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;if(!n)throw Error(k(96));if(!this.orderByIndex)throw Error(k(97));let s=r?Cr(t,r):void 0,c=r!==void 0&&r.length>0,l=r?.[0],u=this.orderByIndex,d=this.options.whereExpression,f=d?ir(d):void 0,p=e=>{if(e!==void 0&&this.aC.has(e))return!1;let t=this.collection.get(e);return t===void 0?!1:f?.(t)??!0},m=l,h=[],g=[];if(c){let{expression:e}=t[0],r=this.collection.currentStateAsChanges({where:In(e,new N(l))});if(r){let e=r.map(e=>e.key).filter(p);g.push(...e);let t=u.take(n-g.length,l,p);g.push(...t)}else g=u.take(n,l,p)}else g=u.takeFromStart(n,p);let _=()=>Math.max(n-h.length,0),v=()=>g.length===0,y=t[0].expression,b=y.type===`ref`?rn(new j(M(y)),!0):null;for(;_()>0&&!v();){for(let e of g){let t=this.collection.get(e);h.push({type:`insert`,key:e,value:t}),m=b?b(t):t}g=u.take(_(),m,p)}for(let e of h)this.aC.add(e.key);if(this.eH(h),this.unsubscribed)return;let x;if(s&&r){let e=wr(t,r);e&&(x={whereFrom:s,whereCurrent:e})}let S=this.collection._optimisticOverlaySize(),C=i===void 0?c?void 0:n+this.aC.size+S:n+S,w={...e?{refetch:!0}:{},where:d,limit:C,orderBy:t,cursor:x,offset:i??0,subscription:this},{demand:T,result:E,started:ee}=this.dD(w);this.a4(T)&&(o?.(E,T.acquisition.options,e=>this.e6(T,e)),this.a4(T)&&(ee&&this.co(E,T,T.acquisition.options,a),this.a4(T)))}d0(e){if(e=this.cy(e),this.loadedInitialState||this.ej)return e;let t=this.fS,n=new Set,r=[];for(let i of e){let e=i;if(!(this.aC.has(i.key)||n.has(i.key))){if(i.type===`update`)e={...i,type:`insert`,previousValue:void 0},n.add(i.key);else if(i.type===`delete`){if(!t)continue}else n.add(i.key)}else if(i.type===`insert`)continue;else i.type===`delete`&&(this.aC.delete(i.key),n.delete(i.key));r.push(e)}return r}cy(e){if(this.ad.size===0)return e;let t=[];for(let n of e){let e=this.ad.get(n.key);e===void 0?t.push(n):(this.ad.delete(n.key),n.type===`delete`?t.push({...n,value:e,previousValue:void 0}):mt(e,n.value)||t.push({...n,type:`update`,previousValue:e}))}if(this.collection.config.syncMode!==`on-demand`&&!this.fS)for(let[e,n]of this.ad)this.collection.has(e)||(this.ad.delete(e),t.push({type:`delete`,key:e,value:n}));return t}fj(e){for(let t of e)t.type===`delete`?this.ac.delete(t.key):this.ac.set(t.key,t.value)}e9(e){for(let t of e)t.type===`delete`?this.aC.delete(t.key):this.aC.add(t.key)}markAllStateAsSeen(){this.ej=!0}unsubscribe(){if(this.unsubscribed)return;this.unsubscribed=!0,this.aV++;let e=[this.ec,this.dB,this.cb];this.ec=void 0,this.dB=void 0,this.cb=void 0,vr([...e.map(e=>()=>e?.()),()=>{this.bP(),this.ad.clear();let e=this.C.filter(e=>e.acquisitionState===`active`).map(e=>e.acquisition);for(let e of this.C)e.initialResult?.reject(new st),this.cO(e),e.acquisitionState===`starting`&&kr(e.acquisition);this.C=[];for(let t of e)this.releaseAcquisition(t)},()=>this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),()=>this.clearListeners()])}},Mr=class{constructor(){this.activeSubscribersCount=0,this.acquiringSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.cM=new Set,this.f2=!1,this.ex=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){_r(()=>{try{vr([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){gr(e)}})}cK(e){return this.state.enrichChangeMessage(e)}eW(e,t){if(!e)return t;if(e.type===`insert`)return t.type===`delete`?void 0:{...t,type:`insert`,previousValue:void 0};let n=e.type===`update`?e.previousValue??e.value:e.value;return t.type===`delete`?{...t,value:n,previousValue:void 0}:{...t,type:`update`,previousValue:n}}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e.map(e=>this.cK(e)));return}let r=e;if(t){if(this.batchedEvents.length>0){let t=new Map;for(let n of[...this.batchedEvents,...e])t.set(n.key,this.eW(t.get(n.key),n));r=[...t.values()].flatMap(e=>e?[e]:[])}this.batchedEvents=[],this.shouldBatchEvents=!1}this.aN?this.aN.publications.push({changes:r,layoutChanged:n}):this.e5(r,n)}deferPublication(){let e=this.aN??={depth:0,discard:!1,stateRevision:this.stateRevision,layoutRevision:this.layoutRevision,publications:[]};e.depth++;let t=!1,n=n=>{if(t||this.aN!==e||(t=!0,e.discard||=n,--e.depth>0))return;let r=e.publications;e.publications=[],this.aN=void 0,e.discard?(this.stateRevision=e.stateRevision,this.layoutRevision=e.layoutRevision):this.e5(r.flatMap(({changes:e})=>e),r.some(({layoutChanged:e})=>e))};return{publish:()=>n(!1),discard:()=>n(!0)}}e5(e,t){if(e.length===0&&!t)return;let n=e.map(e=>this.cK(e)),r=[...this.cM],i=[...this.changeSubscriptions];_r(()=>{let t=i.map(e=>()=>e.emitEvents(n));e.length===0&&t.unshift(...r);try{vr(t)}catch(e){gr(e)}})}subscribeLayoutChanges(e){return this.cM.add(e),()=>this.cM.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw Error(k(95));let{where:n,...r}=t,i=r.whereExpression;n&&(i=K(n(Fn())));let a=r.deferAcquisition===!0;this.ei(a);let o,s={closed:!1};try{o=new jr(this.collection,e,{...r,whereExpression:i,deferAcquisition:a,onResumeAcquisition:()=>this.gA(),onUnsubscribe:()=>{s.closed=!0,this.eB(o?.isDeferringAcquisition()??!1),o&&this.changeSubscriptions.delete(o)}}),t.onStatusChange&&o.on(`status:change`,t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),s.closed||this.changeSubscriptions.add(o)}catch(e){if(o)try{o.unsubscribe()}catch{}else this.eB(a);throw e}return o}hasSubscriberOrPreload(){return this.f2||this.acquiringSubscribersCount>0}onFirstSubscriberOrPreload(e){return this.ex.add(e),()=>this.ex.delete(e)}markSubscriberOrPreload(){if(this.f2)return;this.f2=!0;let e=[];for(let t of[...this.ex])try{t()}catch(t){e.push(t)}if(e.length)throw e[0]}gA(){return this.lifecycle.assertCanStartSync(),this.gT(),()=>this.e2(1)}gT(){let e=this.sync.getSyncRunGeneration();this.markSubscriberOrPreload(),e===this.sync.getSyncRunGeneration()&&(this.gr(),this.sync.resumeStart())}e2(e){let t=this.acquiringSubscribersCount;this.acquiringSubscribersCount+=e,this.events.emitSubscribersChange(this.acquiringSubscribersCount,t),e===1&&this.acquiringSubscribersCount>0&&this.markSubscriberOrPreload()}gr(){(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync()}ei(e){e||this.lifecycle.assertCanStartSync(),this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();let t=!1;try{e?!this.lifecycle.isCleaningUp()&&dt(this.collection.config)&&this.gr():this.gT(),e||(t=!0,this.e2(1))}catch(e){if(this.activeSubscribersCount--,t)try{this.e2(-1)}catch{}throw this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),e}}eB(e){if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new Ee;e||this.e2(-1)}cleanup(){this.f2=[...this.changeSubscriptions].some(e=>!e.isDeferringAcquisition()),this.stateRevision++,this.batchedEvents=[],this.shouldBatchEvents=!1,this.aN&&(this.aN.publications.length=0),this.aN=void 0}},Nr=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),Pr=e=>{clearTimeout(e)},Fr=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>Nr(e),Ir=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):Pr,Lr=()=>globalThis.performance?.now()??Date.now(),Rr=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.dm=!1}static getInstance(){return e.fY??=new e}schedule(e,t,n){let r=Lr()+t;this.tasks.set(e,{executeAt:r,callback:n}),this.dm||(this.dm=!0,Promise.resolve().then(()=>{this.dm=!1,this.fa()}))}cancel(e){this.tasks.delete(e),this.tasks.size===0&&this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}fa(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(let t of this.tasks.values())t.executeAt<e&&(e=t.executeAt);let t=Math.max(0,e-Lr());this.timeoutId=setTimeout(()=>{this.timeoutId=null;let e=Lr();for(let[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(e){console.error(k(214),e)}}this.fa()},t),typeof this.timeoutId==`object`&&this.timeoutId.unref()}};Rr.fY=null;var zr=Rr,Br=class{constructor(e,t,n=()=>{}){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.aI=null,this.failureReason=null,this.a6=!1,this.dk=null,this.cc=null,this.cE=new Vr,this.bw=!1,this.bI=!1,this.g2=!1,this.aP=0,this.aV=0,this.dr=!1,this.b5=null,this.bO=new Set,this.config=e,this.id=t,this.fX=n}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e!==t&&!{idle:[`loading`,`error`,`crashed`,`cleaned-up`],loading:[`ready`,`error`,`crashed`,`cleaned-up`],ready:[`cleaned-up`,`crashed`],error:[`cleaned-up`,`idle`,`crashed`],crashed:[`cleaned-up`],"cleaned-up":[`loading`,`error`,`crashed`]}[e].includes(t)&&!(this.g2&&e===`error`&&t===`ready`))throw new we(e,t,this.id)}setStatus(e,t=!1,n){if(e===`ready`&&!t)throw new be(k(208));this.validateStatusTransition(this.status,e),e===`loading`&&(this.b5=null);let r=++this.aV,i=this.status;this.status=e,n?.();let a=()=>this.aV===r;this.events.emitStatusChange(e,i,a),a()&&this.events.emitHealthChange()}validateCollectionUsable(e){switch(this.status){case`error`:case`crashed`:throw new U(e,this.id);case`cleaned-up`:this.sync.startSync()}}markReady(e){if(this.status===`crashed`||this.bI)return;if(this.b6){this.completeReload(e);return}let t=this.d_(e);if(t){if(this.gn)this.gn(t);else throw t.error}}deferReadyFailures(){let e;return this.gn=t=>{e??=t},()=>(this.gn=void 0,e)}d_(e){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`||this.status===`error`){let t=this.aV+1;if(this.setStatus(`ready`,!0,e),this.status!==`ready`||this.aV!==t)return;let n=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit=!0,n.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),n.push(()=>this.changes.emitEmptyReadyEvent());try{vr(n)}catch(e){return{error:e}}}}fail(e){if(this.status===`crashed`||this.bI)return;this.bI=!0;let t=this.b6;this.b6=void 0,this.status===`ready`?(this.failureReason=null,this.dk=Hr([Wr(e)]),this.events.emitHealthChange()):t&&this.status===`error`?(this.cc=Hr([Wr(e)]),this.events.emitHealthChange()):(this.validateStatusTransition(this.status,`error`),this.cc=Hr([Wr(e)]),this.setStatus(`error`)),t?.reject(e)}get stoppedThisRun(){return this.bI}get inFirstLoad(){return this.status===`loading`||this.reloading&&this.status===`error`}get reloading(){return this.b6!==void 0}beginReload(){if(this.b6)return this.b6.promise;let e=Er();return e.promise.catch(()=>void 0),this.b6=e,this.a6=!1,this.bw=!1,this.bI=!1,this.events.emitHealthChange(),e.promise}completeReload(e){let t=this.b6;if(t){if(this.b6=void 0,this.a6||(this.failureReason=null),this.dk=null,this.bw||(this.cE=new Vr),this.status===`ready`)this.events.emitHealthChange();else{this.cc=null,this.g2=!0;try{this.markReady(e)}catch(e){throw this.status===`ready`?t.resolve():t.reject(e),e}finally{this.g2=!1}}t.resolve()}}retireSubscriptionDemand(){for(let e of[...this.changes.changeSubscriptions])e.retireSyncRun()}abandonReload(e){this.g8(e)&&this.status!==`cleaned-up`&&this.events.emitHealthChange()}g8(e){let t=this.b6;return t?(this.b6=void 0,t.reject(e),!0):!1}crash(e){this.status!==`crashed`&&(this.validateStatusTransition(this.status,`crashed`),this.g8(e),this.cc=Hr([Wr(e)]),this.setStatus(`crashed`))}get problems(){let e=Dr(this.status)?this.cc:this.dk??this.cE.problem;return{failureReason:e?null:this.failureReason,error:e}}get statusProblem(){return Dr(this.status)?this.cc:null}reportError(e){if(this.status===`crashed`)return;this.d4(`reportError`),this.g5(`reportError`);let t=this.reloading&&!this.a6?[]:this.failureReason?.errors??[];t.some(t=>t.cause===e)||(this.failureReason=Hr([...t,Wr(e)]),this.a6=this.reloading,this.events.emitHealthChange())}reportHealthy(e){if(this.status===`crashed`)return;this.d4(`reportHealthy`),this.g5(`reportHealthy`);let t=this.failureReason?.errors??[],n=e===void 0?[]:t.filter(t=>t.cause!==e);n.length!==t.length&&(this.failureReason=n.length>0?Hr(n):null,this.events.emitHealthChange())}reportRequestError(e,t){this.reloading&&!this.bw&&(this.cE=new Vr,this.bw=!0),this.cE.fail(e,t)&&this.events.emitHealthChange()}clearRequestError(e){this.cE.settle(e)&&this.events.emitHealthChange()}d4(e){if(this.bI)throw new be(k(259,{operation:e,id:this.id}))}g5(e){if(this.status!==`ready`)throw new be(k(257,{operation:e,id:this.id,status:this.status}))}getSyncError(){return this.cc?.cause}hasStartedCleanup(){return this.dr||this.status===`cleaned-up`}assertCanStartSync(){if(this.dr)throw new be(k(209,{id:this.id}))}isCleaningUp(){return this.dr}onCleanupStart(e){if(this.bO.add(e),this.dr)try{e()}catch(t){throw this.bO.delete(e),t}return()=>this.bO.delete(e)}startGCTimerIfUnsubscribed(){this.aP=Lr()+50,this.startGCTimer(!0)}dA(){return!this.dr&&this.changes.activeSubscribersCount===0&&!this.sync.hasPendingPreload&&!this.state.hasPersistingTransaction()}startGCTimer(e=!1){if(e||(this.aP=0),this.status===`idle`||this.status===`cleaned-up`||(this.cancelGCTimer(),!this.dA()))return;let t=this.config.gcTime??3e5;t<=0||!Number.isFinite(t)||zr.getInstance().schedule(this,Math.max(t,this.aP-Lr()),()=>{this.dA()&&this.eg()})}cancelGCTimer(){zr.getInstance().cancel(this),this.aI!==null&&(Ir(this.aI),this.aI=null)}eg(){this.aI!==null&&Ir(this.aI),this.aI=Fr(e=>{if(this.dA()){if(!(e.timeRemaining()>0||e.didTimeout)){this.eg();return}this.fe().catch(()=>void 0)}this.aI=null},{timeout:1e3})}fe(){if(this.b5)return this.b5;let e=Er();this.b5=e.promise,this.dr=!0;let t=[],n,r=!0,i=e=>{try{e()}catch(e){t.push(e)}};for(let e of[...this.bO])i(e);let a=n=>{this.dr=!1,this.cc=null,i(()=>this.setStatus(`cleaned-up`)),this.changes.activeSubscribersCount===0&&i(()=>this.events.cleanup());let r=n?[n.error,...t]:t,a=r.length===0?void 0:{error:r.length===1?r[0]:AggregateError(r,k(173,{syncFailure:n!==void 0}),{cause:r[0]})};Promise.resolve().then(()=>Promise.resolve()).then(()=>{this.b5===e.promise&&(this.b5=null),a?e.reject(a.error):e.resolve()})};i(()=>this.fX());try{r=this.sync.cleanup(a)}catch(e){n={error:e}}i(()=>this.state.cleanup()),i(()=>this.changes.cleanup()),i(()=>this.indexes.cleanup()),this.hasBeenReady=!1;let o=this.problems,s=this.reloading;this.bI=!1,this.failureReason=null,this.dk=null,this.cE=new Vr,this.abandonReload(new ot);let c=this.problems;return!s&&(o.error!==c.error||o.failureReason!==c.failureReason)&&this.events.emitHealthChange(),this.onFirstReadyCallbacks=[],r&&a(n),e.promise}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{let t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){return this.cancelGCTimer(),this.fe()}},Vr=class{constructor(){this.failed=new Map,this.open=new Map,this.problem=null}fail(e,t){let n=!1;for(let e of t){let t=this.open.get(e);t?t.requests++:(this.open.set(e,{failure:Wr(e),requests:1}),n=!0)}return n=this.release(e)||n,this.failed.set(e,t),n&&this.hd()}settle(e){return this.release(e)&&this.hd()}release(e){let t=!1;for(let n of this.failed.get(e)??[]){let e=this.open.get(n);--e.requests===0&&(t=this.open.delete(n))}return this.failed.delete(e),t}hd(){let e=Array.from(this.open.values(),({failure:e})=>e);return this.problem=e.length>0?Hr(e):null,!0}};function Hr(e){let t=e[e.length-1];return Ur({...t,errors:e},t.cause)}function Ur(e,t){return Object.defineProperty(e,"cause",{value:t,enumerable:!1})}function Wr(e){let t=`Error`,n=`Collection is in an error state`,r;try{e instanceof Error?(t=e.name,n=e.message):e!==void 0&&(n=String(e)),r=e?.code}catch{}return Ur({name:t,message:n,...typeof r==`string`?{code:r}:{},at:Date.now()},e)}var Gr=Symbol(`tanstack-db.sync-receipt.accepted`);function Kr(e,t){return e[Gr]=t,e}function qr(e){return e===!0?!0:e[Gr]??e}var Jr=Symbol();function Yr(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.is(e[n],t[n]))}var Xr=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.aw=new Set,this.a5=new Set,this.bb=!1,this.bM=!1,this.ab=[],this.bZ=0,this.syncRunGeneration=0,this.bg=!1,this.cL=0,this.config=e,this.id=t,this.syncMode=e.syncMode??`eager`}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this.a3=e.events}f6(e,t,n){let r=n.value,i=this.f4??=new WeakMap;try{let a=i.get(r);if(a&&t===`update`&&!(`previousValue`in n)&&!Yr(a,r))throw new Xe(e);i.set(r,{...r})}catch(e){if(e instanceof Xe)throw e;i.delete(r)}}du(e){let t=this.config.utils?.[lt];return new je(e,this.id,{hasCustomGetKey:t?.hasCustomGetKey??!1,hasJoins:t?.hasJoins??!1,hasDistinct:t?.hasDistinct??!1})}markLayoutChange(){this.aA().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)return;if(this.bb){this.bM=!0;return}let e=++this.bZ;if(this.lifecycle.setStatus(`loading`),e!==this.bZ)return;let t=this.g9(e);if(t)throw t.error}reload(){let e=this.lifecycle.status;if(e===`crashed`)return Promise.reject(new Se(this.id));try{this.lifecycle.assertCanStartSync()}catch(e){return Promise.reject(e)}if(this.lifecycle.reloading)return this.lifecycle.beginReload();if(e===`idle`||e===`cleaned-up`)return this.preload();if(this.bg||this.cL>0)return Promise.reject(new Ce(this.id));let t=++this.bZ,n=this.lifecycle.beginReload();if(this.retireSyncRun().catch(e=>this.lifecycle.crash(e)),this.lifecycle.retireSubscriptionDemand(),t!==this.bZ)return n;try{let e=this.g9(t);e&&yr(e.error)}catch(e){this.lifecycle.abandonReload(e)}return n}g9(e){let t=()=>e===this.bZ,n=!1,r=this.lifecycle.deferReadyFailures(),i;this.bg=!0;try{let e=Zr(this.config.sync.sync({collection:this.collection,begin:e=>{if(!t())return;let n=Er();n.promise.catch(()=>void 0);let r=e?.snapshot===!0;this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],rowMetadataWrites:new Map,explicitRowMetadataWrites:new Map,collectionMetadataWrites:new Map,applied:n,duplicateKeyError:e=>this.du(e),truncate:r,truncateMarkReady:!1}),r&&this.state.refreshPendingSyncedProjection()},write:e=>{if(!t())return;let n=this.ar();if(!n)return;let r=`key`in e?e.key:this.config.getKey(e.value);xt(r,e);let i=e.type;if(e.type===`insert`){let t=this.state.classifyPendingSyncedInsert(r,e.value);if(t===`duplicate`)throw this.du(r);i=t}`value`in e;let a={...e,type:i,key:r,originalSyncType:e.type===`insert`||e[Jr]?`insert`:void 0};n.operations.push(a),this.state.stagePendingSyncOperation(a,n.preserveHydrationSeedKeys?.has(r));let o=ur(a);o&&n.rowMetadataWrites.set(r,o)},commit:e=>{if(!t())return!0;let n=this.state.pendingSyncedTransactions.at(-1);if(!n)throw new Ze;if(n.committed)throw new Qe;return e?.aborted||n.invalidationError!==void 0?(this.state.cancelPendingSyncedTransaction(n,e?.aborted?void 0:n.invalidationError),n.applied.promise):(n.committed=!0,this.state.acceptSyncTransaction(n),!n.applied.isPending()||Kr(n.applied.promise,!0))},markReady:()=>{t()&&this.lifecycle.markReady()},fail:e=>{t()&&this.lifecycle.fail(e)},reportError:e=>{t()&&this.lifecycle.reportError(e)},reportHealthy:e=>{t()&&this.lifecycle.reportHealthy(e)},truncate:e=>{if(!t())return;let n=this.ar();n&&(n.operations=[],n.rowMetadataWrites.clear(),n.explicitRowMetadataWrites.clear(),n.truncate=!0,n.truncateMarkReady=e?.markReady??!0,this.state.refreshPendingSyncedProjection())},invalidateLoadedSubsets:()=>{t()&&!n&&(n=!0,queueMicrotask(()=>{n=!1,t()&&this.a3.emit(`loadedSubsets:invalidated`,{type:`loadedSubsets:invalidated`,collection:this.collection})}))},metadata:this.eT(t)}));if(this.bg=!1,i=r(),!t())return e?.cleanup&&this.dW(e.cleanup),this.ck(),i;if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new V(k(210,{id:this.id}));this.lifecycle.startGCTimerIfUnsubscribed()}catch(e){throw this.bg=!1,this.ck(),r(),t()&&!this.lifecycle.stoppedThisRun&&this.lifecycle.crash(e),e}return i}deferStart(){return this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`?!1:(this.bb=!0,!0)}resumeStart(){if(!this.bb)return;this.bb=!1;let e=this.bM||this.ab.length>0;this.bM=!1;let t=this.ab;this.ab=[];let n=this.syncRunGeneration;try{e&&this.startSync()}catch(e){for(let{deferred:n}of t)n.reject(e);throw e}for(let{options:e,deferred:r}of t){let t=this.syncLoadSubsetFn;try{if(n!==this.syncRunGeneration||e.signal?.aborted)throw new st;let i=!t||this.g_(t,e);i instanceof Promise?i.then(e=>r.resolve(e),e=>r.reject(e)):r.resolve(void 0)}catch(e){r.reject(e)}}}aA(){let e=this.state.pendingSyncedTransactions.at(-1);if(!e)throw new Je;if(e.committed)throw new Ye;return e}ar(){let e=this.aA();return e.invalidationError===void 0?e:void 0}a8(e,t){let n=this.aA();n.explicitRowMetadataWrites.set(e,{position:n.operations.length,write:t}),n.rowMetadataWrites.set(e,t)}eT(e){return{persistence:null,row:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.invalidationError!==void 0)continue;let i=r.rowMetadataWrites.get(t);if(i)return i.type===`delete`?void 0:i.value;if(lr(r,t))return}return this.state.syncedMetadata.get(t)},set:(t,n)=>{e()&&this.a8(t,{type:`set`,value:n})},delete:t=>{e()&&this.a8(t,{type:`delete`})}},collection:{get:t=>{if(!e())return;let n=this.state.pendingSyncedTransactions;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.invalidationError!==void 0)continue;let i=r.collectionMetadataWrites.get(t);if(i)return i.type===`delete`?void 0:i.value}return this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{e()&&this.aA().collectionMetadataWrites.set(t,{type:`set`,value:n})},delete:t=>{e()&&this.aA().collectionMetadataWrites.set(t,{type:`delete`})},list:t=>{if(!e())return[];let n=new Map(this.state.syncedCollectionMetadata);for(let e of this.state.pendingSyncedTransactions)if(e.invalidationError===void 0)for(let[t,r]of e.collectionMetadataWrites)r.type===`delete`?n.delete(t):n.set(t,r.value);return Array.from(n.entries()).filter(([e])=>!t||e.startsWith(t)).map(([e,t])=>({key:e,value:t}))}}}}get hasPendingPreload(){return this.cW!==void 0}preload(){try{this.lifecycle.assertCanStartSync(),this.bb&&this.resumeStart()}catch(e){return Promise.reject(e)}if(this.lifecycle.status===`ready`&&(this.lifecycle.cancelGCTimer(),this.lifecycle.startGCTimerIfUnsubscribed()),this.preloadPromise)return this.preloadPromise;let e=new Promise((e,t)=>{if(this.lifecycle.status===`ready`){e();return}if(Dr(this.lifecycle.status)){t(this.d1());return}let n=!1,r={active:!1,ready:!1},i=()=>{},a=()=>{},o=()=>{n=!0,i(),a(),this.cW===c&&(this.cW=void 0),this.lifecycle.startGCTimerIfUnsubscribed()},s=()=>{r.active?r.ready=!0:n||(o(),e())},c=e=>{n||(o(),t(e))};this.cW=c,this.lifecycle.cancelGCTimer(),a=this.lifecycle.onFirstReady(s);let l=()=>{r.active||c(this.d1())},u=this.collection.on(`status:error`,l),d=this.collection.on(`status:crashed`,l);if(i=()=>{u(),d()},this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`){r.active=!0;let e;try{this.startSync()}catch(t){e={error:t}}finally{r.active=!1}Dr(this.collection.status)?c(this.d1()):r.ready?(e&&yr(e.error),s()):e&&c(e.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}d1(){let e=this.lifecycle.getSyncError();return e===void 0?new Te:e}get isLoadingSubset(){return this.aw.size>0}beginLoadSubsetOperation(){let e=this.aa,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.aa=t,this.a5.add(t),{wait:()=>this.el(t),cancel:()=>{t.completed=!0,this.a5.delete(t),this.aa===t&&(this.aa=e?.completed?void 0:e)}}}el(e){return e.waiting=!0,e.pending.size===0?(this.gm(e),!e.hasError||Promise.reject(e.error)):(e.deferred=Er(),e.deferred.promise)}c9(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(this.gm(e),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}gm(e){e.completed=!0,this.a5.delete(e),this.aa===e&&(this.aa=void 0)}gk(e){this.a3.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:e,previousIsLoadingSubset:!e,loadingSubsetTransition:e?`start`:`end`})}trackLoadSubsetOperationPromise(e){let t=this.aa;t&&!t.pending.has(e)&&(t.pending.add(e),e.then(()=>this.c9(t,e,{ok:!0}),n=>this.c9(t,e,{ok:!1,error:n})))}trackLoadPromise(e){let t=this.syncRunGeneration,n=!this.isLoadingSubset;this.aw.add(e),this.trackLoadSubsetOperationPromise(e),n&&this.gk(!0);let r=()=>{if(t!==this.syncRunGeneration)return;let n=this.aw.size===1&&this.aw.has(e);this.aw.delete(e),n&&this.gk(!1)};e.then(r,r)}getSyncRunGeneration(){return this.syncRunGeneration}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new st);if(this.syncMode===`eager`)return!0;if(this.bb){this.bM=!0;let t=Er();return this.ab.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){let t=this.g_(this.syncLoadSubsetFn,e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}g_(e,t){this.cL++;try{return e(t)}catch(e){return Promise.reject(e)}finally{this.cL--}}unloadSubset(e){this.syncMode!==`eager`&&(this.bb?this.ab=this.ab.filter(t=>t.options!==e||(t.deferred.reject(new st),!1)):this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e))}eC(e){let t=new it(this.id,e);return t.cause=e,e instanceof Error&&(t.stack=e.stack),t}e3(e){if(!e)return!0;try{let t=e();return!Jt(t)||Promise.resolve(t).then(()=>void 0,e=>{throw this.eC(e)})}catch(e){throw this.eC(e)}}dW(e){let t=this.bE;if(t)try{let n=this.e3(e);n!==!0&&(t.tasks.push(n),n.catch(()=>void 0))}catch(e){t.failure??={error:e}}}ck(){let e=this.bE;if(!e)return;this.bE=void 0;let t=t=>{let n=e.failure??t;e.onSettled?.(n),n?e.completion?.reject(n.error):e.completion?.resolve()};e.tasks.length===0?t():Promise.allSettled(e.tasks).then(e=>{let n=e.find(e=>e.status===`rejected`);t(n?{error:n.reason}:void 0)})}retireSyncRun(){this.syncRunGeneration++,this.state.discardOpenSyncTransactions();let e=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.dp();try{let t=this.e3(e);return t===!0?Promise.resolve():t}catch(e){return Promise.reject(e)}}dp(){let e=this.aw.size>0;this.aw.clear(),e&&this.gk(!1),this.aa=void 0;for(let e of this.a5)e.completed||(e.completed=!0,e.pending.clear(),e.hasError=!0,e.error=new st,e.deferred?.reject(e.error));this.a5.clear();let t=this.ab;this.ab=[];for(let e of t)e.deferred.reject(new st)}cleanup(e){++this.bZ,this.syncRunGeneration++,this.cW?.(new ot);let t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;let n=!0,r;try{n=this.e3(t)}catch(e){r={error:e}}if(this.preloadPromise=null,this.bb=!1,this.bM=!1,this.dp(),this.bg){let t=e?void 0:Er(),i={tasks:[],failure:r,onSettled:e,completion:t};return n!==!0&&(i.tasks.push(n),n.catch(()=>void 0)),this.bE=i,!e&&t.promise}if(r)throw r.error;return n===!0?!0:e?(n.then(()=>e(),t=>e({error:t})),!1):n}};function Zr(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var Qr=new WeakMap,$r=1;function ei(e){if(!yt(e))return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype}function ti(e,t){return e===t?0:e<t?-1:1}function ni(e){let t=Qr.get(e)??e.name;return{kind:`constructor`,...t?{name:t}:{}}}function ri(e){if(e==null)return e;switch(typeof e){case`string`:case`boolean`:return e;case`number`:return Number.isFinite(e)?e:null;case`bigint`:return{__type:`bigint`,value:e.toString()};case`function`:case`symbol`:return;case`undefined`:return}if(Array.isArray(e))return e.map(e=>ri(e)??null);if(ei(e))return{__type:e[Symbol.toStringTag],value:String(e)};if(e instanceof Date)return{__type:`date`,value:e.toISOString()};if(e instanceof Set)return{__type:`set`,values:Array.from(e).map(e=>ri(e)??null).sort((e,t)=>ti(ii(e),ii(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:ri(e)??null,value:ri(t)??null})).sort((e,t)=>ti(ii(e.key),ii(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>ti(e,t));for(let[e,r]of n){let n=ri(r);n!==void 0&&(t[e]=n)}return Object.hasOwn(t,`__type`)?{__type:`object`,value:t}:t}function ii(e){return e===null?`null`:Array.isArray(e)?`[${e.map(ii).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>ti(e,t)).map(t=>`${JSON.stringify(t)}:${ii(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function ai(e,t,n,r,i){let a=ni(r),o=ri(t)??null,s=ri(i);return{signatureVersion:$r,signature:ii({signatureVersion:$r,expression:o,options:s??null}),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function oi(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>oi(e));let t={};for(let[n,r]of Object.entries(e))t[n]=oi(r);return t}function si(e){return ei(e)?e:e instanceof Date?new Date(e.getTime()):Array.isArray(e)?e.map(si):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,si(t)])):e}function ci(e){return si(e)}var li=class{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable(`createIndex`);let n=++this.indexCounter,r=K(e(Fn())),i=t.indexType??this.defaultIndexType;if(!i)throw new V(k(207));let a=new i(n,r,t.name,t.options);a.build(this.state.entries()),this.indexes.set(n,a);let o=ai(n,r,t.name,i,t.options);return this.indexMetadata.set(n,o),this.events.emitIndexAdded(o),a}removeIndex(e){this.lifecycle.validateCollectionUsable(`removeIndex`);let t=typeof e==`number`?e:e.id,n=this.indexes.get(t);if(!n||typeof e!=`number`&&n!==e)return!1;this.indexes.delete(t);let r=this.indexMetadata.get(t);return this.indexMetadata.delete(t),r&&this.events.emitIndexRemoved(r),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:ci(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:oi(e.options)}}))}updateIndexes(e){try{for(let t of this.indexes.values())for(let n of e)switch(n.type){case`insert`:t.add(n.key,n.value);break;case`update`:n.previousValue?t.update(n.key,n.previousValue,n.value):t.add(n.key,n.value);break;case`delete`:t.remove(n.key,n.value)}}catch(e){throw this.lifecycle.crash(e),e}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},ui=new WeakMap;function di(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}function fi(e){return typeof e==`object`&&e?ui.get(e)??e:e}var pi=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`,`set`]),mi=new Set([`entries`,`keys`,`values`,`forEach`]);function hi(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!yt(e)}function gi(e,t,n,r){return function(...i){let a=e.apply(t.copy_,i);return n(t),a===t.copy_?r:a}}function _i(e,t,n,r,i){if(mi.has(e)||t===Symbol.iterator)return(...a)=>{let o=n.copy_,s=o instanceof Map;if(s&&e===`keys`)return o.keys();let c=e=>hi(e)?i(e,{tracker:n,prop:``,retainIdentity:!0}).proxy:e;if(e===`forEach`){let e=a[0];if(typeof e!=`function`)throw TypeError(k(109));return o.forEach((t,n)=>{let i=c(t);e.call(a[1],i,s?n:i,r)})}let l=o.entries(),u=e===`entries`||s&&t===Symbol.iterator;return{next(){let e=l.next();if(e.done)return e;let[t,n]=e.value,r=c(n);return{done:!1,value:u?[s?t:r,r]:r}},[Symbol.iterator](){return this}}}}function vi(e,t=new WeakMap,n=!1){if(e=fi(e),typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(e instanceof Date){let n=new Date(e.getTime());return t.set(e,n),n}if(e instanceof RegExp){let n=new RegExp(e.source,e.flags);return n.lastIndex=e.lastIndex,t.set(e,n),n}if(e instanceof URL){let n=new URL(e.href);return t.set(e,n),n}if(Array.isArray(e)){let r=Array(e.length);return t.set(e,r),e.forEach((e,i)=>{r[i]=vi(e,t,n)}),r}let r=Object.prototype.toString.call(e),i=r===`[object ArrayBuffer]`?ArrayBuffer:r===`[object SharedArrayBuffer]`&&typeof SharedArrayBuffer<`u`?SharedArrayBuffer:void 0;if(i){let n;try{n=Object.getOwnPropertyDescriptor(i.prototype,`byteLength`).get.call(e)}catch{}if(n!==void 0){let r=new i(n);return new Uint8Array(r).set(new Uint8Array(e)),t.set(e,r),r}}if(ArrayBuffer.isView(e)){let r=vi(e.buffer,t,n),i=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get.call(e);if(i===void 0){let n=new DataView(r,e.byteOffset,e.byteLength);return t.set(e,n),n}let a=Object.getPrototypeOf(e).constructor,o=e.length,s=Function.prototype.toString.call(a)===Function.prototype.toString.call(globalThis[i])?new a(r,e.byteOffset,o):new a(o);return t.set(e,s),s.set(e),s}if(e instanceof Map){let r=new Map;return t.set(e,r),e.forEach((e,i)=>{r.set(i,vi(e,t,n))}),r}if(e instanceof Set){let r=new Set;return t.set(e,r),e.forEach(e=>{r.add(vi(e,t,n))}),r}if(yt(e))return e;if(n){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e}let a={};t.set(e,a);for(let r of Reflect.ownKeys(e))(typeof r==`symbol`||Object.prototype.propertyIsEnumerable.call(e,r))&&di(a,r,vi(e[r],t,n));return a}function yi(e,t,n){return _t(e,t,n,!0)}function bi(e,t){let n=new Map;function r(e,t){if(n.has(e))return n.get(e);{let r=bi(e,t);return n.set(e,r),r}}let i=t?.tracker.valueCopies??new WeakMap,a={valueCopies:i,copy_:t?i.get(e)??e:vi(e,i),originalObject:t?vi(e):e,modified:!1,assigned_:Object.create(null),parent:t,target:e};function o(e){e.modified||=!0,e.parent&&(!e.parent.retainIdentity&&e.parent.tracker.copy_[e.parent.prop]===e.copy_&&(e.parent.tracker.assigned_[e.parent.prop]=!0),o(e.parent.tracker))}function s(e){if(e.copy_ instanceof Map||e.copy_ instanceof Set)return yi(Array.from(e.copy_),Array.from(e.originalObject));for(let t in e.assigned_)if(!e.assigned_[t]||Object.hasOwn(e.copy_,t)!==Object.hasOwn(e.originalObject,t)||!yi(e.copy_[t],e.originalObject[t]))return!1;return!0}function c(e){if(s(e)){e.modified=!1,e.assigned_=Object.create(null);let t=e.parent;t&&(yi(t.tracker.copy_[t.prop],t.tracker.originalObject[t.prop])&&delete t.tracker.assigned_[t.prop],c(t.tracker))}}function l(e,t){let n=a.originalObject;return Object.hasOwn(n,e)&&yi(t,n[e])}function u(e,t){t?(delete a.assigned_[e.toString()],a.modified=!0,c(a)):(a.assigned_[e.toString()]=!0,o(a))}let d=new Proxy(a.copy_,{get(e,t,n){let s=a.copy_[t],c=Object.getOwnPropertyDescriptor(e,t);if(c?.get)return s;if(c?.configurable===!1&&!c.writable)return hi(s)&&(a.assigned_[String(t)]=!0,o(a)),s;if(typeof s==`function`){if(Object.hasOwn(e,t)||t===`constructor`)return s;let c=t.toString();if(c===`subarray`&&ArrayBuffer.isView(e))return(...t)=>r(s.apply(e,t),{tracker:a,prop:``,retainIdentity:!0}).proxy;if(pi.has(c)&&(Array.isArray(e)||ArrayBuffer.isView(e)))return gi(s,a,o,n);if(Array.isArray(e))return s.bind(n);if(e instanceof Map||e instanceof Set){let l=e=>{let t=fi(e);return typeof t==`object`&&t?i.get(t)??t:t};if(c===`has`||c===`delete`||c===`add`||c===`set`)return(...t)=>{e instanceof Set?t[0]=l(t[0]):c===`set`&&(t[1]=l(t[1]));let r=s.apply(e,t);return c!==`has`&&o(a),r===e?n:r};if(e instanceof Map&&c===`get`)return t=>{let n=e.get(t);return hi(n)?r(n,{tracker:a,prop:``,retainIdentity:!0}).proxy:n};if(c===`clear`)return gi(s,a,o,n);let u=_i(c,t,a,n,r);if(u)return u}return s.bind(e)}return hi(s)?r(s,{tracker:a,prop:String(t)}).proxy:s},set(e,t,n){if(Reflect.getOwnPropertyDescriptor(e,t)?.get)return Reflect.set(e,t,n);let r=a.copy_[t];if(!Object.hasOwn(a.copy_,t)||!yi(r,n)){let e=l(t,n);a.copy_[t]=e?vi(a.originalObject[t]):n,u(t,e)}return!0},defineProperty(e,t,n){let r=Reflect.defineProperty(e,t,n);return r&&(`value`in n||n.get||n.set)&&u(t,l(t,Reflect.get(e,t))),r},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(e,t)},preventExtensions(e){return Reflect.preventExtensions(e)},isExtensible(e){return Reflect.isExtensible(e)},deleteProperty(e,t){let n=typeof t==`symbol`?t.toString():t;if(Object.hasOwn(e,t)){let r=Object.prototype.propertyIsEnumerable.call(a.originalObject,t),i=Reflect.deleteProperty(e,t);return i&&(r?(a.assigned_[n]=!1,o(a)):(delete a.assigned_[n],a.modified=!0,c(a))),i}return!0}});return ui.set(d,a.copy_),{proxy:d,getChanges:()=>{if(!a.modified)return{};if(typeof a.copy_!=`object`||Array.isArray(a.copy_)||Object.keys(a.assigned_).length===0)return a.copy_;let e={},t=Object.keys(a.assigned_).some(e=>typeof a.copy_[e]==`object`||typeof a.originalObject[e]==`object`),n=new Map([[a.copy_,a.originalObject]]);for(let r in a.copy_){let i=a.copy_[r],o=a.originalObject[r];(a.assigned_[r]===!0||t&&!yi(i instanceof Set?Array.from(i):i,o instanceof Set?Array.from(o):o,n))&&di(e,r,a.copy_[r])}for(let t of Object.keys(a.assigned_))a.assigned_[t]===!1&&di(e,t,void 0);return e}}}function xi(e){let t=e.map(e=>bi(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Si(e,t){let{proxy:n,getChanges:r}=bi(e);return t(n),vi(r(),void 0,!0)}function Ci(e,t){let{proxies:n,getChanges:r}=xi(e);return t(n),vi(r(),void 0,!0)}function wi(e){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return!1;for(let t in e){let{value:n,get:r}=Object.getOwnPropertyDescriptor(e,t);if(r||typeof n==`object`&&n)return!1}return Object.getOwnPropertySymbols(e).length===0}function Ti(e,t,n){if(!e.every(wi))return;let r=e.map(e=>({...e}));return t(n?r:r[0]),r.map((t,n)=>{let r=e[n],i={},a=!1;for(let e in t){let n=t[e],o=r[e];(!Object.hasOwn(r,e)||!(n===o||Object.is(n,o)||typeof o==`object`&&o&&yi(n,o)))&&(di(i,e,n),typeof n==`object`&&n&&(a=!0))}for(let e in r)Object.hasOwn(t,e)||di(i,e,void 0);return a?vi(i,void 0,!0):i})}var Ei=new WeakMap;function Di(e){let t=Ei.get(e);if(t)return Ei.delete(e),Promise.allSettled(t).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason})}var Oi=new class{constructor(){this.transactions=[],this.bm=[],this.sequenceNumber=0}createTransaction(e){let t=new Ri(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.bm.at(-1)}getActiveTransactionForCollection(){let e=this.getActiveTransaction();if(e)return e;if(this!==Oi)return Oi.eJ(this)}eJ(e){let t=this.getActiveTransaction();if(!t)return;let n=ji(t);if(n===e)return t;if(n!==this)throw Error(k(162));return this.removeTransaction(t),e.transactions.push(t),e.bm.push(t),t.sequenceNumber=e.sequenceNumber++,ki.set(t,e),t}registerTransaction(e){fr.clear(e.id),this.bm.push(e)}unregisterTransaction(e,t=!1){try{fr.flush(e.id)}finally{t||this.clearTransactionContext(e)}}clearTransactionContext(e){let t=this.bm.lastIndexOf(e);t!==-1&&this.bm.splice(t,1)}removeTransaction(e){let t=this.transactions.indexOf(e);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){let n=[];for(let r of[...this.transactions])if(r!==e&&r.state===`pending`&&r.mutations.some(e=>t.has(e.globalKey)))try{r.rollback({isSecondaryRollback:!0})}catch(e){n.push(e)}if(n.length>0)throw n[0]}clear(){let e=new Set([...this.transactions.map(e=>e.id),...this.bm.map(e=>e.id)]);for(let t of e)fr.clear(t);this.transactions=[],this.bm=[]}},ki=new WeakMap,Ai=new WeakMap;function ji(e){let t=ki.get(e);if(!t)throw Error(k(163));return t}function Mi(e){let t=Ai.get(e);if(!t)throw Error(k(164));return t}function Ni(e,t){switch(t.type){case`update`:{if(e.type===`delete`)break;let n=e.type===`insert`;return{...n?e:t,original:n?{}:e.original,modified:t.modified,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt}}case`delete`:return e.type===`insert`?null:t;case`insert`:{if(e.type===`insert`)return t;if(e.type!==`delete`)break;let n=e.collection._state.syncedData.get(e.key);if(n===void 0)return t;if(mt(n,t.modified))return null;let r=t.modified,i=new Set([...Object.keys(n),...Object.keys(r)]),a={};for(let e of i)(Object.hasOwn(n,e)!==Object.hasOwn(r,e)||!mt(n[e],r[e]))&&(a[e]=r[e]);return{...t,type:`update`,original:n,changes:a,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}}}}let n=`${e.type}-${t.type}`;throw Error(k(165,{combination:n}))}function Pi(e){return Oi.createTransaction(e)}function Fi(){return Oi.getActiveTransaction()}var Ii=new WeakMap;function Li(e){return Ii.get(e)}var Ri=class{constructor(e,t,n){if(this.collections=new Set,e.mutationFn===void 0)throw new Ue;this.id=e.id??z(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[];let r=Er();Ii.set(this,r),r.promise.catch(()=>void 0),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},ki.set(this,t),Ai.set(this,t)}when(e){return Li(this).promise}completeWithoutCommit(){if(this.state!==`pending`)throw new qe;this.setState(`completed`),Li(this).resolve(this)}setState(e){this.state=e,(e===`completed`||e===`failed`)&&ji(this).removeTransaction(this)}mutate(e){if(this.state!==`pending`)throw new We;let t=ji(this),n=new Set([t,Mi(this)]);for(let e of n)e.registerTransaction(this);let r,i=this.gq;this.gq=()=>{i?.(),r??=[...this.mutations]};let a=!1;try{e()}catch(e){let t=r??this.mutations,i=new Set([...t,...this.mutations].map(e=>e.collection));r&&this.mutations.splice(0,this.mutations.length,...r),n.add(ji(this));for(let e of n)e.clearTransactionContext(this);a=!0;let o=[];for(let e of i)try{e._state.onTransactionStateChange()}catch(e){o.push(e)}throw o.length?AggregateError([e,...o],k(174),{cause:e}):e}finally{this.gq=i,n.add(ji(this));for(let e of n)e.unregisterTransaction(this,a)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){this.gq?.();let t=new Map;for(let e of this.mutations)t.set(e.globalKey,e);for(let n of e){let e=n.globalKey,r=t.get(e),i=r?Ni(r,n):n;i===null?t.delete(e):t.set(e,i)}this.mutations.length=0;for(let e of t.values())this.mutations.push(e)}rollback(e){let t=e?.isSecondaryRollback??!1;if(this.state===`completed`)throw new Ge;if(this.state===`failed`)return this;e?.error&&(this.error={message:e.error.message,error:e.error});let n=this.state===`persisting`;this.setState(`failed`);try{if(!t){let e=new Set(this.mutations.map(e=>e.globalKey));ji(this).rollbackConflictingTransactions(this,e)}}finally{Li(this).reject(this.error?.error),this.touchCollection(n)}return this}touchCollection(e=!1){let t=new Set(this.collections);for(let e of this.mutations)t.add(e.collection);(this.state===`completed`||this.state===`failed`)&&this.collections.clear();let n=[];for(let r of t)try{r._state.onTransactionStateChange(),e&&r._lifecycle.startGCTimer(!0),r._state.pendingSyncedTransactions.length>0&&r._state.commitPendingTransactions()}catch(e){n.push(e)}if(n.length>0)throw n[0]}async commit(){if(this.state!==`pending`)throw new qe;if(this.setState(`persisting`),this.mutations.length>0){try{await this.mutationFn({transaction:this});let e=Di(this);e&&await e}catch(e){if(this.state!==`persisting`)return this;let t=Tr(e);try{await Di(this)}catch{}this.error={message:t.message,error:t};try{this.rollback()}catch{}throw t}if(this.state!==`persisting`)return this}this.setState(`completed`);try{this.touchCollection(!0)}finally{Li(this).resolve(this)}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return t===0?this.sequenceNumber-e.sequenceNumber:t}},zi,Bi=0;function Vi(){return zi??=z(),`${zi}-${++Bi}`}var Hi=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=this.getActiveTransaction();if(!r&&!this.config.onInsert)throw new ze;let i=Array.isArray(e)?e:[e],a=new Date,o=[],s=new Set;i.forEach(e=>{let n=this.validateData(e,`insert`),r=this.config.getKey(n);if(s.has(r))throw new Ae(r);s.add(r);let i=this.generateGlobalKey(r,e),c={mutationId:Vi(),original:{},modified:n,changes:Object.fromEntries(Object.keys(e).map(e=>[e,n[e]])),globalKey:i,key:r,metadata:t?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:t?.optimistic??!0,type:`insert`,createdAt:a,updatedAt:a,collection:this.collection};o.push(c)});let c=o.find(({key:e})=>n.has(e));if(c||(this.collection._sync.startSync(),c=o.find(({key:e})=>n.has(e)),c))throw new Ae(c.key);return r?(this.bX(r,o),r):this.cn(`insert`,e=>this.config.onInsert(e),o)},this.delete=(e,t)=>{let n=this.state;this.lifecycle.validateCollectionUsable(`delete`);let r=this.getActiveTransaction();if(!r&&!this.config.onDelete)throw new Ve;if(Array.isArray(e)&&e.length===0)throw new Ie;let i=Array.isArray(e)?e:[e];this.collection._sync.startSync();let a=new Date,o=[];for(let e of i){if(!this.state.has(e))throw new Le(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:Vi(),original:this.state.get(e),modified:this.state.get(e),changes:this.state.get(e),globalKey:r,key:e,metadata:t?.metadata,syncMetadata:n.syncedMetadata.get(e)||{},optimistic:t?.optimistic??!0,type:`delete`,createdAt:a,updatedAt:a,collection:this.collection};o.push(i)}return r?(this.bX(r,o),r):this.cn(`delete`,e=>this.config.onDelete(e),o)},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.fR=e}getActiveTransaction(){return this.fR?this.fR.getActiveTransactionForCollection():Fi()}createTransaction(e){return this.fR?this.fR.createTransaction(e):Pi(e)}eX(e){if(e&&`~standard`in e)return e;throw new ve}validateData(e,t,n){if(!this.config.schema)return e;let r=this.eX(this.config.schema);if(t===`update`&&n){let i=this.state.get(n);if(i&&e&&typeof e==`object`&&typeof i==`object`){let n={...i,...e},a=r[`~standard`].validate(n);if(a instanceof Promise)throw new ye;if(`issues`in a&&a.issues)throw new he(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let o=a.value,s=Object.keys(e);return Object.fromEntries(s.map(e=>[e,o[e]]))}}let i=r[`~standard`].validate(e);if(i instanceof Promise)throw new ye;if(`issues`in i&&i.issues)throw new he(t,i.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return i.value}generateGlobalKey(e,t){return xt(e,t),`KEY::${JSON.stringify([this.id,typeof e,String(e)])}`}f7(e,t){let n=this.state.localOnlyDirectWrite;if(!n?.types.has(t))return;for(let e of this.state.transactions.values())if(e.state===`pending`||e.state===`persisting`)return;let r=this.createTransaction({autoCommit:!1,mutationFn:()=>Promise.resolve()});r.applyMutations(e);try{n.write(e)}finally{r.completeWithoutCommit()}return r}bX(e,t){this.state.trackTransaction(e),e.applyMutations(t),this.state.recomputeOptimisticState(!0)}cn(e,t,n){let r=this.f7(n,e);if(r)return r;let i=this.createTransaction({mutationFn:async e=>await t({transaction:e.transaction,collection:this.collection})});try{this.bX(i,n)}catch(e){try{i.rollback({isSecondaryRollback:!0,error:Tr(e)})}catch{}throw e}return i.commit().catch(()=>void 0),i}update(e,t,n){if(e===void 0)throw new Me;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=this.getActiveTransaction();if(!i&&!this.config.onUpdate)throw new Be;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new Ne;let s=typeof t==`function`?t:n;if(typeof s!=`function`)throw TypeError();let c=typeof t==`function`?{}:t;this.collection._sync.startSync();let l=o.map(e=>{let t=this.state.get(e);if(!t)throw new Pe(e);return t}),u=Ti(l,s,a)??(a?Ci(l,s):[Si(l[0],s)]),d=new Date,f=o.map((e,t)=>{let n=u[t];if(!n||Object.keys(n).length===0)return null;let i=l[t],a=this.validateData(n,`update`,e),o={...i,...a},s=this.config.getKey(i),f=this.config.getKey(o);if(s!==f)throw new Fe(s,f);let p=this.generateGlobalKey(f,o);return{mutationId:Vi(),original:i,modified:o,changes:a===n?n:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),globalKey:p,key:e,metadata:c.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:`update`,createdAt:d,updatedAt:d,collection:this.collection}}).filter(Boolean);if(f.length===0){let e=this.createTransaction({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),e}return i?(this.bX(i,f),i):this.cn(`update`,e=>this.config.onUpdate(e),f)}},Ui=class extends br{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:t,status:e},n),!n())return;let r=`status:${e}`;this.emitInnerWhile(r,{type:r,collection:this.collection,previousStatus:t,status:e},n)}emitHealthChange(){this.emit(`health:change`,{type:`health:change`,collection:this.collection})}emitSubscribersChange(e,t){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:e})}emitIndexRemoved(e){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:e})}cleanup(){this.clearListeners()}},Wi=new WeakMap;function Gi(e,{alias:t,id:n,kind:r}={alias:`root`},i=e){let a=ft(e),o=a?.healthSources()??[],{failureReason:s,error:c}=e._lifecycle.problems,l=o.map(t=>Gi(t.collection,t,e));return Ki(i,n,{alias:t,collectionId:e.id,kind:r??(a?`live-query`:`source`),status:e.status,failureReason:s,error:c,reloading:e._lifecycle.reloading,sources:l})}function Ki(e,t,n){let{failureReason:r,error:i,sources:a}=n;return qi(e,t??n.alias,{...n,hasErrors:r!==null||i!==null||a.some(e=>e.hasErrors)})}function qi(e,t,n){let r=Wi.get(e);r||Wi.set(e,r=new Map);let i=r.get(t);return i&&Ji(i,n)?i:(r.set(t,n),n)}function Ji(e,t){return e.collectionId===t.collectionId&&e.kind===t.kind&&e.status===t.status&&e.hasErrors===t.hasErrors&&e.failureReason===t.failureReason&&e.error===t.error&&e.reloading===t.reloading&&e.sources.length===t.sources.length&&e.sources.every((e,n)=>e===t.sources[n])}var Yi=Symbol.for(`@tanstack/db.collectionSyncConfig.factory`),Xi=Symbol.for(`@tanstack/db.collectionSyncConfig.cleanup`);function Zi(e,t){return Object.defineProperty(e,Yi,{value:t,enumerable:!0}),e}function Qi(e,t,n){let r=e[Yi];if(!r)return{sync:e,utilities:t};let i=Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t));return{sync:r(e,i,n),utilities:i}}function $i(e){let t=e[Xi];t?.()}function ea(e){let t=e[me];return ta(e,t?.())}function ta(e,t){try{return new na(e)}catch(e){throw t?.(),e}}var na=class{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this.cS.insert(e,t),this.delete=(e,t)=>this.cS.delete(e,t),!e)throw new ge;if(!e.sync)throw new _e;this.id=e.id?e.id:z();let{sync:t,utilities:n}=Qi(e.sync,e.utils??{},()=>{this._lifecycle.status===`idle`&&this._sync.startSync()});if(this.config={...e,sync:t,autoIndex:e.autoIndex??`off`,utils:n},this.utils=n,this.config.autoIndex===`eager`&&!e.defaultIndexType)throw new V(k(206));fe(this),this.cC=new Mr,this.a3=new Ui,this.dd=new li,this._lifecycle=new Br(this.config,this.id,()=>$i(this.config.sync)),this.cS=new Hi(this.config,this.id),this._state=new dr(this.config),this._sync=new Xr(this.config,this.id),this.eS=ra(e),this.cC.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this.a3,state:this._state}),this.a3.setDeps({collection:this}),this.dd.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this.a3}),this._lifecycle.setDeps({changes:this.cC,events:this.a3,indexes:this.dd,state:this._state,sync:this._sync}),this.cS.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this.cC,indexes:this.dd,events:this.a3}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this.a3}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get health(){return Gi(this)}_emitHealthChange(){this.a3.emitHealthChange()}get subscriberCount(){return this.cC.acquiringSubscribersCount}get _stateRevision(){return this.cC.stateRevision}get _layoutRevision(){return this.cC.layoutRevision}_subscribeLayoutChanges(e){return this.cC.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this.cC.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_onCleanupStart(e){return this._lifecycle.onCleanupStart(e)}_setTransactionScope(e){this.cS.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}preload(){return this.gz(()=>this._sync.preload())}gz(e){try{this._markPreload()}catch(e){return Promise.reject(e)}return e()}_markPreload(){this.cC.markSubscriberOrPreload()}_hasSubscriberOrPreload(){return this.cC.hasSubscriberOrPreload()}_onFirstSubscriberOrPreload(e){return this.cC.onFirstSubscriberOrPreload(e)}get base(){return this._state.syncedData}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}_optimisticOverlaySize(){return this._state.optimisticDeletes.size+this._state.optimisticUpserts.size}_hasOptimisticOverlay(e){return this._state.optimisticDeletes.has(e)||this._state.optimisticUpserts.has(e)}_hasHeldSyncTransaction(){return this._state.hasHeldSyncTransaction()}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this.dd.createIndex(e,t)}removeIndex(e){return this.dd.removeIndex(e)}getIndexMetadata(){return this.dd.getIndexMetadataSnapshot()}get indexes(){return this.dd.indexes}validateData(e,t,n){return this.cS.validateData(e,t,n)}get compareOptions(){return{...this.eS}}update(e,t,n){return this.cS.update(e,t,n)}get state(){let e=new Map;for(let[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return rr(this,e,e=>this._state.entriesPassing(e))}subscribeChanges(e,t={}){return this.cC.subscribeChanges(t=>e(t),t)}on(e,t){return this.a3.on(e,t)}once(e,t){return this.a3.once(e,t)}off(e,t){this.a3.off(e,t)}waitFor(e,t){return this.a3.waitFor(e,t)}reload(){let e=dt(this.config);return e?e.reload(this):this._sync.reload()}get subscribers(){let e=new Set;for(let t of this.cC.changeSubscriptions)e.add(t.owner??{kind:`subscription`,active:!0,end:()=>(t.unsubscribe(),Promise.resolve())});return[...e]}cleanup(e){let t=this.subscribers.filter(e=>e.kind!==`subscription`);if(!e?.dependents){let e=t.filter(e=>e.active);return e.length>0?Promise.reject(new xe(this.id,e.length)):this._lifecycle.cleanup()}let n=t.map(async e=>e.end());return Promise.allSettled([this._lifecycle.cleanup(),...n]).then(e=>{for(let t of e)if(t.status===`rejected`)throw t.reason})}};function ra(e){let t=e.defaultStringCollation;return t?t.stringSort===`lexical`?{stringSort:`lexical`}:t.stringSort===`custom`?{stringSort:`custom`,compare:t.compare}:{stringSort:`locale`,...`locale`in t&&t.locale!==void 0&&{locale:t.locale},...`localeOptions`in t&&t.localeOptions!==void 0&&{localeOptions:t.localeOptions}}:{stringSort:`locale`}}function ia(e){if(e.where===void 0&&!e.orderBy?.length&&e.limit===void 0&&(e.offset===void 0||e.offset===0)&&e.cursor===void 0)return;let t=new WeakSet,n={type:`loadSubsetDemand`,query:ua(e,`loadSubset`,t)};if(e.limit!==void 0&&(n.limit=J(e.limit,`loadSubset.limit`,t)),e.offset!==void 0&&e.offset!==0&&(n.offset=J(e.offset,`loadSubset.offset`,t)),e.cursor!==void 0){let r={whereFrom:q(e.cursor.whereFrom,`loadSubset.cursor.whereFrom`,t,`exact-output`),whereCurrent:q(e.cursor.whereCurrent,`loadSubset.cursor.whereCurrent`,t,`exact-output`)};e.cursor.lastKey!==void 0&&(r.lastKey=J(e.cursor.lastKey,`loadSubset.cursor.lastKey`,t)),n.cursor=r}return JSON.stringify(n)}function aa(e,t){let n=new Map,r=new Map,i=e=>{e.type===`unionFrom`?e.sources.forEach(i):e.type!==`unionAll`&&(n.has(e.alias)||n.set(e.alias,n.size),r.set(e.bindingId,n.get(e.alias)))};return i(e.from),e.join?.forEach(({from:e})=>i(e)),{bindings:n,bindingIds:r,hasUnqualifiedOutput:e.from.type===`unionAll`,parent:t}}function oa(e,t,n){let r=e,i=0;for(;r;){let e=n===void 0?r.bindings.get(t):r.bindingIds.get(n);if(e!==void 0)return[i,e];if(r.hasUnqualifiedOutput)return;r=r.parent,i++}}function sa(e,t,n,r){return ca(e,t,n,aa(e,r))}function ca(e,t,n,r){if(e.fnSelect)throw new ct(`${t}.fnSelect`,`function select`);if(e.fnWhere?.length)throw new ct(`${t}.fnWhere`,`function where`);if(e.fnHaving?.length)throw new ct(`${t}.fnHaving`,`function having`);let i={type:`query`,from:fa(e.from,`${t}.from`,n,r)};return e.select&&(i.select=pa(e.select,`${t}.select`,n,r)),!e.select&&(e.from.type===`unionFrom`||e.join!==void 0||e.groupBy!==void 0)&&(i.implicitOutput={type:`namespaced`,aliases:Array.from(r.bindings.keys())}),e.join&&(i.join=e.join.map((e,i)=>da(e,`${t}.join[${i}]`,n,r))),e.where&&(i.where=la(e.where,`${t}.where`,n,r)),e.grouping&&(i.grouping=!0),e.groupBy&&(i.groupBy=e.groupBy.map((e,i)=>q(e,`${t}.groupBy[${i}]`,n,`exact-output`,r))),e.having&&(i.having=la(e.having,`${t}.having`,n,r)),e.orderBy&&(i.orderBy=e.orderBy.map((e,i)=>ga(e,`${t}.orderBy[${i}]`,n,`ordering-operand`,r))),e.limit!==void 0&&(i.limit=J(e.limit,`${t}.limit`,n)),e.offset!==void 0&&e.offset!==0&&(i.offset=J(e.offset,`${t}.offset`,n)),e.distinct&&(i.distinct=!0),e.singleResult&&(i.singleResult=!0),i}function la(e,t,n,r){let i=e.map((e,i)=>ha(e,`${t}[${i}]`,n,r));return i.sort(Ta),i.filter((e,t)=>t===0||Ta(e,i[t-1])!==0)}function ua(e,t,n){let r={type:`loadSubsetQuery`};return e.where!==void 0&&(r.where=q(e.where,`${t}.where`,n,`exact-output`)),e.orderBy?.length&&(r.orderBy=e.orderBy.map((e,r)=>ga(e,`${t}.orderBy[${r}]`,n,`ordering-operand`))),r}function da(e,t,n,r){return{type:e.type,from:fa(e.from,`${t}.from`,n,r),on:q(e.on,`${t}.on`,n,`exact-output`,r)}}function fa(e,t,n,r){return e.type===`collectionRef`||e.type===`descriptorRef`?{type:`collectionRef`,collectionId:J(e.type===`descriptorRef`?e.descriptor.id:e.collection.id,`${t}.collection.id`,n)}:e.type===`unionFrom`?{type:`unionFrom`,sources:e.sources.map((e,i)=>fa(e,`${t}.sources[${i}]`,n,r))}:e.type===`unionAll`?{type:`unionAll`,queries:e.queries.map((e,i)=>sa(e,`${t}.queries[${i}]`,n,r.parent))}:{type:`queryRef`,query:sa(e.query,`${t}.query`,n,r)}}function pa(e,t,n,r){return{type:`select`,fields:Object.keys(e).sort().map(i=>[i,ma(e[i],`${t}.${i}`,n,r)])}}function ma(e,t,n,r){return ae(e)?q(K(e),t,n,`exact-output`,r):ka(e)?q(e,t,n,`exact-output`,r):qt(e)?pa(e,t,n,r):Sa(e,t,n)}function ha(e,t,n,r){if(Oa(e)){let i={type:`where`,expression:q(e.expression,`${t}.expression`,n,`exact-output`,r)};return e.residual===!0&&(i.residual=!0),i}return q(e,t,n,`exact-output`,r)}function ga(e,t,n,r=`exact-output`,i){return{expression:q(e.expression,`${t}.expression`,n,r,i),compareOptions:_a(e.compareOptions,`${t}.compareOptions`,n)}}function _a(e,t,n){return J(Et(e),t,n)}function q(e,t,n,r=`exact-output`,i){if(e.type===`ref`){let r=oe(e);if(r!==void 0){let a=oa(i,r,e.bindingId);return a===void 0?{type:`ref`,path:e.path.map((e,r)=>J(e,`${t}.path[${r}]`,n)),sourceAlias:J(r,`${t}.sourceAlias`,n)}:{type:`ref`,path:[[`binding`,...a],...M(e).map((e,r)=>J(e,`${t}.path[${r+1}]`,n))]}}let a=oa(i,e.path[0]??``,e.bindingId);return{type:`ref`,path:a===void 0?e.path.map((e,r)=>J(e,`${t}.path[${r}]`,n)):[[`binding`,...a],...e.path.slice(1).map((e,r)=>J(e,`${t}.path[${r+1}]`,n))]}}if(e.type===`val`)return{type:`val`,value:r===`equality-operand`?Ca(e.value,`${t}.value`,n,i):r===`ordering-operand`?wa(e.value,`${t}.value`,n):Sa(e.value,`${t}.value`,n)};if(e.type===`func`){if(e.name===`in`&&e.args.length===2&&e.args[1]?.type===`val`&&Array.isArray(e.args[1].value)){let r=e.args[1].value.map((e,r)=>Ca(e,`${t}.args[1].value[${r}]`,n,i));return va(e.name,[q(e.args[0],`${t}.args[0]`,n,`equality-operand`,i),{type:`val`,value:[`set`,ya(r)]}])}let r=e.name===`eq`?`equality-operand`:e.name===`gt`||e.name===`gte`||e.name===`lt`||e.name===`lte`?`ordering-operand`:`exact-output`,a=e.args.map((e,a)=>q(e,`${t}.args[${a}]`,n,r,i));return va(e.name,a)}if(e.type===`agg`)return{type:`agg`,...e.grouping?{}:{withoutOperator:!0},name:e.name,args:e.args.map((e,r)=>q(e,`${t}.args[${r}]`,n,`exact-output`,i))};if(e.type===`conditionalSelect`){let r={type:`conditionalSelect`,branches:e.branches.map((e,r)=>({condition:q(e.condition,`${t}.branches[${r}].condition`,n,`exact-output`,i),value:ma(e.value,`${t}.branches[${r}].value`,n,i)}))};return e.defaultValue!==void 0&&(r.defaultValue=ma(e.defaultValue,`${t}.defaultValue`,n,i)),r}let a=aa(e.query,i),o={type:`includesSubquery`,...e.runtime?{}:{withoutOperator:!0},query:ca(e.query,`${t}.query`,n,a),correlationField:q(e.correlationField,`${t}.correlationField`,n,`equality-operand`,i),childCorrelationField:q(e.childCorrelationField,`${t}.childCorrelationField`,n,`equality-operand`,a),fieldName:e.fieldName,materialization:e.materialization};return e.parentFilters&&(o.parentFilters=e.parentFilters.map((e,r)=>ha(e,`${t}.parentFilters[${r}]`,n,i))),e.parentProjection&&(o.parentProjection=e.parentProjection.map((e,r)=>q(e,`${t}.parentProjection[${r}]`,n,`exact-output`,i))),e.scalarField!==void 0&&(o.scalarField=e.scalarField),o}function va(e,t){return(e===`and`||e===`or`)&&t.length>0?{type:`func`,name:e,args:ya(t.flatMap(t=>ba(t,e)?t.args:[t]))}:e===`eq`&&t.length===2?(t.sort(Ta),{type:`func`,name:e,args:t}):(e===`gt`||e===`gte`||e===`lt`||e===`lte`)&&t.length===2&&Ta(t[0],t[1])>0?{type:`func`,name:xa(e),args:[t[1],t[0]]}:{type:`func`,name:e,args:t}}function ya(e){let t=e.map(e=>({key:JSON.stringify(e),value:e}));return t.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),t.filter((e,n)=>n===0||e.key!==t[n-1].key).map(e=>e.value)}function ba(e,t){return typeof e==`object`&&!!e&&!Array.isArray(e)&&e.type===`func`&&e.name===t&&Array.isArray(e.args)}function xa(e){switch(e){case`gt`:return`lt`;case`gte`:return`lte`;case`lt`:return`gt`;case`lte`:return`gte`}}function J(e,t,n){if(e===null)return[`null`];if(typeof e==`string`)return[`string`,e];if(typeof e==`boolean`)return[`boolean`,e];if(typeof e==`number`)return Number.isNaN(e)?[`number`,`NaN`]:e===1/0?[`number`,`Infinity`]:e===-1/0?[`number`,`-Infinity`]:Object.is(e,-0)?[`number`,`-0`]:[`number`,e];if(e===void 0)return[`undefined`];if(typeof e==`bigint`)return[`bigint`,e.toString()];if(typeof e==`function`)throw new ct(t,`function value`);if(typeof e==`symbol`)throw new ct(t,`symbol value`);if(ae(e))return q(K(e),t,n);if(Array.isArray(e))return Da(e,t,n,()=>[`array`,e.map((e,r)=>J(e,`${t}[${r}]`,n))]);if(e instanceof Date){let n=e.getTime();if(Number.isNaN(n))throw new ct(t,`invalid Date`);return[`Date`,e.toISOString()]}if(e instanceof ArrayBuffer)return[`binary`,`ArrayBuffer`,Array.from(new Uint8Array(e))];if(ArrayBuffer.isView(e))return[`binary`,e.constructor.name,Array.from(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))];if(e instanceof Map)return Da(e,t,n,()=>{let r=Array.from(e.entries(),([e,r],i)=>[J(e,`${t}.key[${i}]`,n),J(r,`${t}.value[${i}]`,n)]);return r.sort(Ta),[`Map`,r]});if(e instanceof Set)return Da(e,t,n,()=>{let r=Array.from(e,(e,r)=>J(e,`${t}[${r}]`,n));return r.sort(Ta),[`Set`,r]});if(qt(e))return Ea(e,t,n);throw new ct(t,`non-plain object value`)}function Sa(e,t,n){return typeof e==`object`&&e||typeof e==`function`||typeof e==`symbol`?Tt(e):J(e,t,n)}function Ca(e,t,n,r){if(ae(e))return q(K(e),t,n,`equality-operand`,r);if(typeof e==`number`&&Object.is(e,-0))return J(0,t,n);if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)return[`binary`,`Uint8Array`,Array.from(e)];let i=Rt(e);return i===e?typeof e==`object`&&e||typeof e==`function`||typeof e==`symbol`?Tt(e):J(e,t,n):J(i,t,n)}function wa(e,t,n){if(typeof e==`number`&&Object.is(e,-0))return J(0,t,n);if(e instanceof Date&&Number.isNaN(e.getTime()))return J(NaN,t,n);let r=Rt(e);if(r!==e&&!(e instanceof Uint8Array))return J(r,t,n);try{return J(e,t,n)}catch(t){if(t instanceof ct&&typeof e==`object`&&e)return Tt(e);throw t}}function Ta(e,t){let n=JSON.stringify(e),r=JSON.stringify(t);return n<r?-1:+(n>r)}function Ea(e,t,n){return Da(e,t,n,()=>[`object`,Object.keys(e).sort().map(r=>[r,J(e[r],`${t}.${r}`,n)])])}function Da(e,t,n,r){if(n.has(e))throw new ct(t,`circular value`);n.add(e);try{return r()}finally{n.delete(e)}}function Oa(e){return`expression`in e}function ka(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`agg`||t===`conditionalSelect`||t===`func`||t===`ref`||t===`val`||t===`includesSubquery`}var Aa=Symbol.for(`@tanstack/db.collectionConfig.factory`);function ja(e,t,n){return Object.defineProperty(e,Aa,{value:t,enumerable:!1}),n&&Object.defineProperty(e,me,{value:n,enumerable:!0}),e}var Ma=`@tanstack/db/sync-persistence`;function Na(e){return typeof e==`object`&&!!e}function Pa(e,t,n=t){if(typeof e[t]!=`function`)throw new H(`${n} must be a function`)}function Fa(e){if(e===null)return null;if(!Na(e))throw new H(`expected null or a complete capability object`);if(e.protocol!==`@tanstack/db/sync-persistence`)throw new H(`protocol must be "${Ma}"`);if(e.version!==1)throw new H(`version must be 1`);if(e.managedCacheGeneration!==void 0&&typeof e.managedCacheGeneration!=`boolean`)throw new H(`managedCacheGeneration must be a boolean`);if(e.startupCacheGenerationRotated!==void 0&&typeof e.startupCacheGenerationRotated!=`boolean`)throw new H(`startupCacheGenerationRotated must be a boolean`);Pa(e,`hydrateBaseline`),e.startScopedRecovery!==void 0&&Pa(e,`startScopedRecovery`),Pa(e,`reserveCommitTurn`),Pa(e,`scanPersistedRows`);let t=e.resumeSnapshot;if(!Na(t))throw new H(`resumeSnapshot must be an object`);return Pa(t,`certify`,`resumeSnapshot.certify`),Pa(t,`getKeySetEvidence`,`resumeSnapshot.getKeySetEvidence`),Pa(t,`expectCurrentCommit`,`resumeSnapshot.expectCurrentCommit`),e}var Ia={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},La=new class{#e=Ia;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Ra(e){setTimeout(e,0)}var za=typeof window>`u`||`Deno`in globalThis;function Ba(){}function Va(e,t){return typeof e==`function`?e(t):e}function Ha(e){return typeof e==`number`&&e>=0&&e!==1/0}function Ua(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Y(e,t){return typeof e==`function`?e(t):e}function Wa(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Ka(o,t.options))return!1}else if(!qa(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function Ga(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(X(t.options.mutationKey)!==X(a))return!1}else if(!qa(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ka(e,t){return(t?.queryKeyHashFn||X)(e)}function X(e){return JSON.stringify(e,(e,t)=>Qa(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function qa(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!qa(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!qa(e[r],t[r]))return!1;return!0}return!1}var Ja=Object.prototype.hasOwnProperty;function Ya(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Za(e)&&Za(t);if(!r&&!(Qa(e)&&Qa(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Ja.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Ya(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Xa(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Za(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Qa(e){if(!$a(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!$a(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function $a(e){return Object.prototype.toString.call(e)===`[object Object]`}function eo(e){return new Promise(t=>{La.setTimeout(t,e)})}function to(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Ya(e,t)}function no(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ro(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var io=Symbol();function ao(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===io?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function oo(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var so=()=>za,co=()=>so(),lo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},uo=new class extends lo{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},fo=Ra;function po(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=fo,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var mo=po(),ho=new class extends lo{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function go(e){return Math.min(1e3*2**e,3e4)}function _o(e){return(e??`online`)!==`online`||ho.isOnline()}var vo=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function yo(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Ba);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new vo(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>uo.isFocused()&&(e.networkMode===`always`||ho.isOnline())&&e.canRun(),p=()=>_o(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(co()?0:3),a=e.retryDelay??go,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?h(r):(n++,e.onFail?.(n,r),eo(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var bo=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ha(this.gcTime)&&(this.#e=La.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(co()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(La.clearTimeout(this.#e),this.#e=void 0)}};function xo(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{oo(e,()=>t.signal,()=>n=!0)},u=ao(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?ro:no;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Co:So,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:So(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function So(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Co(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var wo=class extends bo{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Do(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Do(this.options);e.data!==void 0&&(this.setState(Eo(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=to(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Ba).catch(Ba):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(e=>Y(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===io||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Y(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Ua(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=ao(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?xo(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=yo({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof vo&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof vo){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...To(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Eo(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),mo.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function To(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_o(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Eo(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Do(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Oo=class extends lo{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ao(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return jo(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return jo(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Y(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Xa(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Mo(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||Y(this.options.enabled,this.#t)!==Y(t.enabled,this.#t)||Y(this.options.staleTime,this.#t)!==Y(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Y(this.options.enabled,this.#t)!==Y(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Xa(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Ba)),t}#h(e){return!co()&&Y(this.options.enabled,this.#t)!==!1&&Ha(e)}#g(){this.#b();let e=Y(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=Ua(this.#r.dataUpdatedAt,e)+1;this.#u=La.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return Y(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=La.setInterval(()=>{(this.options.refetchIntervalInBackground||uo.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(La.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(La.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Ao(e,t),o=i&&Mo(e,n,t,r);(a||o)&&(l={...l,...To(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=to(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=to(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:No(e,t),refetch:this.refetch,isEnabled:Y(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),Xa(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();mo.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function ko(e,t){return Y(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Y(t.retryOnMount,e)!==!1)}function Ao(e,t){return ko(e,t)||e.state.data!==void 0&&jo(e,t,t.refetchOnMount)}function jo(e,t,n){if(Y(t.enabled,e)!==!1&&Y(t.staleTime,e)!==`static`){let r=Y(n,e);return r===`always`||r!==!1&&No(e,t)}return!1}function Mo(e,t,n,r){return(e!==t||Y(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&No(e,n)}function No(e,t){return Y(t.enabled,e)!==!1&&e.isStaleByTime(Y(t.staleTime,e))}var Po=class extends bo{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Fo(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=yo({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),mo.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Fo(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Io=class extends lo{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Po({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Lo(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Lo(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Lo(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Lo(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){mo.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Ga(t,e))}findAll(e={}){return this.getAll().filter(t=>Ga(e,t))}notify(e){mo.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return mo.batch(()=>Promise.all(e.map(e=>e.continue().catch(Ba))))}};function Lo(e){return e.options.scope?.id}var Ro=class extends lo{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??Ka(r,t),a=this.get(i);return a||(a=new wo({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){mo.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Wa(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Wa(e,t)):t}notify(e){mo.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){mo.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){mo.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},zo=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Ro,this.#t=e.mutationCache||new Io,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=uo.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ho.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Y(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Va(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return mo.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;mo.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return mo.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=mo.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Ba).catch(Ba)}invalidateQueries(e,t={}){return mo.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=mo.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Ba)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Ba)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(Y(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(Y(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Ba).catch(Ba)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Ba).catch(Ba)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return ho.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(X(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{qa(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(X(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{qa(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=Ka(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===io&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Bo=class extends B{constructor(e){super(e),this.name=`QueryCollectionError`}},Vo=class extends Bo{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},Ho=class extends Bo{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},Uo=class extends Bo{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},Wo=class extends Bo{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},Go=class extends Bo{constructor(){super(`[QueryCollection] initialData and initialDataUpdatedAt are only supported when syncMode is 'eager'. Seed or hydrate the exact Query cache key for on-demand subsets instead.`),this.name=`InitialDataInOnDemandModeError`}},Ko=class extends Bo{constructor(e){super(e),this.name=`InvalidQueryResultError`}},qo=class extends Bo{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},Jo=class extends Bo{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},Yo=class extends Bo{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},Xo=class extends Bo{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},Zo=new WeakMap,Qo=new WeakSet;function $o(e,t){let n=Array.isArray(e)?e:[e],r=[];for(let e of n)if(e.type===`delete`){let t=Array.isArray(e.key)?e.key:[e.key];for(let e of t)r.push({type:`delete`,key:e})}else{let n=Array.isArray(e.data)?e.data:[e.data];for(let i of n){let n;if(e.type===`update`)n=t.getKey(i);else{let r=t.collection.validateData(i,e.type===`upsert`?`insert`:e.type);n=t.getKey(r)}r.push({type:e.type,key:n,data:i})}}return r}function es(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new Jo(r.key);if(n.add(r.key),r.type===`insert`){if(t.collection._state.getAcceptedSyncedRow(r.key))throw new je(r.key,t.collection.id)}else if(r.type===`update`){if(!t.collection._state.getAcceptedSyncedRow(r.key))throw new Yo(r.key)}else if(r.type===`delete`&&!t.collection._state.getAcceptedSyncedRow(r.key))throw new Xo(r.key)}}function ts(e,t,n){let r;try{r=$o(e,t)}catch(e){return Promise.reject(e)}let i=t.reserveDirectWrite?.()??0,a=t.earlierCommits?.();if(!a)try{return ns(r,t,i)}catch(e){return Promise.reject(e)}let o=a.then(()=>{if(!n())throw new at;return ns(r,t,i)});return t.noteWaitingDirectWrite?.(o.then(()=>void 0,()=>void 0)),o}function ns(e,t,n){es(e,t),t.claimDirectWriteKeys?.(e.map(e=>e.key),n),t.begin();for(let n of e)switch(n.type){case`insert`:{let e=t.collection.validateData(n.data,`insert`);t.write({type:`insert`,value:e});break}case`update`:{let e={...t.collection._state.getAcceptedSyncedRow(n.key),...n.data},r=t.collection.validateData(e,`update`,n.key);t.write({type:`update`,value:r});break}case`delete`:{let e=t.collection._state.getAcceptedSyncedRow(n.key);t.write({type:`delete`,value:e});break}case`upsert`:{let e=t.collection._state.getAcceptedSyncedRow(n.key)!==void 0,r=t.collection.validateData(n.data,e?`update`:`insert`,n.key);e?t.write({type:`update`,value:r}):t.write({type:`insert`,value:r});break}}let r=qr(t.commit()),i=()=>{let r=e=>e?e.map(e=>t.collection._state.getAcceptedSyncedRow(e)).filter(e=>e!==void 0):Array.from(t.collection._state.acceptedSyncedEntries(),([,e])=>e);t.updateCacheData?t.updateCacheData(r,e.map(e=>e.key),n):t.queryClient.setQueryData(t.queryKey,r())};r===!0&&i();let a=Promise.resolve(r).then(()=>{r!==!0&&i()});return a.catch(()=>void 0),a}function rs(e){function t(){let t=e();if(!t)throw new qo;return t}function n(n){let r=t(),i=Zo.get(r);if(i)return i.operations.push(n),i.completion;let a=ts(n,r,()=>e()===r);return Qo.add(a),a}return{writeInsert(e){return n({type:`insert`,data:e})},writeUpdate(e){return n({type:`update`,data:e})},writeDelete(e){return n({type:`delete`,key:e})},writeUpsert(e){return n({type:`upsert`,data:e})},writeBatch(n){let r=t();if(Zo.get(r))throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let i,a,o=new Promise((e,t)=>{i=e,a=t});Qo.add(o),o.catch(()=>void 0);let s={operations:[],completion:o};Zo.set(r,s);try{let t=n();if(typeof t==`object`&&t&&`then`in t&&typeof t.then==`function`&&!Qo.has(t))throw Promise.resolve(t).catch(()=>void 0),Error(`writeBatch does not support async callbacks. The callback must be synchronous.`);return Zo.delete(r),i(s.operations.length>0?ts(s.operations,r,()=>e()===r):Promise.resolve()),o}catch(e){throw a(e),e}finally{Zo.get(r)===s&&Zo.delete(r)}}}}function is(e,t){let n;try{n=e?.()}catch(e){try{t()}catch(t){throw os(e,t)}throw e}try{t()}catch(e){if(!as(n))throw e;return Promise.resolve(n).then(()=>{throw e},t=>{throw os(t,e)})}return as(n)?Promise.resolve(n):void 0}function as(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function os(e,t){return AggregateError([e,t],`Adapter cleanup and local teardown both failed`,{cause:e})}function ss(e){return typeof e==`object`&&!!e}var cs=[`enabled`,`refetchInterval`,`retry`,`retryDelay`,`staleTime`,`gcTime`,`refetchOnWindowFocus`,`refetchOnReconnect`,`refetchOnMount`,`networkMode`];function ls(e){let t={};for(let n of cs)e[n]!==void 0&&(t[n]=e[n]);return t}var us=`queryCollection:gc:`,ds=0,fs=new WeakMap,Z=new WeakMap,ps=new WeakMap,ms=new WeakMap,hs=new WeakMap,gs=new WeakMap,_s=new WeakMap,vs=class{constructor(e,t,n){this.state=e,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}get isFetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isFetching)}get isRefetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isRefetching)}get isLoading(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isLoading)}get dataUpdatedAt(){return Math.max(0,...Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().dataUpdatedAt))}get fetchStatus(){let e=`idle`;for(let t of this.state.observers.values()){let n=t.getCurrentResult().fetchStatus;if(n===`fetching`)return`fetching`;n===`paused`&&(e=`paused`)}return e}};function ys(e){let{queryKey:t,queryFn:n,select:r,queryClient:i,enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:f,refetchOnMount:p,networkMode:m,initialData:h,initialDataUpdatedAt:g,persistedGcTime:_,getKey:v,onInsert:y,onUpdate:b,onDelete:x,meta:S,...C}=e,w=C.syncMode??`eager`;if(w===`on-demand`&&(h!==void 0||g!==void 0))throw new Go;let T=w===`eager`?{...h!==void 0&&{initialData:h},...g!==void 0&&{initialDataUpdatedAt:g},placeholderData:void 0}:{initialData:()=>void 0,initialDataUpdatedAt:void 0,placeholderData:void 0},E=typeof t==`function`?t({}):t,ee=w===`on-demand`&&typeof t!=`function`?E:void 0,D=ee&&X(ee),te=e=>{typeof t==`function`&&(e.length>=E.length&&E.every((t,n)=>mt(t,e[n]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(E)}, Got: ${JSON.stringify(e)}. This can cause stale cache issues.`))};if(!t)throw new Vo;if(!n)throw new Ho;if(!i)throw new Uo;if(!v)throw new Wo;let O={observers:new Map},k=0,ne=new WeakMap,re=new WeakMap,ie=new WeakSet,ae={},A,j=new WeakMap,oe,M=0,N=!1,P=(e,t)=>{if(A.add(e),t!==void 0){let n=j.get(e)??new Set;n.add(t),j.set(e,n)}},se=(e,t)=>{ie.add(e),P(e,t);let n=gs.get(e)??new Set;n.add(ae),gs.set(e,n)},ce=e=>j.get(e)??new Set([X(e.queryKey)]),F=(e,t,n)=>{let r=re.get(e)??new Map;re.set(e,r);let i=r.get(t)??new Map;r.set(t,i);let a=i.get(n)??{};return i.set(n,a),a},le=(e,t)=>ne.get(t)?.get(e),I=(e,t,n)=>{let r=ne.get(t)??new Map;r.set(e,n),ne.set(t,r)},ue=(e,t)=>{for(let n of ce(e)){let r=O.observers.get(n);if(!r||r.getCurrentQuery()!==e)continue;let i=r.getCurrentResult(),a=F(e,t,n);a.result=i;let o=le(n,i);o&&(a.settlement=o)}},de=(e,t)=>{let n=re.get(e)?.get(t);if(n)for(let[e,t]of n){if(!t.result)continue;let n=le(e,t.result);n&&(t.settlement=n)}},L=(e,t)=>{let n=re.get(e);if(n){for(let e of t)n.delete(e);n.size===0&&re.delete(e)}},fe=e=>oe===void 0||(ps.get(e)??0)>oe,pe=new Map,R=new Map,z=new WeakSet,me=e=>{let t=R.get(e);return t!==void 0&&!z.has(t)},B=new Map,he=new Map,V=new Map,H=0,ge=new Map,_e=new Map,ve=0,ye=new WeakSet,be=new WeakMap,U=new Map,xe=(e,t)=>{let n=Z.get(e)??U.get(t);e.state.fetchStatus===`fetching`&&(n??H)<H&&e.cancel({silent:!0})},Se=new Map,Ce=new Map,we,Te=!1,Ee=new WeakMap,De=0,Oe=new Map,ke=new Map,Ae=()=>{},je=(e,t)=>!1,Me=e=>void 0,Ne,Pe=(e,t)=>{let n=B.get(e)||new Set;n.add(t),B.set(e,n);let r=R.get(t)||new Set;r.add(e),R.set(t,r)},Fe=(e,t)=>{t.size===0?B.delete(e):(B.set(e,new Set(t)),t.forEach(t=>{let n=R.get(t)||new Set;n.add(e),R.set(t,n)}))},Ie=(e,t)=>{let n=B.get(e);return n?.delete(t),n?.size||B.delete(e),R.get(t)?.delete(e),!n?.size},Le=e=>{let t=new Map;R.get(e)?.forEach(n=>{let r=new Set(B.get(n));r.delete(e),t.set(n,r),r.size===0?B.delete(n):B.set(n,r)});let n=new Set;return z.add(n),R.set(e,n),t},Re=e=>{let h={};Ne=h,Se.clear(),oe=void 0,N=!1,A=new Set(i.getQueryCache().findAll({queryKey:E}));for(let e of A)e.state.fetchStatus===`fetching`&&U.set(X(e.queryKey),Z.get(e)??U.get(X(e.queryKey))??H);let{begin:g,write:y,commit:b,markReady:x,fail:C,reportError:k,reportHealthy:ne,invalidateLoadedSubsets:j,collection:F,metadata:z}=e,Re=!1,ze=!1,Ve=()=>{Re||ze||(Re=!0,x())},He=e=>!Re&&(ze=!0,C(e),!0),We=new WeakMap,Ge=new Map,Ke,qe=(e,t,n)=>{let r=e.meta?.loadSubsetOptions;if(w!==`on-demand`||!ss(r)||!r.orderBy?.length)return;let i=We.get(e),{where:a,orderBy:o}=r,s={readKey:i?.readKey??ia({where:a,orderBy:o}),leadingValue:i?.leadingValue??an(o[0].expression),compare:i?.compare??jt(o[0].compareOptions),keys:JSON.stringify(n.map(e=>JSON.stringify(v(e))).sort()),last:void 0};for(let e of n){let t=s.leadingValue(e);(s.last===void 0||s.compare(t,s.last.value)>0)&&(s.last={value:t})}if(We.set(e,s),Ke!==void 0||Ge.has(t)||i?.last===void 0||i.keys===s.keys)return;let c=i.last.value;(s.last===void 0||s.compare(s.last.value,c)<0||[...O.observers.values()].some(e=>{let t=We.get(e.getCurrentQuery());return t!==void 0&&t!==s&&t.readKey===s.readKey&&(t.last===void 0||s.compare(t.last.value,c)>0)}))&&(Ke=setTimeout(()=>{Ke=void 0,Ne===h&&j()},0))},Je=z===void 0?null:Fa(z.persistence);if(Je?.startupCacheGenerationRotated===!0){oe=ds;for(let e of A)e.state.fetchStatus!==`idle`&&Z.get(e)===void 0&&Z.set(e,oe)}let Ye=!1,Xe=!1,Ze=new Map,Qe=new Set,$e=new WeakMap,et=new Map,tt=e=>et.get(e)??0,nt=e=>{et.set(e,tt(e)+1)},rt=new Map,it=new Map,at=e=>{for(let t of it.values())if(t===e)return;ne(e)},ot=(e,t)=>{let n=it.get(e);it.set(e,t),Re&&(k(t),n!==void 0&&at(n))},ct=e=>{let t=it.get(e);it.delete(e)&&Re&&(it.size===0?ne():at(t))},lt=new WeakMap,ut=new Set,dt=new Map,ft=e=>lt.get(e),pt=(e,t)=>{lt.set(e,t)};Me=ft;let ht=new Map,gt=new Map,_t=new Map,vt=Promise.resolve(),yt=e=>{let t=ht.get(e);t?.rollback?.(),Se.delete(e),rt.delete(e),ht.delete(e),t?.abort()},bt=async e=>{for(;;){let t=Se.get(e);if(!t)return;try{await t}catch(n){if(Se.get(e)===t||rt.has(e)&&rt.get(e)===n)throw n}}},xt=(e,t,n,r=()=>!0)=>new Promise((i,a)=>{let o=!0,s=()=>{},c=V.get(t)??new Set,l=e=>{o&&(o=!1,s(),c.delete(u),c.size===0&&V.delete(t),e())},u=()=>{l(()=>a(n()))};c.add(u),V.set(t,c),s=e.subscribe(e=>{queueMicrotask(()=>{(e.isSuccess&&!F.deferDataRefresh||e.isError&&!e.isFetching)&&r(e)&&l(()=>i(e))})})}),St=(e,t)=>{let n=dt.get(t)??new Map,r=n.get(e);if(r)return r;let i=t.then(async()=>{let t=O.observers.get(e);if(!t)throw new vo;let n=await t.refetch();for(;;){if(!n.isSuccess)return n;if(await new Promise(e=>queueMicrotask(e)),F.deferDataRefresh){n=await xt(t,e,()=>new vo);continue}let r=ft(n);if(r?.type===`rejected`)throw r.error;if(r?.type===`pending`)return r.promise;let i=wt(e);return i!==!0&&await i,n}});n.set(e,i),dt.set(t,n);let a=()=>{n.get(e)===i&&(n.delete(e),n.size===0&&dt.delete(t))};return i.then(a,a),i},Ct=(e,t,n)=>{let r=ft(t);if(r?.type===`pending`)return r;let i,a=new Promise((e,t)=>{i=t,n.then(e,t)});a.catch(()=>{});let o={type:`pending`,promise:a,reject:i};return pt(t,o),ut.add(o),a.then(()=>{ut.delete(o)},()=>{ut.delete(o)}),o},wt=e=>Se.get(e)?bt(e):!rt.has(e)||Promise.reject(rt.get(e)),Tt=e=>z?.row.get(e),Et=(e,t)=>{if(!e||typeof e!=`object`)return new Set;let n=e.queryCollection;if(!n||typeof n!=`object`)return new Set;let r=n.owners;if(!r||typeof r!=`object`)return new Set;let i=new Set(Object.keys(r));return t===void 0||i.forEach(e=>{let n=R.get(e);n&&!n.has(t)&&i.delete(e)}),i},Dt=e=>Et(Tt(e),e),W=(e,t)=>{if(!z)return;let n={...Tt(e)??{}};t.size===0?(delete n.queryCollection,Object.keys(n).length===0?z.row.delete(e):z.row.set(e,n)):z.row.set(e,{...n,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},Ot=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.queryHash===t){if(n.mode===`until-revalidated`)return{queryHash:t,mode:`until-revalidated`};if(n.mode===`ttl`&&typeof n.expiresAt==`number`&&Number.isFinite(n.expiresAt))return{queryHash:t,mode:`ttl`,expiresAt:n.expiresAt}}},kt=e=>(vt=vt.then(e,e),vt),At=e=>{let t=_t.get(e);t&&(clearTimeout(t),_t.delete(e))},Mt=e=>{let t=R.get(e);if(t)return new Set(t);let n=new Set,r=Array.from(F._state.syncedData.keys(),e=>[e,Dt(e)]);for(let[t,i]of r)i.size!==0&&(Fe(t,i),i.has(e)&&n.add(t));return n},Nt=async(e,t=!1)=>{let n=M,r=R.get(e);if(r&&(r.size>0||t)&&Array.from(r).every(e=>F.has(e))){let e=new Map;return r.forEach(t=>{let n=F.get(t),r=B.get(t);n&&r&&e.set(t,{value:n,owners:new Set(r)})}),e}let i=Je?.scanPersistedRows;if(!i){let t=new Map;return Mt(e).forEach(e=>{let n=F.get(e),r=B.get(e);n&&r&&t.set(e,{value:n,owners:new Set(r)})}),t}let a=new Map,o=await i();if(n!==M||N)return a;let s=o.map(e=>Et(e.metadata,e.key));return o.forEach((t,n)=>{let r=s[n];r.size!==0&&(Fe(t.key,r),r.has(e)&&a.set(t.key,{value:t.value,owners:r}))}),a},Pt=async e=>{if(!z)return;let t=M,n=await Nt(e);if(t!==M||N)return;let r=[];g(),n.forEach(({value:t,owners:n},i)=>{n.delete(e),W(i,n),Ie(i,e)&&r.push(t)}),r.forEach(e=>{y({type:`delete`,value:e})}),z.collection.delete(`${us}${e}`),b(),R.delete(e)},Ft=e=>{if(e.mode!==`ttl`)return;At(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{_t.delete(e.queryHash),kt(async()=>{let t=z?.collection.get(`${us}${e.queryHash}`),n=Ot(t,e.queryHash);if(n?.mode===`ttl`){if(n.expiresAt>Date.now())return Ft(n);await Pt(e.queryHash)}})},t);_t.set(e.queryHash,n)},It=async()=>{if(!z)return;let e=z.collection.list(us),t=Date.now();for(let{key:n,value:r}of e){let e=n.slice(us.length),i=Ot(r,e);i&&(i.mode===`ttl`&&i.expiresAt<=t?await Pt(i.queryHash):i.mode===`ttl`&&Ft(i))}},Lt=e=>{if(typeof t==`function`){let{refetch:n,...r}=e;return t(r)}if(w===`on-demand`){let n=ia(e);return n===void 0?t:[...t,n]}return t},Rt=z?.collection.list(us),zt=!Rt||Rt.length===0?(Xe=!0,Promise.resolve()):kt(async()=>{try{await It()}finally{Xe=!0}}),Bt=(e,t,n)=>xt(e,t,()=>new st,n).then(e=>{if(e.isError)throw e.error}),Vt=(e,t,n)=>Bt(e,t,n).then(()=>{let e=wt(t);return e===!0?void 0:e}),Ht=async(e,t)=>new Promise((n,r)=>{let i=!0,a=V.get(t)??new Set,o=e=>{if(!i)return;i=!1;let n=Ge.get(t)-1;n===0?Ge.delete(t):Ge.set(t,n),a.delete(s),a.size===0&&V.delete(t),e()},s=()=>{o(()=>r(new st))};a.add(s),V.set(t,a),Ge.set(t,(Ge.get(t)??0)+1),(async()=>{let n=!!F.deferDataRefresh;for(xe(e.getCurrentQuery(),t);;){if(!i)return;try{await e.refetch({throwOnError:!0})}catch(t){let n=Z.get(e.getCurrentQuery());if(oe===void 0||n===void 0||n>oe)throw t;continue}if(await new Promise(e=>queueMicrotask(e)),!i)return;if(fe(e.getCurrentQuery()))break}if(n||!fe(e.getCurrentQuery())){await Vt(e,t);return}let r=wt(t);r!==!0&&await r})().then(()=>o(n),e=>o(()=>r(e)))}),Ut=(e,t)=>{let n=e.getCurrentQuery();if(typeof a==`function`?a(n):a!==!1)return Ht(e,t);let r=n.state.dataUpdateCount;return Vt(e,t,t=>{if(t.isError)return!0;let n=e.getCurrentQuery();return n.state.dataUpdateCount>r&&hs.get(n)===n.state.dataUpdateCount&&fe(n)})},Wt=(e={},t=n)=>{if(!Xe){let n={},r=Ze.get(e)??new Set;return r.add(n),Ze.set(e,r),zt.then(()=>{if(!Ze.get(e)?.delete(n))throw new st;r.size===0&&Ze.delete(e);let i=Wt(e,t);return i===!0?void 0:i})}let g=Lt(e),y=X(g),b=D===void 0?void 0:O.observers.get(D),x=ke.has(y);if(x&&b===void 0)throw Error(`A full-source dependent lost its Query observer`);let C=b?.getCurrentQuery(),E=b?.getCurrentResult(),k=E!==void 0&&le(D,E)!==void 0,ne=z?.collection.get(`${us}${y}`),re=Ot(ne,y)!==void 0,ie=!e.refetch&&ee!==void 0&&D!==y&&(x||!re&&!O.observers.has(y)&&(Oe.get(D)??0)>0&&E?.isSuccess===!0&&C?.state.fetchStatus===`idle`&&fe(C)&&!Se.has(D)&&!rt.has(D)&&k),A=ie?ee:g,j=ie?D:y,{subscription:M,refetch:N,...P}=e,ce={...S};Object.defineProperty(ce,"loadSubsetOptions",{value:P,enumerable:!1,configurable:!0,writable:!0});let I=j===y?ne:z?.collection.get(`${us}${j}`);if(Ot(I,j)!==void 0&&Qe.add(j),At(j),te(A),O.observers.has(j)){Oe.set(j,(Oe.get(j)||0)+1),ie&&ke.set(y,(ke.get(y)??0)+1);let t=O.observers.get(j),n=t.getCurrentResult();if(e.refetch)return Ht(t,j);let r=t.getCurrentQuery(),i=_s.get(r);return Ee.has(r)||w===`on-demand`&&i!==void 0&&(i.owner!==ae||i.session!==h)||H>0&&r.state.dataUpdateCount>(hs.get(r)??0)||!fe(t.getCurrentQuery())?Ut(t,j):n.isSuccess?F.deferDataRefresh?Vt(t,j):wt(j):n.isError&&!n.isFetching?Promise.reject(n.error):Vt(t,j)}let ue={...ls({enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,gcTime:u,refetchOnWindowFocus:d,refetchOnReconnect:f,refetchOnMount:p,networkMode:m}),...T,queryKey:A,queryFn:e=>{let n=X(e.queryKey),r=i.getQueryCache().find({queryKey:e.queryKey,exact:!0});U.set(n,Math.max(U.get(n)??0,H));let a=()=>{let n=Object.defineProperties({},Object.getOwnPropertyDescriptors(e));return n.meta={...e.meta,loadSubsetOptions:{...P,get signal(){return e.signal}}},t(n)};if((Oe.get(n)??0)>1||(r?.getObserversCount()??0)>1||j===D&&ke.size||P.signal?.aborted)return a();let o=t=>{let n=typeof t==`object`&&!!t&&`name`in t&&t.name===`AbortError`;if(!P.signal?.aborted||t!==P.signal.reason&&!n||!r||r.getObserversCount()===0||i.getQueryCache().find({queryKey:e.queryKey,exact:!0})!==r||r.state.fetchStatus!==`fetching`)throw t;return a()};try{return Promise.resolve(t(e)).catch(o)}catch(e){return o(e)}},meta:ce,structuralSharing:!0,notifyOnChangeProps:`all`},de=new Oo(i,ue),L=de.getCurrentQuery();se(L,j);let R=i.getQueryCache().find({queryKey:A,exact:!0})?.gcTime,me=_??R;pe.set(j,A),O.observers.set(j,de);let he=Z.get(L);he!==void 0&&(L.state.fetchStatus===`fetching`||ms.get(L)===L.state.data)&&U.set(j,he),me===void 0?gt.delete(j):gt.set(j,me),Oe.set(j,(Oe.get(j)||0)+1);let V=i.getQueryData(A);if(V!==void 0){let t=_s.get(L),n=w===`on-demand`&&t!==void 0&&(t.owner!==ae||t.session!==h),i=H>0&&L.state.dataUpdateCount>(hs.get(L)??0),a=Je?.scanPersistedRows===void 0?void 0:r?r(V):V,o=Je?.scanPersistedRows!==void 0&&Array.isArray(a)&&a.some(e=>{let t=v(e);return F._state.getAcceptedSyncedRow(t)!==void 0&&!ge.has(t)&&!B.has(t)});(Ye||F.subscriberCount>0)&&en(de,j,n||i||o?{data:L.state.data,version:L.state.dataUpdateCount,fetchStart:Z.get(L)}:void 0);let s=de.getCurrentResult();return e.refetch||Ee.has(L)||n||i||o?e.refetch?Ht(de,j):Ut(de,j):fe(de.getCurrentQuery())?s.isError&&!s.isFetching?Promise.reject(s.error):!s.isSuccess||F.deferDataRefresh?Vt(de,j):wt(j):Ut(de,j)}if(oe!==void 0)return(Ye||F.subscriberCount>0)&&en(de,j),Ut(de,j);let _e=Vt(de,j);return(Ye||F.subscriberCount>0)&&en(de,j),_e},Gt=(e,t)=>{let n=t.data,i=r?r(n):n,a=r?`select()`:`queryFn`;if(!Array.isArray(i))return{error:new Ko(`@tanstack/query-db-collection: ${a} must return an array of objects. Got: ${typeof i} for queryKey ${JSON.stringify(e)}`)};let o=i.findIndex(e=>typeof e!=`object`||!e);if(o!==-1){let t=i[o];return{error:new Ko(`@tanstack/query-db-collection: ${a} must return an array of objects. Invalid item at index ${o}: ${t===null?`null`:typeof t} for queryKey ${JSON.stringify(e)}`)}}return{items:i}},Kt=(e,t,n)=>{let r=new Map(e.map(e=>[v(e),e]));for(let[e,i]of Ce){if(i<=t||w===`on-demand`&&!r.has(e)&&!R.get(n)?.has(e))continue;let a=F._state.getAcceptedSyncedRow(e);a===void 0?r.delete(e):r.set(e,a)}return Array.from(r.values())},qt=async()=>{for(;we;)await we},Jt=(e,t)=>{let n=Gt(e,t);if(`error`in n)throw pt(t,{type:`rejected`,error:n.error}),n.error;return n.items},Yt=(e,t,n,r,a,o)=>{let s=X(e);if(F.status===`cleaned-up`||a?.aborted)throw new st;Be()&&n.settleRefetchAtFetchBoundary?.();let c=o??Jt(e,t),l=new Map(F._state.acceptedSyncedEntries()),u=r!==void 0,d=u?new Set(r.keys()):Mt(s),f=i.getQueryCache().find({queryKey:e,exact:!0}),p=f!==void 0&&ms.get(f)===f.state.data?ps.get(f):void 0;if(w===`eager`)ge.forEach((e,t)=>{l.has(t)&&p!==void 0&&p>e&&d.add(t)});else if(p!==void 0&&(ge.size>0||Je?.scanPersistedRows!==void 0)){let e=O.observers.get(s)?.options.meta?.loadSubsetOptions;if(ss(e)&&e.limit===void 0&&e.offset===void 0&&e.cursor===void 0){let t=e.where?an(e.where):void 0;l.forEach((e,n)=>{let r=ge.get(n);if(!(r===void 0?!Je?.scanPersistedRows||Dt(n).size>0:p<=r)){try{if(t&&!nn(t(e)))return}catch{return}d.add(n)}})}}let m=new Map;c.forEach(e=>{let t=v(e),n=_e.get(t);m.set(t,p!==void 0&&n!==void 0&&n>p&&l.has(t)?l.get(t):e)});let h=new Map,_=new Set,x=R.get(s),S=new Set([...d,...m.keys()]),C=new Map;S.forEach(e=>{let t=B.get(e);C.set(e,t?new Set(t):void 0)});let T=!1,E,ee=()=>{E?.applicationStarted||E===void 0&&Array.from(S).every(e=>{let t=B.get(e)??new Set,n=Et(F._state.syncedMetadata.get(e));return t.size===n.size&&Array.from(t).every(e=>n.has(e))})||O.observers.has(s)&&ht.get(s)===n&&(x===void 0?R.delete(s):R.set(s,x),C.forEach((e,t)=>{e===void 0?B.delete(t):B.set(t,e)}))};n.rollback=ee;let D=e=>{if(ee(),T){let e=new AbortController;e.abort();try{b(e.signal)}catch{}}throw e};try{R.set(s,new Set(d)),g(),T=!0,z&&z.collection.delete(`${us}${s}`),d.forEach(e=>{let t=u?r.get(e)?.value:l.get(e),n=m.get(e);if(n)t&&!mt(t,n)&&y({type:`update`,value:n});else{let t=ge.get(e);t!==void 0&&h.set(e,t);let n=Dt(e);n.delete(s),W(e,n),Ie(e,s)&&(y({type:`delete`,key:e}),_.add(e))}}),m.forEach((e,n)=>{let r=ge.get(n);if(!d.has(n)&&r!==void 0&&(p??0)<=r)return;r!==void 0&&p!==void 0&&p>r&&h.set(n,r);let i=Dt(n),a=!i.has(s),o=!l.has(n);a&&i.add(s),Pe(n,s),o?y({type:`insert`,value:e}):!d.has(n)&&(t.isFetchedAfterMount||r!==void 0&&p!==void 0&&p>r)&&!mt(l.get(n),e)&&y({type:`update`,value:e}),(a||o)&&W(n,i)}),E=F._state.pendingSyncedTransactions.at(-1),Be()&&n.settleRefetchAtFetchBoundary?.();let e=b();n.rollback=void 0,T=!1,Qe.delete(s),At(s);let i=()=>{f&&qe(f,s,c),_.forEach(e=>{F._state.getAcceptedSyncedRow(e)===void 0&&_e.delete(e)});let e=e=>{m.forEach((t,n)=>{F._state.getAcceptedSyncedRow(n)!==void 0&&e>(_e.get(n)??0)&&_e.set(n,e)}),ve=Math.max(ve,e)};if(p!==void 0)e(p);else if(f){let t=f.state.data;queueMicrotask(()=>{if(ms.get(f)===t){let t=ps.get(f);t!==void 0&&e(t)}})}h.forEach((e,t)=>{ge.get(t)===e&&ge.delete(t)}),a?.aborted||Ve()},o=qr(e);return o===!0?i():o.then(i,()=>void 0),e===!0||e.then(()=>void 0,D)}catch(e){return D(e)}},Xt=async(e,t,n,r,a,o)=>{let s=X(e),c=a??Jt(e,t),l=await Nt(s,c.length===0);if(F.status===`cleaned-up`||ht.get(s)!==n)throw new st;let u=H,d=i.getQueryCache().find({queryKey:e,exact:!0}),f=d?Z.get(d):void 0,p=o!==void 0&&o<u?Kt(c,o,s):c;await Yt(e,t,n,l,r,p),o!==void 0&&o<u&&U.get(s)===o&&d&&Z.get(d)===f&&U.set(s,u)},Zt=(e,t,n,r)=>{Se.set(e,t);let i=()=>Se.get(e)===t&&(Se.delete(e),!0);t.then(()=>{i()&&(rt.delete(e),!n&&r===tt(e)&&ct(e))},t=>{i()&&(rt.set(e,t),nt(e),console.error(`[QueryCollection] Error applying query ${String(pe.get(e))}:`,t),He(t)||ot(e,t))})},G=(e,t,n)=>{yt(e);let r=tt(e),i=new AbortController,a=()=>{},o=new Promise(e=>{a=e});i.settleRefetchAtFetchBoundary=a,ht.set(e,i);let s;try{s=n(i.signal,i)}catch(e){s=Promise.reject(e)}if(s===!0){ht.get(e)===i&&(I(e,t,Promise.resolve()),ht.delete(e),rt.delete(e),!t.isFetching&&r===tt(e)&&ct(e));return}let c=Promise.race([s,o]);c.catch(()=>void 0),I(e,t,c);let l=()=>{ht.get(e)===i&&ht.delete(e)};s.then(l,l),ht.get(e)===i&&Zt(e,s,t.isFetching,r)},Qt=e=>{let t=X(e),n=M,r=a=>{if(Ne!==h||N||n!==M)return;let o=O.observers.get(t),s=o?.getCurrentQuery();if(o&&s&&se(s,t),!Te){if(s){let e=Z.get(s);if(a.isError&&oe!==void 0&&e!==void 0&&e<=oe)return;if(a.isSuccess){if(a.isFetching&&!F.deferDataRefresh&&me(t)&&ms.get(s)===s.state.data)return;if(!fe(s)){queueMicrotask(()=>{let e=O.observers.get(t);e&&e===o&&fe(e.getCurrentQuery())&&r(e.getCurrentResult())});return}if((H>0||ve>(Z.get(s)??ve))&&s.state.dataUpdateCount>(hs.get(s)??0)){let e=s.state.dataUpdateCount;if(be.get(s)!==e){be.set(s,e),queueMicrotask(()=>{O.observers.get(t)===o&&s.state.data===a.data&&s.state.dataUpdateCount===e&&r(a)});return}if(H>0&&ms.get(s)!==s.state.data)return}let e=Z.get(s);if(!a.isFetching&&(ge.size>0||Je?.scanPersistedRows!==void 0)&&e!==void 0&&e!==ps.get(s)&&!ye.has(a)){ye.add(a),queueMicrotask(()=>{O.observers.get(t)?.getCurrentResult()===a&&r(a)});return}let n=Ee.get(s);if(n!==void 0){if(s.state.dataUpdateCount<=n)return;Ee.delete(s)}}}if(a.isSuccess&&F.deferDataRefresh){if(a.isFetching){St(t,F.deferDataRefresh);return}Ct(t,a,St(t,F.deferDataRefresh))}else{if(a.isSuccess&&!a.isFetching&&(we!==void 0||(U.get(t)??H)<H)){let n=o?.getCurrentQuery(),i=U.get(t)??0;if(ft(a)?.type===`pending`)return;let s=Gt(e,a);if(n&&`items`in s){De++;let o=(async()=>{await qt();let o=O.observers.get(t);if(o?.getCurrentQuery()!==n)throw new vo;let c=Kt(s.items,i,t),l=()=>{},u=new Promise(e=>{l=o.subscribe(()=>e())}),d=o.getCurrentResult();try{if(U.set(t,H),!Ue(e,c)){G(t,a,(n,r)=>Qe.has(t)?Xt(e,a,r,n,c,i):Yt(e,a,r,void 0,n,c));let n=wt(t);return n!==!0&&await n,o.getCurrentResult()}o.getCurrentResult()===d?r(d):await u}finally{l()}await new Promise(e=>queueMicrotask(e));let f=wt(t);return f!==!0&&await f,o.getCurrentResult()})(),c=()=>{De--};o.then(c,c),Ct(t,a,o);return}}if(a.isSuccess){if(Qe.has(t)){if(i.getQueryCache().find({queryKey:e,exact:!0})?.state.dataUpdateCount===0){a.isFetching||O.observers.get(t)?.refetch().catch(()=>{});return}if(a.isFetching)return;G(t,a,(n,r)=>Xt(e,a,r,n,void 0,U.get(t)??H))}else G(t,a,(t,n)=>Yt(e,a,n,void 0,t))}if(s&&a.errorUpdateCount<($e.get(s)??0)&&$e.delete(s),a.isError&&a.fetchStatus===`idle`){let n=!s||a.errorUpdateCount!==$e.get(s);n&&(s&&$e.set(s,a.errorUpdateCount),nt(t)),console.error(`[QueryCollection] Error observing query ${String(e)}:`,a.error),!He(a.error)&&n&&ot(t,a.error)}}}};return r},$t=e=>he.has(e);je=(e,t)=>{if($t(e))return!1;let n=pe.get(e);return n?(Qt(n)(t),!0):!1};let en=(e,t,n)=>{if(!$t(t)){w===`eager`&&e.setOptions(e.options);let r=pe.get(t),i=Qt(r),a=t=>{if(n&&t.isSuccess){let t=e.getCurrentQuery();if(t.state.data===n.data&&t.state.dataUpdateCount===n.version&&(t.state.fetchStatus!==`idle`||Z.get(t)===n.fetchStart))return}i(t)},o=e.subscribe(a);he.set(t,o);let s=e.getCurrentResult();(s.isSuccess||s.isError)&&a(s)}},tn=()=>{O.observers.forEach((e,t)=>en(e,t))},rn=()=>{he.forEach(e=>{e()}),he.clear()};Ae=()=>{w===`eager`&&O.observers.forEach((e,t)=>{let n=e.getCurrentQuery();i.getQueryCache().get(n.queryHash)!==n&&en(e,t)})},Ye=!0;let on=F.on(`subscribers:change`,({subscriberCount:e})=>{e>0?tn():e===0&&rn()});if(w===`eager`){let e=Wt({});e instanceof Promise&&e.catch(()=>{})}else Xe?Ve():zt.then(Ve);tn(),O.observers.forEach((e,t)=>{let n=e.getCurrentQuery(),r=_s.get(n);if(w===`on-demand`&&r&&(r.owner!==ae||r.session!==h))return;let i=pe.get(t);Qt(i)(e.getCurrentResult())});let sn=e=>{V.get(e)?.forEach(e=>{e()}),V.delete(e)},cn=e=>{let t=O.observers.get(e)?.getCurrentQuery();he.get(e)?.(),he.delete(e),sn(e),At(e),Qe.delete(e),yt(e);let n=Le(e),r=R.get(e),i=()=>{R.get(e)===r&&R.delete(e)},a=[];n.forEach((e,t)=>{let n=F._state.getAcceptedSyncedRow(t);e.size===0&&n&&a.push(n)});let o=z!==void 0&&n.size>0,s=`${us}${e}`,c=z?.collection.get(s)!==void 0,l=o||a.length>0||c;l&&g(),n.forEach((e,t)=>{o&&W(t,e)}),a.length>0&&a.forEach(e=>{y({type:`delete`,value:e})}),c&&z.collection.delete(s);let u=!l||b(),d=()=>{a.forEach(e=>{let t=v(e);F._state.getAcceptedSyncedRow(t)===void 0&&_e.delete(t)})},f=qr(u);f===!0?d():f.then(d,()=>void 0),u===!0?i():u.then(i,()=>void 0),O.observers.delete(e),ct(e),t?.state.fetchStatus!==`fetching`&&U.delete(e),pe.delete(e),et.delete(e),Oe.delete(e),gt.delete(e)},ln=e=>{let t=Oe.get(e)||0,n=O.observers.get(e),r=gt.get(e);t<=0&&(he.get(e)?.(),he.delete(e),sn(e)),!(t>0)&&(n?.hasListeners()??!1?Oe.set(e,0):r!==void 0&&z&&Je?.scanPersistedRows?(yt(e),g(),z.collection.set(`${us}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),b(),r!==1/0&&Ft({queryHash:e,mode:`ttl`,expiresAt:Date.now()+r}),he.get(e)?.(),he.delete(e),O.observers.delete(e),ct(e),n?.getCurrentQuery().state.fetchStatus!==`fetching`&&U.delete(e),pe.delete(e),et.delete(e),Oe.set(e,0)):cn(e))},un=e=>{cn(e)},dn=i.getQueryCache().subscribe(e=>{if(e.type===`added`&&qa(e.query.queryKey,E)&&P(e.query),!A.has(e.query))return;if(e.type===`updated`){if(e.action.type===`fetch`){let t=fs.get(e.action);t===void 0&&(t=++ds,fs.set(e.action,t)),U.set(X(e.query.queryKey),t),O.observers.forEach((n,r)=>{n.getCurrentQuery()===e.query&&U.set(r,t)}),Z.set(e.query,t);let n=[...re.get(e.query)?.keys()??[]].filter(e=>e!==t);n.length>0&&queueMicrotask(()=>L(e.query,n)),ue(e.query,t)}else if(e.action.type===`success`&&!e.action.manual){e.query.state.data===e.action.data&&_s.delete(e.query),ms.set(e.query,e.action.data),hs.set(e.query,e.query.state.dataUpdateCount);let t=Z.get(e.query);t!==void 0&&(ps.set(e.query,t),ue(e.query,t),queueMicrotask(()=>{de(e.query,t),L(e.query,[t])}))}else if(e.action.type===`error`){let t=Z.get(e.query);t!==void 0&&(ue(e.query,t),queueMicrotask(()=>L(e.query,[t])))}else if(e.action.type===`setState`&&e.action.state.fetchStatus===`idle`){let t=Z.get(e.query);t!==void 0&&queueMicrotask(()=>L(e.query,[t]))}}let t=X(e.query.queryKey);if(!O.observers.has(t)&&(e.type===`removed`||e.query.state.fetchStatus!==`fetching`)&&U.delete(t),e.type===`removed`&&(A.delete(e.query),pe.has(t))){if(w===`eager`){he.get(t)?.(),he.delete(t),sn(t),F.subscriberCount>0&&Ae();return}ln(t)}});return{loadSubset:w===`eager`?void 0:Wt,unloadSubset:w===`eager`?void 0:e=>{let t=Ze.get(e);if(t){t.delete(t.values().next().value),t.size===0&&Ze.delete(e);return}let n=X(Lt(e)),r=e.refetch?void 0:ke.get(n);r!==void 0&&(r===1?ke.delete(n):ke.set(n,r-1));let i=r===void 0?n:D,a=(Oe.get(i)||0)-1;a<=0?(Oe.set(i,0),ln(i)):Oe.set(i,a)},restartAfterScopedRecovery:w===`on-demand`?async e=>{let t=++M;N=!0,rn();for(let e of O.observers.keys())sn(e),yt(e);if(await e,Ne!==h)throw new vo;t===M&&(R.clear(),B.clear(),Qe.clear(),Ce.clear(),ge.clear(),_e.clear(),ve=0,_t.forEach(e=>clearTimeout(e)),_t.clear(),oe=ds,N=!1,O.observers.forEach((e,t)=>{(Oe.get(t)??0)>0&&en(e,t)}))}:void 0,cleanup:()=>{Ne===h&&(Ne=void 0),clearTimeout(Ke),Ke=void 0,Ze.clear(),ke.clear(),Ae=()=>{},je=()=>!1,on(),rn(),_t.forEach(e=>{clearTimeout(e)}),_t.clear(),ut.forEach(e=>{e.reject(new vo)}),ut.clear(),dt.clear(),Me===ft&&(Me=()=>void 0);let e=new Set([...O.observers.keys(),...R.keys()]);for(let t of e)un(t);U.clear(),ge.clear(),_e.clear(),ve=0,dn();for(let t of[...A])[...ce(t)].some(t=>e.has(t))&&(w===`eager`||ie.has(t)&&t.getObserversCount()===0)&&i.getQueryCache().remove(t);for(let e of A)gs.get(e)?.delete(ae);A.clear(),ie=new WeakSet}}},ze=async(e,t)=>{let n=[...pe.values()];Ae();let r=Ne,i=M,a=n.map(async n=>{if(N)throw new vo;let a=X(n),o=O.observers.get(a);if(!o)return;let s=Me,c=o.getCurrentQuery(),l,u,d;try{xe(c,a);let t=o.refetch({throwOnError:e?.throwOnError});c=o.getCurrentQuery(),l=o.getCurrentResult();let n=Z.get(c);if(n!==void 0&&(u=F(c,n,a)),d=await t,N||i!==M)throw new vo}catch(e){if(N||i!==M)throw new vo;let t=o.getCurrentResult(),n=je(a,t)?t:u?.result??t;throw u&&(u.result=n,u.settlement??=le(a,n)),e}let f=je(a,d)?d:u?.result??d;u&&(u.result=f,u.settlement??=le(a,f)),await new Promise(e=>queueMicrotask(e));let p=s(f)??s(d),m=u?.settlement??le(a,d)??le(a,l);if(Ne!==r&&p===void 0&&m===void 0)throw new vo;if(t){if(p?.type===`rejected`)throw p.error;if(p?.type===`pending`){let t=await p.promise;if(i!==M)throw new vo;if(!t.isSuccess&&e?.throwOnError)throw t.error;return t}}if(t&&!Be()&&m&&(e?.throwOnError?await m:await m.catch(()=>void 0)),i!==M)throw new vo;return f});return await Promise.all(a)},Be=()=>{if(k>0)return!0;for(let e of Ye?.collection._state.transactions.values()??[])if(e.state===`persisting`)return!0;return!1},Ve=e=>ze(e,!Be()),He=e=>{for(let t of gs.get(e)??[])if(t!==ae)return!0;return!1},Ue=(e,t,n)=>{let a=i.getQueryCache().find({queryKey:e,exact:!0}),o=()=>{a&&Ee.set(a,a.state.dataUpdateCount)};if(w===`on-demand`&&a&&He(a)||a?.state.status===`pending`&&a.state.fetchStatus!==`idle`)return o(),!1;let s=t=>{if(a)_s.set(a,{owner:ae,session:Ne}),a.setState(a.state.status===`pending`?{data:t,status:`success`}:{data:t}),Ee.delete(a);else{i.setQueryData(e,t);let n=i.getQueryCache().find({queryKey:e,exact:!0});n&&_s.set(n,{owner:ae,session:Ne})}};if(r){let e=a?.state.data;if(!e||typeof e!=`object`)return o(),!1;if(Array.isArray(e))return s(t),!0;let i=n??r(e);if(!Array.isArray(i))return o(),!1;let c=Object.keys(e).find(t=>e[t]===i);return c===void 0?(o(),!1):(s({...e,[c]:t}),!0)}{let e=a?.state.data;return e===void 0||Array.isArray(e)?(s(t),!0):!1}},We=()=>{H=++ds;for(let[e,t]of O.observers)t.getCurrentQuery().state.fetchStatus!==`fetching`&&!Se.has(e)&&U.set(e,H);return H},Ge=(e,t)=>{let n=De>0||we!==void 0||Se.size>0;if(!n){for(let e of A)if(e.state.fetchStatus===`fetching`){n=!0;break}}if(!n)Ce.clear();else for(let n of e)Ce.set(n,t)},Ke=e=>{let t=Promise.all([we,e]).then(()=>{we===t&&(we=void 0)},()=>{we===t&&(we=void 0)});we=t},qe=(e,t,n)=>{Te=!0;try{let r=e(t),i=new Map(r.map(e=>[v(e),e]));Je(e,t,i);for(let e of t)if(i.has(e))_e.set(e,n),ve=Math.max(ve,n),(B.get(e)?.size??0)===0?ge.set(e,n):ge.delete(e);else{ge.delete(e),_e.delete(e);for(let t of[...B.get(e)??[]])Ie(e,t)}}finally{Te=!1}},Je=(e,t,n)=>{let a=new Set(t),o=e=>{let t=new Set,r=!1;return{patched:e.flatMap(e=>{let i=v(e);if(t.add(i),!a.has(i))return[e];r=!0;let o=n.get(i);return o===void 0?[]:[o]}),present:t,touched:r}};if(w===`on-demand`){let e=new Set(t.flatMap(e=>[...B.get(e)??[]])),n=new Set;for(let[t,i]of O.observers){let a=i.getCurrentQuery();if(n.has(a)||!e.has(t)&&me(t)&&a.state.fetchStatus!==`fetching`&&!Se.has(t))continue;n.add(a);let s=a.state.data,c=r&&s!==void 0?r(s):s;if(!Array.isArray(c))continue;let{patched:l,touched:u}=o(c);u&&Ue(a.queryKey,l,c)}for(let e of[...A])n.has(e)||He(e)||e.getObserversCount()>0||i.getQueryCache().remove(e);return}let s=[...A];if(s.length>0)for(let i of s){let a=i.state.data,s=r&&a!==void 0?r(a):a;if(!Array.isArray(s)){Ue(i.queryKey,e());continue}let{patched:c,present:l}=o(s);for(let e of t){let t=n.get(e);!l.has(e)&&t!==void 0&&c.push(t)}Ue(i.queryKey,c,s)}else Ue(E,e())},Ye=null,Xe=e=>{let n,r=t=>{let r=e.commit(t),i=qr(r);if(i!==!0){let e=i.then(()=>{n===e&&(n=void 0)},()=>{n===e&&(n=void 0)});n=e}return r},a={...e,commit:r},{begin:o,write:s,collection:c}=a,l=!1,u=()=>{l||=(i.mount(),!0)},d=()=>{l&&=(i.unmount(),!1)};u();let f=typeof t==`function`?t({}):t,p={collection:c,queryClient:i,queryKey:f,getKey:v,begin:o,write:s,commit:r,updateCacheData:qe,reserveDirectWrite:We,claimDirectWriteKeys:Ge,noteWaitingDirectWrite:Ke,earlierCommits:()=>n};Ye=p;let m=Re(a),h=typeof m==`function`?{cleanup:m}:typeof m==`object`?m:{};return{...h,cleanup:()=>(Ye===p&&(Ye=null),is(h.cleanup,d))}},Ze=rs(()=>Ye),Qe=e=>e&&(async t=>{k++;try{await e(t)}finally{k--}}),$e=new vs(O,Ve,Ze),et=Zi({sync:Xe},(e,t,n)=>{let r=t;for(let e of Object.keys(Ze)){let t=r[e];r[e]=(...e)=>(n(),t(...e))}return e}),tt={...C,getKey:v,syncMode:w,sync:et,onInsert:Qe(y),onUpdate:Qe(b),onDelete:Qe(x),utils:$e};return ja(tt,t=>ys({...e,queryClient:t.getDependency(`queryClient`)??e.queryClient,id:tt.id}))}async function bs(e,t,n){for(let r of e){if(!r.wrapMutation)continue;let e=await r.wrapMutation(t,n);if(e?.handled)return{handled:!0,result:e.result}}return{handled:!1}}var xs=new WeakMap,Ss=new WeakMap,Cs=new Set([`__proto__`,`constructor`,`prototype`]),ws=1e7,Ts=1e3,Es=1e3,Ds=1e3,Os=1e6,ks=1e3,As=65536;function js(e,t,n){let r=new TextEncoder().encode(t).byteLength;if(r>e.remaining)throw TypeError(`${n} exceeds the maximum byte limit`);e.remaining-=r}function Ms(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`${t} must be a plain object`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`${t} must be a plain object`);for(let n of Object.keys(e))if(Cs.has(n))throw TypeError(`${t} contains a forbidden key`);return e}function Ns(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw TypeError(`${n} contains ${t}`)}function Ps(e,t,n=2048){if(typeof e!=`string`||e.length===0||e.length>n)throw TypeError(`${t} must be a bounded non-empty string`);return e}function Fs(e,t){if(!Number.isSafeInteger(e)||e<0)throw TypeError(`${t} must be a non-negative safe integer`);return e}function Is(e,t,n){if(typeof e==`string`){if(e.length>65536)throw TypeError(`${t} exceeds the string limit`);return js(n,JSON.stringify(e),t),e}if(e===null||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return js(n,JSON.stringify(e),t),e;throw TypeError(`${t} must be a JSON scalar`)}function Ls(e,t,n,r=0){if(r>16)throw TypeError(`${t} exceeds JSON depth`);if(typeof e==`string`){if(e.length>65536)throw TypeError(`${t} exceeds the string limit`);return js(n,JSON.stringify(e),t),e}if(e===null||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return js(n,JSON.stringify(e),t),e;if(Array.isArray(e)){if(e.length>1e3)throw TypeError(`${t} exceeds the container-item limit`);js(n,`[`,t);let i=[];for(let[a,o]of e.entries())a>0&&js(n,`,`,t),i.push(Ls(o,`${t}[${a}]`,n,r+1));return js(n,`]`,t),i}let i=Ms(e,t);if(Object.keys(i).length>1e3)throw TypeError(`${t} exceeds the container-item limit`);let a=Object.create(null);js(n,`{`,t);for(let[e,o]of Object.keys(i).sort().entries()){if(o.length>65536)throw TypeError(`${t}.${o} exceeds the string limit`);e>0&&js(n,`,`,t),js(n,JSON.stringify(o),`${t}.${o}`),js(n,`:`,t),a[o]=Ls(i[o],`${t}.${o}`,n,r+1)}return js(n,`}`,t),a}function Rs(e){let t=Ms(e,`Data query total`),n=Ps(t.kind,`Data query total kind`);if(n===`unavailable`)return Ns(t,[`kind`,`reason`],`Data query unavailable total`),{kind:n,...t.reason===void 0?{}:{reason:Ps(t.reason,`Data query total reason`)}};if(n!==`exact`&&n!==`estimated`)throw TypeError(`Data query total kind is invalid`);return Ns(t,[`kind`,`value`,`asOf`],`Data query total`),{kind:n,value:Fs(t.value,`Data query total value`),...t.asOf===void 0?{}:{asOf:Ps(t.asOf,`Data query total asOf`,128)}}}function zs(e,t){if(e===void 0)return;if(!Array.isArray(e))throw TypeError(`Data query facets must be an array`);if(e.length>20)throw TypeError(`Data query facets exceed the maximum`);let n=new Set;return e.map((e,r)=>{let i=Ms(e,`Data query facet ${r}`);Ns(i,[`field`,`values`,`truncated`],`Data query facet`);let a=Ps(i.field,`Data query facet field`);if(n.has(a))throw TypeError(`Data query facet fields must be unique`);if(n.add(a),!Array.isArray(i.values))throw TypeError(`Data query facet values must be an array`);if(i.values.length>1e3)throw TypeError(`Data query facet values exceed the maximum`);if(typeof i.truncated!=`boolean`)throw TypeError(`Data query facet truncated must be boolean`);return{field:a,values:i.values.map((e,n)=>{let i=Ms(e,`Data query facet ${r} value ${n}`);return Ns(i,[`value`,`count`],`Data query facet value`),{value:Is(i.value,`Data query facet value`,t),count:Fs(i.count,`Data query facet count`)}}),truncated:i.truncated}})}function Bs(e){let t=Ms(e,`Data query result`);if(Ns(t,[`version`,`requestId`,`queryFingerprint`,`identityField`,`rows`,`page`,`total`,`facets`,`freshness`,`warnings`,`truncated`],`Data query result`),t.version!==1)throw TypeError(`Unsupported data query version`);let n=Ps(t.identityField,`Data query identity field`);if(!Array.isArray(t.rows))throw TypeError(`Data query rows must be an array`);if(t.rows.length>1e3)throw TypeError(`Data query rows exceed the maximum`);let r={remaining:ws},i=t.rows.map((e,t)=>{let i=Ms(Ls(e,`Data query row ${t}`,r),`Data query row ${t}`),a=i[n];if(typeof a!=`string`&&typeof a!=`number`||a===``)throw TypeError(`Data query row is missing its stable identity`);return i}),a;if(t.page!==void 0){let e=Ms(t.page,`Data query page`);Ns(e,[`kind`,`limit`,`offset`,`nextCursor`,`hasMore`],`Data query page`);let n=Ps(e.kind,`Data query page kind`);if(n!==`offset`&&n!==`cursor`)throw TypeError(`Data query page kind is invalid`);if(typeof e.hasMore!=`boolean`)throw TypeError(`Data query page hasMore must be boolean`);let r=Fs(e.limit,`Data query page limit`);if(r===0)throw TypeError(`Data query page limit must be positive`);if(r>1e3)throw TypeError(`Data query page limit exceeds the maximum`);if(n===`offset`){if(e.nextCursor!==void 0||e.offset===void 0)throw TypeError(`Offset data query page must carry only an offset`);let t=Fs(e.offset,`Data query offset`);if(t>1e6)throw TypeError(`Data query offset exceeds the maximum`);a={kind:n,limit:r,offset:t,hasMore:e.hasMore}}else{if(e.offset!==void 0)throw TypeError(`Cursor data query page cannot carry an offset`);let t=e.nextCursor===void 0?void 0:Ps(e.nextCursor,`Data query next cursor`);if(e.hasMore!==!!t)throw TypeError(`Cursor data query page hasMore must match nextCursor`);a={kind:n,limit:r,hasMore:e.hasMore,...t===void 0?{}:{nextCursor:t}}}}if(a&&i.length>a.limit)throw TypeError(`Data query rows exceed the declared page limit`);let o=Ms(t.freshness,`Data query freshness`);Ns(o,[`state`,`asOf`],`Data query freshness`);let s=Ps(o.state,`Data query freshness state`);if(s!==`fresh`&&s!==`stale`&&s!==`unknown`)throw TypeError(`Data query freshness state is invalid`);if(!Array.isArray(t.warnings)||t.warnings.length>100||t.warnings.some(e=>typeof e!=`string`))throw TypeError(`Data query warnings must be strings`);if(typeof t.truncated!=`boolean`)throw TypeError(`Data query truncated must be boolean`);let c=zs(t.facets,r),l=t.warnings.map(e=>Ps(e,`Data query warning`,512)),u={version:1,requestId:Ps(t.requestId,`Data query request id`),queryFingerprint:Ps(t.queryFingerprint,`Data query fingerprint`),identityField:n,rows:i,...a===void 0?{}:{page:a},total:Rs(t.total),...c===void 0?{}:{facets:c},freshness:{state:s,...o.asOf===void 0?{}:{asOf:Ps(o.asOf,`Data query freshness asOf`,128)}},warnings:[...new Set(l)].sort(),truncated:t.truncated};if(new TextEncoder().encode(JSON.stringify(u)).byteLength>1e7)throw TypeError(`Data query result exceeds the maximum byte limit`);return u}async function Vs(e,t,n){let r=Bs(await e.query(t,n));if(r.requestId!==t.requestId)throw TypeError(`Data query result request id does not match its request`);return r}var Hs=1e6,Us=1e3,Ws=new Set([`__proto__`,`constructor`,`prototype`]);function Gs(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`${t} must be a plain object`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`${t} must be a plain object`);for(let n of Object.keys(e))if(Ws.has(n))throw TypeError(`${t} contains a forbidden key`);return e}function Ks(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw TypeError(`${n} contains ${t}`)}function qs(e,t){if(typeof e!=`string`||e.length===0||e.length>256)throw TypeError(`${t} must be a bounded non-empty string`);return e}function Js(e,t,n=0){if(n>16)throw TypeError(`${t} exceeds JSON depth`);if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e)){if(e.length>1e3)throw TypeError(`${t} exceeds the container-item limit`);return e.map((e,r)=>Js(e,`${t}[${r}]`,n+1))}let r=Gs(e,t);if(Object.keys(r).length>1e3)throw TypeError(`${t} exceeds the container-item limit`);let i=Object.create(null);for(let[e,a]of Object.entries(r))i[e]=Js(a,`${t}.${e}`,n+1);return i}function Ys(e){let t=Gs(e,`Data surface identity`);Ks(t,[`surfaceId`,`kind`,`subject`],`Data surface identity`);let n=t.kind;if(![`table`,`list`,`report`,`custom`].includes(n))throw TypeError(`Data surface identity kind is invalid`);let r={surfaceId:qs(t.surfaceId,`Data surface identity surfaceId`),kind:n};if(t.subject!==void 0){let e=Gs(t.subject,`Data surface identity subject`);Ks(e,[`type`,`id`,`label`],`Data surface identity subject`),r.subject={type:qs(e.type,`Data surface identity subject type`),id:qs(e.id,`Data surface identity subject id`),...e.label===void 0?{}:{label:qs(e.label,`Data surface identity subject label`)}}}return r}function Xs(e,t){return e.surfaceId===t.surfaceId&&e.kind===t.kind&&e.subject?.type===t.subject?.type&&e.subject?.id===t.subject?.id}function Zs(e){let t=JSON.stringify(e);if(t===void 0||new TextEncoder().encode(t).byteLength>1e6)throw TypeError(`Data surface action result exceeds the maximum byte limit`);let n=Gs(e,`Data surface action result`);if(Ks(n,[`version`,`requestId`,`identity`,`actionId`,`phase`,`ok`,`reason`,`confirmationToken`,`details`],`Data surface action result`),n.version!==1||n.phase!==`preview`&&n.phase!==`apply`)throw TypeError(`Data surface action result has an invalid version or phase`);if(typeof n.ok!=`boolean`)throw TypeError(`Data surface action result ok must be boolean`);let r={version:1,requestId:qs(n.requestId,`Data surface action result requestId`),identity:Ys(n.identity),actionId:qs(n.actionId,`Data surface action result actionId`),phase:n.phase,ok:n.ok};if(n.reason!==void 0&&(r.reason=qs(n.reason,`Data surface action result reason`)),n.confirmationToken!==void 0&&(r.confirmationToken=qs(n.confirmationToken,`Data surface action result confirmationToken`)),n.details!==void 0){let e=Js(n.details,`Data surface action result details`);if(Array.isArray(e)||typeof e!=`object`||!e)throw TypeError(`Data surface action result details must be an object`);r.details=e}return r}async function Qs(e,t,n){let r=Zs(await e.action(t,n));if(r.requestId!==t.requestId||r.actionId!==t.actionId||r.phase!==t.phase||!Xs(r.identity,t.identity))throw TypeError(`Data surface action result does not match its request`);return r}var $s=new Set([`idempotency_in_progress`,`background_unavailable`,`execution_failed`]),ec=new Set([`auth_required`,`unauthenticated`,`unauthorized`]),tc=new Set([`stale_revision`,`stale_preview`]),nc=new Set([`invalid_or_expired_confirmation`,`confirmation_mismatch`,`confirmation_replayed`,`confirmation_required`,`stale_preview`]);function rc(e){if(e.ok)return{status:`applied`};let t=e.reason??`rejected`;return $s.has(t)?{status:`rejected`,reason:`write_failed`}:ec.has(t)?{status:`rejected`,reason:`auth_required`}:tc.has(t)?{status:`conflict`,reason:`stale_write`}:{status:`rejected`,reason:t}}function ic(e){let t=e.classify??rc;return async n=>{let r=n.pinned;r===void 0&&(r={request:await e.request(n)},await n.pin(r));let i=r.request,a=e=>`${n.idempotencyKey}:${n.attempt}:${e}`,o=t=>Qs(e.transport,{...i,version:1,phase:`apply`,requestId:a(`apply`),idempotencyKey:n.idempotencyKey,...t===void 0?{}:{confirmationToken:t}});if(!e.preview)return t(await o(void 0));if(r.confirmationToken!==void 0){let e=await o(r.confirmationToken);if(e.ok||!nc.has(e.reason??``))return t(e)}let s=await Qs(e.transport,{...i,version:1,phase:`preview`,requestId:a(`preview`)});return s.ok?(r={request:i,...s.confirmationToken===void 0?{}:{confirmationToken:s.confirmationToken}},await n.pin(r),t(await o(s.confirmationToken))):t(s)}}function ac(e){let t=e=>e===void 0?``:`_${encodeURIComponent(e)}`;return`smrt-web:${encodeURIComponent(e.apiBase)}:${t(e.tenantId)}:${t(e.identityId)}:${encodeURIComponent(e.manifestHash)}`}var oc=new Map;function sc(e,t){let n=oc.get(e);return n||(n=new Set,oc.set(e,n)),n.add(t),()=>{let n=oc.get(e);n&&(n.delete(t),n.size===0&&oc.delete(e))}}async function cc(e){let t=oc.get(e);if(!t||t.size===0){oc.delete(e);return}let n=[...t];oc.delete(e),await Promise.allSettled(n.map(e=>e.clear()))}function lc(e,t){let n=oc.get(e);if(!n)return!1;for(let e of n)if(e.kind===t)return!0;return!1}function uc(){return[...oc.keys()]}var Q=`outbox`,dc=`state`;function fc(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function pc(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction failed`)),e.onabort=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction aborted`))})}async function mc(){let e=globalThis.indexedDB;if(!e)return!1;let t=`__smrt_web_outbox_probe__`;try{(await new Promise((n,r)=>{let i=e.open(t,1);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error??Error(`probe failed`)),i.onblocked=()=>r(Error(`probe blocked`))})).close();try{e.deleteDatabase(t)}catch{}return!0}catch{return!1}}var hc=class{db;dbName;constructor(e,t){this.db=e,this.dbName=t}async enqueue(e){let t=Date.now(),n={itemId:e.itemId,object:e.object,op:e.op,id:e.id,payload:e.payload,baseUpdatedAt:e.baseUpdatedAt,...e.transport===void 0?{}:{transport:e.transport},state:`pending`,attempts:0,nextAttemptAt:0,enqueuedAt:t},r=this.db.transaction(Q,`readwrite`),i=await fc(r.objectStore(Q).add(n));return await pc(r),i}async markState(e,t){let n=this.db.transaction(Q,`readwrite`),r=n.objectStore(Q),i=await fc(r.get(e));if(!i){await pc(n);return}let a={...i,...t,seq:e};await fc(r.put(a)),await pc(n)}async listPending(e){let t=this.db.transaction(Q,`readonly`),n=await fc(t.objectStore(Q).index(dc).getAll(IDBKeyRange.only(`pending`)));return await pc(t),n.filter(t=>t.nextAttemptAt<=e).sort((e,t)=>(e.seq??0)-(t.seq??0))}async remove(e){let t=this.db.transaction(Q,`readwrite`);await fc(t.objectStore(Q).delete(e)),await pc(t)}async all(){let e=this.db.transaction(Q,`readonly`),t=await fc(e.objectStore(Q).getAll());return await pc(e),t.sort((e,t)=>(e.seq??0)-(t.seq??0))}async clear(){let e=this.db.transaction(Q,`readwrite`);await fc(e.objectStore(Q).clear()),await pc(e)}close(){this.db.close()}};function gc(e){let t=globalThis.indexedDB;return t?new Promise((n,r)=>{let i=t.open(e,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`outbox`)||e.createObjectStore(Q,{keyPath:`seq`,autoIncrement:!0}).createIndex(dc,`state`,{unique:!1})},i.onsuccess=()=>n(new hc(i.result,e)),i.onerror=()=>r(i.error??Error(`[smrt-web] failed to open outbox database "${e}"`)),i.onblocked=()=>r(Error(`[smrt-web] opening outbox database "${e}" was blocked`))}):Promise.reject(Error(`[smrt-web] IndexedDB is unavailable in this environment`))}function _c(){let e=globalThis.navigator?.locks;if(e&&typeof e.request==`function`)return e}var vc=!1;function yc(e,t,n){let r=_c();if(!r){vc||(vc=!0,console.warn(`[smrt-web] Web Locks API unavailable — the offline outbox falls back to single-tab leadership; the multi-tab exactly-one-replayer guarantee does not hold across tabs.`));let e=!1;return queueMicrotask(()=>{e||t()}),()=>{e||(e=!0,n())}}let i=new AbortController,a,o=!1,s=!1;return r.request(e,{signal:i.signal,mode:`exclusive`},()=>(s=!0,o?Promise.resolve():(t(),new Promise(e=>{a=e})))).catch(e=>{e?.name!==`AbortError`&&console.warn(`[smrt-web] outbox leader lock request failed`,e),o||(o=!0,n())}),()=>{o||(o=!0,s&&a?a():i.abort(),n())}}var bc=1e3,xc=[`sync`,`apply`],Sc={initialDelayMs:1e3,multiplier:2,maxDelayMs:6e4};function Cc(e,t,n=Math.random){let r=Math.max(0,e-1),i=t.initialDelayMs*t.multiplier**r,a=Math.min(t.maxDelayMs,i),o=.5+n()*.5;return Math.round(a*o)}function wc(e){return e===`insert`?`create`:e}var Tc=`sync-apply`;function Ec(e){return e.transport===void 0?Tc:`transport:${e.transport}`}function Dc(e,t){let n=`smrt-web-outbox-leader:${e}`;return t===Tc?n:`${n}:${t}`}function Oc(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`item-${Date.now()}-${Math.random().toString(36).slice(2)}`}function kc(){return globalThis.navigator?.onLine===!1}var Ac=class{config;listenersByObject=new Map;syncApply;refCount=0;queue;ready;degraded=!1;leaders=new Map;unregisterResource;disposed=!1;paused=!1;wipesPending=0;pendingWipes=new Set;draining=!1;activeDrain;drainQueued=!1;backoffTimer;onlineListener;constructor(e){this.config=e,this.ready=this.open(),this.registerForWipe(),this.wireOnlineListener(),this.ready.then(()=>{this.disposed||this.drain()})}async open(){if(!await mc())this.degraded=!0,console.warn(`[smrt-web] IndexedDB unavailable — the offline outbox is disabled; offline writes will not be durable.`);else try{this.queue=await gc(this.config.namespace)}catch(e){this.degraded=!0,console.warn(`[smrt-web] failed to open the offline outbox`,e)}}registerForWipe(){this.unregisterResource||this.disposed||(this.unregisterResource=this.config.registerResource(async()=>{this.unregisterResource=void 0,this.wipesPending+=1;let e=(async()=>{try{await this.ready,await this.queue?.clear()}finally{--this.wipesPending,this.disposed||this.drain()}})();this.pendingWipes.add(e);try{await e}finally{this.pendingWipes.delete(e)}}))}wireOnlineListener(){let e=globalThis;if(typeof e.addEventListener!=`function`)return;let t=()=>{this.drain()};e.addEventListener(`online`,t),this.onlineListener=t}acquireRoute(e){let t=this.leaders.get(e);if(t){t.refs+=1;return}let n=Dc(this.config.namespace,e),r={release:()=>{},isLeader:!1,refs:1};this.leaders.set(e,r),r.release=yc(n,()=>{r.isLeader=!0,this.drain()},()=>{r.isLeader=!1})}releaseRoute(e){let t=this.leaders.get(e);t&&(--t.refs,!(t.refs>0)&&(this.leaders.delete(e),this.settled().then(()=>t.release())))}leads(e){return this.leaders.get(e)?.isLeader===!0}registerCollection(e){this.refCount+=1;let t=e.transport?Ec({transport:e.object}):e.syncApply?Tc:void 0,n={onSyncStateChange:e.onSyncStateChange,onConflict:e.onConflict,transport:e.transport,route:t},r=this.listenersByObject.get(e.object);return r||(r=new Set,this.listenersByObject.set(e.object,r)),r.add(n),e.syncApply&&!this.syncApply&&(this.syncApply=e.syncApply),t&&!this.disposed&&this.acquireRoute(t),n}transportFor(e){let t=this.listenersByObject.get(e);if(t){for(let e of t)if(e.transport)return e.transport}}async unregisterCollection(e,t){let n=this.listenersByObject.get(e);if(n?.delete(t)){n.size===0&&this.listenersByObject.delete(e);let r=t.route;r&&this.releaseRoute(r)}return this.refCount=Math.max(0,this.refCount-1),this.refCount>0?!1:(await this.dispose(),!0)}get referenceCount(){return this.refCount}async enqueue(e){if(await this.ready,!this.queue||this.degraded)return;this.registerForWipe();let t=Oc(),n=wc(e.kind),r=e.rowId||t,i=n===`delete`&&e.transport===void 0?void 0:e.data;return await this.queue.enqueue({itemId:t,object:e.object,op:n,id:r,payload:i,baseUpdatedAt:e.baseUpdatedAt,transport:e.transport}),this.emit({itemId:t,rowId:r,object:e.object,state:`pending`,attempts:0}),this.paused=!1,this.drain(),t}async retry(e){if(await this.ready,!this.queue)return;let t=(await this.queue.all()).find(t=>t.itemId===e&&t.state===`pending`);t&&t.seq!==void 0&&(await this.queue.markState(t.seq,{nextAttemptAt:0}),this.paused=!1,this.drain())}async snapshot(){return await this.ready,this.queue?(await this.queue.all()).map(e=>({itemId:e.itemId,object:e.object,op:e.op,rowId:e.id,state:e.state,attempts:e.attempts,nextAttemptAt:e.nextAttemptAt,lastError:e.lastError,...e.transport===void 0?{}:{transport:e.transport}})):[]}emit(e){let t=this.listenersByObject.get(e.object);if(t)for(let n of t)try{n.onSyncStateChange?.(e)}catch(e){console.warn(`[smrt-web] onSyncStateChange callback threw`,e)}}emitConflict(e){let t=this.listenersByObject.get(e.object);if(t)for(let n of t)try{n.onConflict?.(e)}catch(e){console.warn(`[smrt-web] onConflict callback threw`,e)}}drain(){return this.draining?(this.drainQueued=!0,this.activeDrain??Promise.resolve()):(this.draining=!0,this.activeDrain=(async()=>{try{for(;this.drainQueued=!1,await this.drainOnce(),this.drainQueued;);}finally{this.draining=!1,this.activeDrain=void 0}})(),this.activeDrain)}settled(){return(this.activeDrain??Promise.resolve()).catch(()=>void 0)}async drainOnce(){if(this.disposed||this.wipesPending>0||this.paused||this.degraded||!this.queue||kc())return;let e=new Map;for(let t of await this.queue.all()){if(t.state!==`pending`)continue;let n=Ec(t);if(!this.leads(n))continue;let r=e.get(n);r?r.push(t):e.set(n,[t])}let t=Date.now();for(let[n,r]of e){let e=r.findIndex(e=>e.nextAttemptAt>t),i=e===-1?r:r.slice(0,e);if(n===Tc){let e=this.syncApply;if(!e)continue;for(let t=0;t<i.length&&!(this.disposed||this.paused||!this.leads(n));t+=bc){let n=i.slice(t,t+bc);if(!await this.sendBatch(n,e))break}}else for(let e of i){if(this.disposed||this.paused||!this.leads(n))break;let t=this.transportFor(e.transport??e.object);if(!t||!await this.sendCommand(e,t))break}if(this.disposed||this.paused)return}await this.scheduleNextBackoff()}async sendCommand(e,t){this.emit({itemId:e.itemId,rowId:e.id,object:e.object,state:`uploading`,attempts:e.attempts});let n;try{n=await t({idempotencyKey:e.itemId,name:e.transport??e.object,op:e.op,rowId:e.id,...e.payload===void 0?{}:{payload:e.payload},...e.baseUpdatedAt===void 0?{}:{baseUpdatedAt:e.baseUpdatedAt},attempt:e.attempts+1,...e.pinned===void 0?{}:{pinned:e.pinned},pin:async t=>{if(e.seq===void 0||!this.queue)throw Error(`[smrt-web] outbox row is no longer queued`);await this.queue.markState(e.seq,{pinned:t}),e.pinned=t}})}catch{return await this.requeueRow(e,`network error during command replay`),!1}let r=Nc(e,n);return r?this.applyResult(e,r):(await this.requeueRow(e,`unexpected command result shape`),!1)}async sendBatch(e,t){for(let t of e)this.emit({itemId:t.itemId,rowId:t.id,object:t.object,state:`uploading`,attempts:t.attempts});let n=e.map(e=>({itemId:e.itemId,object:e.object,op:e.op,id:e.id,payload:e.payload,baseUpdatedAt:e.baseUpdatedAt})),r;try{r=await this.postBatch(n,t)}catch{return await this.requeueBatch(e,`network error during sync`),!1}if(!r)return await this.requeueBatch(e,`unexpected sync response shape`),!1;let i=!0;for(let t=0;t<e.length;t+=1){let n=e[t],a=r[t];if(!a){await this.requeueRow(n,`missing result for item`),i=!1;continue}let o=await this.applyResult(n,a);i&&=o}return i}async postBatch(e,t){let n=`${t.basePath}/${xc.join(`/`)}`,r=await t.fetchFn(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({items:e})});if(!r.ok)throw Error(`[smrt-web] sync/apply returned HTTP ${r.status}`);let i=await r.json().catch(()=>null);if(i&&Array.isArray(i.results))return i.results}async applyResult(e,t){if(e.seq===void 0)return!0;if(t.status===`applied`)return await this.finishSynced(e),!0;if(t.status===`conflict`){let n=t.reason===`create_conflict`?`create_conflict`:`stale_write`;return this.emitConflict({itemId:e.itemId,object:e.object,rowId:e.id,reason:n,serverUpdatedAt:t.updatedAt}),await this.finishSynced(e),!0}let n=t.reason;return n===`auth_required`||n===`forbidden`?(this.paused=!0,await this.queue?.markState(e.seq,{state:`pending`,lastError:`sync ${n}`}),this.emit({itemId:e.itemId,rowId:e.id,object:e.object,state:`pending`,attempts:e.attempts,error:`sync ${n}`}),!1):n===`write_failed`?(await this.requeueRow(e,`sync write_failed`),!1):(await this.queue?.remove(e.seq),this.emit({itemId:e.itemId,rowId:e.id,object:e.object,state:`failed`,attempts:e.attempts,error:n?`sync ${n}`:`sync rejected`}),!0)}async finishSynced(e){e.seq!==void 0&&await this.queue?.remove(e.seq),this.emit({itemId:e.itemId,rowId:e.id,object:e.object,state:`synced`,attempts:e.attempts})}async requeueBatch(e,t){for(let n of e)await this.requeueRow(n,t)}async requeueRow(e,t){if(e.seq===void 0)return;let n=e.attempts+1,r=Cc(n,this.config.backoff,this.config.random),i=Date.now()+r;await this.queue?.markState(e.seq,{state:`pending`,attempts:n,nextAttemptAt:i,lastError:t}),this.emit({itemId:e.itemId,rowId:e.id,object:e.object,state:`pending`,attempts:n,error:t})}async scheduleNextBackoff(){if(this.disposed||this.paused||!this.queue)return;let e,t=new Set;for(let n of await this.queue.all()){if(n.state!==`pending`)continue;let r=Ec(n);t.has(r)||(t.add(r),this.leads(r)&&(e=e===void 0?n.nextAttemptAt:Math.min(e,n.nextAttemptAt)))}if(e===void 0)return;let n=Math.max(0,e-Date.now());this.backoffTimer&&clearTimeout(this.backoffTimer);let r=globalThis;typeof r.setTimeout==`function`&&(this.backoffTimer=r.setTimeout(()=>{this.backoffTimer=void 0,this.drain()},n),this.backoffTimer.unref?.())}async dispose(){if(this.disposed)return;this.disposed=!0,this.backoffTimer&&=(clearTimeout(this.backoffTimer),void 0);let e=globalThis;this.onlineListener&&typeof e.removeEventListener==`function`&&(e.removeEventListener(`online`,this.onlineListener),this.onlineListener=void 0);let t=[...this.leaders.values()];this.leaders.clear(),await this.settled();for(let e of t)e.release();this.unregisterResource?.(),this.unregisterResource=void 0,await this.ready.catch(()=>void 0),await Promise.allSettled([...this.pendingWipes]),this.queue?.close(),this.queue=void 0,this.listenersByObject.clear()}},jc=new Map;function Mc(e){let t=jc.get(e.namespace);return t||(t=new Ac(e),jc.set(e.namespace,t)),t}function Nc(e,t){if(!t||typeof t!=`object`)return;let{status:n,reason:r,updatedAt:i}=t,a={itemId:e.itemId,id:e.id,...typeof i==`string`?{updatedAt:i}:{}};if(n===`applied`)return{...a,status:n};if(n===`conflict`)return{...a,status:n,reason:r===`create_conflict`?`create_conflict`:`stale_write`};if(n===`rejected`&&typeof r==`string`&&r)return{...a,status:n,reason:r}}function Pc(e,t){let n=Mc(e);return{engine:n,record:n.registerCollection(t)}}async function Fc(e,t,n,r){await t.unregisterCollection(n,r)&&jc.get(e)===t&&jc.delete(e)}var Ic=`snapshots`,Lc=`::snapshots`;function Rc(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function zc(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction failed`)),e.onabort=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction aborted`))})}async function Bc(){let e=globalThis.indexedDB;if(!e)return!1;let t=`__smrt_web_snapshot_probe__`;try{(await new Promise((n,r)=>{let i=e.open(t,1);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error??Error(`probe failed`)),i.onblocked=()=>r(Error(`probe blocked`))})).close();try{e.deleteDatabase(t)}catch{}return!0}catch{return!1}}var Vc=class{db;dbName;constructor(e,t){this.db=e,this.dbName=t}async load(e){let t=this.db.transaction(Ic,`readonly`),n=await Rc(t.objectStore(Ic).get(e));if(await zc(t),n&&Array.isArray(n.rows))return n.rows}async save(e,t){let n=this.db.transaction(Ic,`readwrite`),r=n.objectStore(Ic),i={collection:e,rows:t};await Rc(r.put(i)),await zc(n)}async remove(e){let t=this.db.transaction(Ic,`readwrite`);await Rc(t.objectStore(Ic).delete(e)),await zc(t)}async clear(){let e=this.db.transaction(Ic,`readwrite`);await Rc(e.objectStore(Ic).clear()),await zc(e)}close(){this.db.close()}};function Hc(e){let t=globalThis.indexedDB;if(!t)return Promise.reject(Error(`[smrt-web] IndexedDB is unavailable in this environment`));let n=`${e}${Lc}`;return new Promise((e,r)=>{let i=t.open(n,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`snapshots`)||e.createObjectStore(Ic,{keyPath:`collection`})},i.onsuccess=()=>e(new Vc(i.result,n)),i.onerror=()=>r(i.error??Error(`[smrt-web] failed to open snapshot database "${n}"`)),i.onblocked=()=>r(Error(`[smrt-web] opening snapshot database "${n}" was blocked`))})}var Uc=`meta`,Wc=`::meta`,Gc=`lastSeenManifestHash`;function Kc(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function qc(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction failed`)),e.onabort=()=>n(e.error??Error(`[smrt-web] IndexedDB transaction aborted`))})}var Jc=class{db;dbName;constructor(e,t){this.db=e,this.dbName=t}async get(e){let t=this.db.transaction(Uc,`readonly`),n=await Kc(t.objectStore(Uc).get(e));return await qc(t),n&&typeof n.value==`string`?n.value:void 0}async set(e,t){let n=this.db.transaction(Uc,`readwrite`),r={key:e,value:t};await Kc(n.objectStore(Uc).put(r)),await qc(n)}async clear(){let e=this.db.transaction(Uc,`readwrite`);await Kc(e.objectStore(Uc).clear()),await qc(e)}close(){this.db.close()}};function Yc(e){let t=globalThis.indexedDB;if(!t)return Promise.reject(Error(`[smrt-web] IndexedDB is unavailable in this environment`));let n=`${e}${Wc}`;return new Promise((e,r)=>{let i=t.open(n,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`meta`)||e.createObjectStore(Uc,{keyPath:`key`})},i.onsuccess=()=>e(new Jc(i.result,n)),i.onerror=()=>r(i.error??Error(`[smrt-web] failed to open meta database "${n}"`)),i.onblocked=()=>r(Error(`[smrt-web] opening meta database "${n}" was blocked`))})}var Xc=/^smrt-web:[^:]*:(?:_[^:]*)?:(?:_[^:]*)?:[^:]*$/;function Zc(e){return typeof e==`string`&&Xc.test(e)}function Qc(e){if(e!==void 0){for(let t of[Lc,Wc])if(e.endsWith(t)){let n=e.slice(0,-t.length);return Zc(n)?n:void 0}return Zc(e)?e:void 0}}function $c(){return globalThis.indexedDB}async function el(){let e=new Set(uc()),t=$c();if(t&&typeof t.databases==`function`)for(let n of await t.databases()){let t=Qc(n.name);t!==void 0&&e.add(t)}return[...e].sort()}function tl(e){let t=e instanceof Date?e.getTime():typeof e==`number`?e:NaN;if(!Number.isFinite(t))throw TypeError(`pruneDurableNamespace requires olderThan as a valid Date or epoch milliseconds`);return t}function nl(e,t){return new Promise((n,r)=>{let i=!1,a=e.open(t);a.onupgradeneeded=()=>{i=!0,a.transaction?.abort()},a.onsuccess=()=>{let e=a.result;i?(e.close(),n(void 0)):(e.onversionchange=()=>e.close(),n(e))},a.onerror=e=>{i?(e.preventDefault(),n(void 0)):r(a.error??Error(`[smrt-web] failed to open durable database "${t}"`))},a.onblocked=()=>r(Error(`[smrt-web] opening durable database "${t}" was blocked`))})}function rl(e,t){return typeof e.enqueuedAt==`number`&&e.enqueuedAt<t}function il(e,t){return new Promise((n,r)=>{let i=new Map,a=e.transaction(Q,`readonly`),o=a.objectStore(Q).openCursor();o.onsuccess=()=>{let e=o.result;if(!e)return;let n=e.value;if(rl(n,t)){let e=Ec(n);i.set(e,(i.get(e)??0)+1)}e.continue()},a.oncomplete=()=>n(i),a.onerror=()=>r(a.error??Error(`[smrt-web] IndexedDB transaction failed`)),a.onabort=()=>r(a.error??Error(`[smrt-web] IndexedDB transaction aborted`))})}function al(e,t,n){return new Promise((r,i)=>{let a=0,o=e.transaction(Q,`readwrite`),s=o.objectStore(Q).openCursor();s.onsuccess=()=>{let e=s.result;if(!e)return;let r=e.value;Ec(r)===n&&rl(r,t)&&(e.delete(),a+=1),e.continue()},o.oncomplete=()=>r(a),o.onerror=()=>i(o.error??Error(`[smrt-web] IndexedDB transaction failed`)),o.onabort=()=>i(o.error??Error(`[smrt-web] IndexedDB transaction aborted`))})}function ol(){let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}async function sl(e,t,n){let r=ol();return r?r.request(Dc(e,t),{mode:`exclusive`,ifAvailable:!0},async e=>e===null?void 0:n()):lc(e,`outbox`)?void 0:n()}async function cl(e,t){if(!Zc(e))throw TypeError(`pruneDurableNamespace requires a durableStoreNamespace() string`);let n=tl(t?.olderThan),r={removed:0,skipped:0},i=$c();if(!i)return r;let a=await nl(i,e);if(!a)return r;try{if(!a.objectStoreNames.contains(`outbox`))return r;let t=await il(a,n);for(let[i,o]of t){let t=await sl(e,i,()=>al(a,n,i));t===void 0?r.skipped+=o:r.removed+=t}return r}finally{a.close()}}function ll(e){return{initialDelayMs:e?.initialDelayMs??Sc.initialDelayMs,multiplier:e?.multiplier??Sc.multiplier,maxDelayMs:e?.maxDelayMs??Sc.maxDelayMs}}var ul=new Map;async function dl(e,t,n,r){let i=t.referenceCount;await Fc(e,t,n,r),i<=1&&ul.get(e)===t&&ul.delete(e)}function fl(e){let t=e.updatedAt??e.updated_at;if(typeof t==`string`)return t;if(t instanceof Date)return t.toISOString()}function pl(e){let t=ac(e.namespace),n=e.syncApplyBasePath??`/api/v1`,r=e.fetchFn??((...e)=>globalThis.fetch(...e)),i=ll(e.backoff),a=e.transport,o=e.object.name,s,c;return{name:`offline-outbox`,onAttach(){let l=Pc({namespace:t,backoff:i,random:e.random,registerResource:e=>sc(t,{kind:`outbox`,clear:e})},{object:o,onSyncStateChange:e.onSyncStateChange,onConflict:e.onConflict,...a?{transport:a}:{syncApply:{basePath:n,fetchFn:r}}});s=l.engine,c=l.record,ul.set(t,s)},async wrapMutation(e){return!s||!await s.enqueue({kind:e.kind,object:o,rowId:e.key,data:e.data,baseUpdatedAt:e.baseUpdatedAt??fl(e.data),...a?{transport:o}:{}})?{handled:!1}:{handled:!0,result:e.data}},async teardown(){if(!s||!c)return;let e=s,n=c;s=void 0,c=void 0,await dl(t,e,o,n)}}}function ml(e){if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`offlineCommandQueue requires a non-empty name`);if(typeof e.transport!=`function`)throw TypeError(`offlineCommandQueue requires a transport function`);let t=ac(e.namespace),n=e.name,r=Pc({namespace:t,backoff:ll(e.backoff),random:e.random,registerResource:e=>sc(t,{kind:`outbox`,clear:e})},{object:n,transport:e.transport,onSyncStateChange:e.onSyncStateChange,onConflict:e.onConflict}),i=r.engine,a=r.record;return ul.set(t,i),{async enqueue(e){if(i)return i.enqueue({kind:e.op===`create`||e.op===void 0?`insert`:e.op,object:n,rowId:e.rowId??``,data:e.payload??{},baseUpdatedAt:e.baseUpdatedAt,transport:n})},snapshot:async()=>i?i.snapshot():[],retry:async e=>{await i?.retry(e)},async dispose(){let e=i;e&&(i=void 0,await dl(t,e,n,a))}}}function hl(e){let t=ul.get(e);if(t)return{snapshot:()=>t.snapshot(),retry:e=>t.retry(e)}}function gl(e,t){e.unregister||=sc(t,{kind:`persisted-collection`,clear:async()=>{e.wipeEpoch+=1,e.unregister=void 0,await(await e.ready)?.clear()}})}var _l=new Map,vl=!1;function yl(){vl||(vl=!0,console.warn(`[smrt-web] IndexedDB is unavailable; persistence is disabled (collections behave as non-persistent).`))}function bl(e){let t=_l.get(e);if(t)return t.refCount+=1,gl(t,e),t;let n={store:void 0,refCount:1,unregister:void 0,ready:Promise.resolve(void 0),wipeEpoch:0};return n.ready=(async()=>{if(!await Bc())yl();else try{let t=await Hc(e);return n.store=t,t}catch{yl();return}})(),_l.set(e,n),gl(n,e),n}async function xl(e){let t=_l.get(e);t&&(--t.refCount,!(t.refCount>0)&&(_l.delete(e),await t.ready,t.unregister?.(),t.unregister=void 0,t.store?.close(),t.store=void 0))}function Sl(e){let t=ac(e.namespace),n=e.collection,r=e.debounceMs??250,i,a,o,s,c=!1,l,u=!1,d=async()=>{for(;u&&!c;){if(u=!1,!i||!s)return;let e=await i.ready;if(c||!e)return;let t=s().map(e=>({...e}));try{await e.save(n,t)}catch{}}},f=()=>{u=!0,!l&&(l=d().finally(()=>{l=void 0,u&&!c&&f()}))},p=()=>{c||(o&&clearTimeout(o),o=setTimeout(()=>{o=void 0,f()},Math.max(0,r)),o.unref?.())};return{name:`persistence`,async warmStart(e){let r=bl(t);i=r,s=e.snapshot?()=>e.snapshot?.()??[]:void 0;let a=await r.ready;if(!a)return;let o=await a.load(n);if(o&&o.length!==0)return o},onAttach(e){i||=bl(t),!s&&e.snapshot&&(s=()=>e.snapshot?.()??[]),e.snapshot&&e.subscribe&&s&&(a=e.subscribe(()=>p()),p())},async teardown(){c=!0,o&&=(clearTimeout(o),void 0),a?.unsubscribe(),a=void 0,s=void 0,l&&await l;let e=i;i=void 0,e&&await xl(t)}}}function Cl(e){if(!e||typeof e.surfaceId!=`string`||e.surfaceId.length===0||typeof e.kind!=`string`)throw TypeError(`persistDataSurface requires an identity with a surfaceId and kind`);return`data-surface:${JSON.stringify([e.kind,e.surfaceId,e.subject?.type??null,e.subject?.id??null])}`}function wl(e){let t=ac(e.namespace),n=Cl(e.identity),r=e.debounceMs??250,i=bl(t),a=i.wipeEpoch,o=e=>e.wipeEpoch!==a,s,c,l=Promise.resolve(),u=()=>{c&&=(clearTimeout(c),void 0);let e=s;s=void 0;let t=i;return!e||!t||(l=l.then(async()=>{let r=await t.ready;if(r&&!o(t))try{await r.save(n,e)}catch{}})),l};return{async load(){let e=i;if(!e)return;let t=await e.ready;if(!t||o(e))return;let r=await t.load(n);if(r&&r.length!==0)return r},save(e){if(i){if(!Array.isArray(e))throw TypeError(`persistDataSurface.save requires an array of rows`);o(i)||(s=e.map(e=>({...e})),c&&clearTimeout(c),c=setTimeout(()=>{c=void 0,u()},Math.max(0,r)),c.unref?.())}},flush:()=>u(),async dispose(){i&&(await u(),i=void 0,await xl(t))}}}function Tl(e){if(Array.isArray(e))return e.map(Tl);if(e&&typeof e==`object`){let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,Tl(t[e])]))}return e}function El(e){let{requestId:t,...n}=e;return JSON.stringify(Tl(n))}function Dl(e,t){return e.requestId===t.requestId?e:{...e,requestId:t.requestId}}function $(){if(typeof DOMException<`u`)return new DOMException(`The operation was aborted`,`AbortError`);let e=Error(`The operation was aborted`);return e.name=`AbortError`,e}function Ol(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function kl(e){if(e.page)return e.page.kind,{...e.page}}function Al(e,t,n={}){let r=n.staleTimeMs??3e4,i=new Map,a=new Map,o=new Map,s=0,c=new Set,l,u,d=new Set,f=0,p,m,h=0,g=!1,_={rows:[],page:void 0,total:void 0,loading:!1,refreshing:!1,stale:!1,error:null,lastUpdated:void 0,result:void 0},v=e=>{_=e;for(let e of c)e(_)},y=e=>i.get(e),b=(e,t,n,r=Date.now())=>{if(g)return!1;let a=o.get(e);return a===void 0||n>a?(o.set(e,n),i.set(e,{result:t,updatedAt:r}),!0):!1},x=(e,t,n=Date.now(),r)=>{(r===void 0||b(El(t),e,r,n))&&v({rows:e.rows,page:kl(e),total:e.total,loading:!1,refreshing:!1,stale:e.freshness.state===`stale`,error:null,lastUpdated:n,result:e})},S=async(e,n)=>{d.add(n);try{let r=await Vs(t,e,{signal:n.signal});if(n.signal.aborted)throw $();return r}catch(e){throw n.signal.aborted?$():e}finally{d.delete(n)}},C=async(e,t={})=>{if(g)throw $();let n=t.mode??`visible`,i=El(e);if(t.signal?.aborted||(t.deadlineMs??1)<=0)throw $();let a=n===`visible`&&m?.active&&(!p||l!==void 0&&El(l)!==i)?m:void 0,o=y(i),s=o!==void 0&&Date.now()-o.updatedAt<r;if(n!==`visible`&&!t.force&&s)return Dl(o.result,e);if(n===`visible`&&!t.force&&s){if(f+=1,u?.abort($()),g)throw $();u=void 0,l=e,a&&p?.disconnect();let t=Dl(o.result,e);if(x(t,e,o.updatedAt),g)throw $();return a?.active&&!p&&te(a),t}if(n===`visible`){if(f+=1,u?.abort($()),g)throw $();let n=new AbortController;u=n,l=e,a&&p?.disconnect();let r=f,s=t.signal,c;if(s?.aborted)n.abort(s.reason);else if(s){let e=()=>n.abort(s.reason);s.addEventListener(`abort`,e,{once:!0}),c=()=>s.removeEventListener(`abort`,e)}if(o){let t=Dl(o.result,e);v({rows:t.rows,page:kl(t),total:t.total,loading:!1,refreshing:!0,stale:!0,error:null,lastUpdated:o.updatedAt,result:t})}else v({..._,loading:!0,refreshing:!1,stale:!1,error:null});t={...t,signal:n.signal,force:!0};try{if(g)throw $();let n=await T(e,i,t);return r===f&&(y(i)?.result===n?x(n,e):v({..._,loading:!1,refreshing:!1}),a?.active&&!p&&te(a)),n}catch(e){throw r===f&&(Ol(e)?v({..._,loading:!1,refreshing:!1}):v({..._,loading:!1,refreshing:!1,stale:o!==void 0,error:e})),e}finally{c?.(),u===n&&(u=void 0)}}return T(e,i,t)},w=(e,t,n,r)=>r.signal?.aborted||(r.deadlineMs??1)<=0?Promise.reject($()):new Promise((i,o)=>{let s=!1,c=()=>{s||(s=!0,--e.waiters,u&&clearTimeout(u),r.signal?.removeEventListener(`abort`,l))},l=()=>{s||(c(),e.waiters===0&&!e.settled&&(e.controller.abort($()),a.get(t)===e&&a.delete(t)),o($()))},u=r.deadlineMs===void 0?void 0:setTimeout(l,r.deadlineMs);e.waiters+=1,r.signal?.addEventListener(`abort`,l,{once:!0}),e.promise.then(e=>{s||(c(),i(Dl(e,n)))},e=>{s||(c(),o(e))})}),T=async(e,t,n)=>{if(n.signal?.aborted||(n.deadlineMs??1)<=0)throw $();if(!n.force){let r=a.get(t);if(r)return w(r,t,e,n)}let r=++s,i=new AbortController,o=S(e,i).then(e=>{if(i.signal.aborted)throw $();return b(t,e,r),e}),c={controller:i,promise:o,waiters:0,settled:!1};return a.set(t,c),o.then(()=>{c.settled=!0,a.get(t)===c&&a.delete(t)},()=>{c.settled=!0,a.get(t)===c&&a.delete(t)}),w(c,t,e,n)},E=(e={})=>l?C(l,{...e,mode:`visible`,force:!0}):Promise.resolve(void 0),ee=e=>{if(g||!e.active||!l||!t.subscribe)return;let n=l,r=++h,i=new AbortController,a=!0,c,u,d=()=>{a&&(a=!1,i.abort(),c.unsubscribe(),p===u&&(p=void 0))};if(u={intent:e,disconnect:d,unsubscribe:()=>{e.active&&(e.active=!1,d(),m===e&&(m=void 0),p?.intent===e&&p.disconnect())},reconnect:()=>{if(!e.active||g)return;if(!a){p?.intent===e&&p.reconnect();return}if(r!==h)return;d();let t=l;t&&El(t)===El(n)&&C(t,{mode:`visible`,force:!0}).catch(()=>void 0).finally(()=>{e.active&&!g&&m===e&&!p&&l&&El(l)===El(n)&&te(e)})}},c=t.subscribe(n,t=>{if(!a||!e.active||g||r!==h||i.signal.aborted)return;let c=++s;(async()=>{let i=await Vs({query:async()=>t},n);a&&e.active&&!g&&r===h&&l&&El(l)===El(n)&&x(Dl(i,l),l,Date.now(),c)})().catch(t=>{let i=o.get(El(n));!Ol(t)&&a&&e.active&&!g&&r===h&&l&&El(l)===El(n)&&(i===void 0||c>i)&&v({..._,error:t})})},{signal:i.signal}),g||!e.active)d();else return p=u,u},D=e=>{e.active=!1,m===e&&(m=void 0)},te=e=>{try{ee(e)}catch(t){D(e),g||v({..._,error:t})}};return{get state(){return _},get request(){return l},execute:C,refresh:E,retry:()=>E(),subscribe(e){return c.add(e),e(_),()=>c.delete(e)},subscribeLive:()=>{if(g||!l||!t.subscribe)return;m&&(m.active=!1,p?.disconnect());let e={active:!0};m=e;try{return ee(e)}catch(t){throw D(e),t}},invalidate(){if(!l)return;let e=El(l),t=i.get(e);o.set(e,++s),t&&i.set(e,{...t,updatedAt:0}),v({..._,loading:!1,refreshing:!1,stale:!0})},dispose(){g=!0,f+=1,h+=1,u?.abort($());for(let e of d)e.abort($());m&&(m.active=!1),p?.disconnect(),p=void 0,m=void 0,l=void 0,c.clear(),i.clear(),o.clear(),a.clear()}}}var jl=2;function Ml(e,t){let n=globalThis.EventSource;if(typeof n==`function`)return new n(e,t)}function Nl(e){let{eventsUrl:t,changesUrl:n,fetchFn:r=(...e)=>globalThis.fetch(...e),eventSourceFactory:i=Ml,pollIntervalMs:a=5e3,withCredentials:o=!0,manifestHash:s,updateState:c}=e,l=new Map,u=null,d=`idle`,f=null,p=null,m=!1,h=()=>[...l.keys()].sort((e,t)=>e.localeCompare(t)),g=(e,t)=>{let r=new URL(n,`http://smrt.local/`);if(r.searchParams.set(`since`,String(e)),r.searchParams.set(`tables`,t.join(`,`)),/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(n))return r.href;let i=`${r.pathname}${r.search}${r.hash}`;return n.startsWith(`//`)?`//${r.host}${i}`:n.startsWith(`/`)?i:i.startsWith(`/`)?i.slice(1):i},_=e=>typeof e==`number`&&Number.isFinite(e),v=(e,t)=>{console.warn(`[smrt-web] live subscriber: ${e}`,t)},y=e=>{if(e&&e.size!==0)for(let t of[...e])try{t()}catch(e){v(`an invalidator threw; ignoring`,e)}},b=e=>{y(l.get(e))},x=()=>{for(let e of l.values())y(e)},S=e=>{let t=Number(e);Number.isFinite(t)&&(u=t)},C=e=>{if(m)return;let t;try{let n=JSON.parse(e.data);typeof n.table==`string`&&(t=n.table)}catch(e){v(`dropping malformed change frame`,e);return}t===void 0?v(`dropping change frame with no table`,e.data):(S(e.lastEventId),b(t))},w=e=>{m||(S(e.lastEventId),x())},T=e=>{if(!m&&s!==void 0&&c)try{let t=JSON.parse(e.data).manifestHash;if(typeof t!=`string`||t.length===0){v(`dropping manifest frame with no manifestHash`,e.data);return}t!==s&&c.notifyContractUpdated()}catch(e){v(`dropping malformed manifest frame`,e)}},E=async()=>{if(m)return;let e=h();if(e.length!==0)try{let t=u??0,n=g(t,e),i=await r(n,{credentials:`include`});if(m)return;let a=await i.json();if(m)return;if(a.resyncRequired){x(),u=_(a.resyncCursor)?a.resyncCursor:_(a.cursor)&&a.cursor>t?a.cursor:null;return}for(let e of a.changes??[])typeof e.table==`string`&&b(e.table);typeof a.cursor==`number`&&(u=a.cursor)}catch(e){v(`poll failed; will retry on the next interval`,e)}},ee=()=>{m||d===`polling`||(d=`polling`,p=setInterval(()=>{E()},a),p.unref?.())},D=e=>{d=`sse`,f=e,e.addEventListener(`change`,C),e.addEventListener(`resync`,w),e.addEventListener(`manifest`,T),e.onerror=()=>{if(!m&&e.readyState===jl){try{e.close()}catch{}f=null,ee()}}},te=i(t,{withCredentials:o});return te?D(te):ee(),{get transport(){return d},registerTable(e,t){let n=l.get(e);return n||(n=new Set,l.set(e,n)),n.add(t),()=>{let n=l.get(e);n&&(n.delete(t),n.size===0&&l.delete(e))}},invalidateAll:x,close(){if(!m){if(m=!0,f){try{f.close()}catch{}f=null}p&&=(clearInterval(p),null),l.clear(),d=`idle`}}}}function Pl(e){let{subscriber:t,tableName:n}=e,r;return{name:`live-invalidation`,onAttach(e){r=t.registerTable(n,()=>e.invalidate())},teardown(){r?.(),r=void 0}}}function Fl(e){let t=ac(e.namespace),n=!1,r=!1,i=new Set,a,o,s=!1,c=()=>({bundle:n,contract:r,updateAvailable:n||r}),l=()=>{let e=c();for(let t of[...i])try{t(e)}catch(e){console.warn(`[smrt-web] updateAvailable subscriber threw`,e)}},u=()=>{n||(n=!0,l())},d=()=>{r||(r=!0,l())};return{get:c,subscribe(e){i.add(e);try{e(c())}catch(e){console.warn(`[smrt-web] updateAvailable subscriber threw`,e)}return()=>{i.delete(e)}},notifyBundleUpdated:u,notifyContractUpdated:d,ready:(async()=>{let n=e.manifestHash;if(n===void 0)return;let r;try{r=await Yc(t)}catch{return}if(s){r.close();return}a=r,o=sc(t,{kind:`persisted-collection`,clear:()=>r.clear()});let i;try{i=await r.get(Gc)}catch{i=void 0}if(!s&&(i!==void 0&&i!==n&&d(),i!==n))try{await r.set(Gc,n)}catch{}})(),dispose(){s=!0,o?.(),o=void 0,a?.close(),a=void 0,i.clear()}}}function Il(){let e=globalThis.document?.modelContext;if(e&&typeof e.registerTool==`function`)return e}function Ll(e,n={}){let r=Wl(n),i=Il();if(!i)return Rl(()=>{},Promise.resolve());let a=n.basePath??`/api/v1`,s=n.client,{tools:c,allowedEffects:l}=Gl(e,n,r);s&&c.some(e=>e.kind===`canonical`&&e.effect!==`read`)&&Eu(s);let u=new AbortController,d=new Map,f=new Map,p=t(c.map(e=>e.name),`generated`),m=!1,h=()=>{if(!m){m=!0,u.abort(),p.release();for(let e of d.values())e.cleanup().catch(()=>void 0)}},g=[];try{for(let e of c){if(e.kind===`legacy`){let{definition:t,descriptor:r}=e,c=f.get(t),p=d.get(t);(!c||!p)&&(c=n.resolveFetchers?n.resolveFetchers(Ql(t)):xu(t,a,n.fetchFn),p=Iu(t,{fetchers:c,basePath:a,fetchFn:n.fetchFn,...s?{client:s}:{},...n.scope?{scope:n.scope}:{}}),f.set(t,c),d.set(t,p)),g.push(Promise.resolve(i.registerTool({[o]:e.effect,name:e.name,description:r.description,inputSchema:r.inputSchema,annotations:tu(e),execute:ru(e,l,()=>m,e=>cu(c,p,t,r.action,r.route,e))},{signal:u.signal})));continue}let{definition:t}=e,r=n.resolveToolFetchers?n.resolveToolFetchers($l(t,{effect:e.effect,destructive:e.destructive,idempotent:e.idempotent,openWorld:e.openWorld})):xu({name:t.collection,endpoint:t.endpoint},a,n.fetchFn);g.push(Promise.resolve(i.registerTool({[o]:e.effect,name:e.name,description:t.description,inputSchema:t.inputSchema,annotations:tu(e),execute:ru(e,l,()=>m,e=>lu(r,t,e,s))},{signal:u.signal})))}}catch(e){throw Promise.all(g).catch(()=>void 0),h(),e}let _=Promise.all(g).then(()=>void 0).catch(e=>{throw h(),e});return _.catch(()=>void 0),Rl(h,_)}function Rl(e,t){return Object.assign(e,{ready:t})}function zl(e,t={}){return Bl(e,t,t.owner??`bespoke`)}function Bl(e,n,r){let{allowedEffects:i}=Wl(n),a=Il();if(!a)return Rl(()=>{},Promise.resolve());let s=ql(`bespoke`,Jl(e.annotations));if(!i.has(s.effect))return Rl(()=>{},Promise.resolve());let c=t([e.name],r),l=new AbortController,u=!1,d=()=>{u||(u=!0,l.abort(),c.release())},f;try{f=a.registerTool({[o]:s.effect,name:e.name,description:e.description,inputSchema:e.inputSchema,annotations:tu(s),execute:nu(e.execute,ru({name:e.name,effect:s.effect},i,()=>u,e.execute))},{signal:l.signal})}catch(e){throw d(),e}let p=Promise.resolve(f).catch(e=>{throw d(),e});return p.catch(()=>void 0),Rl(d,p)}function Vl(e,t,n={}){return Bl(ee(e,t),n,`intent`)}var Hl=s,Ul=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function Wl(e){let t=e.effects??[`read`];for(let e of t)if(!Hl.includes(e))throw Error(`Invalid WebMCP effect: ${String(e)}`);let n=e.maxTools;if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw Error(`WebMCP maxTools must be a non-negative safe integer`);let r=e.namespace;if(r!==void 0&&!Ul.test(r))throw Error(`WebMCP namespace must start with an alphanumeric character and contain only letters, numbers, underscores, or hyphens`);return{allowedEffects:new Set(t),...n===void 0?{}:{maxTools:n},...r===void 0?{}:{namespace:r}}}function Gl(e,t,n){let{allowedEffects:r,maxTools:i,namespace:a}=n,o=e.map(e=>Xl(e)),s=[];for(let e of o){if(iu(e)){let n=c(e);if(!r.has(n.effect))continue;if(t.filter&&!t.filterTool)throw Error(`[smrt-web] canonical WebMCP definitions require filterTool when filter is configured`);let i=$l(e,n);if(t.filterTool&&!t.filterTool($l(i,n)))continue;s.push({kind:`canonical`,definition:i,descriptor:i,name:Kl(i.name,a),identity:`${i.collection}#${i.action}`,...n});continue}let n=Ql(e);for(let e of n.toolDescriptors??[]){if(!n.actions.includes(e.action))throw Error(`WebMCP tool ${e.name} exposes action ${e.action} outside ${n.name}'s allowed actions`);let i=ql(e.action,e);if(!r.has(i.effect))continue;if(t.filterTool&&!t.filter)throw Error(`[smrt-web] legacy WebMCP definitions require filter when filterTool is configured`);let o=Zl(e,i);(!t.filter||t.filter(Ql(n),Zl(o,i)))&&s.push({kind:`legacy`,definition:n,descriptor:o,name:Kl(o.name,a),identity:`${n.name}#${o.action}`,...i})}}return eu(s,i),{tools:s,allowedEffects:r}}function Kl(e,t){return t?`${t}_${e}`:e}function ql(e,t){switch(e){case`list`:case`get`:return{effect:`read`,destructive:!1,idempotent:!0,openWorld:!1};case`create`:return{effect:`write`,destructive:!0,idempotent:!1,openWorld:!1};case`update`:return{effect:`write`,destructive:!0,idempotent:!0,openWorld:!1};case`delete`:return{effect:`destructive`,destructive:!0,idempotent:!0,openWorld:!1};default:return c(t)}}function Jl(e){if(!e)return{};let t=e.destructiveHint===!0?`destructive`:e.readOnlyHint===!0?`read`:e.destructiveHint===!1?`write`:void 0;return{...t?{effect:t}:{},...e.idempotentHint===void 0?{}:{idempotent:e.idempotentHint},...e.openWorldHint===void 0?{}:{openWorld:e.openWorldHint}}}function Yl(e){return e?Xl(e):void 0}function Xl(e,t=new WeakSet,n=`$`){if(e&&typeof e==`object`){if(t.has(e))throw Error(`[smrt-web] WebMCP definitions must be acyclic (cycle at ${n})`);t.add(e)}try{if(Array.isArray(e))return e.map((e,r)=>Xl(e,t,`${n}[${r}]`));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e))r[i]=Xl(a,t,`${n}.${i}`);return r}return e}finally{e&&typeof e==`object`&&t.delete(e)}}function Zl(e,t){return Xl({...e,effect:t.effect,idempotent:t.idempotent,openWorld:t.openWorld,readOnly:t.effect===`read`,route:Yl(e.route)})}function Ql(e){let t=Xl({...e,actions:[...e.actions]});return t.toolDescriptors=t.toolDescriptors?.map(e=>Zl(e,ql(e.action,e))),t}function $l(e,t){return Xl({...e,effect:t.effect,idempotent:t.idempotent,openWorld:t.openWorld,readOnly:t.effect===`read`,route:Yl(e.route)})}function eu(e,t){if(t!==void 0&&e.length>t)throw Error(`WebMCP tool budget exceeded: ${e.length} tools selected, maximum is ${t}`);let n=new Set,r=new Set;for(let t of e){if(n.has(t.name))throw Error(`Duplicate WebMCP tool name: ${t.name}`);if(n.add(t.name),r.has(t.identity))throw Error(`Duplicate WebMCP tool identity: ${t.identity}`);r.add(t.identity)}}function tu(e){return l(e)}function nu(e,t){return a(e)?n(t):t}function ru(e,t,n,r){return(i,a)=>{if(n())throw Error(`WebMCP tool ${e.name} is no longer registered`);if(!t.has(e.effect))throw Error(`WebMCP policy no longer allows ${e.effect} tool ${e.name}`);return a===void 0?r(i??{}):r(i??{},a)}}function iu(e){return`collection`in e&&`readOnly`in e}function au(e,t){let n=e.id;if(typeof n!=`string`||n.length===0)throw Error(`WebMCP ${t} requires a string 'id' argument`);return n}function ou(e){let t=e.id??e.slug;if(typeof t!=`string`||t.length===0)throw Error(`WebMCP get requires a string 'id' or 'slug' argument`);return t}function su(e){let t={};return e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),e.orderBy!==void 0&&(t.orderBy=e.orderBy),e.where!==void 0&&(t.where=e.where),t}async function cu(e,t,n,r,i,a){switch(r){case`list`:{let t=gu(await e.list(su(a)),n.name);return JSON.stringify(t)}case`get`:{if(!e.get)throw Error(`${n.name} has no get action`);let t=_u(await e.get(ou(a)),`get(${n.name})`);return JSON.stringify(t)}case`create`:{let e=Su(),r=_u(await uu(t.insert({...a,id:e}),t,e,a),`create(${n.name})`);return JSON.stringify(r)}case`update`:{if(!e.update)throw Error(`${n.name} has no update action`);let{id:r,...i}=a;await du(e,t,n,au(a,`update`));let o=_u(await uu(t.update(au(a,`update`),i),t,au(a,`update`),i),`update(${n.name})`);return JSON.stringify(o)}case`delete`:{if(!e.delete)throw Error(`${n.name} has no delete action`);let r=au(a,`delete`);return await du(e,t,n,r),await uu(t.delete(r),t,r,{}),JSON.stringify({success:!0,id:r})}default:if(!e.custom)throw Error(`${n.name} has no custom action fetcher`);return JSON.stringify(await t.action(r,a,i))}}async function lu(e,t,n,r){let i;switch(t.action){case`list`:if(!e.list)throw Error(`${t.collection} has no list action`);i=gu(await e.list(su(n)),t.collection);break;case`get`:if(!e.get)throw Error(`${t.collection} has no get action`);i=_u(await e.get(ou(n)),`get(${t.collection})`);break;case`create`:if(!e.create)throw Error(`${t.collection} has no create action`);i=_u(await e.create(n),`create(${t.collection})`);break;case`update`:{if(!e.update)throw Error(`${t.collection} has no update action`);let r=au(n,`update`),{id:a,...o}=n;i=_u(await e.update(r,o),`update(${t.collection})`);break}case`delete`:{if(!e.delete)throw Error(`${t.collection} has no delete action`);let r=au(n,`delete`);vu(await e.delete(r),`delete(${t.collection})`),i={success:!0,id:r};break}default:if(!e.custom)throw Error(`${t.collection} has no custom action fetcher`);i=vu(await e.custom(t.action,n,t.route),`${t.action}(${t.collection})`)}return!t.readOnly&&r&&Ou(r,[t.collection,...t.relationships.map(e=>e.relatedCollection)]),JSON.stringify(i)}async function uu(e,t,n,r){await e.isPersisted.promise;let i=xs.get(t)?.get(n);return i===void 0?t.get(n)??{...r,id:n}:i}async function du(e,t,n,r){if(!e.get)throw Error(`${n.name} has no get action; cannot hydrate mutation target '${r}'`);let i=_u(await e.get(r),`get(${n.name})`),a=Ss.get(t);if(!a)throw Error(`${n.name} cannot hydrate mutation target '${r}'`);await a(i)}var fu=`__smrt_options`,pu=class extends Error{payload;status;code;constructor(e,t,n,r){super(e),this.name=`SmrtWebRequestError`,this.payload=t,n!==void 0&&(this.status=n),r!==void 0&&(this.code=r)}};function mu(e){if(!e||typeof e!=`object`)return{};let t=e.error;if(typeof t==`string`)return{message:t};if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t;return{message:typeof n.message==`string`?n.message:void 0,code:typeof n.code==`string`?n.code:void 0}}function hu(e,t,n){if(t>=500)return new pu(`[smrt-web] ${e} request failed: server error`,void 0,t);let r=mu(n);return new pu(`[smrt-web] ${e} request failed: ${r.message??`HTTP ${t}`}`,n,t,r.code)}function gu(e,t){if(vu(e,`list(${t})`),Array.isArray(e))return e;if(e&&typeof e==`object`){let t=e;if(Array.isArray(t.items))return t.items;if(Array.isArray(t.data))return t.data}throw new pu(`[smrt-web] list(${t}) returned an unexpected payload shape`,e)}function _u(e,t){if(vu(e,t),e&&typeof e==`object`&&!Array.isArray(e)){let t=e;return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:t}throw new pu(`[smrt-web] ${t} returned an unexpected payload shape`,e)}function vu(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return e;let n=e.error;if(typeof n==`string`)throw new pu(`[smrt-web] ${t} failed: ${n}`,e);if(!n||typeof n!=`object`||Array.isArray(n))return e;let r=n;if(r.ok!==!1||typeof r.code!=`string`||typeof r.message!=`string`)return e;let i=typeof r.status==`number`&&Number.isInteger(r.status)&&r.status>=400&&r.status<=599?r.status:void 0;throw i!==void 0&&i>=500?new pu(`[smrt-web] ${t} failed: server error`,void 0,i):new pu(`[smrt-web] ${t} failed: ${r.message}`,e,i,r.code)}var yu={">":`gt`,">=":`gte`,"<":`lt`,"<=":`lte`,"!=":`ne`,in:`in`,like:`like`};function bu(e){if(!e)return``;let t=new URLSearchParams,{limit:n,offset:r,orderBy:i,where:a}=e;if(n!==void 0&&t.set(`limit`,String(n)),r!==void 0&&t.set(`offset`,String(r)),i!==void 0&&t.set(`orderBy`,Array.isArray(i)?i.join(`, `):String(i)),a&&typeof a==`object`)for(let[e,n]of Object.entries(a))if(n&&typeof n==`object`&&!Array.isArray(n)&&`op`in n&&`value`in n){let{op:r,value:i}=n,a=yu[r],o=Array.isArray(i)?i.join(`,`):String(i);t.set(a?`${e}[${a}]`:e,o)}else n!=null&&t.set(e,String(n));let o=t.toString();return o?`?${o}`:``}function xu(e,t=`/api/v1`,n=(...e)=>globalThis.fetch(...e)){let r=`${t}${e.endpoint}`,i={"Content-Type":`application/json`},a=async t=>{if(!t.ok){if(t.status>=500)throw hu(e.name,t.status);let n=await t.json().catch(()=>null);throw hu(e.name,t.status,n)}return t.json().catch(()=>null)};return{list:async e=>a(await n(`${r}${bu(e)}`,{headers:i})),get:async e=>a(await n(`${r}/${e}`,{headers:i})),create:async e=>a(await n(r,{method:`POST`,headers:i,body:JSON.stringify(e)})),update:async(e,t)=>a(await n(`${r}/${e}`,{method:`PUT`,headers:i,body:JSON.stringify(t)})),delete:async t=>{let a=await n(`${r}/${t}`,{method:`DELETE`,headers:i});if(!a.ok){if(a.status>=500)throw hu(e.name,a.status);let t=await a.json().catch(()=>null);throw hu(e.name,a.status,t)}return!0},custom:async(t,o,s)=>{let c=s??{method:`POST`,scope:typeof o.id==`string`?`item`:`collection`,path:[t]},l=c.optionsBag===!0,u=l?o.options:void 0,d=l&&typeof u==`object`&&u?u:o,f=new Set(c.path.filter(e=>/^\[[^\]]+\]$/.test(e)).map(e=>e.slice(1,-1))),p=c.parameterAliases??{},m=e=>Object.entries(p).find(([,t])=>t===e)?.[0]??e,h=e=>o[m(e)]??o[e],g=c.scope===`item`?o.id:void 0;if(c.scope===`item`&&typeof g!=`string`)throw Error(`${e.name} custom action '${t}' requires an id`);for(let n of f)if(h(n)===void 0||h(n)===null)throw Error(`${e.name} custom action '${t}' requires '${n}'`);let _=new Set([...f].map(e=>m(e))),v=new Set(Object.keys(p)),y=l?u:Object.fromEntries(Object.entries(d).filter(([e])=>e!==`id`&&!f.has(e)&&!_.has(e)&&!v.has(e)));if(!l)for(let[e,t]of Object.entries(p))!_.has(e)&&d[e]!==void 0&&t!==`id`&&(y[t]=d[e]);let b=Object.entries(p).find(([,e])=>e===`id`)?.[0];!l&&b&&!_.has(b)&&d[b]!==void 0&&(y.id=d[b]);let x=`${[r,...c.scope===`item`?[encodeURIComponent(String(g))]:[],...c.path.map(e=>/^\[[^\]]+\]$/.test(e)?encodeURIComponent(String(h(e.slice(1,-1))??``)):e)].join(`/`)}`,S={method:c.method,headers:i};if(c.method!==`GET`)S.body=JSON.stringify(y);else{let e=new URLSearchParams;if(l){if(u===void 0&&f.size===0)e.set(fu,`undefined`);else if(u===null&&f.size===0)e.set(fu,`null`);else{let t=Object.entries(typeof u==`object`&&u&&!Array.isArray(u)?u:{}).filter(([,e])=>e!=null);for(let[n,r]of t)e.set(n,typeof r==`object`?JSON.stringify(r):String(r));t.length===0&&f.size===0&&e.set(fu,`object`)}}else{let t=typeof y==`object`&&y&&!Array.isArray(y)?y:{};for(let[n,r]of Object.entries(t))r!=null&&e.set(n,typeof r==`object`?JSON.stringify(r):String(r))}let t=e.toString()?`?${e.toString()}`:``;return a(await n(`${x}${t}`,{...S}))}return a(await n(x,S))}}}function Su(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`local-${Date.now()}-${Math.random().toString(36).slice(2)}`}var Cu=new WeakSet;function wu(){let e={__smrtWebClient:`SmrtWebClient`,queryClient:new zo};return Cu.add(e),e}function Tu(e){if(!e)return new zo;let t=e;if(!Cu.has(t)||t.__smrtWebClient!==`SmrtWebClient`||!t.queryClient)throw new pu(`[smrt-web] options.client must be a handle from createSmrtWebClient()`);return t.queryClient}function Eu(e){Tu(e)}function Du(e,t){t.size!==0&&e.invalidateQueries({predicate:e=>{let n=e.queryKey;if(!Array.isArray(n)||n.length===0)return!1;let r=n[n.length-1];return typeof r==`string`&&t.has(r)}})}function Ou(e,t){Du(Tu(e),new Set(t))}function ku(e){let t={};for(let[n,r]of Object.entries(e))n.charCodeAt(0)!==36&&(t[n]=r);return t}function Au(e){return Array.isArray(e)?e.map(e=>{if(!e||typeof e!=`object`)return e;let t=e,n={...t};return t.value&&typeof t.value==`object`&&(n.value=ku(t.value)),t.previousValue&&typeof t.previousValue==`object`&&(n.previousValue=ku(t.previousValue)),n}):e}function ju(e){let t=e.when(`settled`);return t.catch(()=>{}),{isPersisted:{promise:t}}}function Mu(e){if(!e||typeof e!=`object`)return;let t=e,n=t.updatedAt??t.updated_at;if(typeof n==`string`)return n;if(n instanceof Date)return n.toISOString()}var Nu=new WeakMap;function Pu(e){let t=Nu.get(e);if(t===void 0)throw new pu(`[smrt-web] getEngineCollection: not a smrt-web collection handle`);return t}function Fu(e,t,n){console.warn(`[smrt-web] capability "${e.name}" ${t} threw; ignoring`,n)}function Iu(e,t){let{staleTimeMs:n=3e4,retry:r=!1,scope:i,initialData:a}=t,o=t.capabilities??[],s=t.fetchers??xu(e,t.basePath,t.fetchFn),c=Tu(t.client),l=e.idField||`id`,u=new Map,d=i?`smrt:${i}:${e.name}`:`smrt:${e.name}`,f=i?[`smrt`,i,e.name]:[`smrt`,e.name],p=new Set([e.name]);for(let t of e.relationships??[])p.add(t.relatedCollection);let m=()=>{Du(c,p)},h={definition:e,fetchers:s,get cacheKey(){return f},get cacheId(){return d},invalidate:()=>m(),snapshot:()=>C(),subscribe:e=>w(e)};for(let e of o){let t;try{t=e.contributeCacheKey?.(h)}catch(t){Fu(e,`contributeCacheKey`,t)}if(t&&t.length>0){let e=f[f.length-1];f=[...f.slice(0,-1),...t,e],d=`${d}:${t.join(`:`)}`}}let g=e=>{c.setQueryData(f,t=>t??e)},_=!1,v=async(e,t)=>{try{return await t}catch(t){Fu(e,`warmStart`,t);return}},y;if(a!==void 0)g(a);else for(let e=0;e<o.length;e+=1){let t=o[e],n;try{n=t.warmStart?.(h)}catch(e){Fu(t,`warmStart`,e);continue}if(n!==void 0){if(n instanceof Promise){let r=n;y=(async()=>{let n=await v(t,r);for(let t=e+1;n===void 0&&t<o.length;t+=1){let e=o[t],r;try{r=e.warmStart?.(h)}catch(t){Fu(e,`warmStart`,t);continue}r!==void 0&&(n=await v(e,r))}n!==void 0&&!_&&g(n)})();break}g(n);break}}let b=(e,t)=>{for(let n of o)try{n.onSettled?.(e,t,h)}catch(e){Fu(n,`onSettled`,e)}},x=async(e,t)=>{try{let n=await bs(o,e,h),r=n.handled?n.result:await t();return b(e,{ok:!0,result:r}),{handled:n.handled,result:r}}catch(t){throw b(e,{ok:!1,error:t}),t}},S=ea(ys({id:d,queryKey:f,queryClient:c,staleTime:n,retry:r,queryFn:async()=>gu(await s.list(),e.name),getKey:e=>String(e[l]),onInsert:async({transaction:t,collection:n})=>{let r=!1;for(let n of t.mutations){let t=n.modified,i={kind:`insert`,key:String(t[l]),data:t},a=await x(i,async()=>{let{[l]:n,...r}=t;return _u(await s.create(r),`create(${e.name})`)});u.set(i.key,a.result),r||=a.handled}r?await n.utils.writeUpsert(t.mutations.map(e=>e.modified)):(await n.utils.refetch(),m())},onUpdate:s.update?async({transaction:t,collection:n})=>{let r=!1;for(let n of t.mutations){let t=String(n.key),i=n.changes,a={kind:`update`,key:t,data:i,baseUpdatedAt:Mu(n.original)},o=await x(a,async()=>_u(await s.update(t,i),`update(${e.name})`));u.set(a.key,o.result),r||=o.handled}r?await n.utils.writeUpsert(t.mutations.map(e=>e.modified)):(await n.utils.refetch(),m())}:void 0,onDelete:s.delete?async({transaction:t,collection:n})=>{let r=!1;for(let n of t.mutations){let t=String(n.key),i={kind:`delete`,key:t,data:{},baseUpdatedAt:Mu(n.original)},a=await x(i,async()=>vu(await s.delete(t),`delete(${e.name})`));u.set(i.key,a.result),r||=a.handled}r?await n.utils.writeDelete(t.mutations.map(e=>String(e.key))):(await n.utils.refetch(),m())}:void 0}));function C(){let e=S.toArray.map(e=>ku(e)),t=c.getQueryData(f);if(!Array.isArray(t)||t.length===0)return e;let n=new Map;t.forEach((e,t)=>{let r=String(e[l]);n.has(r)||n.set(r,t)});let r=e=>n.get(String(e[l]))??1/0;return e.sort((e,t)=>{let n=r(e),i=r(t);return n===i?0:n<i?-1:1})}function w(e){let t=()=>{let e=c.getQueryData(f);return Array.isArray(e)?e.map(e=>String(e[l])):[]},n=t(),r=S.subscribeChanges(t=>e(Au(t))),i=c.getQueryCache().subscribe(r=>{if(r.type!==`updated`||JSON.stringify(r.query.queryKey)!==JSON.stringify(f))return;let i=t(),a=new Set(n),o=new Set(i),s=(e,t)=>e.filter(e=>t.has(e)),c=s(n,o),l=s(i,a);n=i,c.length>1&&c.some((e,t)=>e!==l[t])&&e(Au([]))});return{unsubscribe:()=>{i(),r.unsubscribe()}}}let T={get toArray(){return C()},get size(){return S.size},has(e){return S.has(e)},get(e){let t=S.get(e);return t===void 0?void 0:ku(t)},preload(){return y?y.then(()=>{if(!_)return S.preload()}):S.preload()},async cleanup(){_=!0,await S.cleanup({dependents:!0});for(let e of o)try{await e.teardown?.(h)}catch(t){Fu(e,`teardown`,t)}},subscribeChanges(e){return w(e)},insert(e){return ju(S.insert(e))},update(t,n){if(!s.update)throw Error(`${e.name} has no update action`);let{id:r,...i}=n;return ju(S.update(t,e=>{Object.assign(e,i)}))},delete(t){if(!s.delete)throw Error(`${e.name} has no delete action`);return ju(S.delete(t))},async action(t,n,r){if(!s.custom)throw Error(`${e.name} has no custom action fetcher`);let i=r===void 0?await s.custom(t,n):await s.custom(t,n,r);return vu(i,`${t}(${e.name})`),m(),i}};xs.set(T,u),Ss.set(T,async e=>{await S.preload(),await S.utils.writeUpsert(e)}),Nu.set(T,S);for(let e of o)try{e.onAttach?.(h)}catch(t){Fu(e,`onAttach`,t)}return T}var Lu=e({DEFAULT_PERSIST_DEBOUNCE_MS:()=>250,MAX_SMRT_WEB_DATA_QUERY_CONTAINER_ITEMS:()=>ks,MAX_SMRT_WEB_DATA_QUERY_FACETS:()=>20,MAX_SMRT_WEB_DATA_QUERY_FACET_VALUES:()=>Es,MAX_SMRT_WEB_DATA_QUERY_OFFSET:()=>Os,MAX_SMRT_WEB_DATA_QUERY_PAGE_LIMIT:()=>Ds,MAX_SMRT_WEB_DATA_QUERY_RESULT_BYTES:()=>ws,MAX_SMRT_WEB_DATA_QUERY_ROWS:()=>Ts,MAX_SMRT_WEB_DATA_QUERY_STRING_LENGTH:()=>As,MAX_SMRT_WEB_DATA_QUERY_WARNINGS:()=>100,MAX_SMRT_WEB_DATA_SURFACE_ACTION_CONTAINER_ITEMS:()=>Us,MAX_SMRT_WEB_DATA_SURFACE_ACTION_IDENTIFIER_LENGTH:()=>256,MAX_SMRT_WEB_DATA_SURFACE_ACTION_JSON_DEPTH:()=>16,MAX_SMRT_WEB_DATA_SURFACE_ACTION_RESULT_BYTES:()=>Hs,SmrtWebRequestError:()=>pu,WebMcpToolNameCollisionError:()=>r,buildListQuery:()=>bu,classifySmrtWebDataSurfaceActionResult:()=>rc,compileViewIntentToolSpec:()=>ee,createDefinitionFetchers:()=>xu,createSmrtCollection:()=>Iu,createSmrtWebClient:()=>wu,createSmrtWebEventSubscriber:()=>Nl,createSmrtWebQuery:()=>Al,createUpdateState:()=>Fl,dataSurfaceActionCommandTransport:()=>ic,durableStoreNamespace:()=>ac,executeSmrtWebDataQuery:()=>Vs,executeSmrtWebDataSurfaceAction:()=>Qs,getEngineCollection:()=>Pu,getOutboxHandle:()=>hl,invalidateSmrtWebCollections:()=>Ou,listDurableNamespaces:()=>el,liveInvalidation:()=>Pl,newLocalId:()=>Su,normalizeSmrtWebDataQueryResult:()=>Bs,normalizeSmrtWebDataSurfaceActionResult:()=>Zs,offlineCommandQueue:()=>ml,offlineOutbox:()=>pl,persistCollection:()=>Sl,persistDataSurface:()=>wl,pruneDurableNamespace:()=>cl,registerDurableResource:()=>sc,registerViewIntent:()=>Vl,registerWebMcpBespokeTool:()=>zl,registerWebMcpTools:()=>Ll,reserveWebMcpToolNames:()=>t,runWrapMutation:()=>bs,throwIfSmrtWebError:()=>vu,unwrapItemResult:()=>_u,unwrapListResult:()=>gu,validateSmrtWebClient:()=>Eu,viewIntentToolName:()=>m,webMcpToolNameOwner:()=>i,wipeDurableStore:()=>cc});export{Lu as t};