@happyvertical/smrt-planner 0.57.41 → 0.57.43

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 (540) hide show
  1. package/agents/assistant.md +2 -2
  2. package/agents/shell.md +1 -1
  3. package/app/404.html +19 -19
  4. package/app/_app/immutable/assets/2.DONG6EWe.css +1 -0
  5. package/app/_app/immutable/assets/app.CNgJdfDA.css +1 -0
  6. package/app/_app/immutable/chunks/{C1YC2rhY.js → 0HEEaKDE.js} +1 -1
  7. package/app/_app/immutable/chunks/{taDhg4le.js → 3XhH_h7e.js} +1 -1
  8. package/app/_app/immutable/chunks/{CDf6D2PE.js → 77cA2IHw.js} +1 -1
  9. package/app/_app/immutable/chunks/B9-iYiTV.js +1 -0
  10. package/app/_app/immutable/chunks/BAPJxs8s.js +1 -0
  11. package/app/_app/immutable/chunks/{D9u2Mg-P.js → BBmzhVVE.js} +1 -1
  12. package/app/_app/immutable/chunks/{CP5U2sdd.js → BQgJ05r2.js} +1 -1
  13. package/app/_app/immutable/chunks/{DkqJO8K2.js → B_DUvQ2-.js} +1 -1
  14. package/app/_app/immutable/chunks/{BKBQyYIa.js → BeocJqqC.js} +1 -1
  15. package/app/_app/immutable/chunks/{Ba8QYCqr.js → BgOimu0u.js} +1 -1
  16. package/app/_app/immutable/chunks/{Dd0cSvdc.js → BhY9m7ye.js} +1 -1
  17. package/app/_app/immutable/chunks/{BXp_5G-Z.js → Bi1YzXmx.js} +3 -3
  18. package/app/_app/immutable/chunks/{rWYY8AXO.js → CBwPTTnw.js} +1 -1
  19. package/app/_app/immutable/chunks/{DT1JBhRk.js → CGaC_GdN.js} +1 -1
  20. package/app/_app/immutable/chunks/{-zI-HZvG.js → CXSW_54w.js} +1 -1
  21. package/app/_app/immutable/chunks/{B9ToxWrf.js → Cc87O25b.js} +1 -1
  22. package/app/_app/immutable/chunks/{Cx4Tqd_4.js → CxwaJzH4.js} +1 -1
  23. package/app/_app/immutable/chunks/{DANMIVJG.js → D3cv8Pui.js} +1 -1
  24. package/app/_app/immutable/chunks/{BMnSmV3a.js → DCxyGpWs.js} +1 -1
  25. package/app/_app/immutable/chunks/{VsFwp6G3.js → DKO8GXxX.js} +34 -34
  26. package/app/_app/immutable/chunks/{C_ZqLqHp.js → DSdlNRNs.js} +1 -1
  27. package/app/_app/immutable/chunks/{D3RGizRs.js → DYJvnJSH.js} +2 -2
  28. package/app/_app/immutable/chunks/{Cn8nbD9n.js → DhruBIjb.js} +1 -1
  29. package/app/_app/immutable/chunks/DuXHA11S.js +2 -0
  30. package/app/_app/immutable/chunks/{Dxtc6xrY.js → EVM4wuMZ.js} +1 -1
  31. package/app/_app/immutable/chunks/{BOhKr_nv.js → HarHvnXF.js} +1 -1
  32. package/app/_app/immutable/chunks/{SRZuspg7.js → OkFnmq-I.js} +1 -1
  33. package/app/_app/immutable/chunks/{B9K2s1AV.js → P0teM5Ra.js} +1 -1
  34. package/app/_app/immutable/chunks/{BB3IgIsH.js → fuxyXxHR.js} +1 -1
  35. package/app/_app/immutable/chunks/{Cd1LwA-V.js → wpZcOjrw.js} +1 -1
  36. package/app/_app/immutable/entry/{app.jXgO31v0.js → app.CdnA1Er5.js} +2 -2
  37. package/app/_app/immutable/entry/start.yXp5URgB.js +1 -0
  38. package/app/_app/immutable/nodes/{0.BqruDT_Z.js → 0.B3BTaMcH.js} +1 -1
  39. package/app/_app/immutable/nodes/{1.BTiXtbCA.js → 1.Di4EzJ2c.js} +1 -1
  40. package/app/_app/immutable/nodes/{10.DO_Bn-V0.js → 10.B_vnof3P.js} +1 -1
  41. package/app/_app/immutable/nodes/{11.BNz9EIUT.js → 11.Cy9jIwzn.js} +1 -1
  42. package/app/_app/immutable/nodes/{12.CKlLn_Cb.js → 12.DrWof3gr.js} +1 -1
  43. package/app/_app/immutable/nodes/{13.DpAHXZvm.js → 13.Zp6Jo_m4.js} +1 -1
  44. package/app/_app/immutable/nodes/{14.chrK8YCR.js → 14.jRpiEp9_.js} +1 -1
  45. package/app/_app/immutable/nodes/2.Ct5aEJ66.js +26 -0
  46. package/app/_app/immutable/nodes/{3.DMtU3J6w.js → 3.D_V2kkhg.js} +1 -1
  47. package/app/_app/immutable/nodes/{4.DcEv25d3.js → 4.ClirjmB_.js} +1 -1
  48. package/app/_app/immutable/nodes/{5.Dlst1EHE.js → 5.B_Y-4dWg.js} +1 -1
  49. package/app/_app/immutable/nodes/{6.PU-OY_9E.js → 6.BcHTAs2z.js} +1 -1
  50. package/app/_app/immutable/nodes/{7.CrID5mpx.js → 7.DgihUOPX.js} +1 -1
  51. package/app/_app/immutable/nodes/{8.DP_cZ7Vk.js → 8.BsOFrJvG.js} +1 -1
  52. package/app/_app/immutable/nodes/{9.CojOaZNS.js → 9.DyMr7eTc.js} +1 -1
  53. package/app/_app/version.json +1 -1
  54. package/app/advanced-styles/index.html +22 -22
  55. package/app/ai/index.html +25 -25
  56. package/app/blueprint/index.html +20 -20
  57. package/app/cookbook/index.html +20 -20
  58. package/app/index.html +33 -33
  59. package/app/m/ads/AdDeliveryTier/index.html +24 -24
  60. package/app/m/ads/AdEvent/index.html +24 -24
  61. package/app/m/ads/AdFormat/index.html +24 -24
  62. package/app/m/ads/AdGroup/index.html +24 -24
  63. package/app/m/ads/AdVariation/index.html +24 -24
  64. package/app/m/analytics/AnalyticsDataStream/index.html +24 -24
  65. package/app/m/analytics/AnalyticsEvent/index.html +24 -24
  66. package/app/m/analytics/AnalyticsProperty/index.html +24 -24
  67. package/app/m/analytics/AnalyticsReport/index.html +24 -24
  68. package/app/m/approvals/ApprovalEvent/index.html +24 -24
  69. package/app/m/approvals/ApprovalPolicy/index.html +24 -24
  70. package/app/m/approvals/ApprovalRequest/index.html +24 -24
  71. package/app/m/assets/Asset/attachments/index.html +25 -25
  72. package/app/m/assets/Asset/index.html +24 -24
  73. package/app/m/assets/AssetAssociation/index.html +24 -24
  74. package/app/m/assets/AssetMetafield/index.html +24 -24
  75. package/app/m/assets/AssetStatus/index.html +24 -24
  76. package/app/m/assets/AssetType/index.html +24 -24
  77. package/app/m/assets/Folder/index.html +24 -24
  78. package/app/m/chat/AgentSession/index.html +24 -24
  79. package/app/m/chat/ChatMessage/index.html +24 -24
  80. package/app/m/chat/ChatParticipant/index.html +24 -24
  81. package/app/m/chat/ChatReaction/index.html +24 -24
  82. package/app/m/chat/ChatRoom/index.html +24 -24
  83. package/app/m/chat/ChatThread/index.html +24 -24
  84. package/app/m/chat/VoiceGatewayTurn/index.html +24 -24
  85. package/app/m/chat/VoiceSession/index.html +24 -24
  86. package/app/m/commerce/Agreement/index.html +24 -24
  87. package/app/m/commerce/Cart/index.html +24 -24
  88. package/app/m/commerce/Contract/index.html +24 -24
  89. package/app/m/commerce/ContractLineItem/index.html +24 -24
  90. package/app/m/commerce/Customer/index.html +24 -24
  91. package/app/m/commerce/DocumentTax/index.html +24 -24
  92. package/app/m/commerce/Estimate/index.html +24 -24
  93. package/app/m/commerce/Fulfillment/index.html +24 -24
  94. package/app/m/commerce/FulfillmentLineItem/index.html +24 -24
  95. package/app/m/commerce/HistoricalCustomerFunds/index.html +24 -24
  96. package/app/m/commerce/HistoricalCustomerFundsAllocation/index.html +24 -24
  97. package/app/m/commerce/HistoricalSalesLine/index.html +24 -24
  98. package/app/m/commerce/Invoice/index.html +24 -24
  99. package/app/m/commerce/InvoiceLineItem/index.html +24 -24
  100. package/app/m/commerce/Lease/index.html +24 -24
  101. package/app/m/commerce/LicenseSale/index.html +24 -24
  102. package/app/m/commerce/Order/index.html +24 -24
  103. package/app/m/commerce/Payment/index.html +24 -24
  104. package/app/m/commerce/PaymentAllocation/index.html +24 -24
  105. package/app/m/commerce/PaymentInstrument/index.html +24 -24
  106. package/app/m/commerce/PaymentIntent/index.html +24 -24
  107. package/app/m/commerce/Payout/index.html +24 -24
  108. package/app/m/commerce/ProductionOrder/index.html +24 -24
  109. package/app/m/commerce/PurchaseContract/index.html +24 -24
  110. package/app/m/commerce/PurchaseOrder/index.html +24 -24
  111. package/app/m/commerce/SalesContract/index.html +24 -24
  112. package/app/m/commerce/SupplierQuote/index.html +24 -24
  113. package/app/m/commerce/TaxCode/index.html +24 -24
  114. package/app/m/commerce/TaxComponent/index.html +24 -24
  115. package/app/m/commerce/TaxSettings/index.html +24 -24
  116. package/app/m/commerce/TaxSummaryReport/index.html +24 -24
  117. package/app/m/commerce/TenantPaymentAccount/index.html +24 -24
  118. package/app/m/commerce/Vendor/index.html +24 -24
  119. package/app/m/commerce/WholesaleOrder/index.html +24 -24
  120. package/app/m/content/Content/articles/index.html +25 -25
  121. package/app/m/content/Content/index.html +24 -24
  122. package/app/m/content/ContentContribution/index.html +24 -24
  123. package/app/m/content/ContentContributionAttachment/index.html +24 -24
  124. package/app/m/content/ContentContributionRevision/index.html +24 -24
  125. package/app/m/content/ContentContributionType/index.html +24 -24
  126. package/app/m/content/ContentContributor/index.html +24 -24
  127. package/app/m/content/ContentCorrection/index.html +24 -24
  128. package/app/m/content/ContentFeedSource/index.html +24 -24
  129. package/app/m/content/ContentGovernanceAssignment/index.html +24 -24
  130. package/app/m/content/ContentGovernancePolicy/index.html +24 -24
  131. package/app/m/content/ContentGovernanceProfile/index.html +24 -24
  132. package/app/m/content/ContentReference/index.html +24 -24
  133. package/app/m/content/ContentReview/index.html +24 -24
  134. package/app/m/content/ContentVersion/index.html +24 -24
  135. package/app/m/events/Event/index.html +24 -24
  136. package/app/m/events/EventParticipant/index.html +24 -24
  137. package/app/m/events/EventSeries/index.html +24 -24
  138. package/app/m/events/EventType/index.html +24 -24
  139. package/app/m/expenses/Expense/index.html +24 -24
  140. package/app/m/facts/Fact/index.html +24 -24
  141. package/app/m/facts/FactContent/index.html +24 -24
  142. package/app/m/facts/FactEvidence/index.html +24 -24
  143. package/app/m/facts/FactSource/index.html +24 -24
  144. package/app/m/facts/FactSubject/index.html +24 -24
  145. package/app/m/facts/FactTag/index.html +24 -24
  146. package/app/m/fields/FieldPolicy/index.html +24 -24
  147. package/app/m/fields/FieldPolicySuggestion/index.html +24 -24
  148. package/app/m/fields/FieldUsageCounter/index.html +24 -24
  149. package/app/m/human-resources/Employment/index.html +24 -24
  150. package/app/m/human-resources/EmploymentTerm/index.html +24 -24
  151. package/app/m/human-resources/HeldQualification/index.html +24 -24
  152. package/app/m/human-resources/Qualification/index.html +24 -24
  153. package/app/m/images/Image/index.html +24 -24
  154. package/app/m/inventory/InventoryLocation/index.html +24 -24
  155. package/app/m/inventory/Lot/index.html +24 -24
  156. package/app/m/inventory/LotCorrection/index.html +24 -24
  157. package/app/m/inventory/LotDocument/index.html +24 -24
  158. package/app/m/inventory/LotStockLevel/index.html +24 -24
  159. package/app/m/inventory/LotUsage/index.html +24 -24
  160. package/app/m/inventory/StockLevel/index.html +24 -24
  161. package/app/m/inventory/StockMovement/index.html +24 -24
  162. package/app/m/ledgers/Account/index.html +24 -24
  163. package/app/m/ledgers/Journal/index.html +24 -24
  164. package/app/m/ledgers/JournalEntry/index.html +24 -24
  165. package/app/m/ledgers/Ledger/index.html +24 -24
  166. package/app/m/manufacturing/Assembly/index.html +24 -24
  167. package/app/m/manufacturing/BillOfMaterials/index.html +24 -24
  168. package/app/m/manufacturing/BomLine/index.html +24 -24
  169. package/app/m/manufacturing/Operation/index.html +24 -24
  170. package/app/m/manufacturing/ProductionRun/index.html +24 -24
  171. package/app/m/manufacturing/ProductionRunCompletion/index.html +24 -24
  172. package/app/m/manufacturing/RoutingStep/index.html +24 -24
  173. package/app/m/marketing/Campaign/index.html +24 -24
  174. package/app/m/marketing/CampaignChannel/index.html +24 -24
  175. package/app/m/marketing/CampaignMetricSnapshot/index.html +24 -24
  176. package/app/m/messages/Account/index.html +24 -24
  177. package/app/m/messages/Attachment/index.html +24 -24
  178. package/app/m/messages/Blacklist/index.html +24 -24
  179. package/app/m/messages/Email/failed-sends/index.html +25 -25
  180. package/app/m/messages/Email/index.html +24 -24
  181. package/app/m/messages/Email/mailbox/index.html +25 -25
  182. package/app/m/messages/EmailAccount/index.html +24 -24
  183. package/app/m/messages/EmailAttachment/index.html +24 -24
  184. package/app/m/messages/EmailFolder/index.html +24 -24
  185. package/app/m/messages/Message/index.html +24 -24
  186. package/app/m/messages/MessagingEndpoint/index.html +24 -24
  187. package/app/m/messages/PersonaMessageRoute/index.html +24 -24
  188. package/app/m/messages/SlackAccount/index.html +24 -24
  189. package/app/m/messages/SlackMessage/index.html +24 -24
  190. package/app/m/messages/SlackMessage/slack-messages/index.html +25 -25
  191. package/app/m/messages/TelegramAccount/index.html +24 -24
  192. package/app/m/messages/Tweet/index.html +24 -24
  193. package/app/m/messages/TwitterAccount/index.html +24 -24
  194. package/app/m/messages/Whitelist/index.html +24 -24
  195. package/app/m/messages/ZulipAccount/index.html +24 -24
  196. package/app/m/places/Place/index.html +24 -24
  197. package/app/m/places/PlaceType/index.html +24 -24
  198. package/app/m/products/Category/index.html +24 -24
  199. package/app/m/products/Material/index.html +24 -24
  200. package/app/m/products/Product/index.html +24 -24
  201. package/app/m/products/Product/ingredients/index.html +25 -25
  202. package/app/m/products/ProductVariant/index.html +24 -24
  203. package/app/m/products/Sku/index.html +24 -24
  204. package/app/m/profiles/ApiKey/index.html +24 -24
  205. package/app/m/profiles/Bot/index.html +24 -24
  206. package/app/m/profiles/MagicLinkToken/index.html +24 -24
  207. package/app/m/profiles/NostrIdentity/index.html +24 -24
  208. package/app/m/profiles/OidcIdentity/index.html +24 -24
  209. package/app/m/profiles/Organization/index.html +24 -24
  210. package/app/m/profiles/Person/index.html +24 -24
  211. package/app/m/profiles/Profile/index.html +24 -24
  212. package/app/m/profiles/ProfileMetadata/index.html +24 -24
  213. package/app/m/profiles/ProfileMetafield/index.html +24 -24
  214. package/app/m/profiles/ProfileRelationship/index.html +24 -24
  215. package/app/m/profiles/ProfileRelationshipTerm/index.html +24 -24
  216. package/app/m/profiles/ProfileRelationshipType/index.html +24 -24
  217. package/app/m/profiles/ProfileType/index.html +24 -24
  218. package/app/m/projects/Comment/index.html +24 -24
  219. package/app/m/projects/Issue/index.html +24 -24
  220. package/app/m/projects/Label/index.html +24 -24
  221. package/app/m/projects/Project/index.html +24 -24
  222. package/app/m/projects/ProjectIntegration/index.html +24 -24
  223. package/app/m/projects/PullRequest/index.html +24 -24
  224. package/app/m/projects/Repository/index.html +24 -24
  225. package/app/m/properties/Property/index.html +24 -24
  226. package/app/m/properties/Zone/index.html +24 -24
  227. package/app/m/reports/RuntimeReport/index.html +24 -24
  228. package/app/m/reports/SmrtPrincipalReportRefreshTask/index.html +24 -24
  229. package/app/m/reports/SmrtReportLock/index.html +24 -24
  230. package/app/m/reports/SmrtReportRefreshTask/index.html +24 -24
  231. package/app/m/reports/SmrtReportRun/index.html +24 -24
  232. package/app/m/reports/SmrtReportSchedule/index.html +24 -24
  233. package/app/m/reports/SmrtReportWatermark/index.html +24 -24
  234. package/app/m/sales/Agreement/index.html +24 -24
  235. package/app/m/sales/AttributionException/index.html +24 -24
  236. package/app/m/sales/AttributionPolicy/index.html +24 -24
  237. package/app/m/sales/Commission/index.html +24 -24
  238. package/app/m/sales/CommissionAdjustment/index.html +24 -24
  239. package/app/m/sales/CommissionPayout/index.html +24 -24
  240. package/app/m/sales/CommissionPlan/index.html +24 -24
  241. package/app/m/sales/Earner/index.html +24 -24
  242. package/app/m/sales/EarnerSourceAttribution/index.html +24 -24
  243. package/app/m/sales/EarningEvent/index.html +24 -24
  244. package/app/m/sales/ExecutedAgreement/index.html +24 -24
  245. package/app/m/sales/Lead/index.html +24 -24
  246. package/app/m/sales/Opportunity/index.html +24 -24
  247. package/app/m/sales/OpportunityConversion/index.html +24 -24
  248. package/app/m/sales/PipelineDefinition/index.html +24 -24
  249. package/app/m/sales/PipelineStage/index.html +24 -24
  250. package/app/m/sales/Referral/index.html +24 -24
  251. package/app/m/sales/ReferralAgreement/index.html +24 -24
  252. package/app/m/sales/ReferralLink/index.html +24 -24
  253. package/app/m/sales/ReferralProgram/index.html +24 -24
  254. package/app/m/sales/ReferralTermSnapshot/index.html +24 -24
  255. package/app/m/sales/ReferralTouch/index.html +24 -24
  256. package/app/m/sales/Referrer/index.html +24 -24
  257. package/app/m/sales/SalesActivity/index.html +24 -24
  258. package/app/m/sales/SalesRepresentative/index.html +24 -24
  259. package/app/m/sites/Site/index.html +24 -24
  260. package/app/m/sites/SiteAgentBinding/index.html +24 -24
  261. package/app/m/social/OAuthState/index.html +24 -24
  262. package/app/m/social/SocialAccount/index.html +24 -24
  263. package/app/m/social/SocialPost/index.html +24 -24
  264. package/app/m/social/SocialPostAnalyticsSnapshot/index.html +24 -24
  265. package/app/m/subscriptions/BillingAdjustment/index.html +24 -24
  266. package/app/m/subscriptions/ClientCharge/index.html +24 -24
  267. package/app/m/subscriptions/CreditGrant/index.html +24 -24
  268. package/app/m/subscriptions/PricingRule/index.html +24 -24
  269. package/app/m/subscriptions/RetailCharge/index.html +24 -24
  270. package/app/m/subscriptions/SpendingPolicy/index.html +24 -24
  271. package/app/m/subscriptions/SubscriptionPlan/index.html +24 -24
  272. package/app/m/subscriptions/SubscriptionPlanVersion/index.html +24 -24
  273. package/app/m/subscriptions/TenantSubscription/index.html +24 -24
  274. package/app/m/subscriptions/TenantUsageMetric/index.html +24 -24
  275. package/app/m/support/ServiceTimeEntry/index.html +24 -24
  276. package/app/m/support/SupportAiRun/index.html +24 -24
  277. package/app/m/support/SupportAvailability/index.html +24 -24
  278. package/app/m/support/SupportCase/index.html +24 -24
  279. package/app/m/support/SupportCaseEvent/index.html +24 -24
  280. package/app/m/support/SupportChannelBinding/index.html +24 -24
  281. package/app/m/support/SupportCharge/index.html +24 -24
  282. package/app/m/support/SupportCompensation/index.html +24 -24
  283. package/app/m/support/SupportCompensationPlan/index.html +24 -24
  284. package/app/m/support/SupportEscalation/index.html +24 -24
  285. package/app/m/support/SupportInteraction/index.html +24 -24
  286. package/app/m/support/SupportPlan/index.html +24 -24
  287. package/app/m/support/SupportPolicy/index.html +24 -24
  288. package/app/m/support/SupportQualification/index.html +24 -24
  289. package/app/m/support/SupportServiceTarget/index.html +24 -24
  290. package/app/m/support/SupportSpecialist/index.html +24 -24
  291. package/app/m/support/SupportWorkLink/index.html +24 -24
  292. package/app/m/tags/Tag/index.html +24 -24
  293. package/app/m/tags/TagAlias/index.html +24 -24
  294. package/app/m/timesheets/AttendanceBreak/index.html +24 -24
  295. package/app/m/timesheets/AttendancePunch/index.html +24 -24
  296. package/app/m/timesheets/AttendanceSegment/index.html +24 -24
  297. package/app/m/timesheets/ServiceChargeSnapshot/index.html +24 -24
  298. package/app/m/timesheets/ServiceCompensationSnapshot/index.html +24 -24
  299. package/app/m/timesheets/ServiceTimeEntry/index.html +24 -24
  300. package/app/m/users/Group/index.html +24 -24
  301. package/app/m/users/GroupMember/index.html +24 -24
  302. package/app/m/users/GroupRole/index.html +24 -24
  303. package/app/m/users/Membership/index.html +24 -24
  304. package/app/m/users/MembershipOverride/index.html +24 -24
  305. package/app/m/users/Permission/index.html +24 -24
  306. package/app/m/users/Role/index.html +24 -24
  307. package/app/m/users/RolePermission/index.html +24 -24
  308. package/app/m/users/Session/index.html +24 -24
  309. package/app/m/users/Tenant/index.html +24 -24
  310. package/app/m/users/TenantIntegration/index.html +24 -24
  311. package/app/m/users/TenantPermissionOverride/index.html +24 -24
  312. package/app/m/users/User/index.html +24 -24
  313. package/app/m/video/Character/index.html +24 -24
  314. package/app/m/video/CharacterAsset/index.html +24 -24
  315. package/app/m/video/CompositeJob/index.html +24 -24
  316. package/app/m/video/Performer/index.html +24 -24
  317. package/app/m/video/PerformerAsset/index.html +24 -24
  318. package/app/m/video/Scene/index.html +24 -24
  319. package/app/m/video/SceneAsset/index.html +24 -24
  320. package/app/m/video/VideoComposition/index.html +24 -24
  321. package/app/m/video/VideoCompositionAsset/index.html +24 -24
  322. package/app/m/video/VideoSequence/index.html +24 -24
  323. package/app/m/video/VideoSequenceAsset/index.html +24 -24
  324. package/app/m/video/VideoShot/index.html +24 -24
  325. package/app/m/video/VideoShotAsset/index.html +24 -24
  326. package/app/m/video/VideoShotCharacter/index.html +24 -24
  327. package/app/m/video/VideoWorkflow/index.html +24 -24
  328. package/app/m/voice/VoiceOutput/index.html +24 -24
  329. package/app/m/voice/VoiceProfile/index.html +24 -24
  330. package/app/m/voice/VoiceSample/index.html +24 -24
  331. package/app/mcp.html +2 -2
  332. package/app/packages/ads/index.html +22 -22
  333. package/app/packages/analytics/index.html +22 -22
  334. package/app/packages/approvals/index.html +22 -22
  335. package/app/packages/assets/index.html +22 -22
  336. package/app/packages/chat/index.html +22 -22
  337. package/app/packages/comments/index.html +22 -22
  338. package/app/packages/commerce/index.html +22 -22
  339. package/app/packages/content/index.html +22 -22
  340. package/app/packages/events/index.html +22 -22
  341. package/app/packages/expenses/index.html +22 -22
  342. package/app/packages/facts/index.html +22 -22
  343. package/app/packages/fields/index.html +22 -22
  344. package/app/packages/human-resources/index.html +22 -22
  345. package/app/packages/images/index.html +22 -22
  346. package/app/packages/index.html +21 -21
  347. package/app/packages/ingestion/index.html +22 -22
  348. package/app/packages/inventory/index.html +22 -22
  349. package/app/packages/ledgers/index.html +22 -22
  350. package/app/packages/manufacturing/index.html +22 -22
  351. package/app/packages/marketing/index.html +22 -22
  352. package/app/packages/messages/index.html +22 -22
  353. package/app/packages/places/index.html +22 -22
  354. package/app/packages/preferences/index.html +22 -22
  355. package/app/packages/products/index.html +22 -22
  356. package/app/packages/profiles/index.html +22 -22
  357. package/app/packages/projects/index.html +22 -22
  358. package/app/packages/properties/index.html +22 -22
  359. package/app/packages/reactions/index.html +22 -22
  360. package/app/packages/reports/index.html +22 -22
  361. package/app/packages/sales/index.html +22 -22
  362. package/app/packages/sites/index.html +22 -22
  363. package/app/packages/social/index.html +22 -22
  364. package/app/packages/subscriptions/index.html +22 -22
  365. package/app/packages/support/index.html +22 -22
  366. package/app/packages/tags/index.html +22 -22
  367. package/app/packages/timesheets/index.html +22 -22
  368. package/app/packages/users/index.html +23 -23
  369. package/app/packages/video/index.html +22 -22
  370. package/app/packages/voice/index.html +22 -22
  371. package/app/packages/webhooks/index.html +22 -22
  372. package/app/recipes/account-access/help/index.html +23 -23
  373. package/app/recipes/account-access/index.html +24 -24
  374. package/app/recipes/activity/help/index.html +22 -22
  375. package/app/recipes/activity/index.html +24 -24
  376. package/app/recipes/ads.campaigns/help/index.html +22 -22
  377. package/app/recipes/ads.campaigns/index.html +24 -24
  378. package/app/recipes/affiliates.referrals/help/index.html +22 -22
  379. package/app/recipes/affiliates.referrals/index.html +24 -24
  380. package/app/recipes/agreements/help/index.html +22 -22
  381. package/app/recipes/agreements/index.html +24 -24
  382. package/app/recipes/analytics.reports/help/index.html +22 -22
  383. package/app/recipes/analytics.reports/index.html +24 -24
  384. package/app/recipes/approvals.requests/help/index.html +22 -22
  385. package/app/recipes/approvals.requests/index.html +24 -24
  386. package/app/recipes/assets/help/index.html +22 -22
  387. package/app/recipes/assets/index.html +24 -24
  388. package/app/recipes/billing/help/index.html +22 -22
  389. package/app/recipes/billing/index.html +24 -24
  390. package/app/recipes/chat.assistant/help/index.html +22 -22
  391. package/app/recipes/chat.assistant/index.html +24 -24
  392. package/app/recipes/comments/help/index.html +22 -22
  393. package/app/recipes/comments/index.html +24 -24
  394. package/app/recipes/commerce.customers/help/index.html +22 -22
  395. package/app/recipes/commerce.customers/index.html +24 -24
  396. package/app/recipes/commerce.estimates/help/index.html +22 -22
  397. package/app/recipes/commerce.estimates/index.html +24 -24
  398. package/app/recipes/commerce.purchases/help/index.html +22 -22
  399. package/app/recipes/commerce.purchases/index.html +24 -24
  400. package/app/recipes/commerce.sales/help/index.html +22 -22
  401. package/app/recipes/commerce.sales/index.html +24 -24
  402. package/app/recipes/commerce.vendors/help/index.html +22 -22
  403. package/app/recipes/commerce.vendors/index.html +24 -24
  404. package/app/recipes/commerce.wholesale/help/index.html +22 -22
  405. package/app/recipes/commerce.wholesale/index.html +24 -24
  406. package/app/recipes/content.articles/help/index.html +22 -22
  407. package/app/recipes/content.articles/index.html +24 -24
  408. package/app/recipes/events.calendar/help/index.html +22 -22
  409. package/app/recipes/events.calendar/index.html +24 -24
  410. package/app/recipes/expenses.tracking/help/index.html +22 -22
  411. package/app/recipes/expenses.tracking/index.html +24 -24
  412. package/app/recipes/fields.form-customization/help/index.html +22 -22
  413. package/app/recipes/fields.form-customization/index.html +24 -24
  414. package/app/recipes/human-resources.people/help/index.html +22 -22
  415. package/app/recipes/human-resources.people/index.html +24 -24
  416. package/app/recipes/human-resources.qualifications/help/index.html +22 -22
  417. package/app/recipes/human-resources.qualifications/index.html +24 -24
  418. package/app/recipes/ingestion/help/index.html +22 -22
  419. package/app/recipes/ingestion/index.html +24 -24
  420. package/app/recipes/integrations/help/index.html +22 -22
  421. package/app/recipes/integrations/index.html +24 -24
  422. package/app/recipes/inventory.stock/help/index.html +22 -22
  423. package/app/recipes/inventory.stock/index.html +24 -24
  424. package/app/recipes/ledgers.bookkeeping/help/index.html +22 -22
  425. package/app/recipes/ledgers.bookkeeping/index.html +24 -24
  426. package/app/recipes/manufacturing.assemblies/help/index.html +22 -22
  427. package/app/recipes/manufacturing.assemblies/index.html +24 -24
  428. package/app/recipes/manufacturing.production/help/index.html +22 -22
  429. package/app/recipes/manufacturing.production/index.html +24 -24
  430. package/app/recipes/marketing.campaigns/help/index.html +22 -22
  431. package/app/recipes/marketing.campaigns/index.html +24 -24
  432. package/app/recipes/messages/help/index.html +22 -22
  433. package/app/recipes/messages/index.html +24 -24
  434. package/app/recipes/places.locations/help/index.html +22 -22
  435. package/app/recipes/places.locations/index.html +24 -24
  436. package/app/recipes/products/help/index.html +22 -22
  437. package/app/recipes/products/index.html +24 -24
  438. package/app/recipes/projects.tracker/help/index.html +22 -22
  439. package/app/recipes/projects.tracker/index.html +24 -24
  440. package/app/recipes/reports.materialized/help/index.html +22 -22
  441. package/app/recipes/reports.materialized/index.html +24 -24
  442. package/app/recipes/reports.runtime/help/index.html +22 -22
  443. package/app/recipes/reports.runtime/index.html +24 -24
  444. package/app/recipes/sales.pipeline/help/index.html +22 -22
  445. package/app/recipes/sales.pipeline/index.html +24 -24
  446. package/app/recipes/social.posts/help/index.html +22 -22
  447. package/app/recipes/social.posts/index.html +24 -24
  448. package/app/recipes/subscriptions.plans/help/index.html +22 -22
  449. package/app/recipes/subscriptions.plans/index.html +24 -24
  450. package/app/recipes/support.tickets/help/index.html +22 -22
  451. package/app/recipes/support.tickets/index.html +24 -24
  452. package/app/recipes/tags.taxonomy/help/index.html +22 -22
  453. package/app/recipes/tags.taxonomy/index.html +24 -24
  454. package/app/recipes/team-collaboration/help/index.html +22 -22
  455. package/app/recipes/team-collaboration/index.html +24 -24
  456. package/app/recipes/timesheets.time-entries/help/index.html +22 -22
  457. package/app/recipes/timesheets.time-entries/index.html +24 -24
  458. package/app/recipes/video.library/help/index.html +22 -22
  459. package/app/recipes/video.library/index.html +24 -24
  460. package/app/recipes/voice.profiles/help/index.html +22 -22
  461. package/app/recipes/voice.profiles/index.html +24 -24
  462. package/app/s/custom-accounts/index.html +20 -20
  463. package/app/s/custom-appointments/index.html +20 -20
  464. package/app/s/custom-billing/index.html +20 -20
  465. package/app/s/custom-bookings/index.html +20 -20
  466. package/app/s/custom-buying/index.html +20 -20
  467. package/app/s/custom-checkout/index.html +20 -20
  468. package/app/s/custom-classes/index.html +20 -20
  469. package/app/s/custom-clients/index.html +20 -20
  470. package/app/s/custom-events/index.html +20 -20
  471. package/app/s/custom-fleet/index.html +20 -20
  472. package/app/s/custom-gigs/index.html +20 -20
  473. package/app/s/custom-giving/index.html +20 -20
  474. package/app/s/custom-instruments/index.html +20 -20
  475. package/app/s/custom-jobs/index.html +20 -20
  476. package/app/s/custom-kitchen/index.html +20 -20
  477. package/app/s/custom-lessons/index.html +20 -20
  478. package/app/s/custom-material/index.html +20 -20
  479. package/app/s/custom-meetings/index.html +20 -20
  480. package/app/s/custom-members/index.html +20 -20
  481. package/app/s/custom-merch/index.html +20 -20
  482. package/app/s/custom-money/index.html +20 -20
  483. package/app/s/custom-paint/index.html +20 -20
  484. package/app/s/custom-parts/index.html +20 -20
  485. package/app/s/custom-rentals/index.html +20 -20
  486. package/app/s/custom-roastery/index.html +20 -20
  487. package/app/s/custom-schedule/index.html +20 -20
  488. package/app/s/custom-shelf/index.html +20 -20
  489. package/app/s/custom-shop/index.html +20 -20
  490. package/app/s/custom-students/index.html +20 -20
  491. package/app/s/custom-wholesale/index.html +20 -20
  492. package/app/s/custom-work/index.html +20 -20
  493. package/app/s/custom-yard/index.html +20 -20
  494. package/app/s/section-access-control/index.html +20 -20
  495. package/app/s/section-account-security/index.html +20 -20
  496. package/app/s/section-accounting/index.html +20 -20
  497. package/app/s/section-activity/index.html +20 -20
  498. package/app/s/section-agreements/index.html +20 -20
  499. package/app/s/section-analytics/index.html +20 -20
  500. package/app/s/section-approvals/index.html +20 -20
  501. package/app/s/section-assets/index.html +20 -20
  502. package/app/s/section-billing/index.html +20 -20
  503. package/app/s/section-calendar/index.html +20 -20
  504. package/app/s/section-catalog/index.html +20 -20
  505. package/app/s/section-chat.assistant/index.html +20 -20
  506. package/app/s/section-comments/index.html +20 -20
  507. package/app/s/section-fields.form-customization/index.html +20 -20
  508. package/app/s/section-grow/index.html +20 -20
  509. package/app/s/section-ingestion/index.html +20 -20
  510. package/app/s/section-integrations/index.html +20 -20
  511. package/app/s/section-make/index.html +20 -20
  512. package/app/s/section-messages/index.html +20 -20
  513. package/app/s/section-more/index.html +20 -20
  514. package/app/s/section-operations/index.html +20 -20
  515. package/app/s/section-places/index.html +20 -20
  516. package/app/s/section-projects/index.html +20 -20
  517. package/app/s/section-publish/index.html +20 -20
  518. package/app/s/section-purchasing/index.html +20 -20
  519. package/app/s/section-reports.materialized/index.html +20 -20
  520. package/app/s/section-reports.runtime/index.html +20 -20
  521. package/app/s/section-sales/index.html +20 -20
  522. package/app/s/section-staff/index.html +20 -20
  523. package/app/s/section-support/index.html +20 -20
  524. package/app/s/section-taxonomy/index.html +20 -20
  525. package/app/s/section-team/index.html +20 -20
  526. package/app/s/section-work/index.html +20 -20
  527. package/dist/catalog/catalog.json +49 -39
  528. package/dist/components/ExportPanel.svelte +109 -101
  529. package/dist/components/ExportPanel.svelte.d.ts +5 -3
  530. package/dist/components/ExportPanel.svelte.d.ts.map +1 -1
  531. package/dist/smrt-version.d.ts +1 -1
  532. package/dist/smrt-version.js +1 -1
  533. package/package.json +55 -55
  534. package/app/_app/immutable/assets/2.BSQtjEJf.css +0 -1
  535. package/app/_app/immutable/assets/app.CkDD91u6.css +0 -1
  536. package/app/_app/immutable/chunks/BNB4IwPy.js +0 -9
  537. package/app/_app/immutable/chunks/BgqcCcxm.js +0 -1
  538. package/app/_app/immutable/chunks/DUOxZgSW.js +0 -1
  539. package/app/_app/immutable/entry/start.iwVpBav6.js +0 -1
  540. package/app/_app/immutable/nodes/2.1jMCUHMm.js +0 -26
@@ -1,9 +0,0 @@
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;te(e.id,`formId`,i.formId,a.formId),te(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;te(e.id,`surfaceId`,i.surfaceId,a.surfaceId),te(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 te(e,t,n,r){if(n!==void 0&&n!==r)throw Error(`[smrt-web] intent '${e}' declares ${t} '${n}' but was bound to '${r}'`)}var D=class{},ne=class extends D{constructor(e){super(),this.path=e,this.type=`ref`}},O=class extends D{constructor(e){super(),this.value=e,this.type=`val`}},k=class extends D{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}};function A(){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(`No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.`)}var j=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},M=class extends j{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}},N=class extends j{constructor(e){super(e),this.name=`CollectionConfigurationError`}},re=class extends N{constructor(){super(`Collection requires a config`)}},ie=class extends N{constructor(){super(`Collection requires a sync config`)}},ae=class extends N{constructor(){super(`Schema must implement the standard-schema interface`)}},oe=class extends N{constructor(){super(`Schema validation must be synchronous`)}},se=class extends j{constructor(e){super(e),this.name=`CollectionStateError`}},ce=class extends se{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},le=class extends se{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},ue=class extends se{constructor(){super(`Collection is in error state`)}},de=class extends se{constructor(){super(`Active subscribers count is negative - this should never happen`)}},P=class extends j{constructor(e){super(e),this.name=`CollectionOperationError`}},fe=class extends P{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},pe=class extends P{constructor(e,t){super(`getKey returned an invalid key type. Expected string or number, but got ${e===null?`null`:typeof e}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}},me=class extends P{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},he=class extends P{constructor(e,t,n){let r=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${r}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):n?.hasCustomGetKey&&n.hasJoins?super(`${r}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(r)}},ge=class extends P{constructor(){super(`The first argument to update is missing`)}},_e=class extends P{constructor(){super(`No keys were passed to update`)}},ve=class extends P{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},ye=class extends P{constructor(e,t){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${t}". Please delete the old item and create a new one if a key change is necessary.`)}},be=class extends P{constructor(){super(`No keys were passed to delete`)}},xe=class extends P{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},Se=class extends j{constructor(e){super(e),this.name=`MissingHandlerError`}},Ce=class extends Se{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},we=class extends Se{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},Te=class extends Se{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},F=class extends j{constructor(e){super(e),this.name=`TransactionError`}},Ee=class extends F{constructor(){super(`mutationFn is required when creating a transaction`)}},De=class extends F{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},Oe=class extends F{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},ke=class extends F{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},Ae=class extends F{constructor(){super(`No pending sync transaction to write to`)}},je=class extends F{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},Me=class extends F{constructor(){super(`No pending sync transaction to commit`)}},Ne=class extends F{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},Pe=class extends j{constructor(e){super(e),this.name=`QueryCompilationError`}},Fe=class extends Pe{constructor(e){super(`Unknown expression type: ${e}`)}},Ie=class extends Pe{constructor(){super(`Reference path cannot be empty`)}},Le=class extends Pe{constructor(e){super(`Unknown function: ${e}`)}},Re=class extends j{constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name=`SyncCleanupError`}};function I(e,t){return ze(e,t,new Map)}function ze(e,t,n){if(e===t)return!0;if(e==null||t==null||typeof e!=typeof t)return!1;if(e instanceof Date)return t instanceof Date&&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;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.set(e,t);let r=Array.from(e.entries()).every(([e,r])=>t.has(e)&&ze(r,t.get(e),n));return n.delete(e),r}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.set(e,t);let r=Array.from(e),i=Array.from(t);if(r.every(e=>typeof e!=`object`))return n.delete(e),r.every(e=>t.has(e));let a=r.length===i.length;return n.delete(e),a}if(t instanceof Set)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)&&!(e instanceof DataView)&&!(t instanceof DataView)){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!1;return!0}if(ArrayBuffer.isView(t)&&!(t instanceof DataView)&&!ArrayBuffer.isView(e))return!1;if(Ve(e)&&Ve(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(Ve(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=e.every((e,r)=>ze(e,t[r],n));return n.delete(e),r}if(Array.isArray(t))return!1;if(typeof e==`object`){if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return n.delete(e),!1;let a=r.every(r=>r in t&&ze(e[r],t[r],n));return n.delete(e),a}return!1}var Be=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Ve(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&Be.has(t)}var He={direction:`asc`,nulls:`first`,stringSort:`locale`},Ue=new WeakMap,We=1;function Ge(e){if(Ue.has(e))return Ue.get(e);let t=We++;return Ue.set(e,t),t}function L(e){return typeof e==`number`&&Number.isNaN(e)||e instanceof Date&&Number.isNaN(e.getTime())}var Ke=(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=L(e),a=L(t);if(i&&a)return 0;if(i)return 1;if(a)return-1;if(typeof e==`string`&&typeof t==`string`&&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=Ke(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(Ve(e)&&Ve(t)){let n=e.toString(),r=t.toString();return n<r?-1:+(n>r)}let o=typeof e==`object`,s=typeof t==`object`;if(o||s){if(o&&s)return Ge(e)-Ge(t);if(o)return 1;if(s)return-1}return e<t?-1:+(e>t)},qe=(e,t,n)=>Ke(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function Je(e){return(t,n)=>e.direction===`asc`?Ke(t,n,e):qe(t,n,e)}function Ye(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 Xe=128;function Ze(e){return e instanceof Date?e.getTime():Ve(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=Xe?`__u8__${Array.from(e).join(`,`)}`:e}function Qe(e,t){if(e===t)return!0;let n=typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array,r=typeof Buffer<`u`&&t instanceof Buffer||t instanceof Uint8Array;return n&&r?Ye(e,t):!1}function R(e){return e==null}function $e(e,t){return L(e)||L(t)?L(e)&&L(t):Qe(e,t)}function et(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 tt(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function nt(e){return e===!0}function rt(e,t=!1){return at(e,t)}function it(e){return at(e,!0)}function at(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?st(e):ot(e);case`func`:return ct(e,t);default:throw new Fe(e.type)}}function ot(e){let[t,...n]=e.path;if(!t)throw new Ie;if(t===`$selected`){if(n.length===0)return e=>e.$selected;if(n.length===1){let e=n[0];return t=>t.$selected?.[e]}return e=>{let t=e.$selected;if(t===void 0)return;let r=t;for(let e of n){if(r==null)return r;r=r[e]}return r}}let r=t;if(n.length===0)return e=>e[r];if(n.length===1){let e=n[0];return t=>t[r]?.[e]}return e=>{let t=e[r];if(t===void 0)return;let i=t;for(let e of n){if(i==null)return i;i=i[e]}return i}}function st(e){let t=e.path;return e=>{let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}}function ct(e,t){let n=e.args.map(e=>at(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=Ze(e(n)),i=Ze(t(n));return R(r)||R(i)?null:$e(r,i)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:L(r)||L(i)?L(r)&&!L(i):r>i}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:L(r)||L(i)?L(r):r>=i}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:L(r)||L(i)?L(i)&&!L(r):r<i}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:L(r)||L(i)?L(i):r<=i}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;R(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;R(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return R(n)?null:!n}}case`in`:{let e=n[0],t=n[1];return n=>{let r=Ze(e(n)),i=t(n);return R(r)?null:Array.isArray(i)?i.some(e=>$e(Ze(e),r)):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:ut(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return R(r)||R(i)?null:ut(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(`caseWhen() requires at least two arguments`);return r=>{for(let e=0;e<t;e++){let t=n[e*2];if(lt(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=et(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=et(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=et(t(n));return i?tt(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 Le(e.name)}}function lt(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 ut(e,t,n){if(typeof e!=`string`||typeof t!=`string`)return!1;let r=n?e.toLowerCase():e,i=(n?t.toLowerCase():t).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return i=i.replace(/%/g,`.*`),i=i.replace(/_/g,`.`),RegExp(`^${i}$`,`s`).test(r)}var dt=class{constructor(e){this.originalIndex=e}lookup(e,t){let n=e===`gt`?`lt`:e===`gte`?`lte`:e===`lt`?`gt`:e===`lte`?`gte`:e;return this.originalIndex.lookup(n,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}takeReversed(e,t,n){return this.originalIndex.take(e,t,n)}takeReversedFromEnd(e,t){return this.originalIndex.takeFromStart(e,t)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}matchesField(e){return this.originalIndex.matchesField(e)}matchesCompareOptions(e){return this.originalIndex.matchesCompareOptions(e)}matchesDirection(e){return this.originalIndex.matchesDirection(e)}getStats(){return this.originalIndex.getStats()}add(e,t){this.originalIndex.add(e,t)}remove(e,t){this.originalIndex.remove(e,t)}update(e,t,n){this.originalIndex.update(e,t,n)}build(e){this.originalIndex.build(e)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(e){return this.originalIndex.equalityLookup(e)}inArrayLookup(e){return this.originalIndex.inArrayLookup(e)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}};function ft(e,t,n,r,i){let a=e;return{...e,$synced:a.$synced??r(),$origin:a.$origin??i(),$key:a.$key??t,$collectionId:a.$collectionId??n}}var pt=[`$synced`,`$origin`,`$key`,`$collectionId`];function mt(e){return pt.includes(e)}function ht(e){return e.some(e=>mt(e))}function gt(e,t,n){if(ht(t))return;let r=n??{...He,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new dt(n)}function _t(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 vt(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function yt(e){return e!=null}function bt(e){return{...He,...e.compareOptions}.stringSort===`locale`}function xt(e,t){switch(typeof e){case`number`:case`bigint`:case`boolean`:return!1;case`string`:return bt(t);case`object`:return e!==null&&!(e instanceof Date);default:return!1}}function St(e,t,n){return!xt(e,n)&&t.supportsRangeOptimization}function Ct(e,t){return wt(e,t)}function wt(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return Et(e,t);case`and`:return Dt(e,t);case`or`:return Ot(e,t);case`in`:return kt(e,t)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Tt(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.join(`.`),r=o.value;n.has(e)||n.set(e,[]),n.get(e).push({operation:s,value:r,argIndex:t})}}}for(let[e,r]of n)if(r.length>=2){let n=gt(t,e.split(`.`));if(n&&r.some(e=>!St(e.value,n,t)))continue;if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e=Je({...He,...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(!yt(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 Et(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=gt(t,e);if(n){let e=a.value,r=o;return!n.supports(r)||(o===`gt`||o===`gte`||o===`lt`||o===`lte`)&&!St(e,n,t)?{canOptimize:!1,matchingKeys:new Set,isExact:!1}:{canOptimize:!0,matchingKeys:n.lookup(r,e),isExact:o===`lt`||o===`lte`?!1:yt(e)}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Dt(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};let n=Tt(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=wt(o,t);e.canOptimize?(i.push(e),e.isExact||(a=!1)):a=!1}return i.length>0?{canOptimize:!0,matchingKeys:_t(i.map(e=>e.matchingKeys)),isExact:a}:{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function Ot(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=wt(r,t);if(!e.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};n.push(e)}return{canOptimize:!0,matchingKeys:vt(n.map(e=>e.matchingKeys)),isExact:n.every(e=>e.isExact)}}function kt(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=gt(t,e),o=i.every(e=>yt(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 At={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function jt(){return At.enabled&&!1}function Mt(e){if(jt()){if(At.onSuggestion)try{At.onSuggestion(e)}catch{}else console.warn(`[TanStack DB] Index suggestion for "${e.collectionId}":
3
- ${e.message}
4
- Field: ${e.fieldPath.join(`.`)}
5
- Add index: collection.createIndex((row) => row.${e.fieldPath.join(`.`)})`)}}function Nt(e,t,n){jt()&&t>At.collectionSizeThreshold&&Mt({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function Pt(e){return e.config.autoIndex===`eager`}function Ft(e,t,n,r,i){if(ht(t)||!Pt(n))return;let a=r??{...He,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){jt()&&Nt(n.id||`unknown`,n.size,t);try{n.createIndex(e=>{let n=e;for(let e of t)n=n[e];return n},{name:`auto:${t.join(`.`)}`,options:i?{compareFn:i,compareOptions:a}:{}})}catch(e){console.warn(`${n.id?`[${n.id}] `:``}Failed to create auto-index for field path "${t.join(`.`)}":`,e)}}}function It(e,t){if(!Pt(t))return;let n=Lt(e);for(let{fieldName:e,fieldPath:r}of n)Ft(e,r,t)}function Lt(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(![`eq`,`gt`,`gte`,`lt`,`lte`,`in`].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}new class{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!=`object`||!e){let t=String(e),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n}return this.objectIds.has(e)||this.objectIds.set(e,this.nextId++),this.objectIds.get(e)}getStringId(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`obj_${this.getId(e)}`:`str_${String(e)}`}};function Rt(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function zt(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function Bt(e,t={}){let n=t=>{let n=[];for(let[r,i]of e.entries())(t?.(i)??!0)&&n.push({type:`insert`,key:r,value:i});return n};if(t.limit!==void 0&&!t.orderBy)throw Error(`limit cannot be used without orderBy`);if(t.orderBy){let n=t.where?Vt(t.where):void 0,r=Ut(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 n();try{let r=t.where,i=Ct(r,e);if(i.canOptimize){let t=i.isExact?void 0:Vt(r),n=[];for(let r of i.matchingKeys){let i=e.get(r);i!==void 0&&(t?.(i)??!0)&&n.push({type:`insert`,key:r,value:i})}return n}return t.optimizedOnly?void 0:n(Vt(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=Vt(t.where);return t.optimizedOnly?void 0:n(i)}}function Vt(e){let t=it(e);return e=>{try{return nt(t(e))}catch{return!1}}}function Ht(e,t){let n=Vt(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);(r.length>0||t.length===0)&&e(r)}}function Ut(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=zt(i,e);Ft(t[0],t,e,o);let s=gt(e,t,o);if(s&&s.supports(`gt`))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});a.sort((e,n)=>{for(let r of t){let t=Je(r.compareOptions)(Wt(e.value,r.expression),Wt(n.value,r.expression));if(t!==0)return t}return 0});let o=a.map(e=>e.key);return n===void 0?o:o.slice(0,n)}function Wt(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:it(t)(e)}var Gt=class{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,r=this.sortedKeys.length;if(!this.comparator){for(;n<r;){let t=Math.floor((n+r)/2),i=this.sortedKeys[t],a=Rt(e,i);if(a<0)r=t;else if(a>0)n=t+1;else return t}return n}for(;n<r;){let i=Math.floor((n+r)/2),a=this.sortedKeys[i],o=this.map.get(a),s=this.comparator(t,o);if(s<0)r=i;else if(s>0)n=i+1;else{let t=Rt(e,a);if(t<0)r=i;else if(t>0)n=i+1;else return i}}return n}set(e,t){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);this.sortedKeys.splice(n,1)}let n=this.indexOf(e,t);return this.sortedKeys.splice(n,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);return this.sortedKeys.splice(n,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(let e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(let t of this.sortedKeys)e(this.map.get(t),t,this.map)}},Kt=`__tanstack_db_direct`,qt=class{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let e=!1;for(let t of this.transactions.values())if(t.state===`persisting`){e=!0;break}let{committedSyncedTransactions:t,uncommittedSyncedTransactions:n,hasTruncateSync:r,hasImmediateSync:i}=this.pendingSyncedTransactions.reduce((e,t)=>(t.committed?(e.committedSyncedTransactions.push(t),t.truncate&&(e.hasTruncateSync=!0),t.immediate&&(e.hasImmediateSync=!0)):e.uncommittedSyncedTransactions.push(t),e),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!e||r||i){this.isCommittingSyncTransactions=!0;let e=r?t.find(e=>e.truncate)?.optimisticSnapshot:null,i,a,o=new Set;for(let e of t){for(let t of e.operations)o.add(t.key);for(let[t]of e.rowMetadataWrites)o.add(t)}let s=new Set(o);for(let e of this.pendingOptimisticDirectUpserts)s.add(e);for(let e of this.pendingOptimisticDirectDeletes)s.add(e);let c=this.snapshotRowOriginsForKeys(s),l=new Map(this.optimisticUpserts),u=new Set(this.optimisticDeletes),d=this.preSyncVisibleState;if(d.size===0){d=new Map;for(let e of o){let t=this.get(e);t!==void 0&&d.set(e,t)}}let f=[],p=this.config.sync.rowUpdateMode||`partial`,m=new Map;for(let e of this.transactions.values())if(e.state===`completed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&t.optimistic&&m.set(t.key,{type:t.type,value:t.modified});for(let n of t){if(n.truncate){let t=new Set([...this.syncedData.keys(),...e?.upserts.keys()||[]]);for(let n of t){if(e?.deletes.has(n))continue;let t=e?.upserts.get(n)||this.syncedData.get(n);t!==void 0&&f.push({type:`delete`,key:n,value:t})}i=new Set(this.pendingLocalChanges),a=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(let e of o)d.delete(e);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(let e of n.operations){let t=e.key;this.syncedKeys.add(t);let n=this.isLocalOnly||this.pendingLocalChanges.has(t)||this.pendingLocalOrigins.has(t)||i?.has(t)===!0||a?.has(t)===!0?`local`:`remote`;switch(e.type){case`insert`:this.syncedData.set(t,e.value),this.rowOrigins.set(t,n),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t);break;case`update`:if(p===`partial`){let n=Object.assign({},this.syncedData.get(t),e.value);this.syncedData.set(t,n)}else this.syncedData.set(t,e.value);this.rowOrigins.set(t,n),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t);break;case`delete`:this.syncedData.delete(t),this.syncedMetadata.delete(t),this.rowOrigins.delete(t),this.pendingLocalChanges.delete(t),this.pendingLocalOrigins.delete(t),this.pendingOptimisticUpserts.delete(t),this.pendingOptimisticDeletes.delete(t),this.pendingOptimisticDirectUpserts.delete(t),this.pendingOptimisticDirectDeletes.delete(t)}}for(let[e,t]of n.rowMetadataWrites)t.type===`delete`?this.syncedMetadata.delete(e):this.syncedMetadata.set(e,t.value);for(let[e,t]of n.collectionMetadataWrites)t.type===`delete`?this.syncedCollectionMetadata.delete(e):this.syncedCollectionMetadata.set(e,t.value)}if(r){let n=new Set;for(let e of t)for(let t of e.operations)(t.type===`insert`||t.type===`update`)&&n.add(t.key);let r=new Map(e.upserts),i=new Set(e.deletes);for(let[e,t]of r)if(!i.has(e)){if(n.has(e)){let n=!1;for(let r=f.length-1;r>=0;r--){let i=f[r];if(i.key===e&&i.type===`insert`){i.value=t,n=!0;break}}n||f.push({type:`insert`,key:e,value:t})}else f.push({type:`insert`,key:e,value:t})}if(f.length>0&&i.size>0){let e=[];for(let t of f)t.type===`insert`&&i.has(t.key)||e.push(t);f.length=0,f.push(...e)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&e){for(let[t,n]of e.upserts)this.optimisticUpserts.set(t,n);for(let t of e.deletes)this.optimisticDeletes.add(t)}for(let e of this.transactions.values())if(![`completed`,`failed`].includes(e.state)){for(let t of e.mutations)if(this.isThisCollection(t.collection)&&t.optimistic)switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}}for(let e of this.pendingOptimisticDirectUpserts)if(!o.has(e)){if(o.add(e),!d.has(e)){let t=l.get(e);t!==void 0&&d.set(e,t)}this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e)}for(let e of this.pendingOptimisticDirectDeletes)o.has(e)||o.add(e),this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(let e of o){let t=d.get(e),n=this.get(e),r=this.getVirtualPropsSnapshotForState(e,{rowOrigins:c,optimisticUpserts:l,optimisticDeletes:u,completedOptimisticKeys:m}),i=this.getVirtualPropsSnapshotForState(e),a=r.$synced!==i.$synced||r.$origin!==i.$origin,o=t===void 0?void 0:ft(t,e,this.collection.id,()=>r.$synced,()=>r.$origin),s=m.get(e),p=!1;s&&(s.type===`delete`&&t!==void 0&&n===void 0&&I(s.value,t)||n!==void 0&&I(s.value,n))&&(p=!0);let h=a&&t!==void 0&&n!==void 0&&I(t,n);if(!p||h){if(t===void 0&&n!==void 0){let t=m.get(e);if(t){let i=t.value,a=ft(i,e,this.collection.id,()=>r.$synced,()=>r.$origin);f.push({type:`update`,key:e,value:n,previousValue:a})}else f.push({type:`insert`,key:e,value:n})}else t!==void 0&&n===void 0?f.push({type:`delete`,key:e,value:o??t}):t!==void 0&&n!==void 0&&(!I(t,n)||h)&&f.push({type:`update`,key:e,value:n,previousValue:o??t})}}this.size=this.calculateSize(),f.length>0&&this.indexes.updateIndexes(f),this.changes.emitEvents(f,!0),this.pendingSyncedTransactions=n,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||=!0}},this.config=e,this.transactions=new Gt((e,t)=>e.compareCreatedAt(t)),this.syncedData=new Gt(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return this.isLocalOnly?!0:!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?`local`:this.rowOrigins.get(e)??`remote`}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:`local`});let n=t?.optimisticUpserts??this.optimisticUpserts,r=t?.optimisticDeletes??this.optimisticDeletes,i=n.has(e)||r.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!i,$origin:i?`local`:(t?.rowOrigins??this.rowOrigins).get(e)??`remote`})}snapshotRowOriginsForKeys(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}enrichWithVirtualPropsSnapshot(e,t){let n=e,r=n.$synced??t.$synced,i=n.$origin??t.$origin,a=n.$key??t.$key,o=n.$collectionId??t.$collectionId,s=this.virtualPropsCache.get(e);if(s&&s.synced===r&&s.origin===i&&s.key===a&&s.collectionId===o)return s.enriched;let c={...e,$synced:r,$origin:i,$key:a,$collectionId:o};return this.virtualPropsCache.set(e,{synced:r,origin:i,key:a,collectionId:o,enriched:c}),c}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){let{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),r=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:n,previousValue:r,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;if(!t.has(e))return n.has(e)?n.get(e):r.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)?!0: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](){for(let[e,t]of this.entries())yield[e,t]}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}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),r=this.rowOrigins;for(let e of this.transactions.values()){let t=e.metadata[Kt]===!0;if(e.state===`completed`){for(let n of e.mutations)if(this.isThisCollection(n.collection)&&(this.pendingLocalOrigins.add(n.key),n.optimistic))switch(n.type){case`insert`:case`update`:this.pendingOptimisticUpserts.set(n.key,n.modified),this.pendingOptimisticDeletes.delete(n.key),t?(this.pendingOptimisticDirectUpserts.add(n.key),this.pendingOptimisticDirectDeletes.delete(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key));break;case`delete`:this.pendingOptimisticUpserts.delete(n.key),this.pendingOptimisticDeletes.add(n.key),t?(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.add(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key))}}else if(e.state===`failed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&(this.pendingLocalOrigins.delete(t.key),t.optimistic&&(this.pendingOptimisticUpserts.delete(t.key),this.pendingOptimisticDeletes.delete(t.key),this.pendingOptimisticDirectUpserts.delete(t.key),this.pendingOptimisticDirectDeletes.delete(t.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();let i=new Set;for(let e of this.pendingSyncedTransactions)for(let t of e.operations)i.add(t.key);let a=[];for(let[e,t]of this.pendingOptimisticUpserts)i.has(e)||this.pendingOptimisticDirectUpserts.has(e)?this.optimisticUpserts.set(e,t):a.push(e);for(let e of a)this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e);let o=[];for(let e of this.pendingOptimisticDeletes)i.has(e)||this.pendingOptimisticDirectDeletes.has(e)?this.optimisticDeletes.add(e):o.push(e);for(let e of o)this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);let s=[];for(let e of this.transactions.values())[`completed`,`failed`].includes(e.state)||s.push(e);for(let e of s)for(let t of e.mutations)if(this.isThisCollection(t.collection)&&(this.pendingLocalChanges.add(t.key),t.optimistic))switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key)}this.size=this.calculateSize();let c=[];this.collectOptimisticChanges(t,n,r,c);let l=c.filter(t=>!(this.recentlySyncedKeys.has(t.key)&&!e));if(this.pendingSyncedTransactions.length>0&&!e){let t=new Set;for(let e of this.pendingSyncedTransactions)for(let n of e.operations)t.add(n.key);let n=l.filter(e=>!(e.type===`delete`&&t.has(e.key)&&!s.some(t=>t.mutations.some(t=>this.isThisCollection(t.collection)&&t.key===e.key))));n.length>0&&this.indexes.updateIndexes(n),this.changes.emitEvents(n,e)}else l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}calculateSize(){let e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(e=>this.syncedData.has(e)&&!this.optimisticUpserts.has(e)).length,n=Array.from(this.optimisticUpserts.keys()).filter(e=>!this.syncedData.has(e)).length;return e-t+n}collectOptimisticChanges(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.getPreviousValue(a,e,t),s=this.getVirtualPropsSnapshotForState(a,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),c=this.getVirtualPropsSnapshotForState(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&&o!==i&&r.push({type:`update`,key:a,value:i,previousValue:o,__virtualProps:{value:c,previousValue:s}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}scheduleTransactionCleanup(e){e.state===`completed`?this.transactions.delete(e.id):e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;let e=new Set;for(let t of this.pendingSyncedTransactions)for(let n of t.operations)e.add(n.key);for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);e!==void 0&&this.preSyncVisibleState.set(t,e)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}};function Jt(){let e=new Map;function t(n){let r=n.join(`.`);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!==`__type`)return typeof r==`symbol`?Reflect.get(e,r,i):t([...n,String(r)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`||Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return e.set(r,i),i}return t([])}function z(e){if(Yt(e))return new ne(e.__path);if(e&&typeof e==`object`&&(e.__brand===`ToArrayWrapper`||e.__brand===`ConcatToArrayWrapper`||e.__brand===`CaseWhenWrapper`||e.__brand===`MaterializeWrapper`)){let t=e.__brand===`ToArrayWrapper`?`toArray()`:e.__brand===`ConcatToArrayWrapper`?`concat(toArray())`:e.__brand===`CaseWhenWrapper`?`caseWhen()`:`materialize()`;throw Error(`${t} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${t} directly as a select field value instead.`)}return e&&typeof e==`object`&&`type`in e&&(e.type===`func`||e.type===`ref`||e.type===`val`||e.type===`agg`)?e:new O(e)}function Yt(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Xt(e,t){return new k(`eq`,[z(e),z(t)])}function Zt(e,t){return new k(`gt`,[z(e),z(t)])}function Qt(e,t){return new k(`gte`,[z(e),z(t)])}function $t(e,t){return new k(`lt`,[z(e),z(t)])}function en(e,t,...n){return new k(`and`,[e,t,...n].map(e=>z(e)))}function tn(e,t,...n){return new k(`or`,[e,t,...n].map(e=>z(e)))}var nn=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}once(e,t){let n=this.on(e,e=>{t(e),n()});return n}off(e,t){this.listeners.get(e)?.delete(t)}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(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.listeners.get(e)?.forEach(e=>{try{e(t)}catch(e){queueMicrotask(()=>{throw e})}})}clearListeners(){this.listeners.clear()}};function rn(e,t){if(t.length===0||e.length===0)return;if(e.length===1){let{expression:n,compareOptions:r}=e[0];return(r.direction===`asc`?Zt:$t)(n,new O(t[0]))}let n=[];for(let r=0;r<e.length&&r<t.length;r++){let i=e[r],a=t[r],o=[];for(let n=0;n<r;n++){let r=e[n],i=t[n];o.push(Xt(r.expression,new O(i)))}let s=(i.compareOptions.direction===`asc`?Zt:$t)(i.expression,new O(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>en(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>tn(e,t))}var an=class extends nn{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,n.onUnsubscribe&&this.on(`unsubscribed`,e=>n.onUnsubscribe(e)),n.whereExpression&&It(n.whereExpression,this.collection);let r=e=>{t(e),this.trackSentKeys(e)};this.callback=r,this.filteredCallback=n.whereExpression?Ht(this.callback,n):this.callback,this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){let e=[...this.loadedSubsets],t=this.collection._sync.syncLoadSubsetFn!==null;e.length===0||!t?(this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[]):(this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(let t of e){let e=this.collection._sync.loadSubset(t);this.loadedSubsets.push(t),this.trackLoadSubsetPromise(e),e instanceof Promise&&(this.pendingTruncateRefetches.add(e),e.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(e),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}}))}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;let e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}setOrderByIndex(e){this.orderByIndex=e}hasOrderByIndex(){return this.orderByIndex!==void 0}setStatus(e){if(this._status===e)return;let t=this._status;this._status=e,this.emitInner(`status:change`,{type:`status:change`,subscription:this,previousStatus:t,status:e});let n=`status:${e}`;this.emitInner(n,{type:n,subscription:this,previousStatus:t,status:e})}trackLoadSubsetPromise(e){e instanceof Promise&&(this.pendingLoadSubsetPromises.add(e),this.setStatus(`loadingSubset`),e.finally(()=>{this.pendingLoadSubsetPromises.delete(e),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`)}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){let t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):this.filteredCallback(t)}requestSnapshot(e){if(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=en(e,n)}else t.where=n}}else this.loadedInitialState=!0;let n={where:t.where,subscription:this,orderBy:e?.orderBy,limit:e?.limit},r=this.collection._sync.loadSubset(n);e?.onLoadSubsetResult?.(r),this.loadedSubsets.push(n),(e?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(r);let i=this.collection.currentStateAsChanges(t);if(i===void 0)return!1;let a=i.filter(e=>!this.sentKeys.has(e.key));for(let e of a)this.sentKeys.add(e.key);return this.snapshotSent=!0,this.callback(a),!0}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:r,trackLoadSubsetPromise:i=!0,onLoadSubsetResult:a}){if(!t)throw Error(`limit is required`);if(!this.orderByIndex)throw Error(`Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`);let o=n!==void 0&&n.length>0,s=n?.[0],c=this.orderByIndex,l=this.options.whereExpression,u=l?Vt(l):void 0,d=e=>{if(e!==void 0&&this.sentKeys.has(e))return!1;let t=this.collection.get(e);return t===void 0?!1:u?.(t)??!0},f=s,p=[],m=[];if(o){let{expression:n}=e[0],r=this.collection.currentStateAsChanges({where:Xt(n,new O(s))});if(r){let e=r.map(e=>e.key).filter(e=>!this.sentKeys.has(e)&&d(e));m.push(...e);let n=c.take(t-m.length,s,d);m.push(...n)}else m=c.take(t,s,d)}else m=c.takeFromStart(t,d);let h=()=>Math.max(t-p.length,0),g=()=>m.length===0,_=e[0].expression,v=_.type===`ref`?rt(new ne(_.path),!0):null;for(;h()>0&&!g();){let e=new Set;for(let t of m){let n=this.collection.get(t);p.push({type:`insert`,key:t,value:n}),f=v?v(n):n,e.add(t)}m=c.take(h(),f,d)}let y=this.limitedSnapshotRowCount;for(let e of p)this.sentKeys.add(e.key);this.callback(p),this.limitedSnapshotRowCount+=p.length,p.length>0&&(this.lastSentKey=p[p.length-1].key);let b;if(n!==void 0&&n.length>0){let t=rn(e,n);if(t){let{expression:r}=e[0],i=n[0],a;if(i instanceof Date){let e=new Date(i.getTime()+1);a=en(Qt(r,new O(i)),$t(r,new O(e)))}else a=Xt(r,new O(i));b={whereFrom:t,whereCurrent:a,lastKey:this.lastSentKey}}}let x={where:l,limit:t,orderBy:e,cursor:b,offset:r??y,subscription:this},S=this.collection._sync.loadSubset(x);a?.(S),this.loadedSubsets.push(x),i&&this.trackLoadSubsetPromise(S)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;let t=this.isBufferingForTruncate,n=[];for(let r of e){let e=r;if(!this.sentKeys.has(r.key)){if(r.type===`update`)e={...r,type:`insert`,previousValue:void 0};else if(r.type===`delete`&&!t)continue;this.sentKeys.add(r.key)}else if(r.type===`insert`)continue;else r.type===`delete`&&this.sentKeys.delete(r.key);n.push(e)}return n}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(let t of e)t.type===`delete`?this.sentKeys.delete(t.key):this.sentKeys.add(t.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(let e of this.loadedSubsets)this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),this.clearListeners()}},on=class{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){for(let e of this.changeSubscriptions)e.emitEvents([])}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1){if(this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let n=e;if(t&&(this.batchedEvents.length>0&&(n=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),n.length===0)return;let r=n.map(e=>this.enrichChangeWithVirtualProps(e));for(let e of this.changeSubscriptions)e.emitEvents(r)}subscribeChanges(e,t={}){if(this.addSubscriber(),t.where&&t.whereExpression)throw Error(`Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`);let{where:n,...r}=t,i=r.whereExpression;n&&(i=z(n(Jt())));let a=new an(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(a)}});return t.onStatusChange&&a.on(`status:change`,t.onStatusChange),t.includeInitialState?a.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&a.markAllStateAsSeen(),this.changeSubscriptions.add(a),a}addSubscriber(){let e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){let e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new de;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}},sn=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),cn=e=>{clearTimeout(e)},ln=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>sn(e),un=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):cn,dn=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return e.instance||=new e,e.instance}schedule(e,t,n){let r=Date.now()+t;this.tasks.set(e,{executeAt:r,callback:n}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){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-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;let e=Date.now();for(let[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(e){console.error(`Error in CleanupQueue task:`,e)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){e.instance&&=(e.instance.timeoutId!==null&&clearTimeout(e.instance.timeoutId),null)}};dn.instance=null;var fn=dn,pn=class{constructor(e,t){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=e,this.id=t}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`,`cleaned-up`],loading:[`ready`,`error`,`cleaned-up`],ready:[`cleaned-up`,`error`],error:[`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[e].includes(t))throw new le(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new se(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);let n=this.status;this.status=e,this.events.emitStatusChange(e,n)}validateCollectionUsable(e){switch(this.status){case`error`:throw new ce(e,this.id);case`cleaned-up`:this.sync.startSync()}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`){if(this.setStatus(`ready`,!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||=!0;let e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(e=>e())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){let e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||fn.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){fn.getInstance().cancel(this),this.idleCallbackId!==null&&(un(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&un(this.idleCallbackId),this.idleCallbackId=ln(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(!e||e.timeRemaining()>0||e.didTimeout){this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),fn.getInstance().cancel(this),this.hasBeenReady=!1;let e=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],e.forEach(e=>{try{e()}catch(e){console.error(`${this.config.id?`[${this.config.id}] `:``}Error in onFirstReady callback during cleanup:`,e)}}),this.setStatus(`cleaned-up`),this.events.cleanup(),!0}return this.scheduleIdleCleanup(),!1}onFirstReady(e){this.hasBeenReady?e():this.onFirstReadyCallbacks.push(e)}cleanup(){this.idleCallbackId!==null&&(un(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}},mn=Symbol(`liveQueryInternal`),hn=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,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._events=e.events}startSync(){if(this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`){this.lifecycle.setStatus(`loading`);try{let e=gn(this.config.sync.sync({collection:this.collection,begin:e=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:e?.immediate})},write:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Ae;if(t.committed)throw new je;let n;n=`key`in e?e.key:this.config.getKey(e.value),this.state.pendingLocalChanges.has(n)&&this.state.pendingLocalOrigins.add(n);let r=e.type;if(e.type===`insert`){let i=this.state.syncedData.has(n),a=t.deletedKeys.has(n),o=t.truncate===!0;if(i&&!a&&!o){let t=this.state.syncedData.get(n);if(t!==void 0&&I(t,e.value))r=`update`;else{let e=this.config.utils?.[mn];throw new he(n,this.id,{hasCustomGetKey:e?.hasCustomGetKey??!1,hasJoins:e?.hasJoins??!1,hasDistinct:e?.hasDistinct??!1})}}}let i={...e,type:r,key:n};t.operations.push(i),r===`delete`?(t.deletedKeys.add(n),t.rowMetadataWrites.set(n,{type:`delete`})):r===`insert`?i.metadata===void 0?t.rowMetadataWrites.set(n,{type:`delete`}):t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata}):i.metadata!==void 0&&t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata})},commit:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Me;if(e.committed)throw new Ne;e.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Ae;if(e.committed)throw new je;e.operations=[],e.deletedKeys.clear(),e.rowMetadataWrites.clear(),e.truncate=!0,e.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new N(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(e){throw this.lifecycle.setStatus(`error`),e}}}getActivePendingSyncTransaction(){let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Ae;if(e.committed)throw new je;return e}createSyncMetadataApi(){return{row:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],n=t?.rowMetadataWrites.get(e);if(n)return n.type===`delete`?void 0:n.value;if(!t?.truncate)return this.state.syncedMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`delete`})}},collection:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(e);return t?t.type===`delete`?void 0:t.value:this.state.syncedCollectionMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`delete`})},list:e=>{let t=new Map(this.state.syncedCollectionMetadata),n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(n)for(let[e,r]of n.collectionMetadataWrites)r.type===`delete`?t.delete(e):t.set(e,r.value);return Array.from(t.entries()).filter(([t])=>!e||t.startsWith(e)).map(([e,t])=>({key:e,value:t}))}}}}preload(){return this.preloadPromise||=(this.syncMode===`on-demand`&&console.warn(`${this.id?`[${this.id}] `:``}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`),new Promise((e,t)=>{if(this.lifecycle.status===`ready`)e();else if(this.lifecycle.status===`error`)t(new ue);else if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`)try{this.startSync()}catch(e){t(e);return}})),this.preloadPromise}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){let t=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`}),e.finally(()=>{let t=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})})}loadSubset(e){if(this.syncMode===`eager`)return!0;if(this.syncLoadSubsetFn){let t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&=(this.syncCleanupFn(),null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){let t=new Re(this.id,e);throw t.cause=e,t.stack=e.stack,t}throw new Re(this.id,e)})}this.preloadPromise=null}};function gn(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var _n=1;function vn(e,t){return e===t?0:e<t?-1:1}function yn(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function bn(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=>bn(e)??null);if(e instanceof Date)return{__type:`date`,value:e.toISOString()};if(e instanceof Set)return{__type:`set`,values:Array.from(e).map(e=>bn(e)??null).sort((e,t)=>vn(xn(e),xn(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:bn(e)??null,value:bn(t)??null})).sort((e,t)=>vn(xn(e.key),xn(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>vn(e,t));for(let[e,r]of n){let n=bn(r);n!==void 0&&(t[e]=n)}return t}function xn(e){return e===null?`null`:Array.isArray(e)?`[${e.map(xn).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>vn(e,t)).map(t=>`${JSON.stringify(t)}:${xn(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function Sn(e,t,n,r,i){let a=yn(r),o=bn(t)??null,s=bn(i);return{signatureVersion:_n,signature:xn(bn({signatureVersion:_n,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function Cn(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>Cn(e));let t={};for(let[n,r]of Object.entries(e))t[n]=Cn(r);return t}function wn(e){return JSON.parse(JSON.stringify(e))}var Tn=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=z(e(Jt())),i=t.indexType??this.defaultIndexType;if(!i)throw new N(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
6
- import { BasicIndex } from '@tanstack/db'
7
- createCollection({ defaultIndexType: BasicIndex, ... })`);let a=new i(n,r,t.name,t.options);a.build(this.state.entries()),this.indexes.set(n,a);let o=Sn(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:wn(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Cn(e.options)}}))}updateIndexes(e){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)}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},En=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),Dn=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),On=new Set([`set`,`delete`,`clear`,`add`]),kn=new Set([`entries`,`keys`,`values`,`forEach`]);function An(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!Ve(e)}function jn(e,t,n,r){if(En.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(An(e)){let{proxy:i}=r(e,{tracker:n,prop:String(t)});return i}return e},s=function(e,t,n){let r=o(e,t);return a.call(this,r,t,n)};if(e===`reduce`||e===`reduceRight`)return t.apply(n.copy_,[function(e,t,n,r){let i=o(t,n);return a.call(this,e,i,n,r)},...i.slice(1)]);let c=t.apply(n.copy_,[s,...i.slice(1)]);if((e===`find`||e===`findLast`)&&c&&typeof c==`object`){let e=n.copy_.indexOf(c);if(e!==-1)return o(c,e)}return e===`filter`&&Array.isArray(c)?c.map(e=>{let t=n.copy_.indexOf(e);return t===-1?e:o(e,t)}):c}}function Mn(e,t){return function(){let n=e.copy_,r=0;return{next(){if(r>=n.length)return{done:!0,value:void 0};let i=n[r],a=i;if(An(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function Nn(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function Pn(e,t,n,r,i,a,o){if(kn.has(e)||t===Symbol.iterator)return function(...s){let c=n.apply(i.copy_,s);if(e===`forEach`){let e=s[0];if(typeof e==`function`)return n.apply(r,[function(t,n,r){let a=e.call(this,t,n,r);return o(i),a},...s.slice(1)])}if(e===`entries`||e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator){let n=c,o=new Map;if(e===`values`&&r instanceof Map)for(let[e,t]of i.copy_.entries())o.set(t,e);let s=new Map;if(r instanceof Set)for(let e of i.copy_.values())s.set(e,e);return{next(){let c=n.next();if(!c.done&&c.value&&typeof c.value==`object`){if(e===`entries`&&Array.isArray(c.value)&&c.value.length===2){if(c.value[1]&&typeof c.value[1]==`object`){let e=c.value[0],t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value[1],t);c.value[1]=n}}else if(e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator){if(e===`values`&&r instanceof Map){let e=o.get(c.value);if(e!==void 0){let t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value,t);c.value=n}}else if(r instanceof Set){let e=c.value,t={tracker:i,prop:e,updateSet:t=>{i.copy_ instanceof Set&&(i.copy_.delete(e),i.copy_.add(t),s.set(e,t))}},{proxy:n}=a(c.value,t);c.value=n}else{let e=Symbol(`iterator-value`),{proxy:t}=a(c.value,{tracker:i,prop:e});c.value=t}}}return c},[Symbol.iterator](){return this}}}return c}}function B(...e){let t=typeof window<`u`&&typeof localStorage<`u`;(t&&localStorage.getItem(`DEBUG`)===`true`||!t&&typeof process<`u`&&{}.DEBUG===`true`)&&console.log(`[proxy]`,...e)}function V(e,t=new WeakMap){if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e)){let n=[];return t.set(e,n),e.forEach((e,r)=>{n[r]=V(e,t)}),n}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)){let n=Object.getPrototypeOf(e).constructor,r=new n(e.length);t.set(e,r);for(let t=0;t<e.length;t++)r[t]=e[t];return r}if(e instanceof Map){let n=new Map;return t.set(e,n),e.forEach((e,r)=>{n.set(r,V(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(V(e,t))}),n}if(Ve(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=V(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=V(e[i],t);return n}var Fn=0;function In(){return Fn+=1,Fn}function Ln(e,t){let n=new Map;function r(e,t){if(B(`Object ID:`,e.constructor.name),n.has(e))return n.get(e);{let r=Ln(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:V(e),originalObject:V(e),proxyCount:In(),modified:!1,assigned_:{},parent:t,target:e};B(`createChangeProxy called for target`,e,a.proxyCount);function o(e){e.modified||=!0,e.parent&&(B(`propagating change to parent`),`updateMap`in e.parent?e.parent.updateMap(e.copy_):`updateSet`in e.parent?e.parent.updateSet(e.copy_):(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(B(`checkIfReverted called with assigned keys:`,Object.keys(e.assigned_)),Object.keys(e.assigned_).length===0&&Object.getOwnPropertySymbols(e.assigned_).length===0)return B(`No assigned properties, returning true`),!0;for(let t in e.assigned_)if(e.assigned_[t]===!0){let n=e.copy_[t],r=e.originalObject[t];if(B(`Checking property ${String(t)}, current:`,n,`original:`,r),!I(n,r))return B(`Property ${String(t)} is different, returning false`),!1}else if(e.assigned_[t]===!1)return B(`Property ${String(t)} was deleted, returning false`),!1;let t=Object.getOwnPropertySymbols(e.assigned_);for(let n of t)if(e.assigned_[n]===!0){let t=e.copy_[n],r=e.originalObject[n];if(!I(t,r))return B(`Symbol property is different, returning false`),!1}else if(e.assigned_[n]===!1)return B(`Symbol property was deleted, returning false`),!1;return B(`All properties match original values, returning true`),!0}function c(e,t){B(`checkParentStatus called for child prop:`,t);let n=s(e);B(`Parent checkIfReverted returned:`,n),n&&(B(`Parent is fully reverted, clearing tracking`),e.modified=!1,e.assigned_={},e.parent&&(B(`Continuing up the parent chain`),c(e.parent.tracker,e.parent.prop)))}function l(e){if(B(`createObjectProxy`,e),i.has(e))return B(`proxyCache found match`),i.get(e);let n=new Proxy(e,{get(e,t){B(`get`,e,t);let n=a.copy_[t]??a.originalObject[t],s=a.originalObject[t];if(B(`value (at top of proxy get)`,n),Object.getOwnPropertyDescriptor(e,t)?.get)return n;if(typeof n==`function`){if(Array.isArray(e)){let e=t.toString();if(Dn.has(e))return Nn(n,a,o);let i=jn(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return Mn(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(On.has(i))return Nn(n,a,o);let s=Pn(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(An(n)){let{proxy:e}=r(s,{tracker:a,prop:String(t)});return i.set(n,e),e}return n},set(e,n,r){let i=a.copy_[n];if(B(`set called for property ${String(n)}, current:`,i,`new:`,r),I(i,r))B(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=I(r,e);if(B(`value:`,r,`original:`,e,`isRevertToOriginal:`,i),i){B(`Reverting property ${String(n)} to original value`),delete a.assigned_[n.toString()],B(`Updating copy with original value for ${String(n)}`),a.copy_[n]=V(e),B(`Checking if all properties reverted`);let r=s(a);B(`All reverted:`,r),r?(B(`All properties reverted, clearing tracking`),a.modified=!1,a.assigned_={},t&&(B(`Updating parent for property:`,t.prop),c(t.tracker,t.prop))):(B(`Some properties still changed, keeping modified flag`),a.modified=!0)}else B(`Setting new value for property ${String(n)}`),a.copy_[n]=r,a.assigned_[n.toString()]=!0,B(`Marking object and ancestors as modified`,a),o(a)}return!0},defineProperty(e,t,n){let r=Reflect.defineProperty(e,t,n);return r&&`value`in n&&(a.copy_[t]=V(n.value),a.assigned_[t.toString()]=!0,o(a)),r},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(e,t)},preventExtensions(e){return Reflect.preventExtensions(e)},isExtensible(e){return Reflect.isExtensible(e)},deleteProperty(e,t){B(`deleteProperty`,e,t);let n=typeof t==`symbol`?t.toString():t;if(n in e){let r=n in a.originalObject,i=Reflect.deleteProperty(e,t);return i&&(r?(a.assigned_[n]=!1,o(a)):(delete a.assigned_[n],Object.keys(a.assigned_).length===0&&Object.getOwnPropertySymbols(a.assigned_).length===0?a.modified=!1:a.modified=!0)),i}return!0}});return i.set(e,n),n}return{proxy:l(a.copy_),getChanges:()=>{if(B(`getChanges called, modified:`,a.modified),B(a),!a.modified)return B(`Object not modified, returning empty object`),{};if(typeof a.copy_!=`object`||Array.isArray(a.copy_)||Object.keys(a.assigned_).length===0)return a.copy_;let e={};for(let t in a.copy_)a.assigned_[t]===!0&&t in a.copy_&&(e[t]=a.copy_[t]);return B(`Returning copy:`,e),e}}}function Rn(e){let t=e.map(e=>Ln(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function zn(e,t){let{proxy:n,getChanges:r}=Ln(e);return t(n),r()}function Bn(e,t){let{proxies:n,getChanges:r}=Rn(e);return t(n),r()}function Vn(){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 Hn(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var Un=new class{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(e===void 0){r();return}let i=this.getOrCreateContext(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);i.completed.delete(t)}flush(e){let t=this.contexts.get(e);if(!t)return;let{queue:n,jobs:r,dependencies:i,completed:a}=t;for(;n.length>0;){let t=!1,o=n.length;for(let s=0;s<o;s++){let o=n.shift(),s=r.get(o);if(!s){i.delete(o),a.delete(o);continue}let c=i.get(o),l=!c;if(c){l=!0;for(let t of c){if(t===o)continue;let n=Hn(t)&&t.hasPendingGraphRun(e);if(r.has(t)&&!a.has(t)||!r.has(t)&&n){l=!1;break}}}l?(r.delete(o),i.delete(o),s(),a.add(o),t=!0):n.push(o)}if(!t)throw Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(let e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(t=>t(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){let t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){let n=this.contexts.get(e);n&&(n.jobs.delete(t),n.dependencies.delete(t),n.completed.delete(t),n.queue=n.queue.filter(e=>e!==t),n.jobs.size===0&&this.contexts.delete(e))}},Wn=[],Gn=[],Kn=0;function qn(e,t){switch(`${e.type}-${t.type}`){case`insert-update`:return{...e,type:`insert`,original:{},modified:t.modified,changes:{...e.changes,...t.changes},key:e.key,globalKey:e.globalKey,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case`insert-delete`:return null;case`update-delete`:return t;case`update-update`:return{...t,original:e.original,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}};case`delete-delete`:case`insert-insert`:return t;default:{let n=`${e.type}-${t.type}`;throw Error(`Unhandled mutation combination: ${n}`)}}}function Jn(e){let t=new $n(e);return Wn.push(t),t}function Yn(){if(Gn.length>0)return Gn.slice(-1)[0]}function Xn(e){Un.clear(e.id),Gn.push(e)}function Zn(e){try{Un.flush(e.id)}finally{Gn=Gn.filter(t=>t.id!==e.id)}}function Qn(e){let t=Wn.findIndex(t=>t.id===e.id);t!==-1&&Wn.splice(t,1)}var $n=class{constructor(e){if(e.mutationFn===void 0)throw new Ee;this.id=e.id??A(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Vn(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Kn++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e===`completed`||e===`failed`)&&Qn(this)}mutate(e){if(this.state!==`pending`)throw new De;Xn(this);try{e()}finally{Zn(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){let t=new Map;for(let e of this.mutations)t.set(e.globalKey,e);for(let n of e){let e=t.get(n.globalKey);if(e){let r=qn(e,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}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 Oe;if(this.setState(`failed`),!t){let e=new Set;this.mutations.forEach(t=>e.add(t.globalKey));for(let t of Wn)t.state===`pending`&&t.mutations.some(t=>e.has(t.globalKey))&&t.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){let e=new Set;for(let t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if(this.state!==`pending`)throw new ke;if(this.setState(`persisting`),this.mutations.length===0)return this.setState(`completed`),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState(`completed`),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return t===0?this.sequenceNumber-e.sequenceNumber:t}},er=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=Yn();if(!r&&!this.config.onInsert)throw new Ce;let i=Array.isArray(e)?e:[e],a=[],o=new Set;if(i.forEach(e=>{let n=this.validateData(e,`insert`),r=this.config.getKey(n);if(this.state.has(r)||o.has(r))throw new me(r);o.add(r);let i=this.generateGlobalKey(r,e),s={mutationId:A(),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:new Date,updatedAt:new Date,collection:this.collection};a.push(s)}),r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;{let e=Jn({metadata:{[Kt]:!0},mutationFn:async e=>await this.config.onInsert({transaction:e.transaction,collection:this.collection})});return e.applyMutations(a),this.markPendingLocalOrigins(a),e.commit().catch(()=>void 0),n.transactions.set(e.id,e),n.scheduleTransactionCleanup(e),n.recomputeOptimisticState(!0),e}},this.delete=(e,t)=>{let n=this.state;this.lifecycle.validateCollectionUsable(`delete`);let r=Yn();if(!r&&!this.config.onDelete)throw new Te;if(Array.isArray(e)&&e.length===0)throw new be;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new xe(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:A(),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:new Date,updatedAt:new Date,collection:this.collection};a.push(i)}if(r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;let o=Jn({autoCommit:!0,metadata:{[Kt]:!0},mutationFn:async e=>this.config.onDelete({transaction:e.transaction,collection:this.collection})});return o.applyMutations(a),this.markPendingLocalOrigins(a),o.commit().catch(()=>void 0),n.transactions.set(o.id,o),n.scheduleTransactionCleanup(o),n.recomputeOptimisticState(!0),o},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}ensureStandardSchema(e){if(e&&`~standard`in e)return e;throw new ae}validateData(e,t,n){if(!this.config.schema)return e;let r=this.ensureStandardSchema(this.config.schema);if(t===`update`&&n){let i=this.state.get(n);if(i&&e&&typeof e==`object`&&typeof i==`object`){let n=Object.assign({},i,e),a=r[`~standard`].validate(n);if(a instanceof Promise)throw new oe;if(`issues`in a&&a.issues)throw new M(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 oe;if(`issues`in i&&i.issues)throw new M(t,i.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return i.value}generateGlobalKey(e,t){if(typeof e!=`string`&&typeof e!=`number`)throw e===void 0?new fe(t):new pe(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(let t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(e===void 0)throw new ge;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=Yn();if(!i&&!this.config.onUpdate)throw new we;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new _e;let s=typeof t==`function`?t:n,c=typeof t==`function`?{}:t,l=o.map(e=>{let t=this.state.get(e);if(!t)throw new ve(e);return t}),u;u=a?Bn(l,s):[zn(l[0],s)];let d=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=Object.assign({},i,a),s=this.config.getKey(i),d=this.config.getKey(o);if(s!==d)throw new ye(s,d);let f=this.generateGlobalKey(d,o);return{mutationId:A(),original:i,modified:o,changes:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),globalKey:f,key:e,metadata:c.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:`update`,createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(d.length===0){let e=Jn({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),r.scheduleTransactionCleanup(e),e}if(i)return i.applyMutations(d),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;let f=Jn({metadata:{[Kt]:!0},mutationFn:async e=>this.config.onUpdate({transaction:e.transaction,collection:this.collection})});return f.applyMutations(d),this.markPendingLocalOrigins(d),f.commit().catch(()=>void 0),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}},tr=class extends nn{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t){this.emit(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:t,status:e});let n=`status:${e}`;this.emit(n,{type:n,collection:this.collection,previousStatus:t,status:e})}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()}};function nr(e){let t=new rr(e);return t.utils=e.utils?e.utils:{},t}var rr=class{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this._mutations.insert(e,t),this.delete=(e,t)=>this._mutations.delete(e,t),!e)throw new re;if(!e.sync)throw new ie;if(this.id=e.id?e.id:A(),this.config={...e,autoIndex:e.autoIndex??`off`},this.config.autoIndex===`eager`&&!e.defaultIndexType)throw new N(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
8
- import { BasicIndex } from '@tanstack/db'
9
- createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new on,this._events=new tr,this._indexes=new Tn,this._lifecycle=new pn(e,this.id),this._mutations=new er(e,this.id),this._state=new qt(e),this._sync=new hn(e,this.id),this.comparisonOpts=ir(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}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._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.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.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return Bt(this,e)}subscribeChanges(e,t={}){return this._changes.subscribeChanges(e,t)}on(e,t){return this._events.on(e,t)}once(e,t){return this._events.once(e,t)}off(e,t){this._events.off(e,t)}waitFor(e,t){return this._events.waitFor(e,t)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}};function ir(e){if(e.defaultStringCollation){let t=e.defaultStringCollation;return{stringSort:t.stringSort??`locale`,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}}return{stringSort:`locale`}}var ar={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},or=new class{#e=ar;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 sr(e){setTimeout(e,0)}var cr=typeof window>`u`||`Deno`in globalThis;function H(){}function lr(e,t){return typeof e==`function`?e(t):e}function ur(e){return typeof e==`number`&&e>=0&&e!==1/0}function dr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function U(e,t){return typeof e==`function`?e(t):e}function fr(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==mr(o,t.options))return!1}else if(!hr(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 pr(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(W(t.options.mutationKey)!==W(a))return!1}else if(!hr(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function mr(e,t){return(t?.queryKeyHashFn||W)(e)}function W(e){return JSON.stringify(e,(e,t)=>br(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function hr(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(!hr(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!hr(e[r],t[r]))return!1;return!0}return!1}var gr=Object.prototype.hasOwnProperty;function _r(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=yr(e)&&yr(t);if(!r&&!(br(e)&&br(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:gr.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=_r(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function vr(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 yr(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function br(e){if(!xr(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!(!xr(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function xr(e){return Object.prototype.toString.call(e)===`[object Object]`}function Sr(e){return new Promise(t=>{or.setTimeout(t,e)})}function Cr(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:_r(e,t)}function wr(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Tr(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Er=Symbol();function Dr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Er?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Or(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 kr=()=>cr,Ar=()=>kr(),jr=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(){}},Mr=new class extends jr{#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`}},Nr=sr;function Pr(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Nr,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 G=Pr(),Fr=new class extends jr{#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 Ir(e){return Math.min(1e3*2**e,3e4)}function Lr(e){return(e??`online`)!==`online`||Fr.isOnline()}var Rr=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function zr(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(H);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Rr(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Mr.isFocused()&&(e.networkMode===`always`||Fr.isOnline())&&e.canRun(),p=()=>Lr(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??(Ar()?0:3),a=e.retryDelay??Ir,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),Sr(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 Br=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ur(this.gcTime)&&(this.#e=or.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ar()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(or.clearTimeout(this.#e),this.#e=void 0)}};function Vr(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=>{Or(e,()=>t.signal,()=>n=!0)},u=Dr(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?Tr:wr;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Ur:Hr,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:Hr(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 Hr(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 Ur(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Wr=class extends Br{#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=qr(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=qr(this.options);e.data!==void 0&&(this.setState(Kr(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Cr(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(H).catch(H):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=>U(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Er||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>U(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:!dr(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=Dr(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`?Vr(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=zr({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Rr&&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 Rr){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,...Gr(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Kr(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),G.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Gr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Lr(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Kr(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function qr(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 Jr=class extends jr{#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),Xr(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zr(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zr(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 U(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&&!vr(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Qr(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||U(this.options.enabled,this.#t)!==U(t.enabled,this.#t)||U(this.options.staleTime,this.#t)!==U(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||U(this.options.enabled,this.#t)!==U(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 vr(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(H)),t}#h(e){return!Ar()&&U(this.options.enabled,this.#t)!==!1&&ur(e)}#g(){this.#b();let e=U(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=dr(this.#r.dataUpdatedAt,e)+1;this.#u=or.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return U(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=or.setInterval(()=>{(this.options.refetchIntervalInBackground||Mr.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(or.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(or.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&&Xr(e,t),o=i&&Qr(e,n,t,r);(a||o)&&(l={...l,...Gr(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=Cr(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=Cr(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:$r(e,t),refetch:this.refetch,isEnabled:U(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),vr(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)})})();G.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 Yr(e,t){return U(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||U(t.retryOnMount,e)!==!1)}function Xr(e,t){return Yr(e,t)||e.state.data!==void 0&&Zr(e,t,t.refetchOnMount)}function Zr(e,t,n){if(U(t.enabled,e)!==!1&&U(t.staleTime,e)!==`static`){let r=U(n,e);return r===`always`||r!==!1&&$r(e,t)}return!1}function Qr(e,t,n,r){return(e!==t||U(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&$r(e,n)}function $r(e,t){return U(t.enabled,e)!==!1&&e.isStaleByTime(U(t.staleTime,e))}var ei=class extends Br{#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||ti(),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=zr({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),G.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function ti(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var ni=class extends jr{#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 ei({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=ri(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=ri(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=ri(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=ri(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){G.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=>pr(t,e))}findAll(e={}){return this.getAll().filter(t=>pr(e,t))}notify(e){G.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return G.batch(()=>Promise.all(e.map(e=>e.continue().catch(H))))}};function ri(e){return e.options.scope?.id}var ii=class extends jr{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??mr(r,t),a=this.get(i);return a||(a=new Wr({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(){G.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=>fr(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>fr(e,t)):t}notify(e){G.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){G.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){G.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ai=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new ii,this.#t=e.mutationCache||new ni,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Mr.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Fr.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(U(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=lr(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return G.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;G.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return G.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=G.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(H).catch(H)}invalidateQueries(e,t={}){return G.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=G.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(H)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(H)}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(U(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(U(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(H).catch(H)}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(H).catch(H)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Fr.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(W(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{hr(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(W(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{hr(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||=mr(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===Er&&(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()}},oi=class extends j{constructor(e){super(e),this.name=`QueryCollectionError`}},si=class extends oi{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},ci=class extends oi{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},li=class extends oi{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},ui=class extends oi{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},di=class extends oi{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},fi=class extends oi{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},pi=class extends oi{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},mi=class extends oi{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},hi=new WeakMap;function gi(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 _i(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new fi(r.key);if(n.add(r.key),r.type===`update`){if(!t.collection._state.syncedData.has(r.key))throw new pi(r.key)}else if(r.type===`delete`&&!t.collection._state.syncedData.has(r.key))throw new mi(r.key)}}function vi(e,t){let n=gi(e,t);_i(n,t),t.begin({immediate:!0});for(let e of n)switch(e.type){case`insert`:{let n=t.collection.validateData(e.data,`insert`);t.write({type:`insert`,value:n});break}case`update`:{let n={...t.collection._state.syncedData.get(e.key),...e.data},r=t.collection.validateData(n,`update`,e.key);t.write({type:`update`,value:r});break}case`delete`:{let n=t.collection._state.syncedData.get(e.key);t.write({type:`delete`,value:n});break}case`upsert`:{let n=t.collection._state.syncedData.has(e.key),r=t.collection.validateData(e.data,n?`update`:`insert`,e.key);n?t.write({type:`update`,value:r}):t.write({type:`insert`,value:r});break}}t.commit();let r=Array.from(t.collection._state.syncedData.values());t.updateCacheData?t.updateCacheData(r):t.queryClient.setQueryData(t.queryKey,r)}function yi(e){function t(){let t=e();if(!t)throw new di;return t}return{writeInsert(e){let n={type:`insert`,data:e},r=t(),i=hi.get(r);i?.isActive?i.operations.push(n):vi(n,r)},writeUpdate(e){let n={type:`update`,data:e},r=t(),i=hi.get(r);i?.isActive?i.operations.push(n):vi(n,r)},writeDelete(e){let n={type:`delete`,key:e},r=t(),i=hi.get(r);i?.isActive?i.operations.push(n):vi(n,r)},writeUpsert(e){let n={type:`upsert`,data:e},r=t(),i=hi.get(r);i?.isActive?i.operations.push(n):vi(n,r)},writeBatch(e){let n=t();if(hi.get(n)?.isActive)throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let r={operations:[],isActive:!0};hi.set(n,r);try{let t=e();if(t&&typeof t==`object`&&`then`in t&&typeof t.then==`function`)throw Error(`writeBatch does not support async callbacks. The callback must be synchronous.`);r.operations.length>0&&vi(r.operations,n)}finally{r.isActive=!1,hi.delete(n)}}}}function bi(e){if(!e)return;let t={};return e.where&&(t.where=xi(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:xi(e.expression),direction:e.compareOptions.direction,nulls:e.compareOptions.nulls,stringSort:e.compareOptions.stringSort};return e.compareOptions.stringSort===`locale`?{...t,locale:e.compareOptions.locale,localeOptions:e.compareOptions.localeOptions}:t})),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),Object.keys(t).length===0?void 0:JSON.stringify(t)}function xi(e){if(!e)return null;switch(e.type){case`val`:return{type:`val`,value:Si(e.value)};case`ref`:return{type:`ref`,path:[...e.path]};case`func`:return{type:`func`,name:e.name,args:e.args.map(e=>xi(e))};default:return null}}function Si(e){if(e===void 0)return{__type:`undefined`};if(typeof e==`number`){if(Number.isNaN(e))return{__type:`nan`};if(e===1/0)return{__type:`infinity`,sign:1};if(e===-1/0)return{__type:`infinity`,sign:-1}}return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:e instanceof Date?{__type:`date`,value:e.toJSON()}:Array.isArray(e)?e.map(e=>Si(e)):typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Si(t)])):e}var Ci=`queryCollection:gc:`,wi=class{constructor(e,t,n){this.state=e,this.refetchFn=t,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}async clearError(){this.state.lastError=void 0,this.state.errorCount=0,this.state.lastErrorUpdatedAt=0,await this.refetchFn({throwOnError:!0})}get lastError(){return this.state.lastError}get isError(){return!!this.state.lastError}get errorCount(){return this.state.errorCount}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(){return Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().fetchStatus)}};function Ti(e){let{queryKey:t,queryFn:n,select:r,queryClient:i,enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,gcTime:u,persistedGcTime:d,getKey:f,onInsert:p,onUpdate:m,onDelete:h,meta:g,..._}=e,v=_.syncMode??`eager`,y=typeof t==`function`?t({}):t,b=e=>{typeof t==`function`&&(e.length>=y.length&&y.every((t,n)=>I(t,e[n]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(y)}, Got: ${JSON.stringify(e)}. This can cause stale cache issues.`))};if(!t)throw new si;if(!n)throw new ci;if(!i)throw new li;if(!f)throw new ui;let x={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},S=new Map,C=new Map,w=new Map,T=new Map,E=new Map,ee=(e,t)=>{let n=w.get(e)||new Set;n.add(t),w.set(e,n);let r=C.get(t)||new Set;r.add(e),C.set(t,r)},te=(e,t)=>{let n=w.get(e)||new Set;n.delete(t),w.set(e,n);let r=C.get(t)||new Set;return r.delete(e),C.set(t,r),n.size===0},D=e=>{let{begin:p,write:m,commit:h,markReady:_,collection:y,metadata:D}=e,ne=D,O=!1,k=!1,A=new Set,j=new Map,M=new Map,N=Promise.resolve(),re=e=>D?.row.get(e)??y._state.syncedMetadata.get(e),ie=e=>{let t=re(e)?.queryCollection;if(!t||typeof t!=`object`)return new Set;let n=t.owners;return!n||typeof n!=`object`?new Set:new Set(Object.keys(n))},ae=(e,t)=>{if(!D)return;let n={...re(e)??{}};t.size===0?(delete n.queryCollection,Object.keys(n).length===0?D.row.delete(e):D.row.set(e,n)):D.row.set(e,{...n,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},oe=(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}}},se=e=>(N=N.then(e,e),N),ce=e=>{let t=M.get(e);t&&(clearTimeout(t),M.delete(e))},le=e=>{let t=C.get(e);if(t)return new Set(t);let n=new Set;for(let[t]of y._state.syncedData.entries()){let r=ie(t);r.size!==0&&(w.set(t,new Set(r)),r.forEach(e=>{let n=C.get(e)||new Set;n.add(t),C.set(e,n)}),r.has(e)&&n.add(t))}return n},ue=async e=>{let t=C.get(e);if(t&&Array.from(t).every(e=>y.has(e))){let e=new Map;return t.forEach(t=>{let n=y.get(t),r=w.get(t);n&&r&&e.set(t,{value:n,owners:new Set(r)})}),e}let n=ne?.row.scanPersisted;if(!n){let t=new Map;return le(e).forEach(e=>{let n=y.get(e),r=w.get(e);n&&r&&t.set(e,{value:n,owners:new Set(r)})}),t}let r=new Map;return(await n()).forEach(t=>{let n=t.metadata?.queryCollection;if(!n||typeof n!=`object`)return;let i=n.owners;if(!i||typeof i!=`object`)return;let a=new Set(Object.keys(i));a.size!==0&&(w.set(t.key,new Set(a)),a.forEach(e=>{let n=C.get(e)||new Set;n.add(t.key),C.set(e,n)}),a.has(e)&&r.set(t.key,{value:t.value,owners:a}))}),r},de=async e=>{if(!D)return;let t=await ue(e),n=[];p(),t.forEach(({value:t,owners:r},i)=>{r.delete(e),ae(i,r),te(i,e)&&n.push(t)}),n.forEach(e=>{m({type:`delete`,value:e})}),D.collection.delete(`${Ci}${e}`),h()},P=e=>{if(e.mode!==`ttl`)return;ce(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{M.delete(e.queryHash),se(async()=>{let t=D?.collection.get(`${Ci}${e.queryHash}`),n=oe(t,e.queryHash);!n||n.mode!==`ttl`||n.expiresAt>Date.now()||await de(e.queryHash)})},t);M.set(e.queryHash,n)},fe=async()=>{if(!D)return;let e=D.collection.list(Ci),t=Date.now();for(let{key:n,value:r}of e){let e=n.slice(Ci.length),i=oe(r,e);i&&(i.mode===`ttl`&&i.expiresAt<=t?await de(i.queryHash):i.mode===`ttl`&&P(i))}},pe=e=>{if(typeof t==`function`)return t(e);if(v===`on-demand`){let n=bi(e);return n===void 0?t:[...t,n]}return t},me=D?.collection.list(Ci),he=!me||me.length===0?(k=!0,Promise.resolve()):se(async()=>{try{await fe()}finally{k=!0}}),ge=(e={},t=n)=>{if(!k)return he.then(()=>{let n=ge(e,t);return n===!0?void 0:n});let r=pe(e),f=W(r),p={...g,loadSubsetOptions:e},m=D?.collection.get(`${Ci}${f}`);if(oe(m,f)!==void 0&&A.add(f),ce(f),b(r),x.observers.has(f)){E.set(f,(E.get(f)||0)+1);let e=x.observers.get(f),t=e.getCurrentResult();return t.isSuccess?!0:t.isError?Promise.reject(t.error):i.getQueryData(r)!==void 0||new Promise((t,n)=>{let r=e.subscribe(e=>{queueMicrotask(()=>{e.isSuccess?(r(),t()):e.isError&&(r(),n(e.error))})})})}let h={queryKey:r,queryFn:t,meta:p,structuralSharing:!0,notifyOnChangeProps:`all`,...a!==void 0&&{enabled:a},...o!==void 0&&{refetchInterval:o},...s!==void 0&&{retry:s},...c!==void 0&&{retryDelay:c},...l!==void 0&&{staleTime:l},...u!==void 0&&{gcTime:u}},_=new Jr(i,h),v=i.getQueryCache().find({queryKey:r,exact:!0})?.gcTime,C=d??v;if(S.set(f,r),x.observers.set(f,_),C===void 0?j.delete(f):j.set(f,C),E.set(f,(E.get(f)||0)+1),i.getQueryData(r)!==void 0)return(O||y.subscriberCount>0)&&xe(_,f),!0;let w=new Promise((e,t)=>{let n=_.subscribe(r=>{queueMicrotask(()=>{r.isSuccess?(n(),e()):r.isError&&(n(),t(r.error))})})});return(O||y.subscriberCount>0)&&xe(_,f),w},_e=(e,t,n)=>{let i=W(e);if(y.status===`cleaned-up`)return;x.lastError=void 0,x.errorCount=0;let a=t.data,o=r?r(a):a;if(!Array.isArray(o)||o.some(e=>typeof e!=`object`)){let t=r?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`;console.error(t);return}let s=new Map(y._state.syncedData.entries()),c=n!==void 0,l=c?new Set(n.keys()):le(i),u=new Map;o.forEach(e=>{let t=f(e);u.set(t,e)}),p(),D&&D.collection.delete(`${Ci}${i}`),l.forEach(e=>{let t=c?n.get(e)?.value:s.get(e);if(!t)return;let r=u.get(e);if(r)I(t,r)||m({type:`update`,value:r});else{let n=ie(e);n.delete(i),ae(e,n),te(e,i)&&m({type:`delete`,value:t})}}),u.forEach((e,t)=>{let n=ie(t);n.has(i)||(n.add(i),ae(t,n)),ee(t,i),s.has(t)||m({type:`insert`,value:e})}),h(),A.delete(i),ce(i),_()},ve=async(e,t)=>{let n=W(e),r=await ue(n);y.status!==`cleaned-up`&&_e(e,t,r)},ye=e=>{let t=W(e);return n=>{if(n.isSuccess){if(y.deferDataRefresh){y.deferDataRefresh.then(()=>{let e=x.observers.get(t);e&&e.refetch().catch(()=>{})});return}A.has(t)?ve(e,n).catch(t=>{console.error(`[QueryCollection] Error reconciling query ${String(e)}:`,t)}):_e(e,n)}else n.isError&&((n.errorUpdatedAt!==x.lastErrorUpdatedAt||n.error!==x.lastError)&&(x.lastError=n.error,x.errorCount++,x.lastErrorUpdatedAt=n.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(e)}:`,n.error),_())}},be=e=>T.has(e),xe=(e,t)=>{if(!be(t)){let n=S.get(t),r=ye(n),i=e.subscribe(r);T.set(t,i);let a=e.getCurrentResult();(a.isSuccess||a.isError)&&r(a)}},Se=()=>{x.observers.forEach(xe)},Ce=()=>{T.forEach(e=>{e()}),T.clear()};O=!0;let we=y.on(`subscribers:change`,({subscriberCount:e})=>{e>0?Se():e===0&&Ce()});if(v===`eager`){let e=ge({});e instanceof Promise&&e.catch(()=>{})}else k?_():he.then(()=>{_()});Se(),x.observers.forEach((e,t)=>{let n=S.get(t);ye(n)(e.getCurrentResult())});let Te=e=>{T.get(e)?.(),T.delete(e),ce(e),A.delete(e);let t=C.get(e)??new Set,n=new Map,r=[];t.forEach(t=>{let i=w.get(t);if(!i)return;let a=new Set(i);a.delete(e),n.set(t,a),a.size===0&&y.has(t)&&r.push(y.get(t))});let i=D!==void 0&&n.size>0,a=i||r.length>0;a&&p(),n.forEach((e,t)=>{e.size===0?w.delete(t):w.set(t,e),i&&ae(t,e)}),r.length>0&&r.forEach(e=>{m({type:`delete`,value:e})}),a&&h(),x.observers.delete(e),C.delete(e),S.delete(e),E.delete(e),j.delete(e)},F=e=>{let t=E.get(e)||0,n=x.observers.get(e),r=j.get(e);t<=0&&(T.get(e)?.(),T.delete(e)),n?.hasListeners()??!1?E.set(e,0):(t>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${t} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:e}),r!==void 0&&D&&ne?.row.scanPersisted?(p(),D.collection.set(`${Ci}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),h(),r!==1/0&&P({queryHash:e,mode:`ttl`,expiresAt:Date.now()+r}),T.get(e)?.(),T.delete(e),x.observers.delete(e),S.delete(e),E.set(e,0)):Te(e))},Ee=e=>{Te(e)},De=i.getQueryCache().subscribe(e=>{let t=e.query.queryHash;e.type===`removed`&&S.has(t)&&F(t)});return{loadSubset:v===`eager`?void 0:ge,unloadSubset:v===`eager`?void 0:e=>{let t=W(pe(e)),n=(E.get(t)||0)-1;n<=0?(E.set(t,0),F(t)):E.set(t,n)},cleanup:async()=>{we(),Ce(),M.forEach(e=>{clearTimeout(e)}),M.clear();let e=[...S.values()],t=[...x.observers.keys()];for(let e of t)Ee(e);De(),await Promise.all(e.map(async e=>{await i.cancelQueries({queryKey:e,exact:!0}),i.removeQueries({queryKey:e,exact:!0})}))}}},ne=async e=>{let t=[...S.values()].map(t=>x.observers.get(W(t)).refetch({throwOnError:e?.throwOnError}));return Promise.all(t)},O=(e,t)=>{r?i.setQueryData(e,e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return t;let n=r(e);if(Array.isArray(n)){for(let r of Object.keys(e))if(e[r]===n)return{...e,[r]:t}}if(Array.isArray(e.data))return{...e,data:t};if(Array.isArray(e.items))return{...e,items:t};if(Array.isArray(e.results))return{...e,results:t};for(let n of Object.keys(e))if(Array.isArray(e[n]))return{...e,[n]:t};return e}):i.setQueryData(e,t)},k=e=>{let t=i.getQueryCache().findAll({queryKey:y});if(t.length>0)for(let n of t)O(n.queryKey,e);else O(y,e)},A=null,j=e=>{let{begin:n,write:r,commit:a,collection:o}=e,s=typeof t==`function`?t({}):t;return A={collection:o,queryClient:i,queryKey:s,getKey:f,begin:n,write:r,commit:a,updateCacheData:k},D(e)},M=yi(()=>A),N=p?async e=>{let t=await p(e)??{};return t.refetch!==!1&&await ne(),t}:void 0,re=m?async e=>{let t=await m(e)??{};return t.refetch!==!1&&await ne(),t}:void 0,ie=h?async e=>{let t=await h(e)??{};return t.refetch!==!1&&await ne(),t}:void 0,ae=new wi(x,ne,M);return{..._,getKey:f,syncMode:v,sync:{sync:j},onInsert:N,onUpdate:re,onDelete:ie,utils:ae}}async function Ei(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 Di=new WeakMap,Oi=new WeakMap,ki=new Set([`__proto__`,`constructor`,`prototype`]),Ai=1e7,ji=1e3,Mi=1e3,Ni=1e3,Pi=1e6,Fi=1e3,Ii=65536;function K(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 Li(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(ki.has(n))throw TypeError(`${t} contains a forbidden key`);return e}function Ri(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 q(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 zi(e,t){if(!Number.isSafeInteger(e)||e<0)throw TypeError(`${t} must be a non-negative safe integer`);return e}function Bi(e,t,n){if(typeof e==`string`){if(e.length>65536)throw TypeError(`${t} exceeds the string limit`);return K(n,JSON.stringify(e),t),e}if(e===null||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return K(n,JSON.stringify(e),t),e;throw TypeError(`${t} must be a JSON scalar`)}function Vi(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 K(n,JSON.stringify(e),t),e}if(e===null||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return K(n,JSON.stringify(e),t),e;if(Array.isArray(e)){if(e.length>1e3)throw TypeError(`${t} exceeds the container-item limit`);K(n,`[`,t);let i=[];for(let[a,o]of e.entries())a>0&&K(n,`,`,t),i.push(Vi(o,`${t}[${a}]`,n,r+1));return K(n,`]`,t),i}let i=Li(e,t);if(Object.keys(i).length>1e3)throw TypeError(`${t} exceeds the container-item limit`);let a=Object.create(null);K(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&&K(n,`,`,t),K(n,JSON.stringify(o),`${t}.${o}`),K(n,`:`,t),a[o]=Vi(i[o],`${t}.${o}`,n,r+1)}return K(n,`}`,t),a}function Hi(e){let t=Li(e,`Data query total`),n=q(t.kind,`Data query total kind`);if(n===`unavailable`)return Ri(t,[`kind`,`reason`],`Data query unavailable total`),{kind:n,...t.reason===void 0?{}:{reason:q(t.reason,`Data query total reason`)}};if(n!==`exact`&&n!==`estimated`)throw TypeError(`Data query total kind is invalid`);return Ri(t,[`kind`,`value`,`asOf`],`Data query total`),{kind:n,value:zi(t.value,`Data query total value`),...t.asOf===void 0?{}:{asOf:q(t.asOf,`Data query total asOf`,128)}}}function Ui(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=Li(e,`Data query facet ${r}`);Ri(i,[`field`,`values`,`truncated`],`Data query facet`);let a=q(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=Li(e,`Data query facet ${r} value ${n}`);return Ri(i,[`value`,`count`],`Data query facet value`),{value:Bi(i.value,`Data query facet value`,t),count:zi(i.count,`Data query facet count`)}}),truncated:i.truncated}})}function Wi(e){let t=Li(e,`Data query result`);if(Ri(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=q(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:Ai},i=t.rows.map((e,t)=>{let i=Li(Vi(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=Li(t.page,`Data query page`);Ri(e,[`kind`,`limit`,`offset`,`nextCursor`,`hasMore`],`Data query page`);let n=q(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=zi(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=zi(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:q(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=Li(t.freshness,`Data query freshness`);Ri(o,[`state`,`asOf`],`Data query freshness`);let s=q(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=Ui(t.facets,r),l=t.warnings.map(e=>q(e,`Data query warning`,512)),u={version:1,requestId:q(t.requestId,`Data query request id`),queryFingerprint:q(t.queryFingerprint,`Data query fingerprint`),identityField:n,rows:i,...a===void 0?{}:{page:a},total:Hi(t.total),...c===void 0?{}:{facets:c},freshness:{state:s,...o.asOf===void 0?{}:{asOf:q(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 Gi(e,t,n){let r=Wi(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 Ki=1e6,qi=1e3,Ji=new Set([`__proto__`,`constructor`,`prototype`]);function Yi(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(Ji.has(n))throw TypeError(`${t} contains a forbidden key`);return e}function Xi(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 Zi(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 Qi(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)=>Qi(e,`${t}[${r}]`,n+1))}let r=Yi(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]=Qi(a,`${t}.${e}`,n+1);return i}function $i(e){let t=Yi(e,`Data surface identity`);Xi(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:Zi(t.surfaceId,`Data surface identity surfaceId`),kind:n};if(t.subject!==void 0){let e=Yi(t.subject,`Data surface identity subject`);Xi(e,[`type`,`id`,`label`],`Data surface identity subject`),r.subject={type:Zi(e.type,`Data surface identity subject type`),id:Zi(e.id,`Data surface identity subject id`),...e.label===void 0?{}:{label:Zi(e.label,`Data surface identity subject label`)}}}return r}function ea(e,t){return e.surfaceId===t.surfaceId&&e.kind===t.kind&&e.subject?.type===t.subject?.type&&e.subject?.id===t.subject?.id}function ta(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=Yi(e,`Data surface action result`);if(Xi(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:Zi(n.requestId,`Data surface action result requestId`),identity:$i(n.identity),actionId:Zi(n.actionId,`Data surface action result actionId`),phase:n.phase,ok:n.ok};if(n.reason!==void 0&&(r.reason=Zi(n.reason,`Data surface action result reason`)),n.confirmationToken!==void 0&&(r.confirmationToken=Zi(n.confirmationToken,`Data surface action result confirmationToken`)),n.details!==void 0){let e=Qi(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 na(e,t,n){let r=ta(await e.action(t,n));if(r.requestId!==t.requestId||r.actionId!==t.actionId||r.phase!==t.phase||!ea(r.identity,t.identity))throw TypeError(`Data surface action result does not match its request`);return r}var ra=new Set([`idempotency_in_progress`,`background_unavailable`,`execution_failed`]),ia=new Set([`auth_required`,`unauthenticated`,`unauthorized`]),aa=new Set([`stale_revision`,`stale_preview`]),oa=new Set([`invalid_or_expired_confirmation`,`confirmation_mismatch`,`confirmation_replayed`,`confirmation_required`,`stale_preview`]);function sa(e){if(e.ok)return{status:`applied`};let t=e.reason??`rejected`;return ra.has(t)?{status:`rejected`,reason:`write_failed`}:ia.has(t)?{status:`rejected`,reason:`auth_required`}:aa.has(t)?{status:`conflict`,reason:`stale_write`}:{status:`rejected`,reason:t}}function ca(e){let t=e.classify??sa;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=>na(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||!oa.has(e.reason??``))return t(e)}let s=await na(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 la(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 J=new Map;function ua(e,t){let n=J.get(e);return n||(n=new Set,J.set(e,n)),n.add(t),()=>{let n=J.get(e);n&&(n.delete(t),n.size===0&&J.delete(e))}}async function da(e){let t=J.get(e);if(!t||t.size===0){J.delete(e);return}let n=[...t];J.delete(e),await Promise.allSettled(n.map(e=>e.clear()))}function fa(e,t){let n=J.get(e);if(!n)return!1;for(let e of n)if(e.kind===t)return!0;return!1}function pa(){return[...J.keys()]}var Y=`outbox`,ma=`state`;function ha(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function ga(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 _a(){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 va=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(Y,`readwrite`),i=await ha(r.objectStore(Y).add(n));return await ga(r),i}async markState(e,t){let n=this.db.transaction(Y,`readwrite`),r=n.objectStore(Y),i=await ha(r.get(e));if(!i){await ga(n);return}let a={...i,...t,seq:e};await ha(r.put(a)),await ga(n)}async listPending(e){let t=this.db.transaction(Y,`readonly`),n=await ha(t.objectStore(Y).index(ma).getAll(IDBKeyRange.only(`pending`)));return await ga(t),n.filter(t=>t.nextAttemptAt<=e).sort((e,t)=>(e.seq??0)-(t.seq??0))}async remove(e){let t=this.db.transaction(Y,`readwrite`);await ha(t.objectStore(Y).delete(e)),await ga(t)}async all(){let e=this.db.transaction(Y,`readonly`),t=await ha(e.objectStore(Y).getAll());return await ga(e),t.sort((e,t)=>(e.seq??0)-(t.seq??0))}async clear(){let e=this.db.transaction(Y,`readwrite`);await ha(e.objectStore(Y).clear()),await ga(e)}close(){this.db.close()}};function ya(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(Y,{keyPath:`seq`,autoIncrement:!0}).createIndex(ma,`state`,{unique:!1})},i.onsuccess=()=>n(new va(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 ba(){let e=globalThis.navigator?.locks;if(e&&typeof e.request==`function`)return e}var xa=!1;function Sa(e,t,n){let r=ba();if(!r){xa||(xa=!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 Ca=1e3,wa=[`sync`,`apply`],Ta={initialDelayMs:1e3,multiplier:2,maxDelayMs:6e4};function Ea(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 Da(e){return e===`insert`?`create`:e}var Oa=`sync-apply`;function ka(e){return e.transport===void 0?Oa:`transport:${e.transport}`}function Aa(e,t){let n=`smrt-web-outbox-leader:${e}`;return t===Oa?n:`${n}:${t}`}function ja(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`item-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Ma(){return globalThis.navigator?.onLine===!1}var Na=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 _a())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 ya(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=Aa(this.config.namespace,e),r={release:()=>{},isLeader:!1,refs:1};this.leaders.set(e,r),r.release=Sa(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?ka({transport:e.object}):e.syncApply?Oa: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=ja(),n=Da(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||Ma())return;let e=new Map;for(let t of await this.queue.all()){if(t.state!==`pending`)continue;let n=ka(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===Oa){let e=this.syncApply;if(!e)continue;for(let t=0;t<i.length&&!(this.disposed||this.paused||!this.leads(n));t+=Ca){let n=i.slice(t,t+Ca);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=Ia(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}/${wa.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=Ea(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=ka(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()}},Pa=new Map;function Fa(e){let t=Pa.get(e.namespace);return t||(t=new Na(e),Pa.set(e.namespace,t)),t}function Ia(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 La(e,t){let n=Fa(e);return{engine:n,record:n.registerCollection(t)}}async function Ra(e,t,n,r){await t.unregisterCollection(n,r)&&Pa.get(e)===t&&Pa.delete(e)}var za=`snapshots`,Ba=`::snapshots`;function Va(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function Ha(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 Ua(){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 Wa=class{db;dbName;constructor(e,t){this.db=e,this.dbName=t}async load(e){let t=this.db.transaction(za,`readonly`),n=await Va(t.objectStore(za).get(e));if(await Ha(t),n&&Array.isArray(n.rows))return n.rows}async save(e,t){let n=this.db.transaction(za,`readwrite`),r=n.objectStore(za),i={collection:e,rows:t};await Va(r.put(i)),await Ha(n)}async remove(e){let t=this.db.transaction(za,`readwrite`);await Va(t.objectStore(za).delete(e)),await Ha(t)}async clear(){let e=this.db.transaction(za,`readwrite`);await Va(e.objectStore(za).clear()),await Ha(e)}close(){this.db.close()}};function Ga(e){let t=globalThis.indexedDB;if(!t)return Promise.reject(Error(`[smrt-web] IndexedDB is unavailable in this environment`));let n=`${e}${Ba}`;return new Promise((e,r)=>{let i=t.open(n,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`snapshots`)||e.createObjectStore(za,{keyPath:`collection`})},i.onsuccess=()=>e(new Wa(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 Ka=`meta`,qa=`::meta`,Ja=`lastSeenManifestHash`;function Ya(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`[smrt-web] IndexedDB request failed`))})}function Xa(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 Za=class{db;dbName;constructor(e,t){this.db=e,this.dbName=t}async get(e){let t=this.db.transaction(Ka,`readonly`),n=await Ya(t.objectStore(Ka).get(e));return await Xa(t),n&&typeof n.value==`string`?n.value:void 0}async set(e,t){let n=this.db.transaction(Ka,`readwrite`),r={key:e,value:t};await Ya(n.objectStore(Ka).put(r)),await Xa(n)}async clear(){let e=this.db.transaction(Ka,`readwrite`);await Ya(e.objectStore(Ka).clear()),await Xa(e)}close(){this.db.close()}};function Qa(e){let t=globalThis.indexedDB;if(!t)return Promise.reject(Error(`[smrt-web] IndexedDB is unavailable in this environment`));let n=`${e}${qa}`;return new Promise((e,r)=>{let i=t.open(n,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`meta`)||e.createObjectStore(Ka,{keyPath:`key`})},i.onsuccess=()=>e(new Za(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 $a=/^smrt-web:[^:]*:(?:_[^:]*)?:(?:_[^:]*)?:[^:]*$/;function eo(e){return typeof e==`string`&&$a.test(e)}function to(e){if(e!==void 0){for(let t of[Ba,qa])if(e.endsWith(t)){let n=e.slice(0,-t.length);return eo(n)?n:void 0}return eo(e)?e:void 0}}function no(){return globalThis.indexedDB}async function ro(){let e=new Set(pa()),t=no();if(t&&typeof t.databases==`function`)for(let n of await t.databases()){let t=to(n.name);t!==void 0&&e.add(t)}return[...e].sort()}function io(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 ao(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 oo(e,t){return typeof e.enqueuedAt==`number`&&e.enqueuedAt<t}function so(e,t){return new Promise((n,r)=>{let i=new Map,a=e.transaction(Y,`readonly`),o=a.objectStore(Y).openCursor();o.onsuccess=()=>{let e=o.result;if(!e)return;let n=e.value;if(oo(n,t)){let e=ka(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 co(e,t,n){return new Promise((r,i)=>{let a=0,o=e.transaction(Y,`readwrite`),s=o.objectStore(Y).openCursor();s.onsuccess=()=>{let e=s.result;if(!e)return;let r=e.value;ka(r)===n&&oo(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 lo(){let e=globalThis.navigator?.locks;return e&&typeof e.request==`function`?e:void 0}async function uo(e,t,n){let r=lo();return r?r.request(Aa(e,t),{mode:`exclusive`,ifAvailable:!0},async e=>e===null?void 0:n()):fa(e,`outbox`)?void 0:n()}async function fo(e,t){if(!eo(e))throw TypeError(`pruneDurableNamespace requires a durableStoreNamespace() string`);let n=io(t?.olderThan),r={removed:0,skipped:0},i=no();if(!i)return r;let a=await ao(i,e);if(!a)return r;try{if(!a.objectStoreNames.contains(`outbox`))return r;let t=await so(a,n);for(let[i,o]of t){let t=await uo(e,i,()=>co(a,n,i));t===void 0?r.skipped+=o:r.removed+=t}return r}finally{a.close()}}function po(e){return{initialDelayMs:e?.initialDelayMs??Ta.initialDelayMs,multiplier:e?.multiplier??Ta.multiplier,maxDelayMs:e?.maxDelayMs??Ta.maxDelayMs}}var mo=new Map;async function ho(e,t,n,r){let i=t.referenceCount;await Ra(e,t,n,r),i<=1&&mo.get(e)===t&&mo.delete(e)}function go(e){let t=e.updatedAt??e.updated_at;if(typeof t==`string`)return t;if(t instanceof Date)return t.toISOString()}function _o(e){let t=la(e.namespace),n=e.syncApplyBasePath??`/api/v1`,r=e.fetchFn??((...e)=>globalThis.fetch(...e)),i=po(e.backoff),a=e.transport,o=e.object.name,s,c;return{name:`offline-outbox`,onAttach(){let l=La({namespace:t,backoff:i,random:e.random,registerResource:e=>ua(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,mo.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??go(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 ho(t,e,o,n)}}}function vo(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=la(e.namespace),n=e.name,r=La({namespace:t,backoff:po(e.backoff),random:e.random,registerResource:e=>ua(t,{kind:`outbox`,clear:e})},{object:n,transport:e.transport,onSyncStateChange:e.onSyncStateChange,onConflict:e.onConflict}),i=r.engine,a=r.record;return mo.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 ho(t,e,n,a))}}}function yo(e){let t=mo.get(e);if(t)return{snapshot:()=>t.snapshot(),retry:e=>t.retry(e)}}function bo(e,t){e.unregister||=ua(t,{kind:`persisted-collection`,clear:async()=>{e.wipeEpoch+=1,e.unregister=void 0,await(await e.ready)?.clear()}})}var xo=new Map,So=!1;function Co(){So||(So=!0,console.warn(`[smrt-web] IndexedDB is unavailable; persistence is disabled (collections behave as non-persistent).`))}function wo(e){let t=xo.get(e);if(t)return t.refCount+=1,bo(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 Ua())Co();else try{let t=await Ga(e);return n.store=t,t}catch{Co();return}})(),xo.set(e,n),bo(n,e),n}async function To(e){let t=xo.get(e);t&&(--t.refCount,!(t.refCount>0)&&(xo.delete(e),await t.ready,t.unregister?.(),t.unregister=void 0,t.store?.close(),t.store=void 0))}function Eo(e){let t=la(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=wo(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||=wo(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 To(t)}}}function Do(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 Oo(e){let t=la(e.namespace),n=Do(e.identity),r=e.debounceMs??250,i=wo(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 To(t))}}}function ko(e){if(Array.isArray(e))return e.map(ko);if(e&&typeof e==`object`){let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,ko(t[e])]))}return e}function X(e){let{requestId:t,...n}=e;return JSON.stringify(ko(n))}function Ao(e,t){return e.requestId===t.requestId?e:{...e,requestId:t.requestId}}function Z(){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 jo(e){return!!e&&typeof e==`object`&&e.name===`AbortError`}function Mo(e){if(e.page)return e.page.kind,{...e.page}}function No(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(X(t),e,r,n))&&v({rows:e.rows,page:Mo(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 Gi(t,e,{signal:n.signal});if(n.signal.aborted)throw Z();return r}catch(e){throw n.signal.aborted?Z():e}finally{d.delete(n)}},C=async(e,t={})=>{if(g)throw Z();let n=t.mode??`visible`,i=X(e);if(t.signal?.aborted||(t.deadlineMs??1)<=0)throw Z();let a=n===`visible`&&m?.active&&(!p||l!==void 0&&X(l)!==i)?m:void 0,o=y(i),s=o!==void 0&&Date.now()-o.updatedAt<r;if(n!==`visible`&&!t.force&&s)return Ao(o.result,e);if(n===`visible`&&!t.force&&s){if(f+=1,u?.abort(Z()),g)throw Z();u=void 0,l=e,a&&p?.disconnect();let t=Ao(o.result,e);if(x(t,e,o.updatedAt),g)throw Z();return a?.active&&!p&&D(a),t}if(n===`visible`){if(f+=1,u?.abort(Z()),g)throw Z();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=Ao(o.result,e);v({rows:t.rows,page:Mo(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 Z();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&&D(a)),n}catch(e){throw r===f&&(jo(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(Z()):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(Z()),a.get(t)===e&&a.delete(t)),o(Z()))},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(Ao(e,n)))},e=>{s||(c(),o(e))})}),T=async(e,t,n)=>{if(n.signal?.aborted||(n.deadlineMs??1)<=0)throw Z();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 Z();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&&X(t)===X(n)&&C(t,{mode:`visible`,force:!0}).catch(()=>void 0).finally(()=>{e.active&&!g&&m===e&&!p&&l&&X(l)===X(n)&&D(e)})}},c=t.subscribe(n,t=>{if(!a||!e.active||g||r!==h||i.signal.aborted)return;let c=++s;(async()=>{let i=await Gi({query:async()=>t},n);a&&e.active&&!g&&r===h&&l&&X(l)===X(n)&&x(Ao(i,l),l,Date.now(),c)})().catch(t=>{let i=o.get(X(n));!jo(t)&&a&&e.active&&!g&&r===h&&l&&X(l)===X(n)&&(i===void 0||c>i)&&v({..._,error:t})})},{signal:i.signal}),g||!e.active)d();else return p=u,u},te=e=>{e.active=!1,m===e&&(m=void 0)},D=e=>{try{ee(e)}catch(t){te(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 te(e),t}},invalidate(){if(!l)return;let e=X(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(Z());for(let e of d)e.abort(Z());m&&(m.active=!1),p?.disconnect(),p=void 0,m=void 0,l=void 0,c.clear(),i.clear(),o.clear(),a.clear()}}}var Po=2;function Fo(e,t){let n=globalThis.EventSource;if(typeof n==`function`)return new n(e,t)}function Io(e){let{eventsUrl:t,changesUrl:n,fetchFn:r=(...e)=>globalThis.fetch(...e),eventSourceFactory:i=Fo,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?.())},te=e=>{d=`sse`,f=e,e.addEventListener(`change`,C),e.addEventListener(`resync`,w),e.addEventListener(`manifest`,T),e.onerror=()=>{if(!m&&e.readyState===Po){try{e.close()}catch{}f=null,ee()}}},D=i(t,{withCredentials:o});return D?te(D):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 Lo(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 Ro(e){let t=la(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 Qa(t)}catch{return}if(s){r.close();return}a=r,o=ua(t,{kind:`persisted-collection`,clear:()=>r.clear()});let i;try{i=await r.get(Ja)}catch{i=void 0}if(!s&&(i!==void 0&&i!==n&&d(),i!==n))try{await r.set(Ja,n)}catch{}})(),dispose(){s=!0,o?.(),o=void 0,a?.close(),a=void 0,i.clear()}}}function zo(){let e=globalThis.document?.modelContext;if(e&&typeof e.registerTool==`function`)return e}function Bo(e,n={}){let r=qo(n),i=zo();if(!i)return Vo(()=>{},Promise.resolve());let a=n.basePath??`/api/v1`,s=n.client,{tools:c,allowedEffects:l}=Jo(e,n,r);s&&c.some(e=>e.kind===`canonical`&&e.effect!==`read`)&&Ds(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(ts(t)):Ss(t,a,n.fetchFn),p=Is(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:is(e),execute:os(e,l,()=>m,e=>ds(c,p,t,r.action,r.route,e))},{signal:u.signal})));continue}let{definition:t}=e,r=n.resolveToolFetchers?n.resolveToolFetchers(ns(t,{effect:e.effect,destructive:e.destructive,idempotent:e.idempotent,openWorld:e.openWorld})):Ss({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:is(e),execute:os(e,l,()=>m,e=>fs(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),Vo(h,_)}function Vo(e,t){return Object.assign(e,{ready:t})}function Ho(e,t={}){return Uo(e,t,t.owner??`bespoke`)}function Uo(e,n,r){let{allowedEffects:i}=qo(n),a=zo();if(!a)return Vo(()=>{},Promise.resolve());let s=Xo(`bespoke`,Zo(e.annotations));if(!i.has(s.effect))return Vo(()=>{},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:is(s),execute:as(e.execute,os({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),Vo(d,p)}function Wo(e,t,n={}){return Uo(ee(e,t),n,`intent`)}var Go=s,Ko=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function qo(e){let t=e.effects??[`read`];for(let e of t)if(!Go.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&&!Ko.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 Jo(e,t,n){let{allowedEffects:r,maxTools:i,namespace:a}=n,o=e.map(e=>$o(e)),s=[];for(let e of o){if(ss(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=ns(e,n);if(t.filterTool&&!t.filterTool(ns(i,n)))continue;s.push({kind:`canonical`,definition:i,descriptor:i,name:Yo(i.name,a),identity:`${i.collection}#${i.action}`,...n});continue}let n=ts(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=Xo(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=es(e,i);(!t.filter||t.filter(ts(n),es(o,i)))&&s.push({kind:`legacy`,definition:n,descriptor:o,name:Yo(o.name,a),identity:`${n.name}#${o.action}`,...i})}}return rs(s,i),{tools:s,allowedEffects:r}}function Yo(e,t){return t?`${t}_${e}`:e}function Xo(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 Zo(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 Qo(e){return e?$o(e):void 0}function $o(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)=>$o(e,t,`${n}[${r}]`));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e))r[i]=$o(a,t,`${n}.${i}`);return r}return e}finally{e&&typeof e==`object`&&t.delete(e)}}function es(e,t){return $o({...e,effect:t.effect,idempotent:t.idempotent,openWorld:t.openWorld,readOnly:t.effect===`read`,route:Qo(e.route)})}function ts(e){let t=$o({...e,actions:[...e.actions]});return t.toolDescriptors=t.toolDescriptors?.map(e=>es(e,Xo(e.action,e))),t}function ns(e,t){return $o({...e,effect:t.effect,idempotent:t.idempotent,openWorld:t.openWorld,readOnly:t.effect===`read`,route:Qo(e.route)})}function rs(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 is(e){return l(e)}function as(e,t){return a(e)?n(t):t}function os(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 ss(e){return`collection`in e&&`readOnly`in e}function cs(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 ls(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 us(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 ds(e,t,n,r,i,a){switch(r){case`list`:{let t=vs(await e.list(us(a)),n.name);return JSON.stringify(t)}case`get`:{if(!e.get)throw Error(`${n.name} has no get action`);let t=$(await e.get(ls(a)),`get(${n.name})`);return JSON.stringify(t)}case`create`:{let e=Cs(),r=$(await ps(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 ms(e,t,n,cs(a,`update`));let o=$(await ps(t.update(cs(a,`update`),i),t,cs(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=cs(a,`delete`);return await ms(e,t,n,r),await ps(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 fs(e,t,n,r){let i;switch(t.action){case`list`:if(!e.list)throw Error(`${t.collection} has no list action`);i=vs(await e.list(us(n)),t.collection);break;case`get`:if(!e.get)throw Error(`${t.collection} has no get action`);i=$(await e.get(ls(n)),`get(${t.collection})`);break;case`create`:if(!e.create)throw Error(`${t.collection} has no create action`);i=$(await e.create(n),`create(${t.collection})`);break;case`update`:{if(!e.update)throw Error(`${t.collection} has no update action`);let r=cs(n,`update`),{id:a,...o}=n;i=$(await e.update(r,o),`update(${t.collection})`);break}case`delete`:{if(!e.delete)throw Error(`${t.collection} has no delete action`);let r=cs(n,`delete`);ys(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=ys(await e.custom(t.action,n,t.route),`${t.action}(${t.collection})`)}return!t.readOnly&&r&&ks(r,[t.collection,...t.relationships.map(e=>e.relatedCollection)]),JSON.stringify(i)}async function ps(e,t,n,r){await e.isPersisted.promise;let i=Di.get(t)?.get(n);return i===void 0?t.get(n)??{...r,id:n}:i}async function ms(e,t,n,r){if(!e.get)throw Error(`${n.name} has no get action; cannot hydrate mutation target '${r}'`);let i=$(await e.get(r),`get(${n.name})`),a=Oi.get(t);if(!a)throw Error(`${n.name} cannot hydrate mutation target '${r}'`);await a(i)}var hs=`__smrt_options`,Q=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 gs(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 _s(e,t,n){if(t>=500)return new Q(`[smrt-web] ${e} request failed: server error`,void 0,t);let r=gs(n);return new Q(`[smrt-web] ${e} request failed: ${r.message??`HTTP ${t}`}`,n,t,r.code)}function vs(e,t){if(ys(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 Q(`[smrt-web] list(${t}) returned an unexpected payload shape`,e)}function $(e,t){if(ys(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 Q(`[smrt-web] ${t} returned an unexpected payload shape`,e)}function ys(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return e;let n=e.error;if(typeof n==`string`)throw new Q(`[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 Q(`[smrt-web] ${t} failed: server error`,void 0,i):new Q(`[smrt-web] ${t} failed: ${r.message}`,e,i,r.code)}var bs={">":`gt`,">=":`gte`,"<":`lt`,"<=":`lte`,"!=":`ne`,in:`in`,like:`like`};function xs(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=bs[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 Ss(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 _s(e.name,t.status);let n=await t.json().catch(()=>null);throw _s(e.name,t.status,n)}return t.json().catch(()=>null)};return{list:async e=>a(await n(`${r}${xs(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 _s(e.name,a.status);let t=await a.json().catch(()=>null);throw _s(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(hs,`undefined`);else if(u===null&&f.size===0)e.set(hs,`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(hs,`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 Cs(){let e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`local-${Date.now()}-${Math.random().toString(36).slice(2)}`}var ws=new WeakSet;function Ts(){let e={__smrtWebClient:`SmrtWebClient`,queryClient:new ai};return ws.add(e),e}function Es(e){if(!e)return new ai;let t=e;if(!ws.has(t)||t.__smrtWebClient!==`SmrtWebClient`||!t.queryClient)throw new Q(`[smrt-web] options.client must be a handle from createSmrtWebClient()`);return t.queryClient}function Ds(e){Es(e)}function Os(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 ks(e,t){Os(Es(e),new Set(t))}function As(e){let t={};for(let[n,r]of Object.entries(e))n.charCodeAt(0)!==36&&(t[n]=r);return t}function js(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=As(t.value)),t.previousValue&&typeof t.previousValue==`object`&&(n.previousValue=As(t.previousValue)),n}):e}function Ms(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 Ns=new WeakMap;function Ps(e){let t=Ns.get(e);if(t===void 0)throw new Q(`[smrt-web] getEngineCollection: not a smrt-web collection handle`);return t}function Fs(e,t,n){console.warn(`[smrt-web] capability "${e.name}" ${t} threw; ignoring`,n)}function Is(e,t){let{staleTimeMs:n=3e4,retry:r=!1,scope:i,initialData:a}=t,o=t.capabilities??[],s=t.fetchers??Ss(e,t.basePath,t.fetchFn),c=Es(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=()=>{Os(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){Fs(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){Fs(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){Fs(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){Fs(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){Fs(n,`onSettled`,e)}},x=async(e,t)=>{try{let n=await Ei(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=nr(Ti({id:d,queryKey:f,queryClient:c,staleTime:n,retry:r,queryFn:async()=>vs(await s.list(),e.name),getKey:e=>String(e[l]),onInsert:async({transaction:t})=>{let n=!1;for(let r of t.mutations){let t=r.modified,i={kind:`insert`,key:String(t[l]),data:t},a=await x(i,async()=>{let{[l]:n,...r}=t;return $(await s.create(r),`create(${e.name})`)});u.set(i.key,a.result),n||=a.handled}if(n)return{refetch:!1};m()},onUpdate:s.update?async({transaction:t})=>{let n=!1;for(let r of t.mutations){let t=String(r.key),i=r.changes,a={kind:`update`,key:t,data:i,baseUpdatedAt:Ms(r.original)},o=await x(a,async()=>$(await s.update(t,i),`update(${e.name})`));u.set(a.key,o.result),n||=o.handled}if(n)return{refetch:!1};m()}:void 0,onDelete:s.delete?async({transaction:t})=>{let n=!1;for(let r of t.mutations){let t=String(r.key),i={kind:`delete`,key:t,data:{},baseUpdatedAt:Ms(r.original)},a=await x(i,async()=>ys(await s.delete(t),`delete(${e.name})`));u.set(i.key,a.result),n||=a.handled}if(n)return{refetch:!1};m()}:void 0}));function C(){let e=S.toArray.map(e=>As(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(js(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(js([]))});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:As(t)},preload(){return y?y.then(()=>{if(!_)return S.preload()}):S.preload()},async cleanup(){_=!0,await S.cleanup();for(let e of o)try{await e.teardown?.(h)}catch(t){Fs(e,`teardown`,t)}},subscribeChanges(e){return w(e)},insert(e){return S.insert(e)},update(t,n){if(!s.update)throw Error(`${e.name} has no update action`);let{id:r,...i}=n;return S.update(t,e=>{Object.assign(e,i)})},delete(t){if(!s.delete)throw Error(`${e.name} has no delete action`);return 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 ys(i,`${t}(${e.name})`),m(),i}};Di.set(T,u),Oi.set(T,async e=>{await S.preload(),S.utils.writeUpsert(e)}),Ns.set(T,S);for(let e of o)try{e.onAttach?.(h)}catch(t){Fs(e,`onAttach`,t)}return T}var Ls=e({DEFAULT_PERSIST_DEBOUNCE_MS:()=>250,MAX_SMRT_WEB_DATA_QUERY_CONTAINER_ITEMS:()=>Fi,MAX_SMRT_WEB_DATA_QUERY_FACETS:()=>20,MAX_SMRT_WEB_DATA_QUERY_FACET_VALUES:()=>Mi,MAX_SMRT_WEB_DATA_QUERY_OFFSET:()=>Pi,MAX_SMRT_WEB_DATA_QUERY_PAGE_LIMIT:()=>Ni,MAX_SMRT_WEB_DATA_QUERY_RESULT_BYTES:()=>Ai,MAX_SMRT_WEB_DATA_QUERY_ROWS:()=>ji,MAX_SMRT_WEB_DATA_QUERY_STRING_LENGTH:()=>Ii,MAX_SMRT_WEB_DATA_QUERY_WARNINGS:()=>100,MAX_SMRT_WEB_DATA_SURFACE_ACTION_CONTAINER_ITEMS:()=>qi,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:()=>Ki,SmrtWebRequestError:()=>Q,WebMcpToolNameCollisionError:()=>r,buildListQuery:()=>xs,classifySmrtWebDataSurfaceActionResult:()=>sa,compileViewIntentToolSpec:()=>ee,createDefinitionFetchers:()=>Ss,createSmrtCollection:()=>Is,createSmrtWebClient:()=>Ts,createSmrtWebEventSubscriber:()=>Io,createSmrtWebQuery:()=>No,createUpdateState:()=>Ro,dataSurfaceActionCommandTransport:()=>ca,durableStoreNamespace:()=>la,executeSmrtWebDataQuery:()=>Gi,executeSmrtWebDataSurfaceAction:()=>na,getEngineCollection:()=>Ps,getOutboxHandle:()=>yo,invalidateSmrtWebCollections:()=>ks,listDurableNamespaces:()=>ro,liveInvalidation:()=>Lo,newLocalId:()=>Cs,normalizeSmrtWebDataQueryResult:()=>Wi,normalizeSmrtWebDataSurfaceActionResult:()=>ta,offlineCommandQueue:()=>vo,offlineOutbox:()=>_o,persistCollection:()=>Eo,persistDataSurface:()=>Oo,pruneDurableNamespace:()=>fo,registerDurableResource:()=>ua,registerViewIntent:()=>Wo,registerWebMcpBespokeTool:()=>Ho,registerWebMcpTools:()=>Bo,reserveWebMcpToolNames:()=>t,runWrapMutation:()=>Ei,throwIfSmrtWebError:()=>ys,unwrapItemResult:()=>$,unwrapListResult:()=>vs,validateSmrtWebClient:()=>Ds,viewIntentToolName:()=>m,webMcpToolNameOwner:()=>i,wipeDurableStore:()=>da});export{Ls as t};
@@ -1 +0,0 @@
1
- import"./DG3qFFTE.js";import"./xihTtKlq.js";import"./VsFwp6G3.js";import"./BXp_5G-Z.js";import"./v8gneLl4.js";import"./BKBQyYIa.js";import"./CGVkRTMI.js";function e(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}export{e as t};
@@ -1 +0,0 @@
1
- import"./DkqJO8K2.js";
@@ -1 +0,0 @@
1
- export{l as load_css,o as start}from"../chunks/DkqJO8K2.js";