@undefineds.co/xpod 0.4.25 → 0.4.28

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 (155) hide show
  1. package/dist/api/ApiServer.d.ts +1 -0
  2. package/dist/api/ApiServer.js +38 -0
  3. package/dist/api/ai-config/AiConfigStore.js +18 -6
  4. package/dist/api/ai-gateway/connect/index.d.ts +1 -0
  5. package/dist/api/ai-gateway/connect/index.js +39 -18
  6. package/dist/api/ai-gateway/models/ProviderModelsAdapter.js +5 -2
  7. package/dist/api/container/common.js +8 -2
  8. package/dist/api/container/index.js +2 -2
  9. package/dist/api/container/local.js +6 -3
  10. package/dist/api/handlers/AiGatewayHandler.d.ts +1 -0
  11. package/dist/api/handlers/AiGatewayHandler.js +53 -3
  12. package/dist/api/handlers/AiGatewayManagementHandler.js +9 -0
  13. package/dist/api/handlers/TaskHandler.js +15 -10
  14. package/dist/api/network/NetworkEnvironmentConfigurationStore.js +1 -1
  15. package/dist/api/runs/ManagedRunWorker.d.ts +0 -1
  16. package/dist/api/runs/ManagedRunWorker.js +2 -14
  17. package/dist/api/runs/PiAgentRuntimeDriver.d.ts +0 -8
  18. package/dist/api/runs/PiAgentRuntimeDriver.js +65 -21
  19. package/dist/api/runs/RunStateCenter.js +1 -0
  20. package/dist/api/runs/store.d.ts +1 -0
  21. package/dist/api/runs/store.js +13 -0
  22. package/dist/api/tasks/TaskMaterializer.js +13 -6
  23. package/dist/api/tasks/TaskResumeDiagnostics.d.ts +28 -0
  24. package/dist/api/tasks/TaskResumeDiagnostics.js +148 -0
  25. package/dist/api/tasks/TaskService.js +40 -23
  26. package/dist/storage/conditions/StorageETagHandler.d.ts +1 -1
  27. package/dist/storage/conditions/StorageETagHandler.js +13 -4
  28. package/dist/util/task-model-diagnostics.d.ts +67 -0
  29. package/dist/util/task-model-diagnostics.js +118 -0
  30. package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.d.ts +1 -0
  31. package/node_modules/@undefineds.co/ai-connections/dist/AiApiKeyPool.js +2 -1
  32. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectDialog.d.ts +1 -0
  33. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +1 -0
  34. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +10 -10
  35. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +3 -1
  36. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +2 -2
  37. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +77 -23
  38. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +1 -0
  39. package/node_modules/@undefineds.co/ai-connections/dist/AiSortableCredentialList.js +59 -59
  40. package/node_modules/@undefineds.co/ai-connections/dist/collection-runtime.js +2 -0
  41. package/node_modules/@undefineds.co/ai-connections/dist/collections.js +14 -6
  42. package/node_modules/@undefineds.co/ai-connections/dist/contract/ai-connections-client.d.ts +2 -1
  43. package/node_modules/@undefineds.co/ai-connections/dist/contract/ai-connections-client.js +1 -0
  44. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/gateway-model-roles.d.ts +11 -0
  45. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/gateway-model-roles.js +11 -0
  46. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +2 -1
  47. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +12 -5
  48. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.js +10 -2
  49. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +10 -0
  50. package/node_modules/@undefineds.co/ai-connections/package.json +1 -1
  51. package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +1 -0
  52. package/node_modules/@undefineds.co/extension-sdk/package.json +1 -1
  53. package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +60 -13
  54. package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +16 -1
  55. package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +51 -0
  56. package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +14 -18
  57. package/node_modules/@undefineds.co/pod-collections/package.json +1 -1
  58. package/node_modules/@undefineds.co/shared-ui/dist/list.d.ts +8 -1
  59. package/node_modules/@undefineds.co/shared-ui/dist/list.js +4 -1
  60. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +1 -1
  61. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +2 -2
  62. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +2 -2
  63. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +3 -3
  64. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +5 -5
  65. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +5 -5
  66. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +5 -5
  67. package/node_modules/@undefineds.co/shared-ui/dist/section-header.js +1 -1
  68. package/node_modules/@undefineds.co/shared-ui/dist/theme.css +5 -32
  69. package/node_modules/@undefineds.co/shared-ui/package.json +1 -1
  70. package/node_modules/@undefineds.co/solid-sdk/package.json +1 -1
  71. package/package.json +2 -2
  72. package/static/app/assets/main.css +1 -1
  73. package/static/app/assets/main.js +1 -1
  74. package/static/dashboard/assets/AccountAuthBoundary-Dv52SZc6.js +1 -0
  75. package/static/dashboard/assets/DesktopOidcCallback-DaT_Rumf.js +1 -0
  76. package/static/dashboard/assets/DevicePages-HjclpIVm.js +2 -0
  77. package/static/dashboard/assets/ModelsPage-Be2TPd-x.js +11 -0
  78. package/static/dashboard/assets/{PaneListHeader-Dn5O0mwy.js → PaneListHeader-DtvnRmFq.js} +1 -1
  79. package/static/dashboard/assets/{PodDeletionAuthorizationPanel-D3NOG6ZM.js → PodDeletionAuthorizationPanel-BJk_8rJq.js} +3 -3
  80. package/static/dashboard/assets/PodPage-C4gzEspV.js +1 -0
  81. package/static/dashboard/assets/{SystemSettingsPage-BNQP_Yuc.js → SystemSettingsPage-HaNrP1H1.js} +1 -1
  82. package/static/dashboard/assets/TasksPage-BdO5K2L7.js +1 -0
  83. package/static/dashboard/assets/{WebDesktopEntry-vnb4CZWp.js → WebDesktopEntry-Cj9_ZfJU.js} +1 -1
  84. package/static/dashboard/assets/XpodAiConnectionsPodStore-B7gmXBmC.js +3 -0
  85. package/static/dashboard/assets/XpodShellApp-D_KY4nCW.js +4 -0
  86. package/static/dashboard/assets/{account-session-DCUmCop1.js → account-session-DlcKNG7k.js} +1 -1
  87. package/static/dashboard/assets/{button-By5Bgvmb.js → button-wslF55uZ.js} +1 -1
  88. package/static/dashboard/assets/collection-runtime-uxxgEu13.js +1 -0
  89. package/static/dashboard/assets/{createLucideIcon-bunMzPms.js → createLucideIcon-BJQl82Qk.js} +1 -1
  90. package/static/dashboard/assets/dashboard-CbJ-JkrI.css +1 -0
  91. package/static/dashboard/assets/{dashboard-mlsg3yaw.js → dashboard-Or0gnkou.js} +2 -2
  92. package/static/dashboard/assets/index-BqFeOML9.js +1 -0
  93. package/static/dashboard/assets/{index-DvMG5pHk.js → index-DgKn1twH.js} +2 -2
  94. package/static/dashboard/assets/{label-Bj03L9xs.js → label-CS6Sx6Zb.js} +1 -1
  95. package/static/dashboard/assets/list-UyhlCFKk.js +1 -0
  96. package/static/dashboard/assets/{nav-item-style-BNqWQY6p.js → nav-item-style-CW1Nnorq.js} +1 -1
  97. package/static/dashboard/assets/{pod-collections-host-KnnGFZHL.js → pod-collections-host-DjK2xf-b.js} +6 -6
  98. package/static/dashboard/assets/{safe-continuation-D9AhcWiB.js → safe-continuation-ClWAhcma.js} +1 -1
  99. package/static/dashboard/assets/{section-header-CLCzbOp_.js → section-header-CEIEcco-.js} +1 -1
  100. package/static/dashboard/assets/{setting-row-DTCec8A2.js → setting-row-CaYv3dfF.js} +1 -1
  101. package/static/dashboard/assets/xpod-remembered-login-BUF9fin1.js +310 -0
  102. package/static/dashboard/dashboard.html +2 -2
  103. package/static/settings/assets/{AccountAuthBoundary-C0og_gIA.js → AccountAuthBoundary-Chqd38oU.js} +1 -1
  104. package/static/settings/assets/{DesktopOidcCallback-C5q4oFZ0.js → DesktopOidcCallback-VUrOSM_q.js} +1 -1
  105. package/static/settings/assets/DevicePages-C6qwvWwu.js +2 -0
  106. package/static/settings/assets/ModelsPage-Ry_dObRQ.js +11 -0
  107. package/static/settings/assets/{PaneListHeader-DqVlMe2D.js → PaneListHeader-B5RkRqr4.js} +1 -1
  108. package/static/settings/assets/{PodDeletionAuthorizationPanel-DgVvarVY.js → PodDeletionAuthorizationPanel-DPM-5Izt.js} +3 -3
  109. package/static/settings/assets/PodPage-CxND6wwc.js +1 -0
  110. package/static/settings/assets/{SystemSettingsPage-Crzm_DrI.js → SystemSettingsPage-C8EdMkW7.js} +1 -1
  111. package/static/settings/assets/TasksPage-DuqptEm8.js +1 -0
  112. package/static/settings/assets/{WebDesktopEntry-BGC5eRF2.js → WebDesktopEntry-BRcyktkv.js} +1 -1
  113. package/static/settings/assets/XpodAiConnectionsPodStore-CyA_BJVC.js +3 -0
  114. package/static/settings/assets/XpodShellApp-CsivHJl0.js +4 -0
  115. package/static/settings/assets/XpodThemeProvider-CbJ-JkrI.css +1 -0
  116. package/static/settings/assets/{XpodThemeProvider-CB6LepTA.js → XpodThemeProvider-DK3pIdRG.js} +2 -2
  117. package/static/settings/assets/{account-session-BcLjCj0x.js → account-session-DJOZ03xr.js} +1 -1
  118. package/static/settings/assets/auth-callback-GIBYEz_7.js +1 -0
  119. package/static/settings/assets/{button-BObT8pTE.js → button-D3yW-2o1.js} +1 -1
  120. package/static/settings/assets/collection-runtime-DfGo25mh.js +1 -0
  121. package/static/settings/assets/{createLucideIcon-BVsUxXpZ.js → createLucideIcon-CacwLsmB.js} +1 -1
  122. package/static/settings/assets/{index-ktjMkj7-.js → index-r5KRYsKC.js} +1 -1
  123. package/static/settings/assets/{label-BrqO8_m_.js → label-MJjUmvzG.js} +1 -1
  124. package/static/settings/assets/list-Ce-5k1MX.js +1 -0
  125. package/static/settings/assets/{nav-item-style-Di2CxkDU.js → nav-item-style-ZUbL8KOZ.js} +1 -1
  126. package/static/settings/assets/{pod-collections-host-KnnGFZHL.js → pod-collections-host-DjK2xf-b.js} +6 -6
  127. package/static/settings/assets/{safe-continuation-Dx6ceJpY.js → safe-continuation-vlBZFSlU.js} +1 -1
  128. package/static/settings/assets/{section-header-Dtl7yjVr.js → section-header-DGJdEvQw.js} +1 -1
  129. package/static/settings/assets/{setting-row-BL6Hhe8N.js → setting-row-C7tuFiho.js} +1 -1
  130. package/static/settings/assets/{settings-DaRBxoZk.js → settings-CyQPih1O.js} +1 -1
  131. package/static/settings/assets/xpod-remembered-login-D-TzzT5K.js +567 -0
  132. package/static/settings/auth-callback.html +3 -3
  133. package/static/settings/settings.html +3 -3
  134. package/static/dashboard/assets/AccountAuthBoundary-BvoDydRz.js +0 -1
  135. package/static/dashboard/assets/DesktopOidcCallback-BwIj874x.js +0 -1
  136. package/static/dashboard/assets/DevicePages-jOjMcvsr.js +0 -2
  137. package/static/dashboard/assets/ModelsPage-CMTdfqBR.js +0 -11
  138. package/static/dashboard/assets/PodPage-BueBdJ9_.js +0 -1
  139. package/static/dashboard/assets/TasksPage-CxtLJiSF.js +0 -1
  140. package/static/dashboard/assets/XpodAiConnectionsPodStore-wx3Ttupm.js +0 -18
  141. package/static/dashboard/assets/XpodShellApp-5FWY8-d5.js +0 -4
  142. package/static/dashboard/assets/collection-runtime-BnomuB0E.js +0 -1
  143. package/static/dashboard/assets/dashboard-C64R553B.css +0 -1
  144. package/static/dashboard/assets/xpod-remembered-login-Dr69A0Rv.js +0 -295
  145. package/static/settings/assets/DevicePages-fyHjjucT.js +0 -2
  146. package/static/settings/assets/ModelsPage-EyOByLyE.js +0 -11
  147. package/static/settings/assets/PodPage-DY4Oi9wg.js +0 -1
  148. package/static/settings/assets/TasksPage-CfXJbnlt.js +0 -1
  149. package/static/settings/assets/XpodAiConnectionsPodStore-CXcmgKmQ.js +0 -3
  150. package/static/settings/assets/XpodShellApp-D1PS3Iut.js +0 -4
  151. package/static/settings/assets/XpodThemeProvider-C64R553B.css +0 -1
  152. package/static/settings/assets/auth-callback-DSPQ28ar.js +0 -1
  153. package/static/settings/assets/collection-runtime-DzNbdZGe.js +0 -1
  154. package/static/settings/assets/index-browser-3WfrNbcG.js +0 -273
  155. package/static/settings/assets/xpod-remembered-login-Q66DH12t.js +0 -295
@@ -1,8 +1,8 @@
1
- import{P as F,r as Nt,a as Wt,b as Bt,c as Oe,s as Ge,d as Ht,e as Ct}from"./layout-DB3pMyTl.js";class Ke{}class Rt extends Ke{constructor(e){super(),this.path=e,this.type="ref"}}class Q extends Ke{constructor(e){super(),this.value=e,this.type="val"}}class j extends Ke{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}function Ye(s,e){if(typeof s==typeof e){if(typeof s=="number"&&typeof e=="number"){const t=Number.isNaN(s),n=Number.isNaN(e);if(t||n)return t&&n?0:t?1:-1}return s<e?-1:s>e?1:0}return typeof s=="string"?-1:1}Gt();function Gt(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}function Yt(){return Math.random()*(2**31-1)>>>0}const Jt=Yt(),Je=new WeakMap;function Qt(s){Zt(s)}let Qe=1;function Zt(s){let e=Je.get(s);return e===void 0&&(e=Qe^Jt,Qe++,Je.set(s,e)),e}function le(){const s=typeof globalThis<"u"?globalThis.crypto:void 0;if(s&&typeof s.randomUUID=="function")return s.randomUUID();if(s&&typeof s.getRandomValues=="function"){const e=s.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[];for(let n=0;n<16;n++)t.push(e[n].toString(16).padStart(2,"0"));return t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10,16).join("")}throw new Error("No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.")}class H extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class Ze extends H{constructor(e,t,n){const i=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(r=>`
2
- - ${r.message} - path: ${r.path}`).join("")}`;super(n||i),this.name="SchemaValidationError",this.type=e,this.issues=t}}class ee extends H{constructor(e){super(e),this.name="CollectionConfigurationError"}}class Xt extends ee{constructor(){super("Collection requires a config")}}class es extends ee{constructor(){super("Collection requires a sync config")}}class ts extends ee{constructor(){super("Schema must implement the standard-schema interface")}}class Xe extends ee{constructor(){super("Schema validation must be synchronous")}}class ie extends H{constructor(e){super(e),this.name="CollectionStateError"}}class ss extends ie{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class ns extends ie{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class is extends ie{constructor(){super("Collection is in error state")}}class rs extends ie{constructor(){super("Active subscribers count is negative - this should never happen")}}class q extends H{constructor(e){super(e),this.name="CollectionOperationError"}}class os extends q{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class as extends q{constructor(e,t){const n=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${n}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class cs extends q{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class ls extends q{constructor(e,t,n){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${i}. 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(`${i}. 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(i)}}class us extends q{constructor(){super("The first argument to update is missing")}}class ds extends q{constructor(){super("No keys were passed to update")}}class hs extends q{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class fs extends q{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.`)}}class ps extends q{constructor(){super("No keys were passed to delete")}}class ys extends q{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class Fe extends H{constructor(e){super(e),this.name="MissingHandlerError"}}class ms extends Fe{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class gs extends Fe{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class Ss extends Fe{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class G extends H{constructor(e){super(e),this.name="TransactionError"}}class bs extends G{constructor(){super("mutationFn is required when creating a transaction")}}class ws extends G{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class vs extends G{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class ks extends G{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Te extends G{constructor(){super("No pending sync transaction to write to")}}class xe extends G{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Cs extends G{constructor(){super("No pending sync transaction to commit")}}class Rs extends G{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class Ve extends H{constructor(e){super(e),this.name="QueryCompilationError"}}class Os extends Ve{constructor(e){super(`Unknown expression type: ${e}`)}}class Ts extends Ve{constructor(){super("Reference path cannot be empty")}}class xs extends Ve{constructor(e){super(`Unknown function: ${e}`)}}class et extends H{constructor(e,t){const n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name="SyncCleanupError"}}class tt extends Error{constructor(){super("Sync transaction was aborted before application"),this.name="AbortError"}}class Es extends Error{constructor(){super("Collection preload was abandoned during cleanup"),this.name="AbortError"}}class $ extends Error{constructor(){super("Load subset operation was aborted before its result became visible"),this.name="AbortError"}}function K(s,e){return pe(s,e,new Map)}function st(s){const e=Object.keys(s);for(const t of Object.getOwnPropertySymbols(s))Object.prototype.propertyIsEnumerable.call(s,t)&&e.push(t);return e}function pe(s,e,t){if(s===e)return!0;if(s==null||e==null||typeof s!=typeof e)return!1;if(s instanceof Date)return e instanceof Date?s.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(s instanceof RegExp)return e instanceof RegExp?s.source===e.source&&s.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(s instanceof Map){if(!(e instanceof Map)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const i=Array.from(s.entries()).every(([r,o])=>e.has(r)&&pe(o,e.get(r),t));return t.delete(s),i}if(e instanceof Map)return!1;if(s instanceof Set){if(!(e instanceof Set)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Array.from(s),i=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const r=n.length===i.length;return t.delete(s),r}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,i=e;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!==i[r])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(z(s)&&z(e)){const n=s[Symbol.toStringTag],i=e[Symbol.toStringTag];return n!==i?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(z(e))return!1;if(Array.isArray(s)){if(!Array.isArray(e)||s.length!==e.length)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=s.every((i,r)=>pe(i,e[r],t));return t.delete(s),n}if(Array.isArray(e))return!1;if(typeof s=="object"){if(t.has(s))return t.get(s)===e;t.set(s,e);const n=st(s),i=st(e);if(n.length!==i.length)return t.delete(s),!1;const r=n.every(o=>Object.prototype.propertyIsEnumerable.call(e,o)&&pe(s[o],e[o],t));return t.delete(s),r}return!1}const Ds=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function z(s){if(s==null||typeof s!="object")return!1;const e=s[Symbol.toStringTag];return typeof e=="string"&&Ds.has(e)}const ve={direction:"asc",nulls:"first",stringSort:"locale"};function Ps(){const s=new WeakMap;let e,t,n,i=0;const r=(o,a)=>{let c=o.get(a);return c===void 0&&(c=++i,o.set(a,c)),c};return o=>{n??=As();let a;if(typeof o=="symbol"){const c=Symbol.keyFor(o);c===void 0?(e??=Is(),a=r(e,o)):(t??=new Map,a=r(t,c))}else a=r(s,o);return["runtimeReference",n,a]}}function Is(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}let nt;function it(s){return nt??=Ps(),nt(s)}function As(){const s=new Uint32Array(4),e=Reflect.get(globalThis,"crypto");return typeof e?.getRandomValues=="function"?(e.getRandomValues(s),Array.from(s,t=>t.toString(36)).join("-")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}const Ee=new WeakMap;let _s=1;function rt(s){if(Ee.has(s))return Ee.get(s);const e=_s++;return Ee.set(s,e),e}function I(s){return typeof s=="number"&&Number.isNaN(s)||s instanceof Date&&Number.isNaN(s.getTime())}const Ue=(s,e,t)=>{const{nulls:n}=t;if(s==null&&e==null)return 0;if(s==null)return n==="first"?-1:1;if(e==null)return n==="first"?1:-1;const i=I(s),r=I(e);if(i&&r)return 0;if(i)return 1;if(r)return-1;if(typeof s=="string"&&typeof e=="string"&&t.stringSort==="locale")return s.localeCompare(e,t.locale,t.localeOptions);if(Array.isArray(s)&&Array.isArray(e)){for(let d=0;d<Math.min(s.length,e.length);d++){const h=Ue(s[d],e[d],t);if(h!==0)return h}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();if(z(s)&&z(e))return xt(s,e);const o=typeof s=="symbol",a=typeof e=="symbol";if(o&&a)return s===e?0:it(s)[2]-it(e)[2];if(o)return 1;if(a)return-1;const c=typeof s=="object",u=typeof e=="object";if(c||u){if(c&&u){const d=rt(s),h=rt(e);return d-h}if(c)return 1;if(u)return-1}return s<e?-1:s>e?1:0},Ms=(s,e,t)=>Ue(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function Ot(s){return(e,t)=>s.direction==="asc"?Ue(e,t,s):Ms(e,t,s)}function Se(s){return s instanceof Uint8Array||typeof Buffer<"u"&&s instanceof Buffer}function Ls(s,e){if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}const Tt="\0tanstack-db:";function _e(s,e){return`${Tt}${s}:${e}`}function Ks(s){let e="";for(let t=0;t<s.byteLength;t++)e+=String.fromCharCode(s[t]);return _e("binary",e)}function Fs(s){return typeof s=="string"?s.startsWith(Tt)?_e("string",s):s:typeof s!="object"||s===null?s:s instanceof Date?s.getTime():z(s)?_e("temporal",`${s[Symbol.toStringTag]}:${s.toString()}`):Se(s)?Ks(s):s}const ot=new Map;function xt(s,e){const t=s[Symbol.toStringTag],n=e[Symbol.toStringTag];if(t!==n)throw new TypeError(`Cannot order Temporal values of different types: ${t} vs ${n}`);let i=ot.get(t);if(i===void 0){const r=s.constructor.compare;i=typeof r=="function"?r:null,ot.set(t,i)}if(i===null)throw new TypeError(`${t} has no defined ordering`);return i(s,e)}function he(s,e){return z(s)&&z(e)?xt(s,e):s<e?-1:s>e?1:0}function Vs(s,e){return s===e?!0:Se(s)&&Se(e)?Ls(s,e):!1}function _(s){return s==null}function fe(s){return Se(s)?s:Fs(s)}function at(s,e){return I(s)||I(e)?I(s)&&I(e):Vs(s,e)}function De(s){if(s instanceof Date)return Number.isNaN(s.getTime())?null:s;if(typeof s=="string"||typeof s=="number"){const e=new Date(s);return Number.isNaN(e.getTime())?null:e}return null}function Us(s,e){return s==="%Y-%m-%d"?e.toISOString().slice(0,10):e.toISOString()}function $s(s){return s===!0}function zs(s,e=!1){return $e(s,e)}function Et(s){return $e(s,!0)}function $e(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?js(s):qs(s);case"func":return Ns(s,e);default:throw new Os(s.type)}}function qs(s){const[e,...t]=s.path;if(!e)throw new Ts;if(e==="$selected"){if(t.length===0)return i=>i.$selected;if(t.length===1){const i=t[0];return r=>r.$selected?.[i]}else return i=>{const r=i.$selected;if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return i=>i[n];if(t.length===1){const i=t[0];return r=>r[n]?.[i]}else return i=>{const r=i[n];if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}function js(s){const e=s.path;return t=>{let n=t;for(const i of e){if(n==null)return n;n=n[i]}return n}}function Ns(s,e){const t=s.args.map(n=>$e(n,e));switch(s.name){case"eq":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=fe(i(r));return _(o)||_(a)?null:at(o,a)}}case"gt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(o)&&!I(a):he(o,a)>0}}case"gte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(o):he(o,a)>=0}}case"lt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(a)&&!I(o):he(o,a)<0}}case"lte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:I(o)||I(a)?I(a):he(o,a)<=0}}case"and":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!1)return!1;_(o)&&(i=!0)}return i?null:!0};case"or":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!0)return!0;_(o)&&(i=!0)}return i?null:!1};case"not":{const n=t[0];return i=>{const r=n(i);return _(r)?null:!r}}case"in":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=i(r);return _(o)?null:Array.isArray(a)?a.some(c=>at(fe(c),o)):!1}}case"like":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:ct(o,a,!1)}}case"ilike":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return _(o)||_(a)?null:ct(o,a,!0)}}case"upper":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toUpperCase():r}}case"lower":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toLowerCase():r}}case"length":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"||Array.isArray(r)?r.length:0}}case"concat":return n=>t.map(i=>{const r=i(n);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const i of t){const r=i(n);if(r!=null)return r}return null};case"caseWhen":{const n=t.length%2===1,i=Math.floor(t.length/2);if(t.length<2)throw new Error("caseWhen() requires at least two arguments");return r=>{for(let o=0;o<i;o++){const a=t[o*2];if(Ws(a(r))){const c=t[o*2+1];return c(r)}}return n?t[t.length-1](r):null}}case"add":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)+(a??0)}}case"subtract":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)-(a??0)}}case"multiply":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)*(a??0)}}case"divide":{const n=t[0],i=t[1];return r=>{const o=n(r),c=i(r)??0;return c!==0?(o??0)/c:null}}case"date":{const n=t[0];return i=>{const r=n(i),o=De(r);return o?o.toISOString().slice(0,10):null}}case"datetime":{const n=t[0];return i=>{const r=n(i),o=De(r);return o?o.toISOString():null}}case"strftime":{const n=t[0],i=t[1];return r=>{const o=n(r);if(typeof o!="string")return null;const a=i(r),c=De(a);return c?Us(o,c):null}}case"isUndefined":{const n=t[0];return i=>n(i)===void 0}case"isNull":{const n=t[0];return i=>n(i)===null}default:throw new xs(s.name)}}function Ws(s){return s==null||s===!1?!1:s===!0?!0:typeof s=="number"?s!==0&&!Number.isNaN(s):typeof s=="bigint"?s!==0n:!!s}function ct(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let r=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r=r.replace(/%/g,".*"),r=r.replace(/_/g,"."),new RegExp(`^${r}$`,"s").test(n)}class Bs{constructor(e){this.originalIndex=e}lookup(e,t){const 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)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}canOptimizeRangeFor(e){return this.originalIndex.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.originalIndex.keyCount}}function lt(s,e,t,n,i){const r=s;return{...s,$synced:r.$synced??n(),$origin:r.$origin??i(),$key:r.$key??e,$collectionId:r.$collectionId??t}}const Hs=["$synced","$origin","$key","$collectionId"];function Gs(s){return Hs.includes(s)}function Dt(s){return s.some(e=>Gs(e))}function ke(s,e,t){if(Dt(e))return;const n=t??{...ve,...s.compareOptions};for(const i of s.indexes.values())if(i.matchesField(e)&&i.matchesCompareOptions(n))return i.matchesDirection(n.direction)?i:new Bs(i)}function Ys(s){if(s.length===0)return new Set;if(s.length===1)return new Set(s[0]);let e=new Set(s[0]);for(let t=1;t<s.length;t++){const n=new Set;for(const i of e)s[t].has(i)&&n.add(i);e=n}return e}function Js(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function ze(s){return s!=null}function Qs(s){return{...ve,...s.compareOptions}.stringSort==="locale"}function Zs(s,e){switch(typeof s){case"number":case"bigint":case"boolean":return!1;case"string":return Qs(e);case"symbol":return!0;case"object":return s===null?!1:!(s instanceof Date);default:return!1}}function Pt(s,e,t){return!Zs(s,t)&&e.supportsRangeOptimization&&(e.canOptimizeRangeFor?.(s)??!0)}function Xs(s,e){return qe(s,e)}function qe(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return tn(s,e);case"and":return sn(s,e);case"or":return nn(s,e);case"in":return rn(s,e)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function en(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};const t=new Map;for(const[n,i]of s.args.entries())if(i.type==="func"&&["gt","gte","lt","lte"].includes(i.name)){const r=i;if(r.args.length===2){const o=r.args[0],a=r.args[1];let c=null,u=null,d=r.name;if(o.type==="ref"&&a.type==="val")c=o,u=a;else if(o.type==="val"&&a.type==="ref")switch(c=a,u=o,d){case"gt":d="lt";break;case"gte":d="lte";break;case"lt":d="gt";break;case"lte":d="gte";break}if(c&&u){const l=c.path.join("."),p=u.value;t.has(l)||t.set(l,[]),t.get(l).push({operation:d,value:p,argIndex:n})}}}for(const[n,i]of t)if(i.length>=2){const r=n.split("."),o=ke(e,r);if(o&&i.some(a=>!Pt(a.value,o,e)))continue;if(o&&o.supports("gt")&&o.supports("lt")){const a=Ot({...ve,...e.compareOptions,direction:"asc"});let c,u,d=!1,h=!1,l=!0,p=!0,f=!1;for(const{operation:b,value:x}of i){if(!ze(x)){f=!0;continue}switch(b){case"gt":case"gte":{const v=d?a(x,c):1;v>0?(c=x,d=!0,l=b==="gte"):v===0&&b==="gt"&&(l=!1);break}case"lt":case"lte":{const v=h?a(x,u):-1;v<0?(u=x,h=!0,p=b==="lte"):v===0&&b==="lt"&&(p=!1);break}}}const g={};return d&&(g.from=c,g.fromInclusive=l),h&&(g.to=u,g.toInclusive=p),{canOptimize:!0,matchingKeys:o.rangeQuery(g),isExact:d&&!f,coveredArgIndices:new Set(i.map(b=>b.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function tn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];let i=null,r=null,o=s.name;if(t.type==="ref"&&n.type==="val")i=t,r=n;else if(t.type==="val"&&n.type==="ref")switch(i=n,r=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(i&&r){const a=i.path,c=ke(e,a);if(c){const u=r.value,d=o;if(!c.supports(d))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};if((o==="gt"||o==="gte"||o==="lt"||o==="lte")&&!Pt(u,c,e))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const h=c.lookup(d,u),l=o==="lt"||o==="lte"?!1:ze(u);return{canOptimize:!0,matchingKeys:h,isExact:l}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function sn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=en(s,e),n=t.canOptimize?t.coveredArgIndices:new Set,i=[];t.canOptimize&&i.push(t);let r=t.canOptimize?t.isExact:!0;for(const[o,a]of s.args.entries()){if(n.has(o))continue;const c=qe(a,e);c.canOptimize?(i.push(c),c.isExact||(r=!1)):r=!1}if(i.length>0){const o=i.map(c=>c.matchingKeys);return{canOptimize:!0,matchingKeys:Ys(o),isExact:r}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function nn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=[];for(const r of s.args){const o=qe(r,e);if(!o.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};t.push(o)}const n=t.map(r=>r.matchingKeys);return{canOptimize:!0,matchingKeys:Js(n),isExact:t.every(r=>r.isExact)}}function rn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const i=t.path,r=n.value,o=ke(e,i),a=r.every(c=>ze(c));if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",r),isExact:a};if(o.supports("eq")){const c=new Set;for(const u of r){const d=o.lookup("eq",u);for(const h of d)c.add(h)}return{canOptimize:!0,matchingKeys:c,isExact:a}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function It(s){return s.config.autoIndex==="eager"}function At(s,e,t,n,i){if(Dt(e)||!It(t))return;const r=n??{...ve,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(r)))try{t.createIndex(a=>{let c=a;for(const u of e)c=c[u];return c},{name:`auto:${e.join(".")}`,options:i?{compareFn:i,compareOptions:r}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function on(s,e){if(!It(e))return;const t=an(s);for(const{fieldName:n,fieldPath:i}of t)At(n,i,e)}function an(s){const e=[];function t(n){if(n.type!=="func")return;const i=n;if(i.name==="and"){for(const u of i.args)t(u);return}if(!["eq","gt","gte","lt","lte","in"].includes(i.name)||i.args.length<1||i.args[0].type!=="ref")return;const a=i.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}function cn(s,e){return ln(s,e.compareOptions)}function ln(s,e){return s.compareOptions.stringSort===void 0?{...e,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}:s.compareOptions}function un(s,e={}){const t=n=>{const i=[];for(const[r,o]of s.entries())(n?.(o)??!0)&&i.push({type:"insert",key:r,value:o});return i};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?te(e.where):void 0,i=hn(s,e.orderBy,e.limit,n,e.optimizedOnly);if(i===void 0)return;const r=[];for(const o of i){const a=s.get(o);a!==void 0&&r.push({type:"insert",key:o,value:a})}return r}if(!e.where)return t();try{const n=e.where,i=Xs(n,s);if(i.canOptimize){const r=i.isExact?void 0:te(n),o=[];for(const a of i.matchingKeys){const c=s.get(a);c!==void 0&&(r?.(c)??!0)&&o.push({type:"insert",key:a,value:c})}return o}else{if(e.optimizedOnly)return;const r=te(n);return t(r)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const i=te(e.where);return e.optimizedOnly?void 0:t(i)}}function te(s){const e=Et(s);return t=>{try{const n=e(t);return $s(n)}catch{return!1}}}function dn(s,e){const t=te(e.whereExpression);return n=>{const i=[];for(const r of n)if(r.type==="insert")t(r.value)&&i.push(r);else if(r.type==="update"){const o=t(r.value),a=r.previousValue?t(r.previousValue):!1;o&&a?i.push(r):o&&!a?i.push({...r,type:"insert"}):!o&&a&&i.push({...r,type:"delete",value:r.previousValue})}else t(r.value)&&i.push(r);return i.length>0||n.length===0?(s(i),!0):!1}}function hn(s,e,t,n,i){if(e.length===1){const c=e[0],u=c.expression;if(u.type==="ref"){const h=u.path,l=cn(c,s);At(h[0],h,s,l);const p=ke(s,h,l);if(p&&p.supports("gt")){const f=g=>{const w=s.get(g);return w===void 0?!1:n?.(w)??!0};return p.takeFromStart(t??p.keyCount,f)}}}if(i)return;const r=[];for(const[c,u]of s.entries())(n?.(u)??!0)&&r.push({key:c,value:u});const o=(c,u)=>{for(const d of e){const h=Ot(d.compareOptions),l=ut(c.value,d.expression),p=ut(u.value,d.expression),f=h(l,p);if(f!==0)return f}return 0};r.sort(o);const a=r.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function ut(s,e){if(e.type==="ref"){const t=e;let n=s;for(const i of t.path)n=n?.[i];return n}else return e.type==="val"?e.value:Et(e)(s)}class dt{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,i=this.sortedKeys.length;if(!this.comparator){for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=Ye(e,o);if(a<0)i=r;else if(a>0)n=r+1;else return r}return n}for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=this.map.get(o),c=this.comparator(t,a);if(c<0)i=r;else if(c>0)n=r+1;else{const u=Ye(e,o);if(u<0)i=r;else if(u>0)n=r+1;else return r}}return n}set(e,t){if(this.map.has(e)){const i=this.map.get(e),r=this.indexOf(e,i);this.sortedKeys.splice(r,1)}const 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)){const 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(const 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(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const t of this.sortedKeys)e(this.map.get(t),t,this.map)}}const ye="__tanstack_db_direct";class fn{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,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.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isDrainingSyncTransactions=!1,this.syncSessionGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.isDrainingSyncTransactions)return;this.isDrainingSyncTransactions=!0;let t=!1,n;try{let i;do i=this.commitNextPendingTransactionBatch(),i.failure&&!t&&(t=!0,n=i.failure.error);while(i.processed)}finally{this.isDrainingSyncTransactions=!1}if(t)throw n},this.config=e,this.transactions=new dt((t,n)=>t.compareCreatedAt(n)),this.syncedData=new dt(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"});const n=t?.optimisticUpserts??this.optimisticUpserts,i=t?.optimisticDeletes??this.optimisticDeletes,r=n.has(e)||i.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!r,$origin:r?"local":(t?.rowOrigins??this.rowOrigins).get(e)??"remote"})}snapshotRowOriginsForKeys(e){const t=new Map;for(const n of e){const i=this.rowOrigins.get(n);i!==void 0&&t.set(n,i)}return t}enrichWithVirtualPropsSnapshot(e,t){const n=e,i=n.$synced??t.$synced,r=n.$origin??t.$origin,o=n.$key??t.$key,a=n.$collectionId??t.$collectionId,c=this.virtualPropsCache.get(e);if(c&&c.synced===i&&c.origin===r&&c.key===o&&c.collectionId===a)return c.enriched;const u={...e,$synced:i,$origin:r,$key:o,$collectionId:a};return this.virtualPropsCache.set(e,{synced:i,origin:r,key:o,collectionId:a,enriched:u}),u}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){const{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),i=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:i,metadata:e.metadata}}getWithVirtualProps(e){const t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;if(!t.has(e))return n.has(e)?n.get(e):i.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;return t.has(e)?!1:n.has(e)?!0:i.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const i of e.keys())t.has(i)||(yield i);for(const i of n.keys())!e.has(i)&&!t.has(i)&&(yield i)}*values(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(const[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;const t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),i=this.rowOrigins;for(const h of this.transactions.values()){const l=h.metadata[ye]===!0;if(h.state==="completed"){for(const p of h.mutations)if(this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.add(p.key),!!p.optimistic))switch(p.type){case"insert":case"update":this.pendingOptimisticUpserts.set(p.key,p.modified),this.pendingOptimisticDeletes.delete(p.key),l?(this.pendingOptimisticDirectUpserts.add(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break;case"delete":this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.add(p.key),l?(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.add(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break}}else if(h.state==="failed")for(const p of h.mutations)this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.delete(p.key),p.optimistic&&(this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.delete(p.key),this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const r=new Set;for(const h of this.pendingSyncedTransactions)for(const l of h.operations)r.add(l.key);const o=[];for(const[h,l]of this.pendingOptimisticUpserts)r.has(h)||this.pendingOptimisticDirectUpserts.has(h)?this.optimisticUpserts.set(h,l):o.push(h);for(const h of o)this.pendingOptimisticUpserts.delete(h),this.pendingLocalOrigins.delete(h);const a=[];for(const h of this.pendingOptimisticDeletes)r.has(h)||this.pendingOptimisticDirectDeletes.has(h)?this.optimisticDeletes.add(h):a.push(h);for(const h of a)this.pendingOptimisticDeletes.delete(h),this.pendingLocalOrigins.delete(h);const c=[];for(const h of this.transactions.values())["completed","failed"].includes(h.state)||c.push(h);for(const h of c)for(const l of h.mutations)if(this.isThisCollection(l.collection)&&(this.pendingLocalChanges.add(l.key),l.optimistic))switch(l.type){case"insert":case"update":this.optimisticUpserts.set(l.key,l.modified),this.optimisticDeletes.delete(l.key);break;case"delete":this.optimisticUpserts.delete(l.key),this.optimisticDeletes.add(l.key);break}this.size=this.calculateSize();const u=[];this.collectOptimisticChanges(t,n,i,u);const d=u.filter(h=>!!(!this.recentlySyncedKeys.has(h.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const h=new Set;for(const p of this.pendingSyncedTransactions)for(const f of p.operations)h.add(f.key);const l=d.filter(p=>!(p.type==="delete"&&h.has(p.key)&&!c.some(g=>g.mutations.some(w=>this.isThisCollection(w.collection)&&w.key===p.key))));l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}else d.length>0&&this.indexes.updateIndexes(d),this.changes.emitEvents(d,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(i=>this.syncedData.has(i)&&!this.optimisticUpserts.has(i)).length,n=Array.from(this.optimisticUpserts.keys()).filter(i=>!this.syncedData.has(i)).length;return e-t+n}collectOptimisticChanges(e,t,n,i){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const o of r){const a=this.get(o),c=this.getPreviousValue(o,e,t),u=this.getVirtualPropsSnapshotForState(o,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),d=this.getVirtualPropsSnapshotForState(o);c!==void 0&&a===void 0?i.push({type:"delete",key:o,value:c,__virtualProps:{value:u}}):c===void 0&&a!==void 0?i.push({type:"insert",key:o,value:a,__virtualProps:{value:d}}):c!==void 0&&a!==void 0&&c!==a&&i.push({type:"update",key:o,value:a,previousValue:c,__virtualProps:{value:d,previousValue:u}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}commitNextPendingTransactionBatch(){const e=this.syncSessionGeneration;let t=!1;for(const c of this.transactions.values())if(c.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:i,hasTruncateSync:r,hasImmediateSync:o,layoutChanged:a}=this.pendingSyncedTransactions.reduce((c,u)=>(u.committed?(c.committedSyncedTransactions.push(u),c.layoutChanged||=u.layoutChanged,u.truncate&&(c.hasTruncateSync=!0),u.immediate&&(c.hasImmediateSync=!0)):c.uncommittedSyncedTransactions.push(u),c),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1,layoutChanged:!1});if(n.length===0)return{processed:!1};if(!t||r||o){const c=a?[...this.keys()]:void 0;this.pendingSyncedTransactions=i;for(const m of n)m.applicationStarted=!0;this.isCommittingSyncTransactions=!0;const u=r?n.find(m=>m.truncate)?.optimisticSnapshot:null;let d,h;const l=new Set;for(const m of n){for(const S of m.operations)l.add(S.key);for(const[S]of m.rowMetadataWrites)l.add(S)}const p=new Set(l);for(const m of this.pendingOptimisticDirectUpserts)p.add(m);for(const m of this.pendingOptimisticDirectDeletes)p.add(m);const f=this.snapshotRowOriginsForKeys(p),g=new Map(this.optimisticUpserts),w=new Set(this.optimisticDeletes),b=new Set(this.pendingOptimisticDirectUpserts),x=new Set(this.pendingOptimisticDirectDeletes);let v=this.preSyncVisibleState;if(v.size===0){v=new Map;for(const m of l){const S=this.get(m);S!==void 0&&v.set(m,S)}}const k=[],M=this.config.sync.rowUpdateMode||"partial",T=new Map;for(const m of this.transactions.values())if(m.state==="completed")for(const S of m.mutations)this.isThisCollection(S.collection)&&S.optimistic&&T.set(S.key,{type:S.type,value:S.modified});for(const m of n){if(m.truncate){const S=new Set([...this.syncedData.keys(),...u?.upserts.keys()||[]]);for(const y of S){if(u?.deletes.has(y))continue;const O=u?.upserts.get(y)||this.syncedData.get(y);O!==void 0&&k.push({type:"delete",key:y,value:O})}d=new Set(this.pendingLocalChanges),h=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState();for(const y of l)v.delete(y);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const S of m.operations){const y=S.key,O=(d?.has(y)===!0||h?.has(y)===!0)&&!b.has(y)&&!x.has(y),C=this.isLocalOnly||this.pendingLocalChanges.has(y)||this.pendingLocalOrigins.has(y)||O?"local":"remote";switch(S.type){case"insert":this.syncedData.set(y,S.value),this.rowOrigins.set(y,C),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break;case"update":{if(M==="partial"){const A=Object.assign({},this.syncedData.get(y),S.value);this.syncedData.set(y,A)}else this.syncedData.set(y,S.value);this.rowOrigins.set(y,C),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break}case"delete":this.syncedData.delete(y),this.syncedMetadata.delete(y),this.rowOrigins.delete(y),this.pendingLocalChanges.delete(y),this.pendingLocalOrigins.delete(y),this.pendingOptimisticUpserts.delete(y),this.pendingOptimisticDeletes.delete(y),this.pendingOptimisticDirectUpserts.delete(y),this.pendingOptimisticDirectDeletes.delete(y);break}m.preserveHydrationSeedKeys||(this.hydrationSeedKeys.delete(y),this.hydratedKeys.delete(y))}for(const[S,y]of m.rowMetadataWrites){if(y.type==="delete"){this.syncedMetadata.delete(S);continue}this.syncedMetadata.set(S,y.value)}for(const[S,y]of m.collectionMetadataWrites){if(y.type==="delete"){this.syncedCollectionMetadata.delete(S);continue}this.syncedCollectionMetadata.set(S,y.value)}}if(r){const m=new Set;for(const O of n)for(const C of O.operations)(C.type==="insert"||C.type==="update")&&m.add(C.key);const S=new Map(u.upserts),y=new Set(u.deletes);for(const O of b)l.has(O)&&S.delete(O);for(const O of x)l.has(O)&&y.delete(O);for(const[O,C]of S)if(!y.has(O))if(m.has(O)){let A=!1;for(let V=k.length-1;V>=0;V--){const R=k[V];if(R.key===O&&R.type==="insert"){R.value=C,A=!0;break}}A||k.push({type:"insert",key:O,value:C})}else k.push({type:"insert",key:O,value:C});if(k.length>0&&y.size>0){const O=[];for(const C of k)C.type==="insert"&&y.has(C.key)||O.push(C);k.length=0,k.push(...O)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&u){for(const[m,S]of u.upserts)b.has(m)&&l.has(m)||this.optimisticUpserts.set(m,S);for(const m of u.deletes)x.has(m)&&l.has(m)||this.optimisticDeletes.add(m)}for(const m of this.transactions.values())if(!["completed","failed"].includes(m.state)){for(const S of m.mutations)if(this.isThisCollection(S.collection)&&S.optimistic)switch(S.type){case"insert":case"update":this.optimisticUpserts.set(S.key,S.modified),this.optimisticDeletes.delete(S.key);break;case"delete":this.optimisticUpserts.delete(S.key),this.optimisticDeletes.add(S.key);break}}for(const m of this.pendingOptimisticDirectUpserts)if(!l.has(m)){if(l.add(m),!v.has(m)){const S=g.get(m);S!==void 0&&v.set(m,S)}this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m)}for(const m of this.pendingOptimisticDirectDeletes)l.has(m)||l.add(m),this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(const m of l){const S=v.get(m),y=this.get(m),O=this.preSyncVirtualState.get(m)??this.getVirtualPropsSnapshotForState(m,{rowOrigins:f,optimisticUpserts:g,optimisticDeletes:w,completedOptimisticKeys:T}),C=this.getVirtualPropsSnapshotForState(m),A=O.$synced!==C.$synced||O.$origin!==C.$origin,V=S!==void 0?lt(S,m,this.collection.id,()=>O.$synced,()=>O.$origin):void 0,R=T.get(m);let D=!1;R&&(R.type==="delete"&&S!==void 0&&y===void 0&&K(R.value,S)||y!==void 0&&K(R.value,y))&&(D=!0);const Y=A&&S!==void 0&&y!==void 0&&K(S,y);if(!(D&&!Y))if(S===void 0&&y!==void 0){const re=T.get(m);if(re){const Ce=re.value,Re=lt(Ce,m,this.collection.id,()=>O.$synced,()=>O.$origin);k.push({type:"update",key:m,value:y,previousValue:Re})}else k.push({type:"insert",key:m,value:y})}else S!==void 0&&y===void 0?k.push({type:"delete",key:m,value:V??S}):S!==void 0&&y!==void 0&&(!K(S,y)||Y)&&k.push({type:"update",key:m,value:y,previousValue:V??S})}this.size=this.calculateSize(),k.length>0&&this.indexes.updateIndexes(k);let E;try{const m=c!==void 0&&(c.length!==this.size||[...this.keys()].some((S,y)=>S!==c[y]));this.changes.emitEvents(k,!0,m)}catch(m){E={error:m}}this.syncSessionGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncSessionGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0));for(const m of n)m.applied.resolve();return{processed:!0,failure:E}}return{processed:!1}}cancelPendingSyncedTransaction(e){if(e.applicationStarted)return;const t=this.pendingSyncedTransactions.indexOf(e);if(t===-1)return;this.pendingSyncedTransactions.splice(t,1),e.applied.reject(new tt);const n=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)n.add(r.key);for(const i of e.operations){const r=i.key;n.has(r)||(this.recentlySyncedKeys.delete(r),this.preSyncVisibleState.delete(r),this.preSyncVirtualState.delete(r))}this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}scheduleTransactionCleanup(e){if(e.state==="completed"){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const e=new Set;for(const t of this.pendingSyncedTransactions)for(const n of t.operations)e.add(n.key);for(const t of e)this.recentlySyncedKeys.add(t);for(const t of e)if(!this.preSyncVisibleState.has(t)){const n=this.get(t);n!==void 0&&(this.preSyncVisibleState.set(t,n),this.preSyncVirtualState.set(t,this.getVirtualPropsSnapshotForState(t)))}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncSessionGeneration++;for(const e of this.pendingSyncedTransactions)e.applied.reject(new tt);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.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function Z(s){let e;for(const t of s)try{t()}catch(n){e??={error:n}}if(e)throw e.error}function pn(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class yn{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},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:i}){if(typeof e>"u"){i();return}const r=this.getOrCreateContext(e);if(r.jobs.has(t)||r.queue.push(t),r.jobs.set(t,i),n){const o=new Set(n);o.delete(t),r.dependencies.set(t,o)}else r.dependencies.has(t)||r.dependencies.set(t,new Set)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:i,dependencies:r}=t;for(;n.length>0;){let o=!1;const a=n.length;for(let c=0;c<a;c++){const u=n.shift(),d=i.get(u);if(!d){r.delete(u);continue}const h=r.get(u);let l=!h;if(h){l=!0;for(const p of h){if(p===u)continue;const f=pn(p)&&p.hasPendingGraphRun(e);if(i.has(p)||f){l=!1;break}}}l?(i.delete(u),r.delete(u),d(),o=!0):n.push(u)}if(!o)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}clear(e){this.contexts.delete(e),Z([...this.clearListeners].map(t=>()=>t(e)))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}}const ue=new yn;let me,be;function ht(){return be}function ft(s){if(me===void 0)throw s;be??={error:s}}function pt(s){if(me!==void 0)return s();const e=Symbol("collection-publication");me=e,be=void 0;let t,n;try{t=s(),ue.flush(e),n=ht()}catch(i){try{ue.clear(e)}catch{}const r=ht();throw r?r.error:i}finally{me=void 0,be=void 0}if(n)throw n.error;return t}function _t(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const i=new Proxy({},{get(r,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,a);const c=[...t,String(o)];return e(c)},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(r,o)},ownKeys(r){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(r,o)}});return s.set(n,i),i}return e([])}function L(s){if(mn(s))return new Rt(s.__path);if(s&&typeof s=="object"&&(s.__brand==="ToArrayWrapper"||s.__brand==="ConcatToArrayWrapper"||s.__brand==="CaseWhenWrapper"||s.__brand==="MaterializeWrapper")){const e=s.__brand==="ToArrayWrapper"?"toArray()":s.__brand==="ConcatToArrayWrapper"?"concat(toArray())":s.__brand==="CaseWhenWrapper"?"caseWhen()":"materialize()";throw new Error(`${e} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${e} directly as a select field value instead.`)}return s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new Q(s)}function mn(s){return s&&typeof s=="object"&&s.__refProxy===!0}function Mt(s,e){return new j("eq",[L(s),L(e)])}function gn(s,e){return new j("gt",[L(s),L(e)])}function Sn(s,e){return new j("gte",[L(s),L(e)])}function Lt(s,e){return new j("lt",[L(s),L(e)])}function Me(s,e,...t){const n=[s,e,...t];return new j("and",n.map(i=>L(i)))}function Kt(s,e,...t){const n=[s,e,...t];return new j("or",n.map(i=>L(i)))}function bn(s){return new j("not",[L(s)])}function wn(s){return new j("isUndefined",[L(s)])}function vn(s){return new j("isNull",[L(s)])}class Ft{constructor(){this.listeners=new Map,this.onceCallbacks=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);const n=this.listeners.get(e),i=t;let r=n.get(i);return r||(r={},n.set(i,r)),()=>{const o=this.listeners.get(e);o?.get(i)===r&&o.delete(i)}}once(e,t){let n=()=>{};const i=r=>{n(),t(r)};return this.onceCallbacks.set(i,t),n=this.on(e,i),n}off(e,t){const n=this.listeners.get(e);if(n)for(const i of n.keys())(i===t||this.onceCallbacks.get(i)===t)&&n.delete(i)}waitFor(e,t){return new Promise((n,i)=>{let r;const o=this.on(e,a=>{r&&(clearTimeout(r),r=void 0),n(a),o()});t&&(r=setTimeout(()=>{r=void 0,o(),i(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){const i=this.listeners.get(e);if(i)for(const[r,o]of[...i]){if(!n())break;if(this.listeners.get(e)?.get(r)===o)try{r(t)}catch(a){queueMicrotask(()=>{throw a})}}}clearListeners(){this.listeners.clear()}}function Vt(s){return Kt(vn(s),wn(s))}function kn(s,e){const t=Vt(s.expression);if(e==null)return s.compareOptions.nulls==="first"?bn(t):new Q(!1);const i=(s.compareOptions.direction==="asc"?gn:Lt)(s.expression,new Q(e));return s.compareOptions.nulls==="last"?Kt(i,t):i}function Cn(s,e){if(e.length!==0){if(s.length!==1||e.length!==1)throw new Error("Only single-column cursors are supported");return kn(s[0],e[0])}}function Rn(s,e){const{expression:t}=s[0]??{};if(!t||e.length===0)return;const n=e[0];if(n==null)return Vt(t);if(n instanceof Date)return Number.isFinite(n.getTime())?Me(Sn(t,new Q(n)),Lt(t,new Q(new Date(n.getTime()+1)))):void 0;if(typeof n!="object")return Mt(t,new Q(n))}const W=s=>{try{return s instanceof Error?s:new Error(String(s))}catch{return new Error("Unknown error")}};function se(){let s,e,t=!0;return{promise:new Promise((i,r)=>{s=o=>{t=!1,i(o)},e=o=>{t=!1,r(o)}}),resolve:s,reject:e,isPending:()=>t}}function yt(){const s=se();return s.promise.catch(()=>{}),s}function oe(s){s.abortController?.abort(),s.removeRequestAbortListener?.()}class On extends Ft{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.subsetDemands=[],this.primaryFailureDeliveryDepth=0,this.requestedSubsetWhere=new WeakMap,this.sentKeys=new Set,this.publishedRows=new Map,this.stalePublishedRows=new Map,this.limitedSnapshotRowCount=0,this._status="ready",this.statusRevision=0,this.pendingLoadSubsetParticipants=new Set,this.loadSubsetPromiseErrors=new WeakMap,this.truncateReplacementPending=!1,this.unsubscribed=!1,n.onUnsubscribe&&this.on("unsubscribed",n.onUnsubscribe),n.onLoadSubsetError&&this.on("loadSubset:error",n.onLoadSubsetError),n.whereExpression&&on(n.whereExpression,this.collection);const i=r=>{this.trackPublishedRows(r),this.trackSentKeys(r),t(r)};this.callback=i,this.filteredCallback=n.whereExpression?dn(this.callback,n):r=>(this.callback(r),!0),this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()}),this.collectionCleanup=this.collection.on("status:cleaned-up",()=>{this.handleCollectionCleanup()}),this.collectionRestartCleanup=this.collection.on("status:change",({status:r})=>{if(r!=="loading"&&r!=="ready")return;const o=this.collection._sync.getLoadSubsetSession(),a=this.truncateReplaySession;this.subsetDemands.some(c=>c.acquisitionState==="detached")&&this.setStatus("loadingSubset"),queueMicrotask(()=>{this.truncateReplaySession===a&&this.restartDetachedDemands(o)})})}get status(){return this._status}get lastError(){return this._lastError}handleCollectionCleanup(){this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.pendingLoadSubsetParticipants.clear();for(const e of[...this.subsetDemands])if(e.initialResult?.reject(new $),oe(e.acquisition),e.acquisitionState==="starting"){const t=this.subsetDemands.indexOf(e);t!==-1&&this.subsetDemands.splice(t,1)}else e.acquisitionState="detached",e.acquisition={options:e.requestOptions,loadSubsetSession:e.acquisition.loadSubsetSession};this.setReadyIfIdle()}restartDetachedDemands(e){if(this.unsubscribed||!this.isLoadSubsetSessionCurrent(e))return;if(this.collection.status==="error"||this.collection._sync.syncLoadSubsetFn===null){this.setReadyIfIdle();return}const t=this.subsetDemands.filter(r=>r.acquisitionState==="detached"&&!r.requestOptions.signal?.aborted);if(t.length===0){this.setReadyIfIdle();return}const n=this.createTruncateReplaySession(e,()=>{const r=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((r??[]).filter(o=>o.type!=="delete").map(o=>[o.key,o.value]))}),i=n.currentAttempt;this.truncateReplaySession=n,this.setStatus("loadingSubset"),this.truncateReplaySession===n&&this.startTruncateReplayAttempt(n,i,t)}handleTruncate(){const t=this.collection._sync.syncLoadSubsetFn!==null?[...this.subsetDemands]:[];if(t.length===0&&this.stalePublishedRows.size===0){this.resetSnapshotTracking();return}let n=this.truncateReplaySession;n?(n.completion.isPending()||(n.completion=yt()),n.pendingSetups++,n.failures.clear(),n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.createTruncateReplaySession(this.collection._sync.getLoadSubsetSession(),()=>new Map(this.publishedRows)),this.truncateReplaySession=n);const i=n.currentAttempt;if(this.setStatus("loadingSubset"),this.truncateReplaySession===n){this.options.truncateReplayPublication&&(this.truncateReplacementPending=!0,this.options.truncateReplayPublication.start());for(const r of t)r.acquisition.abortController?.abort();this.resetSnapshotTracking(),queueMicrotask(()=>{if(this.truncateReplaySession===n){if(!this.isLoadSubsetSessionCurrent(n.loadSubsetSession)){this.retireStaleTruncateReplay(n);return}this.startTruncateReplayAttempt(n,i,n.currentAttempt===i?t:[])}})}}startTruncateReplayDemand(e,t,n){const i=()=>this.truncateReplaySession===e&&e.currentAttempt===t,r=()=>i()&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.isDemandActive(n),o=h=>{r()&&e.failures.set(n,W(h))};n.initialResult&&e.completion.promise.then(n.initialResult.resolve,n.initialResult.reject);const a=n.acquisition,c=n.acquisitionState==="active";if(n.acquisitionState="detached",c)try{this.releaseAcquisition(a)}catch(h){o(h);return}if(!r()||n.requestOptions.signal?.aborted)return;const u=this.createSubsetAcquisition(n);n.acquisition=u,n.acquisitionState="starting";let d;try{d=this.loadSubset(u.options,r)}catch(h){n.acquisition===u&&(n.acquisitionState="detached"),oe(u),o(h);return}if(!r()){n.acquisition===u&&(n.acquisitionState="detached");try{this.releaseAcquisition(u)}catch(h){o(h)}return}n.acquisitionState="active",this.trackTruncateReplayParticipant(e,t,n,d),this.observeLoadSubsetResult(d,n,u.options,!0,()=>r()&&!u.options.signal?.aborted)}settleTruncateReplay(e,t){try{if(this.truncateReplaySession!==e)return;if(!this.isLoadSubsetSessionCurrent(e.loadSubsetSession)){this.retireStaleTruncateReplay(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.checkTruncateReplayComplete(e)}catch(n){queueMicrotask(()=>{throw n})}}trackTruncateReplayParticipant(e,t,n,i){if(this.truncateReplaySession!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(i instanceof Promise))return;const r={demand:n,attempt:t};t.pendingCount++,e.pending.add(r),i.then(()=>this.settleTruncateReplay(e,r),o=>{if(this.truncateReplaySession===e&&e.currentAttempt===t&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.subsetDemands.includes(n)){const a=this.normalizeLoadSubsetPromiseError(i,o);e.failures.set(n,a)}this.settleTruncateReplay(e,r)})}removeTruncateReplayParticipant(e){const t=this.truncateReplaySession;if(t){t.failures.delete(e);for(const n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}checkTruncateReplayComplete(e){if(this.truncateReplaySession!==e||e.pendingSetups>0||e.pending.size>0)return;const t=[...e.failures].find(([n])=>this.subsetDemands.includes(n));try{t?this.abandonTruncateReplay(e,t[1]):this.flushTruncateReplay(e)}finally{this.setReadyIfIdle()}}abandonTruncateReplay(e,t){if(this.truncateReplaySession!==e||(e.completion.reject(t),!e.privateRows))return;const n=e.publicationState;this.loadedInitialState=n.loadedInitialState,this.snapshotSent=n.snapshotSent,this.limitedSnapshotRowCount=n.limitedSnapshotRowCount,this.lastSentKey=n.lastSentKey}flushTruncateReplay(e){if(this.truncateReplaySession!==e)return;this.truncateReplaySession=void 0,this.truncateReplacementPending=!1;const{privateRows:t}=e;for(const n of this.stalePublishedRows.keys())t?.delete(n);this.stalePublishedRows.clear();try{if(t){const n=this.createStateDiff(this.publishedRows,t);n.length>0&&this.filteredCallback(n)}}finally{this.restorePublishedSnapshotTracking(),e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}restorePublishedSnapshotTracking(){if(this.sentKeys=new Set(this.publishedRows.keys()),!this.orderByIndex)return;this.limitedSnapshotRowCount=this.sentKeys.size;const e=this.orderByIndex.takeFromStart(this.sentKeys.size,t=>this.sentKeys.has(t));this.lastSentKey=e.at(-1)}bufferPrivately(e){const t=this.truncateReplaySession?.privateRows;if(!t)return!1;for(const n of e)n.type==="delete"?t.delete(n.key):t.set(n.key,n.value);return!0}createStateDiff(e,t){const n=[];for(const[i,r]of e){const o=t.get(i);o===void 0?n.push({type:"delete",key:i,value:r}):K(o,r)||n.push({type:"update",key:i,value:o,previousValue:r})}for(const[i,r]of t)e.has(i)||n.push({type:"insert",key:i,value:r});return n}get isBufferingForTruncate(){return this.truncateReplaySession!==void 0}setReadyIfIdle(){const e=this.truncateReplaySession,t=e&&(e.pendingSetups>0||e.pending.size>0);this.pendingLoadSubsetParticipants.size===0&&!t&&this.setStatus("ready")}isLoadSubsetSessionCurrent(e){return e===this.collection._sync.getLoadSubsetSession()}retireStaleTruncateReplay(e){this.truncateReplaySession===e&&(this.discardTruncateReplay(),this.stalePublishedRows.clear())}discardTruncateReplay(){const e=this.truncateReplaySession;e?.completion.isPending()&&e.completion.reject(new $),this.truncateReplaySession=void 0,this.truncateReplacementPending=!1}resetSnapshotTracking(){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0}createTruncateReplaySession(e,t){return{loadSubsetSession:e,publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent,limitedSnapshotRowCount:this.limitedSnapshotRowCount,lastSentKey:this.lastSentKey},privateRows:this.options.truncateReplayPublication?void 0:t(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,completion:yt()}}startTruncateReplayAttempt(e,t,n){for(const i of n)if(this.subsetDemands.includes(i)&&(this.startTruncateReplayDemand(e,t,i),this.truncateReplaySession!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.checkTruncateReplayComplete(e)}get hasPendingTruncateReplacement(){return this.truncateReplacementPending}get pendingTruncateReplacement(){const e=this.truncateReplaySession?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){const e=this.truncateReplaySession?.completion;return this.truncateReplacementPending&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this._status===e)return;const t=this._status;this._status=e;const n=++this.statusRevision;if(this.emitInnerWhile("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n),this.statusRevision!==n)return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n)}observeLoadSubsetResult(e,t,n,i,r=()=>!0){if(!(e instanceof Promise))return;const o=this.collection._sync.getLoadSubsetSession(),a={demand:t,promise:e};i&&(this.pendingLoadSubsetParticipants.add(a),this.setStatus("loadingSubset"));const c=()=>{i&&(this.pendingLoadSubsetParticipants.delete(a),this.isLoadSubsetSessionCurrent(o)&&this.setReadyIfIdle())};e.then(c,u=>{this.isLoadSubsetSessionCurrent(o)&&r()&&this.recordLoadSubsetError(n,this.normalizeLoadSubsetPromiseError(e,u)),c()})}normalizeLoadSubsetPromiseError(e,t){const n=this.loadSubsetPromiseErrors.get(e);if(n)return n;const i=W(t);return this.loadSubsetPromiseErrors.set(e,i),i}stopDemandStatusParticipants(e){for(const t of this.pendingLoadSubsetParticipants)t.demand===e&&this.pendingLoadSubsetParticipants.delete(t);this.setReadyIfIdle()}loadSubset(e,t=()=>!0){try{return this.collection._sync.loadSubset(e)}catch(n){const i=W(n);throw t()&&this.recordLoadSubsetError(e,i),i}}createSubsetAcquisition(e){const t=new AbortController,n=e.requestOptions.signal;let i;if(n?.aborted)t.abort(n.reason);else if(n){const r=()=>t.abort(n.reason);n.addEventListener("abort",r,{once:!0}),i=()=>n.removeEventListener("abort",r)}return{options:{...e.requestOptions,signal:t.signal},loadSubsetSession:this.collection._sync.getLoadSubsetSession(),abortController:t,removeRequestAbortListener:i}}releaseAcquisition(e,t=this.primaryFailureDeliveryDepth===0){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.collection._sync.unloadSubset(e.options)}catch(n){throw t?this.recordLoadSubsetError(e.options,W(n),!0):W(n)}finally{e.removeRequestAbortListener?.()}}}startSubsetDemand(e){const t={requestOptions:e,acquisition:{options:e,loadSubsetSession:this.collection._sync.getLoadSubsetSession()},acquisitionState:"starting"};if(this.collection.status==="cleaned-up"||this.collection.config.syncMode==="on-demand"&&(this.collection.status==="error"||this.collection.status!=="idle"&&this.collection._sync.syncLoadSubsetFn===null)){t.acquisitionState="detached",this.subsetDemands.push(t);const c=se();t.initialResult=c;const u=()=>c.reject(new $);e.signal?.addEventListener("abort",u,{once:!0});const d=()=>{e.signal?.removeEventListener("abort",u),t.initialResult=void 0};return c.promise.then(d,d),{demand:t,result:c.promise,started:!1}}const n=this.createSubsetAcquisition(t);t.acquisition=n;const i=this.truncateReplaySession,r=i?.currentAttempt,o=this.collection._sync.getLoadSubsetSession();this.subsetDemands.push(t);let a;try{a=this.loadSubset(n.options,()=>this.isLoadSubsetSessionCurrent(o)&&this.subsetDemands.includes(t)&&(i===void 0||this.truncateReplaySession===i&&i.currentAttempt===r))}catch(c){const u=this.subsetDemands.indexOf(t);throw u!==-1&&(i&&r&&this.truncateReplaySession===i&&i.currentAttempt===r&&i.failures.set(t,W(c)),this.subsetDemands.splice(u,1)),oe(n),c}if(!this.isLoadSubsetSessionCurrent(o)){const c=this.subsetDemands.indexOf(t);return c!==-1&&this.subsetDemands.splice(c,1),oe(n),{demand:t,result:a,started:!0}}return t.acquisitionState="active",this.subsetDemands.includes(t)?(i&&r&&this.trackTruncateReplayParticipant(i,r,t,a),{demand:t,result:a,started:!0}):(this.releaseAcquisition(n),{demand:t,result:a,started:!0})}isDemandActive(e){return!this.unsubscribed&&this.subsetDemands.includes(e)}recordLoadSubsetError(e,t,n=!1){const i=W(t);if(e.signal?.aborted&&!n)return i;this._lastError=i,this.primaryFailureDeliveryDepth++;try{this.emitInner("loadSubset:error",{type:"loadSubset:error",subscription:this,options:e,error:i})}finally{this.primaryFailureDeliveryDepth--}return i}emitEvents(e){if(this.unsubscribed)return!1;const t=this.filterAndFlipChanges(e);return e.length>0&&t.length===0||this.bufferPrivately(t)?!1:this.filteredCallback(t)}publishSnapshot(e){this.bufferPrivately(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const d=e.where;if(t.where){const h=t.where,l=Me(h,d);t.where=l}else t.where=d}}else this.loadedInitialState=!0;const n={where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit},{demand:i,result:r,started:o}=this.startSubsetDemand(n);if(!this.isDemandActive(i)||(e?.where&&this.requestedSubsetWhere.set(n,e.where),e?.onLoadSubsetResult?.(r,i.acquisition.options,d=>this.releaseDemand(i,d)),!this.isDemandActive(i))||(o&&this.observeLoadSubsetResult(r,i,i.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.isDemandActive(i)))return!1;let a;if(e?.onUnoptimized){if(a=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),a===void 0){if(e.onUnoptimized(),this.unsubscribed)return!1;a=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else a=this.collection.currentStateAsChanges(t);if(this.unsubscribed||a===void 0)return!1;const c=this.truncateReplaySession?.privateRows??this.publishedRows,u=a.filter(d=>!this.isBufferingForTruncate&&this.stalePublishedRows.has(d.key)||!this.sentKeys.has(d.key)&&!c.has(d.key));for(const d of u)this.sentKeys.add(d.key);return this.snapshotSent=!0,this.publishSnapshot(this.isBufferingForTruncate?u:this.reconcileStalePublishedChanges(u)),!0}releaseSnapshot(e){const t=this.subsetDemands.findIndex(n=>n.requestOptions.where===e||this.requestedSubsetWhere.get(n.requestOptions)===e);t!==-1&&this.releaseDemandAt(t)}releaseDemand(e,t){if(!t){const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n);return}try{this.recordLoadSubsetError(e.acquisition.options,t.error,!0)}finally{const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n,!1)}}releaseDemandAt(e,t=this.primaryFailureDeliveryDepth===0){const n=this.subsetDemands[e];if(!n)return;const i=this.truncateReplaySession,r=n.acquisition;this.subsetDemands.splice(e,1),n.initialResult?.reject(new $);const o=[()=>this.removeTruncateReplayParticipant(n),...n.acquisitionState==="active"?[()=>this.releaseAcquisition(r,t)]:[],()=>this.retireEmptyReplay(),()=>{i&&this.checkTruncateReplayComplete(i)},()=>this.stopDemandStatusParticipants(n)];Z(o)}retireEmptyReplay(){this.subsetDemands.length!==0||!this.truncateReplaySession||(this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.restorePublishedSnapshotTracking(),this.options.truncateReplayPublication?.succeed())}readOrderedSnapshot(e){const t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(i=>i!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((i,r)=>Me(i,r)):void 0});return Array.isArray(n)?n:[]}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:i,trackLoadSubsetPromise:r=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;if(!t)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const a=n?Cn(e,n):void 0,c=n!==void 0&&n.length>0,d=n?.[0],h=this.orderByIndex,l=this.options.whereExpression,p=l?te(l):void 0,f=C=>{if(C!==void 0&&this.sentKeys.has(C))return!1;const A=this.collection.get(C);return A===void 0?!1:p?.(A)??!0};let g=d;const w=[];let b=[];if(c){const{expression:C}=e[0],A=this.collection.currentStateAsChanges({where:Mt(C,new Q(d))});if(A){const V=A.map(D=>D.key).filter(D=>!this.sentKeys.has(D)&&f(D));b.push(...V);const R=h.take(t-b.length,d,f);b.push(...R)}else b=h.take(t,d,f)}else b=h.takeFromStart(t,f);const x=()=>Math.max(t-w.length,0),v=()=>b.length===0,k=e[0].expression,M=k.type==="ref"?zs(new Rt(k.path),!0):null;for(;x()>0&&!v();){for(const C of b){const A=this.collection.get(C);w.push({type:"insert",key:C,value:A}),g=M?M(A):A}b=h.take(x(),g,f)}const T=this.limitedSnapshotRowCount;for(const C of w)this.sentKeys.add(C.key);if(this.publishSnapshot(w),this.unsubscribed)return;this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,T+w.length),w.length>0&&(this.lastSentKey=w[w.length-1].key);let E;if(a&&n){const C=Rn(e,n);C&&(E={whereFrom:a,whereCurrent:C,lastKey:this.lastSentKey})}const m={where:l,limit:t,orderBy:e,cursor:E,offset:i??T,subscription:this},{demand:S,result:y,started:O}=this.startSubsetDemand(m);this.isDemandActive(S)&&(o?.(y,S.acquisition.options,C=>this.releaseDemand(S,C)),this.isDemandActive(S)&&(O&&this.observeLoadSubsetResult(y,S,S.acquisition.options,r),this.isDemandActive(S)))}filterAndFlipChanges(e){if(e=this.reconcileStalePublishedChanges(e),this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const i of e){let r=i;if(this.sentKeys.has(i.key)){if(i.type==="insert")continue;i.type==="delete"&&this.sentKeys.delete(i.key)}else if(i.type==="update")r={...i,type:"insert",previousValue:void 0},this.sentKeys.add(i.key);else if(i.type==="delete"){if(!t)continue}else this.sentKeys.add(i.key);n.push(r)}return n}reconcileStalePublishedChanges(e){if(this.stalePublishedRows.size===0)return e;const t=[];for(const n of e){const i=this.stalePublishedRows.get(n.key);if(i===void 0){t.push(n);continue}this.stalePublishedRows.delete(n.key),n.type==="delete"?t.push({...n,value:i,previousValue:void 0}):K(i,n.value)||t.push({...n,type:"update",previousValue:i})}if(this.collection.config.syncMode!=="on-demand"&&!this.isBufferingForTruncate)for(const[n,i]of this.stalePublishedRows)this.collection.has(n)||(this.stalePublishedRows.delete(n),t.push({type:"delete",key:n,value:i}));return t}trackPublishedRows(e){for(const t of e)t.type==="delete"?this.publishedRows.delete(t.key):this.publishedRows.set(t.key,t.value)}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(const 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(){if(this.unsubscribed)return;this.unsubscribed=!0,this.statusRevision++;const e=[this.truncateCleanup,this.collectionCleanup,this.collectionRestartCleanup];this.truncateCleanup=void 0,this.collectionCleanup=void 0,this.collectionRestartCleanup=void 0,Z([...e.map(t=>()=>t?.()),()=>{this.discardTruncateReplay(),this.stalePublishedRows.clear();const t=this.subsetDemands.filter(n=>n.acquisitionState==="active").map(n=>n.acquisition);for(const n of this.subsetDemands)n.initialResult?.reject(new $),this.stopDemandStatusParticipants(n),n.acquisitionState==="starting"&&oe(n.acquisition);this.subsetDemands=[],Z(t.map(n=>()=>this.releaseAcquisition(n)))},()=>this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),()=>this.clearListeners()])}}class Tn{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.publicationDeferralDepth=0,this.discardDeferredPublications=!1,this.deferredStateRevision=0,this.deferredLayoutRevision=0,this.deferredPublications=[],this.layoutChangeListeners=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){pt(()=>{try{Z([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){ft(e)}})}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let i=e;if(t){if(this.batchedEvents.length>0){const r=new Map(this.batchedEvents.map(o=>[o.key,o]));for(const o of e){const a=r.get(o.key);r.set(o.key,a?.type==="delete"&&o.type==="insert"?{...o,type:"update",previousValue:a.value}:o)}i=[...r.values()]}this.batchedEvents=[],this.shouldBatchEvents=!1}if(this.publicationDeferralDepth>0){this.deferredPublications.push({changes:i,layoutChanged:n});return}this.publishEvents(i,n)}deferPublication(){this.publicationDeferralDepth===0&&(this.deferredStateRevision=this.stateRevision,this.deferredLayoutRevision=this.layoutRevision),this.publicationDeferralDepth++;let e=!1;const t=n=>{if(e||(e=!0,this.publicationDeferralDepth===0)||(this.discardDeferredPublications||=n,this.publicationDeferralDepth--,this.publicationDeferralDepth>0))return;const i=this.deferredPublications;if(this.deferredPublications=[],this.discardDeferredPublications){this.discardDeferredPublications=!1,this.stateRevision=this.deferredStateRevision,this.layoutRevision=this.deferredLayoutRevision;return}this.publishEvents(i.flatMap(({changes:r})=>r),i.some(({layoutChanged:r})=>r))};return{publish:()=>t(!1),discard:()=>t(!0)}}publishEvents(e,t){if(e.length===0&&!t)return;const n=e.map(o=>this.enrichChangeWithVirtualProps(o)),i=[...this.layoutChangeListeners],r=[...this.changeSubscriptions];pt(()=>{const o=r.map(a=>()=>a.emitEvents(n));e.length===0&&o.unshift(...i);try{Z(o)}catch(a){ft(a)}})}subscribeLayoutChanges(e){return this.layoutChangeListeners.add(e),()=>this.layoutChangeListeners.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...i}=t;let r=i.whereExpression;if(n){const c=_t(),u=n(c);r=L(u)}this.addSubscriber();let o;const a={closed:!1};try{o=new On(this.collection,e,{...i,whereExpression:r,onUnsubscribe:()=>{a.closed=!0,this.removeSubscriber(),o&&this.changeSubscriptions.delete(o)}}),t.onStatusChange&&o.on("status:change",t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),a.closed||this.changeSubscriptions.add(o)}catch(c){if(o)try{o.unsubscribe()}catch{}else this.removeSubscriber();throw c}return o}addSubscriber(){const e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();try{(this.lifecycle.status==="cleaned-up"||this.lifecycle.status==="idle")&&this.sync.startSync()}catch(t){throw this.activeSubscribersCount=e,this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),t}this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new rs;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1,this.deferredPublications=[],this.publicationDeferralDepth=0}}const xn=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),En=s=>{clearTimeout(s)},Dn=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>xn(s),Pe=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):En,Ut=class ae{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}schedule(e,t,n){const i=Date.now()+t;this.tasks.set(e,{executeAt:i,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(const n of this.tasks.values())n.executeAt<e&&(e=n.executeAt);const t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;const e=Date.now();for(const[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(i){console.error("Error in CleanupQueue task:",i)}}this.tasks.size>0&&this.updateTimeout()}};Ut.instance=null;let Ie=Ut;class Pn{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.statusRevision=0,this.cleaningUp=!1,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)return;if(!{idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["ready","cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(t))throw new ns(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new ie(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=++this.statusRevision,i=this.status;this.status=e,this.events.emitStatusChange(e,i,()=>this.statusRevision===n)}validateCollectionUsable(e){switch(this.status){case"error":throw new ss(e,this.id);case"cleaned-up":this.sync.startSync();break}}markReady(){const e=this.applyReadyTransition();if(e)throw e.error}markReadyDuringSyncStart(){return this.applyReadyTransition()}applyReadyTransition(){if(this.validateStatusTransition(this.status,"ready"),this.status==="loading"||this.status==="error"){this.syncError=void 0;const e=this.statusRevision+1;if(this.setStatus("ready",!0),this.status!=="ready"||this.statusRevision!==e)return;const t=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0),t.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),t.push(()=>this.changes.emitEmptyReadyEvent());try{Z(t)}catch(n){return{error:n}}}}markError(e){this.validateStatusTransition(this.status,"error"),this.syncError=e,this.setStatus("error")}getSyncError(){return this.syncError}assertCanStartSync(){if(this.cleaningUp)throw new ie(`Cannot start collection "${this.id}" during cleanup. Restart after cleanup() completes.`)}startGCTimer(){const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Ie.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Ie.getInstance().cancel(this),this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Pe(this.idleCallbackId),this.idleCallbackId=Dn(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(this.cleaningUp)return!0;if(!e||e.timeRemaining()>0||e.didTimeout){this.cleaningUp=!0;try{this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Ie.getInstance().cancel(this),this.hasBeenReady=!1,this.syncError=void 0,this.onFirstReadyCallbacks=[]}finally{this.cleaningUp=!1}return this.setStatus("cleaned-up"),this.changes.activeSubscribersCount===0&&this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{const t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const In=Symbol("liveQueryInternal");class An{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.loadSubsetOperations=new Set,this.syncStartDeferred=!1,this.syncStartRequested=!1,this.deferredLoadSubsets=[],this.syncEpoch=0,this.loadSubsetSession=0,this.config=e,this.id=t,this.syncMode=e.syncMode??"eager"}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}markLayoutChange(){this.getActivePendingSyncTransaction().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up")return;if(this.syncStartDeferred){this.syncStartRequested=!0;return}const e=++this.syncEpoch,t=()=>e===this.syncEpoch;if(this.lifecycle.setStatus("loading"),!t())return;let n=!0,i;try{const r=_n(this.config.sync.sync({collection:this.collection,begin:o=>{if(!t())return;const a=se();a.promise.catch(()=>{}),this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:o?.immediate,applied:a})},write:o=>{if(!t())return;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Te;if(a.committed)throw new xe;let c;"key"in o?c=o.key:c=this.config.getKey(o.value),this.state.pendingLocalChanges.has(c)&&this.state.pendingLocalOrigins.add(c);let u=o.type;if(o.type==="insert"){const h=this.state.syncedData.has(c),l=a.deletedKeys.has(c),p=a.truncate===!0;if(h&&!l&&!p){const f=this.state.syncedData.get(c);if(f!==void 0&&K(f,o.value)||this.state.hydrationSeedKeys.has(c))u="update";else{const b=this.config.utils?.[In];throw new ls(c,this.id,{hasCustomGetKey:b?.hasCustomGetKey??!1,hasJoins:b?.hasJoins??!1,hasDistinct:b?.hasDistinct??!1})}}}const d={...o,type:u,key:c};a.operations.push(d),u==="delete"?(a.deletedKeys.add(c),a.rowMetadataWrites.set(c,{type:"delete"})):u==="insert"?d.metadata!==void 0?a.rowMetadataWrites.set(c,{type:"set",value:d.metadata}):a.rowMetadataWrites.set(c,{type:"delete"}):d.metadata!==void 0&&a.rowMetadataWrites.set(c,{type:"set",value:d.metadata})},commit:o=>{if(!t())return!0;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Cs;if(a.committed)throw new Rs;if(o?.aborted)return this.state.cancelPendingSyncedTransaction(a),a.applied.promise;a.committed=!0;const c=()=>{this.state.cancelPendingSyncedTransaction(a)};if(o?.addEventListener("abort",c,{once:!0}),this.state.commitPendingTransactions(),!a.applied.isPending())return o?.removeEventListener("abort",c),!0;const u=a.applied.promise;if(o){const d=()=>{o.removeEventListener("abort",c)};u.then(d,d)}return u},markReady:()=>{t()&&(n?i??=this.lifecycle.markReadyDuringSyncStart():this.lifecycle.markReady())},markError:o=>{t()&&this.lifecycle.markError(o)},truncate:()=>{if(!t())return;const o=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!o)throw new Te;if(o.committed)throw new xe;o.operations=[],o.deletedKeys.clear(),o.rowMetadataWrites.clear(),o.truncate=!0,o.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi(t)}));if(n=!1,!t()){if(r?.cleanup?.(),i)throw i.error;return}if(this.syncCleanupFn=r?.cleanup??null,this.syncLoadSubsetFn=r?.loadSubset??null,this.syncUnloadSubsetFn=r?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new ee(`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(r){throw n=!1,t()&&this.lifecycle.markError(r),r}if(i)throw i.error}deferStart(){return this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up"?!1:(this.syncStartDeferred=!0,!0)}resumeStart(){if(!this.syncStartDeferred)return;this.syncStartDeferred=!1;const e=this.syncStartRequested||this.deferredLoadSubsets.length>0;this.syncStartRequested=!1;const t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];const n=this.loadSubsetSession;try{e&&this.startSync()}catch(i){for(const{deferred:r}of t)r.reject(i);throw i}for(const{options:i,deferred:r}of t){const o=this.syncLoadSubsetFn;try{if(n!==this.loadSubsetSession||i.signal?.aborted)throw new $;const a=o?.(i)??!0;a instanceof Promise?a.then(c=>r.resolve(c),c=>r.reject(c)):r.resolve(void 0)}catch(a){r.reject(a)}}}getActivePendingSyncTransaction(){const e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Te;if(e.committed)throw new xe;return e}createSyncMetadataApi(e){return{row:{get:t=>{if(!e())return;const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],i=n?.rowMetadataWrites.get(t);if(i)return i.type==="delete"?void 0:i.value;if(!n?.truncate)return this.state.syncedMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"delete"})}},collection:{get:t=>{if(!e())return;const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return i?i.type==="delete"?void 0:i.value:this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"delete"})},list:t=>{if(!e())return[];const n=new Map(this.state.syncedCollectionMetadata),i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(i)for(const[r,o]of i.collectionMetadataWrites)o.type==="delete"?n.delete(r):n.set(r,o.value);return Array.from(n.entries()).filter(([r])=>t?r.startsWith(t):!0).map(([r,o])=>({key:r,value:o}))}}}}preload(){try{this.lifecycle.assertCanStartSync()}catch(t){return Promise.reject(t)}if(this.preloadPromise)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.`);const e=new Promise((t,n)=>{if(this.lifecycle.status==="ready"){t();return}if(this.lifecycle.status==="error"){n(this.getPreloadError());return}let i=!1;const r={active:!1,ready:!1};let o=()=>{},a=()=>{};const c=()=>{if(r.active){r.ready=!0;return}i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),t())},u=d=>{i||(i=!0,o(),a(),this.rejectPreload===u&&(this.rejectPreload=void 0),n(d))};if(this.rejectPreload=u,a=this.lifecycle.onFirstReady(c),o=this.collection.on("status:error",()=>{r.active||u(this.getPreloadError())}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up"){r.active=!0;let d;try{this.startSync()}catch(h){d={error:h}}finally{r.active=!1}this.collection.status==="error"?u(this.getPreloadError()):r.ready?c():d&&u(d.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}getPreloadError(){const e=this.lifecycle.getSyncError();return e===void 0?new is:e}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}beginLoadSubsetOperation(){const e=this.activeLoadSubsetOperation,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.activeLoadSubsetOperation=t,this.loadSubsetOperations.add(t),{wait:()=>this.waitForLoadSubsetOperation(t),cancel:()=>{t.completed=!0,this.loadSubsetOperations.delete(t),this.activeLoadSubsetOperation===t&&(this.activeLoadSubsetOperation=e?.completed?void 0:e)}}}waitForLoadSubsetOperation(e){return e.waiting=!0,e.pending.size===0?(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?Promise.reject(e.error):!0):(e.deferred=se(),e.deferred.promise)}settleLoadSubsetOperation(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}trackLoadSubsetOperationPromise(e){const t=this.activeLoadSubsetOperation;!t||t.pending.has(e)||(t.pending.add(e),e.then(()=>this.settleLoadSubsetOperation(t,e,{ok:!0}),n=>this.settleLoadSubsetOperation(t,e,{ok:!1,error:n})))}trackLoadPromise(e){const t=this.loadSubsetSession,n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),this.trackLoadSubsetOperationPromise(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"});const i=()=>{if(t!==this.loadSubsetSession)return;const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),r&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})};e.then(i,i)}getLoadSubsetSession(){return this.loadSubsetSession}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new $);if(this.syncMode==="eager")return!0;if(this.syncStartDeferred){this.syncStartRequested=!0;const t=se();return this.deferredLoadSubsets.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){const t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){if(this.syncMode!=="eager"){if(this.syncStartDeferred){this.deferredLoadSubsets=this.deferredLoadSubsets.filter(t=>t.options!==e?!0:(t.deferred.reject(new $),!1));return}this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}}cleanup(){const e=++this.syncEpoch;this.loadSubsetSession++,this.rejectPreload?.(new Es);const t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;try{t?.()}catch(r){this.syncEpoch===e&&(this.syncCleanupFn=t),queueMicrotask(()=>{if(r instanceof Error){const o=new et(this.id,r);throw o.cause=r,o.stack=r.stack,o}else throw new et(this.id,r)})}this.preloadPromise=null,this.syncStartDeferred=!1,this.syncStartRequested=!1;const n=this.pendingLoadSubsetPromises.size>0;this.pendingLoadSubsetPromises.clear(),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"}),this.activeLoadSubsetOperation=void 0;for(const r of this.loadSubsetOperations)r.completed||(r.completed=!0,r.pending.clear(),r.hasError=!0,r.error=new $,r.deferred?.reject(r.error));this.loadSubsetOperations.clear();const i=this.deferredLoadSubsets;this.deferredLoadSubsets=[];for(const r of i)r.deferred.reject(new $)}}function _n(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}const mt=1;function ge(s,e){return s===e?0:s<e?-1:1}function Mn(s){return{kind:"constructor",...s.name?{name:s.name}:{}}}function B(s){if(s==null)return s;switch(typeof s){case"string":case"boolean":return s;case"number":return Number.isFinite(s)?s:null;case"bigint":return{__type:"bigint",value:s.toString()};case"function":case"symbol":return;case"undefined":return}if(Array.isArray(s))return s.map(n=>B(n)??null);if(s instanceof Date)return{__type:"date",value:s.toISOString()};if(s instanceof Set)return{__type:"set",values:Array.from(s).map(i=>B(i)??null).sort((i,r)=>ge(J(i),J(r)))};if(s instanceof Map)return{__type:"map",entries:Array.from(s.entries()).map(([i,r])=>({key:B(i)??null,value:B(r)??null})).sort((i,r)=>ge(J(i.key),J(r.key)))};if(s instanceof RegExp)return{__type:"regexp",value:s.toString()};const e={},t=Object.entries(s).sort(([n],[i])=>ge(n,i));for(const[n,i]of t){const r=B(i);r!==void 0&&(e[n]=r)}return e}function J(s){return s===null?"null":Array.isArray(s)?`[${s.map(J).join(",")}]`:typeof s!="object"?JSON.stringify(s):`{${Object.keys(s).sort((n,i)=>ge(n,i)).map(n=>`${JSON.stringify(n)}:${J(s[n])}`).join(",")}}`}function Ln(s,e,t,n,i){const r=Mn(n),o=B(e)??null,a=B(i),u=B({signatureVersion:mt,expression:o,options:a??null})??null,d=J(u);return{signatureVersion:mt,signature:d,indexId:s,name:t,expression:e,resolver:r,...a===void 0?{}:{options:a}}}function Le(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(t=>Le(t));const e={};for(const[t,n]of Object.entries(s))e[t]=Le(n);return e}function Kn(s){return JSON.parse(JSON.stringify(s))}class Fn{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");const n=++this.indexCounter,i=_t(),r=e(i),o=L(r),a=t.indexType??this.defaultIndexType;if(!a)throw new ee(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
1
+ import{P as F,r as Ht,a as Gt,b as Yt,c as Te,s as Ye,d as Jt,e as Rt}from"./layout-DB3pMyTl.js";class Ue{}class Ot extends Ue{constructor(e){super(),this.path=e,this.type="ref"}}class Q extends Ue{constructor(e){super(),this.value=e,this.type="val"}}class q extends Ue{constructor(e,t){super(),this.name=e,this.args=t,this.type="func"}}function Je(s,e){if(typeof s==typeof e){if(typeof s=="number"&&typeof e=="number"){const t=Number.isNaN(s),n=Number.isNaN(e);if(t||n)return t&&n?0:t?1:-1}return s<e?-1:s>e?1:0}return typeof s=="string"?-1:1}Qt();function Qt(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}function Zt(){return Math.random()*(2**31-1)>>>0}const Xt=Zt(),Qe=new WeakMap;function es(s){ts(s)}let Ze=1;function ts(s){let e=Qe.get(s);return e===void 0&&(e=Ze^Xt,Ze++,Qe.set(s,e)),e}function le(){const s=typeof globalThis<"u"?globalThis.crypto:void 0;if(s&&typeof s.randomUUID=="function")return s.randomUUID();if(s&&typeof s.getRandomValues=="function"){const e=s.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[];for(let n=0;n<16;n++)t.push(e[n].toString(16).padStart(2,"0"));return t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10,16).join("")}throw new Error("No secure random number generator available: neither crypto.randomUUID nor crypto.getRandomValues is defined in this environment.")}class H extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class Xe extends H{constructor(e,t,n){const i=`${e==="insert"?"Insert":"Update"} validation failed: ${t.map(r=>`
2
+ - ${r.message} - path: ${r.path}`).join("")}`;super(n||i),this.name="SchemaValidationError",this.type=e,this.issues=t}}class ee extends H{constructor(e){super(e),this.name="CollectionConfigurationError"}}class ss extends ee{constructor(){super("Collection requires a config")}}class ns extends ee{constructor(){super("Collection requires a sync config")}}class is extends ee{constructor(){super("Schema must implement the standard-schema interface")}}class et extends ee{constructor(){super("Schema validation must be synchronous")}}class ie extends H{constructor(e){super(e),this.name="CollectionStateError"}}class rs extends ie{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class os extends ie{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}}class as extends ie{constructor(){super("Collection is in error state")}}class cs extends ie{constructor(){super("Active subscribers count is negative - this should never happen")}}class j extends H{constructor(e){super(e),this.name="CollectionOperationError"}}class ls extends j{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class us extends j{constructor(e,t){const n=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${n}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}}class ds extends j{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class hs extends j{constructor(e,t,n){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${i}. 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(`${i}. 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(i)}}class fs extends j{constructor(){super("The first argument to update is missing")}}class ps extends j{constructor(){super("No keys were passed to update")}}class ys extends j{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class ms extends j{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.`)}}class gs extends j{constructor(){super("No keys were passed to delete")}}class Ss extends j{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class Ve extends H{constructor(e){super(e),this.name="MissingHandlerError"}}class bs extends Ve{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class ws extends Ve{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class vs extends Ve{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class G extends H{constructor(e){super(e),this.name="TransactionError"}}class ks extends G{constructor(){super("mutationFn is required when creating a transaction")}}class Cs extends G{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class Rs extends G{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class Os extends G{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Ee extends G{constructor(){super("No pending sync transaction to write to")}}class xe extends G{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Ts extends G{constructor(){super("No pending sync transaction to commit")}}class Es extends G{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class $e extends H{constructor(e){super(e),this.name="QueryCompilationError"}}class xs extends $e{constructor(e){super(`Unknown expression type: ${e}`)}}class Ds extends $e{constructor(){super("Reference path cannot be empty")}}class Is extends $e{constructor(e){super(`Unknown function: ${e}`)}}class tt extends H{constructor(e,t){const n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name="SyncCleanupError"}}class st extends Error{constructor(){super("Sync transaction was aborted before application"),this.name="AbortError"}}class Ps extends Error{constructor(){super("Collection preload was abandoned during cleanup"),this.name="AbortError"}}class $ extends Error{constructor(){super("Load subset operation was aborted before its result became visible"),this.name="AbortError"}}function K(s,e){return pe(s,e,new Map)}function nt(s){const e=Object.keys(s);for(const t of Object.getOwnPropertySymbols(s))Object.prototype.propertyIsEnumerable.call(s,t)&&e.push(t);return e}function pe(s,e,t){if(s===e)return!0;if(s==null||e==null||typeof s!=typeof e)return!1;if(s instanceof Date)return e instanceof Date?s.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(s instanceof RegExp)return e instanceof RegExp?s.source===e.source&&s.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(s instanceof Map){if(!(e instanceof Map)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const i=Array.from(s.entries()).every(([r,o])=>e.has(r)&&pe(o,e.get(r),t));return t.delete(s),i}if(e instanceof Map)return!1;if(s instanceof Set){if(!(e instanceof Set)||s.size!==e.size)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=Array.from(s),i=Array.from(e);if(n.every(o=>typeof o!="object"))return t.delete(s),n.every(o=>e.has(o));const r=n.length===i.length;return t.delete(s),r}if(e instanceof Set)return!1;if(ArrayBuffer.isView(s)&&ArrayBuffer.isView(e)&&!(s instanceof DataView)&&!(e instanceof DataView)){const n=s,i=e;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!==i[r])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(s))return!1;if(z(s)&&z(e)){const n=s[Symbol.toStringTag],i=e[Symbol.toStringTag];return n!==i?!1:typeof s.equals=="function"?s.equals(e):s.toString()===e.toString()}if(z(e))return!1;if(Array.isArray(s)){if(!Array.isArray(e)||s.length!==e.length)return!1;if(t.has(s))return t.get(s)===e;t.set(s,e);const n=s.every((i,r)=>pe(i,e[r],t));return t.delete(s),n}if(Array.isArray(e))return!1;if(typeof s=="object"){if(t.has(s))return t.get(s)===e;t.set(s,e);const n=nt(s),i=nt(e);if(n.length!==i.length)return t.delete(s),!1;const r=n.every(o=>Object.prototype.propertyIsEnumerable.call(e,o)&&pe(s[o],e[o],t));return t.delete(s),r}return!1}const As=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function z(s){if(s==null||typeof s!="object")return!1;const e=s[Symbol.toStringTag];return typeof e=="string"&&As.has(e)}const ve={direction:"asc",nulls:"first",stringSort:"locale"};function _s(){const s=new WeakMap;let e,t,n,i=0;const r=(o,a)=>{let c=o.get(a);return c===void 0&&(c=++i,o.set(a,c)),c};return o=>{n??=Ls();let a;if(typeof o=="symbol"){const c=Symbol.keyFor(o);c===void 0?(e??=Ms(),a=r(e,o)):(t??=new Map,a=r(t,c))}else a=r(s,o);return["runtimeReference",n,a]}}function Ms(){const s=new WeakMap,e=Symbol();try{if(s.set(e,0),s.get(e)===0)return s}catch{}return new Map}let it;function rt(s){return it??=_s(),it(s)}function Ls(){const s=new Uint32Array(4),e=Reflect.get(globalThis,"crypto");return typeof e?.getRandomValues=="function"?(e.getRandomValues(s),Array.from(s,t=>t.toString(36)).join("-")):`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}const De=new WeakMap;let Ks=1;function ot(s){if(De.has(s))return De.get(s);const e=Ks++;return De.set(s,e),e}function P(s){return typeof s=="number"&&Number.isNaN(s)||s instanceof Date&&Number.isNaN(s.getTime())}const ze=(s,e,t)=>{const{nulls:n}=t;if(s==null&&e==null)return 0;if(s==null)return n==="first"?-1:1;if(e==null)return n==="first"?1:-1;const i=P(s),r=P(e);if(i&&r)return 0;if(i)return 1;if(r)return-1;if(typeof s=="string"&&typeof e=="string"&&t.stringSort==="locale")return s.localeCompare(e,t.locale,t.localeOptions);if(Array.isArray(s)&&Array.isArray(e)){for(let u=0;u<Math.min(s.length,e.length);u++){const h=ze(s[u],e[u],t);if(h!==0)return h}return s.length-e.length}if(s instanceof Date&&e instanceof Date)return s.getTime()-e.getTime();if(z(s)&&z(e))return xt(s,e);const o=typeof s=="symbol",a=typeof e=="symbol";if(o&&a)return s===e?0:rt(s)[2]-rt(e)[2];if(o)return 1;if(a)return-1;const c=typeof s=="object",d=typeof e=="object";if(c||d){if(c&&d){const u=ot(s),h=ot(e);return u-h}if(c)return 1;if(d)return-1}return s<e?-1:s>e?1:0},Fs=(s,e,t)=>ze(e,s,{...t,nulls:t.nulls==="first"?"last":"first"});function Tt(s){return(e,t)=>s.direction==="asc"?ze(e,t,s):Fs(e,t,s)}function Se(s){return s instanceof Uint8Array||typeof Buffer<"u"&&s instanceof Buffer}function Us(s,e){if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}const Et="\0tanstack-db:";function Me(s,e){return`${Et}${s}:${e}`}function Vs(s){let e="";for(let t=0;t<s.byteLength;t++)e+=String.fromCharCode(s[t]);return Me("binary",e)}function $s(s){return typeof s=="string"?s.startsWith(Et)?Me("string",s):s:typeof s!="object"||s===null?s:s instanceof Date?s.getTime():z(s)?Me("temporal",`${s[Symbol.toStringTag]}:${s.toString()}`):Se(s)?Vs(s):s}const at=new Map;function xt(s,e){const t=s[Symbol.toStringTag],n=e[Symbol.toStringTag];if(t!==n)throw new TypeError(`Cannot order Temporal values of different types: ${t} vs ${n}`);let i=at.get(t);if(i===void 0){const r=s.constructor.compare;i=typeof r=="function"?r:null,at.set(t,i)}if(i===null)throw new TypeError(`${t} has no defined ordering`);return i(s,e)}function he(s,e){return z(s)&&z(e)?xt(s,e):s<e?-1:s>e?1:0}function zs(s,e){return s===e?!0:Se(s)&&Se(e)?Us(s,e):!1}function M(s){return s==null}function fe(s){return Se(s)?s:$s(s)}function ct(s,e){return P(s)||P(e)?P(s)&&P(e):zs(s,e)}function Ie(s){if(s instanceof Date)return Number.isNaN(s.getTime())?null:s;if(typeof s=="string"||typeof s=="number"){const e=new Date(s);return Number.isNaN(e.getTime())?null:e}return null}function js(s,e){return s==="%Y-%m-%d"?e.toISOString().slice(0,10):e.toISOString()}function qs(s){return s===!0}function Ns(s,e=!1){return je(s,e)}function Dt(s){return je(s,!0)}function je(s,e){switch(s.type){case"val":{const t=s.value;return()=>t}case"ref":return e?Bs(s):Ws(s);case"func":return Hs(s,e);default:throw new xs(s.type)}}function Ws(s){const[e,...t]=s.path;if(!e)throw new Ds;if(e==="$selected"){if(t.length===0)return i=>i.$selected;if(t.length===1){const i=t[0];return r=>r.$selected?.[i]}else return i=>{const r=i.$selected;if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}const n=e;if(t.length===0)return i=>i[n];if(t.length===1){const i=t[0];return r=>r[n]?.[i]}else return i=>{const r=i[n];if(r===void 0)return;let o=r;for(const a of t){if(o==null)return o;o=o[a]}return o}}function Bs(s){const e=s.path;return t=>{let n=t;for(const i of e){if(n==null)return n;n=n[i]}return n}}function Hs(s,e){const t=s.args.map(n=>je(n,e));switch(s.name){case"eq":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=fe(i(r));return M(o)||M(a)?null:ct(o,a)}}case"gt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:P(o)||P(a)?P(o)&&!P(a):he(o,a)>0}}case"gte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:P(o)||P(a)?P(o):he(o,a)>=0}}case"lt":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:P(o)||P(a)?P(a)&&!P(o):he(o,a)<0}}case"lte":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:P(o)||P(a)?P(a):he(o,a)<=0}}case"and":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!1)return!1;M(o)&&(i=!0)}return i?null:!0};case"or":return n=>{let i=!1;for(const r of t){const o=r(n);if(o===!0)return!0;M(o)&&(i=!0)}return i?null:!1};case"not":{const n=t[0];return i=>{const r=n(i);return M(r)?null:!r}}case"in":{const n=t[0],i=t[1];return r=>{const o=fe(n(r)),a=i(r);return M(o)?null:Array.isArray(a)?a.some(c=>ct(fe(c),o)):!1}}case"like":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:lt(o,a,!1)}}case"ilike":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return M(o)||M(a)?null:lt(o,a,!0)}}case"upper":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toUpperCase():r}}case"lower":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"?r.toLowerCase():r}}case"length":{const n=t[0];return i=>{const r=n(i);return typeof r=="string"||Array.isArray(r)?r.length:0}}case"concat":return n=>t.map(i=>{const r=i(n);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return n=>{for(const i of t){const r=i(n);if(r!=null)return r}return null};case"caseWhen":{const n=t.length%2===1,i=Math.floor(t.length/2);if(t.length<2)throw new Error("caseWhen() requires at least two arguments");return r=>{for(let o=0;o<i;o++){const a=t[o*2];if(Gs(a(r))){const c=t[o*2+1];return c(r)}}return n?t[t.length-1](r):null}}case"add":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)+(a??0)}}case"subtract":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)-(a??0)}}case"multiply":{const n=t[0],i=t[1];return r=>{const o=n(r),a=i(r);return(o??0)*(a??0)}}case"divide":{const n=t[0],i=t[1];return r=>{const o=n(r),c=i(r)??0;return c!==0?(o??0)/c:null}}case"date":{const n=t[0];return i=>{const r=n(i),o=Ie(r);return o?o.toISOString().slice(0,10):null}}case"datetime":{const n=t[0];return i=>{const r=n(i),o=Ie(r);return o?o.toISOString():null}}case"strftime":{const n=t[0],i=t[1];return r=>{const o=n(r);if(typeof o!="string")return null;const a=i(r),c=Ie(a);return c?js(o,c):null}}case"isUndefined":{const n=t[0];return i=>n(i)===void 0}case"isNull":{const n=t[0];return i=>n(i)===null}default:throw new Is(s.name)}}function Gs(s){return s==null||s===!1?!1:s===!0?!0:typeof s=="number"?s!==0&&!Number.isNaN(s):typeof s=="bigint"?s!==0n:!!s}function lt(s,e,t){if(typeof s!="string"||typeof e!="string")return!1;const n=t?s.toLowerCase():s;let r=(t?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r=r.replace(/%/g,".*"),r=r.replace(/_/g,"."),new RegExp(`^${r}$`,"s").test(n)}class Ys{constructor(e){this.originalIndex=e}lookup(e,t){const 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)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}supports(e){return this.originalIndex.supports(e)}get supportsRangeOptimization(){return this.originalIndex.supportsRangeOptimization}canOptimizeRangeFor(e){return this.originalIndex.canOptimizeRangeFor?.(e)??!0}get keyCount(){return this.originalIndex.keyCount}}function ut(s,e,t,n,i){const r=s;return{...s,$synced:r.$synced??n(),$origin:r.$origin??i(),$key:r.$key??e,$collectionId:r.$collectionId??t}}const Js=["$synced","$origin","$key","$collectionId"];function Qs(s){return Js.includes(s)}function It(s){return s.some(e=>Qs(e))}function ke(s,e,t){if(It(e))return;const n=t??{...ve,...s.compareOptions};for(const i of s.indexes.values())if(i.matchesField(e)&&i.matchesCompareOptions(n))return i.matchesDirection(n.direction)?i:new Ys(i)}function Zs(s){if(s.length===0)return new Set;if(s.length===1)return new Set(s[0]);let e=new Set(s[0]);for(let t=1;t<s.length;t++){const n=new Set;for(const i of e)s[t].has(i)&&n.add(i);e=n}return e}function Xs(s){const e=new Set;for(const t of s)for(const n of t)e.add(n);return e}function qe(s){return s!=null}function en(s){return{...ve,...s.compareOptions}.stringSort==="locale"}function tn(s,e){switch(typeof s){case"number":case"bigint":case"boolean":return!1;case"string":return en(e);case"symbol":return!0;case"object":return s===null?!1:!(s instanceof Date);default:return!1}}function Pt(s,e,t){return!tn(s,t)&&e.supportsRangeOptimization&&(e.canOptimizeRangeFor?.(s)??!0)}function sn(s,e){return Ne(s,e)}function Ne(s,e){if(s.type==="func")switch(s.name){case"eq":case"gt":case"gte":case"lt":case"lte":return rn(s,e);case"and":return on(s,e);case"or":return an(s,e);case"in":return cn(s,e)}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function nn(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set};const t=new Map;for(const[n,i]of s.args.entries())if(i.type==="func"&&["gt","gte","lt","lte"].includes(i.name)){const r=i;if(r.args.length===2){const o=r.args[0],a=r.args[1];let c=null,d=null,u=r.name;if(o.type==="ref"&&a.type==="val")c=o,d=a;else if(o.type==="val"&&a.type==="ref")switch(c=a,d=o,u){case"gt":u="lt";break;case"gte":u="lte";break;case"lt":u="gt";break;case"lte":u="gte";break}if(c&&d){const l=c.path.join("."),f=d.value;t.has(l)||t.set(l,[]),t.get(l).push({operation:u,value:f,argIndex:n})}}}for(const[n,i]of t)if(i.length>=2){const r=n.split("."),o=ke(e,r);if(o&&i.some(a=>!Pt(a.value,o,e)))continue;if(o&&o.supports("gt")&&o.supports("lt")){const a=Tt({...ve,...e.compareOptions,direction:"asc"});let c,d,u=!1,h=!1,l=!0,f=!0,p=!1;for(const{operation:b,value:T}of i){if(!qe(T)){p=!0;continue}switch(b){case"gt":case"gte":{const v=u?a(T,c):1;v>0?(c=T,u=!0,l=b==="gte"):v===0&&b==="gt"&&(l=!1);break}case"lt":case"lte":{const v=h?a(T,d):-1;v<0?(d=T,h=!0,f=b==="lte"):v===0&&b==="lt"&&(f=!1);break}}}const y={};return u&&(y.from=c,y.fromInclusive=l),h&&(y.to=d,y.toInclusive=f),{canOptimize:!0,matchingKeys:o.rangeQuery(y),isExact:u&&!p,coveredArgIndices:new Set(i.map(b=>b.argIndex))}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1,coveredArgIndices:new Set}}function rn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];let i=null,r=null,o=s.name;if(t.type==="ref"&&n.type==="val")i=t,r=n;else if(t.type==="val"&&n.type==="ref")switch(i=n,r=t,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(i&&r){const a=i.path,c=ke(e,a);if(c){const d=r.value,u=o;if(!c.supports(u))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};if((o==="gt"||o==="gte"||o==="lt"||o==="lte")&&!Pt(d,c,e))return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const h=c.lookup(u,d),l=o==="lt"||o==="lte"?!1:qe(d);return{canOptimize:!0,matchingKeys:h,isExact:l}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function on(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=nn(s,e),n=t.canOptimize?t.coveredArgIndices:new Set,i=[];t.canOptimize&&i.push(t);let r=t.canOptimize?t.isExact:!0;for(const[o,a]of s.args.entries()){if(n.has(o))continue;const c=Ne(a,e);c.canOptimize?(i.push(c),c.isExact||(r=!1)):r=!1}if(i.length>0){const o=i.map(c=>c.matchingKeys);return{canOptimize:!0,matchingKeys:Zs(o),isExact:r}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function an(s,e){if(s.type!=="func"||s.args.length<2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=[];for(const r of s.args){const o=Ne(r,e);if(!o.canOptimize)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};t.push(o)}const n=t.map(r=>r.matchingKeys);return{canOptimize:!0,matchingKeys:Xs(n),isExact:t.every(r=>r.isExact)}}function cn(s,e){if(s.type!=="func"||s.args.length!==2)return{canOptimize:!1,matchingKeys:new Set,isExact:!1};const t=s.args[0],n=s.args[1];if(t.type==="ref"&&n.type==="val"&&Array.isArray(n.value)){const i=t.path,r=n.value,o=ke(e,i),a=r.every(c=>qe(c));if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",r),isExact:a};if(o.supports("eq")){const c=new Set;for(const d of r){const u=o.lookup("eq",d);for(const h of u)c.add(h)}return{canOptimize:!0,matchingKeys:c,isExact:a}}}}return{canOptimize:!1,matchingKeys:new Set,isExact:!1}}function At(s){return s.config.autoIndex==="eager"}function _t(s,e,t,n,i){if(It(e)||!At(t))return;const r=n??{...ve,...t.compareOptions};if(!Array.from(t.indexes.values()).find(a=>a.matchesField(e)&&a.matchesCompareOptions(r)))try{t.createIndex(a=>{let c=a;for(const d of e)c=c[d];return c},{name:`auto:${e.join(".")}`,options:i?{compareFn:i,compareOptions:r}:{}})}catch(a){console.warn(`${t.id?`[${t.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,a)}}function ln(s,e){if(!At(e))return;const t=un(s);for(const{fieldName:n,fieldPath:i}of t)_t(n,i,e)}function un(s){const e=[];function t(n){if(n.type!=="func")return;const i=n;if(i.name==="and"){for(const d of i.args)t(d);return}if(!["eq","gt","gte","lt","lte","in"].includes(i.name)||i.args.length<1||i.args[0].type!=="ref")return;const a=i.args[0].path;if(a.length===0)return;const c=a.join("_");e.push({fieldName:c,fieldPath:a})}return t(s),e}function dn(s,e){return hn(s,e.compareOptions)}function hn(s,e){return s.compareOptions.stringSort===void 0?{...e,direction:s.compareOptions.direction,nulls:s.compareOptions.nulls}:s.compareOptions}function fn(s,e={}){const t=n=>{const i=[];for(const[r,o]of s.entries())(n?.(o)??!0)&&i.push({type:"insert",key:r,value:o});return i};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const n=e.where?te(e.where):void 0,i=yn(s,e.orderBy,e.limit,n,e.optimizedOnly);if(i===void 0)return;const r=[];for(const o of i){const a=s.get(o);a!==void 0&&r.push({type:"insert",key:o,value:a})}return r}if(!e.where)return t();try{const n=e.where,i=sn(n,s);if(i.canOptimize){const r=i.isExact?void 0:te(n),o=[];for(const a of i.matchingKeys){const c=s.get(a);c!==void 0&&(r?.(c)??!0)&&o.push({type:"insert",key:a,value:c})}return o}else{if(e.optimizedOnly)return;const r=te(n);return t(r)}}catch(n){console.warn(`${s.id?`[${s.id}] `:""}Error processing where clause, falling back to full scan:`,n);const i=te(e.where);return e.optimizedOnly?void 0:t(i)}}function te(s){const e=Dt(s);return t=>{try{const n=e(t);return qs(n)}catch{return!1}}}function pn(s,e){const t=te(e.whereExpression);return n=>{const i=[];for(const r of n)if(r.type==="insert")t(r.value)&&i.push(r);else if(r.type==="update"){const o=t(r.value),a=r.previousValue?t(r.previousValue):!1;o&&a?i.push(r):o&&!a?i.push({...r,type:"insert"}):!o&&a&&i.push({...r,type:"delete",value:r.previousValue})}else t(r.value)&&i.push(r);return i.length>0||n.length===0?(s(i),!0):!1}}function yn(s,e,t,n,i){if(e.length===1){const c=e[0],d=c.expression;if(d.type==="ref"){const h=d.path,l=dn(c,s);_t(h[0],h,s,l);const f=ke(s,h,l);if(f&&f.supports("gt")){const p=y=>{const w=s.get(y);return w===void 0?!1:n?.(w)??!0};return f.takeFromStart(t??f.keyCount,p)}}}if(i)return;const r=[];for(const[c,d]of s.entries())(n?.(d)??!0)&&r.push({key:c,value:d});const o=(c,d)=>{for(const u of e){const h=Tt(u.compareOptions),l=dt(c.value,u.expression),f=dt(d.value,u.expression),p=h(l,f);if(p!==0)return p}return 0};r.sort(o);const a=r.map(c=>c.key);return t!==void 0?a.slice(0,t):a}function dt(s,e){if(e.type==="ref"){const t=e;let n=s;for(const i of t.path)n=n?.[i];return n}else return e.type==="val"?e.value:Dt(e)(s)}class ht{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,i=this.sortedKeys.length;if(!this.comparator){for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=Je(e,o);if(a<0)i=r;else if(a>0)n=r+1;else return r}return n}for(;n<i;){const r=Math.floor((n+i)/2),o=this.sortedKeys[r],a=this.map.get(o),c=this.comparator(t,a);if(c<0)i=r;else if(c>0)n=r+1;else{const d=Je(e,o);if(d<0)i=r;else if(d>0)n=r+1;else return r}}return n}set(e,t){if(this.map.has(e)){const i=this.map.get(e),r=this.indexOf(e,i);this.sortedKeys.splice(r,1)}const 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)){const 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(const 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(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const t of this.sortedKeys)e(this.map.get(t),t,this.map)}}const ye="__tanstack_db_direct";class mn{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.hydrationSeedKeys=new Set,this.hydratedKeys=new Set,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.preSyncVisibleState=new Map,this.preSyncVirtualState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isDrainingSyncTransactions=!1,this.syncSessionGeneration=0,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{if(this.isDrainingSyncTransactions)return;this.isDrainingSyncTransactions=!0;let t=!1,n;try{let i;do i=this.commitNextPendingTransactionBatch(),i.failure&&!t&&(t=!0,n=i.failure.error);while(i.processed)}finally{this.isDrainingSyncTransactions=!1}if(t)throw n},this.config=e,this.transactions=new ht((t,n)=>t.compareCreatedAt(n)),this.syncedData=new ht(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"});const n=t?.optimisticUpserts??this.optimisticUpserts,i=t?.optimisticDeletes??this.optimisticDeletes,r=n.has(e)||i.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!r,$origin:r?"local":(t?.rowOrigins??this.rowOrigins).get(e)??"remote"})}snapshotRowOriginsForKeys(e){const t=new Map;for(const n of e){const i=this.rowOrigins.get(n);i!==void 0&&t.set(n,i)}return t}enrichWithVirtualPropsSnapshot(e,t){const n=e,i=n.$synced??t.$synced,r=n.$origin??t.$origin,o=n.$key??t.$key,a=n.$collectionId??t.$collectionId,c=this.virtualPropsCache.get(e);if(c&&c.synced===i&&c.origin===r&&c.key===o&&c.collectionId===a)return c.enriched;const d={...e,$synced:i,$origin:r,$key:o,$collectionId:a};return this.virtualPropsCache.set(e,{synced:i,origin:r,key:o,collectionId:a,enriched:d}),d}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){const{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),i=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:i,metadata:e.metadata}}getWithVirtualProps(e){const t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;if(!t.has(e))return n.has(e)?n.get(e):i.get(e)}has(e){const{optimisticDeletes:t,optimisticUpserts:n,syncedData:i}=this;return t.has(e)?!1:n.has(e)?!0:i.has(e)}*keys(){const{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(const i of e.keys())t.has(i)||(yield i);for(const i of n.keys())!e.has(i)&&!t.has(i)&&(yield i)}*values(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(const[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;const t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),i=this.rowOrigins;for(const h of this.transactions.values()){const l=h.metadata[ye]===!0;if(h.state==="completed"){for(const f of h.mutations)if(this.isThisCollection(f.collection)&&(this.pendingLocalOrigins.add(f.key),!!f.optimistic))switch(f.type){case"insert":case"update":this.pendingOptimisticUpserts.set(f.key,f.modified),this.pendingOptimisticDeletes.delete(f.key),l?(this.pendingOptimisticDirectUpserts.add(f.key),this.pendingOptimisticDirectDeletes.delete(f.key)):(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key));break;case"delete":this.pendingOptimisticUpserts.delete(f.key),this.pendingOptimisticDeletes.add(f.key),l?(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.add(f.key)):(this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key));break}}else if(h.state==="failed")for(const f of h.mutations)this.isThisCollection(f.collection)&&(this.pendingLocalOrigins.delete(f.key),f.optimistic&&(this.pendingOptimisticUpserts.delete(f.key),this.pendingOptimisticDeletes.delete(f.key),this.pendingOptimisticDirectUpserts.delete(f.key),this.pendingOptimisticDirectDeletes.delete(f.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const r=new Set;for(const h of this.pendingSyncedTransactions)for(const l of h.operations)r.add(l.key);const o=[];for(const[h,l]of this.pendingOptimisticUpserts)r.has(h)||this.pendingOptimisticDirectUpserts.has(h)?this.optimisticUpserts.set(h,l):o.push(h);for(const h of o)this.pendingOptimisticUpserts.delete(h),this.pendingLocalOrigins.delete(h);const a=[];for(const h of this.pendingOptimisticDeletes)r.has(h)||this.pendingOptimisticDirectDeletes.has(h)?this.optimisticDeletes.add(h):a.push(h);for(const h of a)this.pendingOptimisticDeletes.delete(h),this.pendingLocalOrigins.delete(h);const c=[];for(const h of this.transactions.values())["completed","failed"].includes(h.state)||c.push(h);for(const h of c)for(const l of h.mutations)if(this.isThisCollection(l.collection)&&(this.pendingLocalChanges.add(l.key),l.optimistic))switch(l.type){case"insert":case"update":this.optimisticUpserts.set(l.key,l.modified),this.optimisticDeletes.delete(l.key);break;case"delete":this.optimisticUpserts.delete(l.key),this.optimisticDeletes.add(l.key);break}this.size=this.calculateSize();const d=[];this.collectOptimisticChanges(t,n,i,d);const u=d.filter(h=>!!(!this.recentlySyncedKeys.has(h.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const h=new Set;for(const f of this.pendingSyncedTransactions)for(const p of f.operations)h.add(p.key);const l=u.filter(f=>!(f.type==="delete"&&h.has(f.key)&&!c.some(y=>y.mutations.some(w=>this.isThisCollection(w.collection)&&w.key===f.key))));l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}else u.length>0&&this.indexes.updateIndexes(u),this.changes.emitEvents(u,e)}calculateSize(){const e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(i=>this.syncedData.has(i)&&!this.optimisticUpserts.has(i)).length,n=Array.from(this.optimisticUpserts.keys()).filter(i=>!this.syncedData.has(i)).length;return e-t+n}collectOptimisticChanges(e,t,n,i){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(const o of r){const a=this.get(o),c=this.getPreviousValue(o,e,t),d=this.getVirtualPropsSnapshotForState(o,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),u=this.getVirtualPropsSnapshotForState(o);c!==void 0&&a===void 0?i.push({type:"delete",key:o,value:c,__virtualProps:{value:d}}):c===void 0&&a!==void 0?i.push({type:"insert",key:o,value:a,__virtualProps:{value:u}}):c!==void 0&&a!==void 0&&c!==a&&i.push({type:"update",key:o,value:a,previousValue:c,__virtualProps:{value:u,previousValue:d}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}commitNextPendingTransactionBatch(){const e=this.syncSessionGeneration;let t=!1;for(const c of this.transactions.values())if(c.state==="persisting"){t=!0;break}const{committedSyncedTransactions:n,uncommittedSyncedTransactions:i,hasTruncateSync:r,hasImmediateSync:o,layoutChanged:a}=this.pendingSyncedTransactions.reduce((c,d)=>(d.committed?(c.committedSyncedTransactions.push(d),c.layoutChanged||=d.layoutChanged,d.truncate&&(c.hasTruncateSync=!0),d.immediate&&(c.hasImmediateSync=!0)):c.uncommittedSyncedTransactions.push(d),c),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1,layoutChanged:!1});if(n.length===0)return{processed:!1};if(!t||r||o){const c=a?[...this.keys()]:void 0;this.pendingSyncedTransactions=i;for(const g of n)g.applicationStarted=!0;this.isCommittingSyncTransactions=!0;const d=r?n.find(g=>g.truncate)?.optimisticSnapshot:null;let u,h;const l=new Set;for(const g of n){for(const S of g.operations)l.add(S.key);for(const[S]of g.rowMetadataWrites)l.add(S)}const f=new Set(l);for(const g of this.pendingOptimisticDirectUpserts)f.add(g);for(const g of this.pendingOptimisticDirectDeletes)f.add(g);const p=this.snapshotRowOriginsForKeys(f),y=new Map(this.optimisticUpserts),w=new Set(this.optimisticDeletes),b=new Set(this.pendingOptimisticDirectUpserts),T=new Set(this.pendingOptimisticDirectDeletes);let v=this.preSyncVisibleState;if(v.size===0){v=new Map;for(const g of l){const S=this.get(g);S!==void 0&&v.set(g,S)}}const k=[],A=this.config.sync.rowUpdateMode||"partial",E=new Map;for(const g of this.transactions.values())if(g.state==="completed")for(const S of g.mutations)this.isThisCollection(S.collection)&&S.optimistic&&E.set(S.key,{type:S.type,value:S.modified});for(const g of n){if(g.truncate){const S=new Set([...this.syncedData.keys(),...d?.upserts.keys()||[]]);for(const m of S){if(d?.deletes.has(m))continue;const O=d?.upserts.get(m)||this.syncedData.get(m);O!==void 0&&k.push({type:"delete",key:m,value:O})}u=new Set(this.pendingLocalChanges),h=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState();for(const m of l)v.delete(m);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const S of g.operations){const m=S.key,O=(u?.has(m)===!0||h?.has(m)===!0)&&!b.has(m)&&!T.has(m),C=this.isLocalOnly||this.pendingLocalChanges.has(m)||this.pendingLocalOrigins.has(m)||O?"local":"remote";switch(S.type){case"insert":this.syncedData.set(m,S.value),this.rowOrigins.set(m,C),this.pendingLocalChanges.delete(m),this.pendingLocalOrigins.delete(m),this.pendingOptimisticUpserts.delete(m),this.pendingOptimisticDeletes.delete(m),this.pendingOptimisticDirectUpserts.delete(m),this.pendingOptimisticDirectDeletes.delete(m);break;case"update":{if(A==="partial"){const _=Object.assign({},this.syncedData.get(m),S.value);this.syncedData.set(m,_)}else this.syncedData.set(m,S.value);this.rowOrigins.set(m,C),this.pendingLocalChanges.delete(m),this.pendingLocalOrigins.delete(m),this.pendingOptimisticUpserts.delete(m),this.pendingOptimisticDeletes.delete(m),this.pendingOptimisticDirectUpserts.delete(m),this.pendingOptimisticDirectDeletes.delete(m);break}case"delete":this.syncedData.delete(m),this.syncedMetadata.delete(m),this.rowOrigins.delete(m),this.pendingLocalChanges.delete(m),this.pendingLocalOrigins.delete(m),this.pendingOptimisticUpserts.delete(m),this.pendingOptimisticDeletes.delete(m),this.pendingOptimisticDirectUpserts.delete(m),this.pendingOptimisticDirectDeletes.delete(m);break}g.preserveHydrationSeedKeys||(this.hydrationSeedKeys.delete(m),this.hydratedKeys.delete(m))}for(const[S,m]of g.rowMetadataWrites){if(m.type==="delete"){this.syncedMetadata.delete(S);continue}this.syncedMetadata.set(S,m.value)}for(const[S,m]of g.collectionMetadataWrites){if(m.type==="delete"){this.syncedCollectionMetadata.delete(S);continue}this.syncedCollectionMetadata.set(S,m.value)}}if(r){const g=new Set;for(const O of n)for(const C of O.operations)(C.type==="insert"||C.type==="update")&&g.add(C.key);const S=new Map(d.upserts),m=new Set(d.deletes);for(const O of b)l.has(O)&&S.delete(O);for(const O of T)l.has(O)&&m.delete(O);for(const[O,C]of S)if(!m.has(O))if(g.has(O)){let _=!1;for(let U=k.length-1;U>=0;U--){const R=k[U];if(R.key===O&&R.type==="insert"){R.value=C,_=!0;break}}_||k.push({type:"insert",key:O,value:C})}else k.push({type:"insert",key:O,value:C});if(k.length>0&&m.size>0){const O=[];for(const C of k)C.type==="insert"&&m.has(C.key)||O.push(C);k.length=0,k.push(...O)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&d){for(const[g,S]of d.upserts)b.has(g)&&l.has(g)||this.optimisticUpserts.set(g,S);for(const g of d.deletes)T.has(g)&&l.has(g)||this.optimisticDeletes.add(g)}for(const g of this.transactions.values())if(!["completed","failed"].includes(g.state)){for(const S of g.mutations)if(this.isThisCollection(S.collection)&&S.optimistic)switch(S.type){case"insert":case"update":this.optimisticUpserts.set(S.key,S.modified),this.optimisticDeletes.delete(S.key);break;case"delete":this.optimisticUpserts.delete(S.key),this.optimisticDeletes.add(S.key);break}}for(const g of this.pendingOptimisticDirectUpserts)if(!l.has(g)){if(l.add(g),!v.has(g)){const S=y.get(g);S!==void 0&&v.set(g,S)}this.pendingOptimisticUpserts.delete(g),this.pendingLocalOrigins.delete(g)}for(const g of this.pendingOptimisticDirectDeletes)l.has(g)||l.add(g),this.pendingOptimisticDeletes.delete(g),this.pendingLocalOrigins.delete(g);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(const g of l){const S=v.get(g),m=this.get(g),O=this.preSyncVirtualState.get(g)??this.getVirtualPropsSnapshotForState(g,{rowOrigins:p,optimisticUpserts:y,optimisticDeletes:w,completedOptimisticKeys:E}),C=this.getVirtualPropsSnapshotForState(g),_=O.$synced!==C.$synced||O.$origin!==C.$origin,U=S!==void 0?ut(S,g,this.collection.id,()=>O.$synced,()=>O.$origin):void 0,R=E.get(g);let D=!1;R&&(R.type==="delete"&&S!==void 0&&m===void 0&&K(R.value,S)||m!==void 0&&K(R.value,m))&&(D=!0);const Y=_&&S!==void 0&&m!==void 0&&K(S,m);if(!(D&&!Y))if(S===void 0&&m!==void 0){const re=E.get(g);if(re){const Re=re.value,Oe=ut(Re,g,this.collection.id,()=>O.$synced,()=>O.$origin);k.push({type:"update",key:g,value:m,previousValue:Oe})}else k.push({type:"insert",key:g,value:m})}else S!==void 0&&m===void 0?k.push({type:"delete",key:g,value:U??S}):S!==void 0&&m!==void 0&&(!K(S,m)||Y)&&k.push({type:"update",key:g,value:m,previousValue:U??S})}this.size=this.calculateSize(),k.length>0&&this.indexes.updateIndexes(k);let x;try{const g=c!==void 0&&(c.length!==this.size||[...this.keys()].some((S,m)=>S!==c[m]));this.changes.emitEvents(k,!0,g)}catch(g){x={error:g}}this.syncSessionGeneration===e&&(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),Promise.resolve().then(()=>{this.syncSessionGeneration===e&&this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0));for(const g of n)g.applied.resolve();return{processed:!0,failure:x}}return{processed:!1}}cancelPendingSyncedTransaction(e){if(e.applicationStarted)return;const t=this.pendingSyncedTransactions.indexOf(e);if(t===-1)return;this.pendingSyncedTransactions.splice(t,1),e.applied.reject(new st);const n=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)n.add(r.key);for(const i of e.operations){const r=i.key;n.has(r)||(this.recentlySyncedKeys.delete(r),this.preSyncVisibleState.delete(r),this.preSyncVirtualState.delete(r))}this.pendingSyncedTransactions.length===0?(this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.changes.emitEvents([],!0)):this.recomputeOptimisticState(!1)}scheduleTransactionCleanup(e){if(e.state==="completed"){this.transactions.delete(e.id);return}e.isPersisted.promise.then(()=>{this.transactions.delete(e.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const e=new Set;for(const t of this.pendingSyncedTransactions)for(const n of t.operations)e.add(n.key);for(const t of e)this.recentlySyncedKeys.add(t);for(const t of e)if(!this.preSyncVisibleState.has(t)){const n=this.get(t);n!==void 0&&(this.preSyncVisibleState.set(t,n),this.preSyncVirtualState.set(t,this.getVirtualPropsSnapshotForState(t)))}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncSessionGeneration++;for(const e of this.pendingSyncedTransactions)e.applied.reject(new st);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.hydrationSeedKeys.clear(),this.hydratedKeys.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.preSyncVisibleState.clear(),this.preSyncVirtualState.clear(),this.recentlySyncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function Z(s){let e;for(const t of s)try{t()}catch(n){e??={error:n}}if(e)throw e.error}function gn(s){return typeof s=="object"&&s!==null&&typeof s.hasPendingGraphRun=="function"}class Sn{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},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:i}){if(typeof e>"u"){i();return}const r=this.getOrCreateContext(e);if(r.jobs.has(t)||r.queue.push(t),r.jobs.set(t,i),n){const o=new Set(n);o.delete(t),r.dependencies.set(t,o)}else r.dependencies.has(t)||r.dependencies.set(t,new Set)}flush(e){const t=this.contexts.get(e);if(!t)return;const{queue:n,jobs:i,dependencies:r}=t;for(;n.length>0;){let o=!1;const a=n.length;for(let c=0;c<a;c++){const d=n.shift(),u=i.get(d);if(!u){r.delete(d);continue}const h=r.get(d);let l=!h;if(h){l=!0;for(const f of h){if(f===d)continue;const p=gn(f)&&f.hasPendingGraphRun(e);if(i.has(f)||p){l=!1;break}}}l?(i.delete(d),r.delete(d),u(),o=!0):n.push(d)}if(!o)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}clear(e){this.contexts.delete(e),Z([...this.clearListeners].map(t=>()=>t(e)))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}}const ue=new Sn;let me,be;function ft(){return be}function pt(s){if(me===void 0)throw s;be??={error:s}}function yt(s){if(me!==void 0)return s();const e=Symbol("collection-publication");me=e,be=void 0;let t,n;try{t=s(),ue.flush(e),n=ft()}catch(i){try{ue.clear(e)}catch{}const r=ft();throw r?r.error:i}finally{me=void 0,be=void 0}if(n)throw n.error;return t}function Mt(){const s=new Map;function e(t){const n=t.join(".");if(s.has(n))return s.get(n);const i=new Proxy({},{get(r,o,a){if(o==="__refProxy")return!0;if(o==="__path")return t;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,a);const c=[...t,String(o)];return e(c)},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(r,o)},ownKeys(r){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(r,o)}});return s.set(n,i),i}return e([])}function L(s){if(bn(s))return new Ot(s.__path);if(s&&typeof s=="object"&&(s.__brand==="ToArrayWrapper"||s.__brand==="ConcatToArrayWrapper"||s.__brand==="CaseWhenWrapper"||s.__brand==="MaterializeWrapper")){const e=s.__brand==="ToArrayWrapper"?"toArray()":s.__brand==="ConcatToArrayWrapper"?"concat(toArray())":s.__brand==="CaseWhenWrapper"?"caseWhen()":"materialize()";throw new Error(`${e} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${e} directly as a select field value instead.`)}return s&&typeof s=="object"&&"type"in s&&(s.type==="func"||s.type==="ref"||s.type==="val"||s.type==="agg")?s:new Q(s)}function bn(s){return s&&typeof s=="object"&&s.__refProxy===!0}function Lt(s,e){return new q("eq",[L(s),L(e)])}function wn(s,e){return new q("gt",[L(s),L(e)])}function vn(s,e){return new q("gte",[L(s),L(e)])}function Kt(s,e){return new q("lt",[L(s),L(e)])}function Le(s,e,...t){const n=[s,e,...t];return new q("and",n.map(i=>L(i)))}function Ft(s,e,...t){const n=[s,e,...t];return new q("or",n.map(i=>L(i)))}function kn(s){return new q("not",[L(s)])}function Cn(s){return new q("isUndefined",[L(s)])}function Rn(s){return new q("isNull",[L(s)])}class Ut{constructor(){this.listeners=new Map,this.onceCallbacks=new WeakMap}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Map);const n=this.listeners.get(e),i=t;let r=n.get(i);return r||(r={},n.set(i,r)),()=>{const o=this.listeners.get(e);o?.get(i)===r&&o.delete(i)}}once(e,t){let n=()=>{};const i=r=>{n(),t(r)};return this.onceCallbacks.set(i,t),n=this.on(e,i),n}off(e,t){const n=this.listeners.get(e);if(n)for(const i of n.keys())(i===t||this.onceCallbacks.get(i)===t)&&n.delete(i)}waitFor(e,t){return new Promise((n,i)=>{let r;const o=this.on(e,a=>{r&&(clearTimeout(r),r=void 0),n(a),o()});t&&(r=setTimeout(()=>{r=void 0,o(),i(new Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.emitInnerWhile(e,t,()=>!0)}emitInnerWhile(e,t,n){const i=this.listeners.get(e);if(i)for(const[r,o]of[...i]){if(!n())break;if(this.listeners.get(e)?.get(r)===o)try{r(t)}catch(a){queueMicrotask(()=>{throw a})}}}clearListeners(){this.listeners.clear()}}function Vt(s){return Ft(Rn(s),Cn(s))}function On(s,e){const t=Vt(s.expression);if(e==null)return s.compareOptions.nulls==="first"?kn(t):new Q(!1);const i=(s.compareOptions.direction==="asc"?wn:Kt)(s.expression,new Q(e));return s.compareOptions.nulls==="last"?Ft(i,t):i}function Tn(s,e){if(e.length!==0){if(s.length!==1||e.length!==1)throw new Error("Only single-column cursors are supported");return On(s[0],e[0])}}function En(s,e){const{expression:t}=s[0]??{};if(!t||e.length===0)return;const n=e[0];if(n==null)return Vt(t);if(n instanceof Date)return Number.isFinite(n.getTime())?Le(vn(t,new Q(n)),Kt(t,new Q(new Date(n.getTime()+1)))):void 0;if(typeof n!="object")return Lt(t,new Q(n))}const W=s=>{try{return s instanceof Error?s:new Error(String(s))}catch{return new Error("Unknown error")}};function se(){let s,e,t=!0;return{promise:new Promise((i,r)=>{s=o=>{t=!1,i(o)},e=o=>{t=!1,r(o)}}),resolve:s,reject:e,isPending:()=>t}}function mt(){const s=se();return s.promise.catch(()=>{}),s}function oe(s){s.abortController?.abort(),s.removeRequestAbortListener?.()}class xn extends Ut{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.subsetDemands=[],this.primaryFailureDeliveryDepth=0,this.requestedSubsetWhere=new WeakMap,this.sentKeys=new Set,this.publishedRows=new Map,this.stalePublishedRows=new Map,this.limitedSnapshotRowCount=0,this._status="ready",this.statusRevision=0,this.pendingLoadSubsetParticipants=new Set,this.loadSubsetPromiseErrors=new WeakMap,this.truncateReplacementPending=!1,this.unsubscribed=!1,n.onUnsubscribe&&this.on("unsubscribed",n.onUnsubscribe),n.onLoadSubsetError&&this.on("loadSubset:error",n.onLoadSubsetError),n.whereExpression&&ln(n.whereExpression,this.collection);const i=r=>{this.trackPublishedRows(r),this.trackSentKeys(r),t(r)};this.callback=i,this.filteredCallback=n.whereExpression?pn(this.callback,n):r=>(this.callback(r),!0),this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()}),this.collectionCleanup=this.collection.on("status:cleaned-up",()=>{this.handleCollectionCleanup()}),this.collectionRestartCleanup=this.collection.on("status:change",({status:r})=>{if(r!=="loading"&&r!=="ready")return;const o=this.collection._sync.getLoadSubsetSession(),a=this.truncateReplaySession;this.subsetDemands.some(c=>c.acquisitionState==="detached")&&this.setStatus("loadingSubset"),queueMicrotask(()=>{this.truncateReplaySession===a&&this.restartDetachedDemands(o)})})}get status(){return this._status}get lastError(){return this._lastError}handleCollectionCleanup(){this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.pendingLoadSubsetParticipants.clear();for(const e of[...this.subsetDemands])if(e.initialResult?.reject(new $),oe(e.acquisition),e.acquisitionState==="starting"){const t=this.subsetDemands.indexOf(e);t!==-1&&this.subsetDemands.splice(t,1)}else e.acquisitionState="detached",e.acquisition={options:e.requestOptions,loadSubsetSession:e.acquisition.loadSubsetSession};this.setReadyIfIdle()}restartDetachedDemands(e){if(this.unsubscribed||!this.isLoadSubsetSessionCurrent(e))return;if(this.collection.status==="error"||this.collection._sync.syncLoadSubsetFn===null){this.setReadyIfIdle();return}const t=this.subsetDemands.filter(r=>r.acquisitionState==="detached"&&!r.requestOptions.signal?.aborted);if(t.length===0){this.setReadyIfIdle();return}const n=this.createTruncateReplaySession(e,()=>{const r=this.collection.currentStateAsChanges({optimizedOnly:!1});return new Map((r??[]).filter(o=>o.type!=="delete").map(o=>[o.key,o.value]))}),i=n.currentAttempt;this.truncateReplaySession=n,this.setStatus("loadingSubset"),this.truncateReplaySession===n&&this.startTruncateReplayAttempt(n,i,t)}handleTruncate(){const t=this.collection._sync.syncLoadSubsetFn!==null?[...this.subsetDemands]:[];if(t.length===0&&this.stalePublishedRows.size===0){this.resetSnapshotTracking();return}let n=this.truncateReplaySession;n?(n.completion.isPending()||(n.completion=mt()),n.pendingSetups++,n.failures.clear(),n.currentAttempt={pendingCount:0,setupComplete:!1}):(n=this.createTruncateReplaySession(this.collection._sync.getLoadSubsetSession(),()=>new Map(this.publishedRows)),this.truncateReplaySession=n);const i=n.currentAttempt;if(this.setStatus("loadingSubset"),this.truncateReplaySession===n){this.options.truncateReplayPublication&&(this.truncateReplacementPending=!0,this.options.truncateReplayPublication.start());for(const r of t)r.acquisition.abortController?.abort();this.resetSnapshotTracking(),queueMicrotask(()=>{if(this.truncateReplaySession===n){if(!this.isLoadSubsetSessionCurrent(n.loadSubsetSession)){this.retireStaleTruncateReplay(n);return}this.startTruncateReplayAttempt(n,i,n.currentAttempt===i?t:[])}})}}startTruncateReplayDemand(e,t,n){const i=()=>this.truncateReplaySession===e&&e.currentAttempt===t,r=()=>i()&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.isDemandActive(n),o=h=>{r()&&e.failures.set(n,W(h))};n.initialResult&&e.completion.promise.then(n.initialResult.resolve,n.initialResult.reject);const a=n.acquisition,c=n.acquisitionState==="active";if(n.acquisitionState="detached",c)try{this.releaseAcquisition(a)}catch(h){o(h);return}if(!r()||n.requestOptions.signal?.aborted)return;const d=this.createSubsetAcquisition(n);n.acquisition=d,n.acquisitionState="starting";let u;try{u=this.loadSubset(d.options,r)}catch(h){n.acquisition===d&&(n.acquisitionState="detached"),oe(d),o(h);return}if(!r()){n.acquisition===d&&(n.acquisitionState="detached");try{this.releaseAcquisition(d)}catch(h){o(h)}return}n.acquisitionState="active",this.trackTruncateReplayParticipant(e,t,n,u),this.observeLoadSubsetResult(u,n,d.options,!0,()=>r()&&!d.options.signal?.aborted)}settleTruncateReplay(e,t){try{if(this.truncateReplaySession!==e)return;if(!this.isLoadSubsetSessionCurrent(e.loadSubsetSession)){this.retireStaleTruncateReplay(e);return}e.pending.delete(t)&&t.attempt.pendingCount--,this.checkTruncateReplayComplete(e)}catch(n){queueMicrotask(()=>{throw n})}}trackTruncateReplayParticipant(e,t,n,i){if(this.truncateReplaySession!==e||e.currentAttempt!==t&&t.setupComplete&&t.pendingCount===0||!(i instanceof Promise))return;const r={demand:n,attempt:t};t.pendingCount++,e.pending.add(r),i.then(()=>this.settleTruncateReplay(e,r),o=>{if(this.truncateReplaySession===e&&e.currentAttempt===t&&this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.subsetDemands.includes(n)){const a=this.normalizeLoadSubsetPromiseError(i,o);e.failures.set(n,a)}this.settleTruncateReplay(e,r)})}removeTruncateReplayParticipant(e){const t=this.truncateReplaySession;if(t){t.failures.delete(e);for(const n of t.pending)n.demand===e&&(t.pending.delete(n),n.attempt.pendingCount--)}}checkTruncateReplayComplete(e){if(this.truncateReplaySession!==e||e.pendingSetups>0||e.pending.size>0)return;const t=[...e.failures].find(([n])=>this.subsetDemands.includes(n));try{t?this.abandonTruncateReplay(e,t[1]):this.flushTruncateReplay(e)}finally{this.setReadyIfIdle()}}abandonTruncateReplay(e,t){if(this.truncateReplaySession!==e||(e.completion.reject(t),!e.privateRows))return;const n=e.publicationState;this.loadedInitialState=n.loadedInitialState,this.snapshotSent=n.snapshotSent,this.limitedSnapshotRowCount=n.limitedSnapshotRowCount,this.lastSentKey=n.lastSentKey}flushTruncateReplay(e){if(this.truncateReplaySession!==e)return;this.truncateReplaySession=void 0,this.truncateReplacementPending=!1;const{privateRows:t}=e;for(const n of this.stalePublishedRows.keys())t?.delete(n);this.stalePublishedRows.clear();try{if(t){const n=this.createStateDiff(this.publishedRows,t);n.length>0&&this.filteredCallback(n)}}finally{this.restorePublishedSnapshotTracking(),e.completion.resolve(),this.options.truncateReplayPublication?.succeed()}}restorePublishedSnapshotTracking(){if(this.sentKeys=new Set(this.publishedRows.keys()),!this.orderByIndex)return;this.limitedSnapshotRowCount=this.sentKeys.size;const e=this.orderByIndex.takeFromStart(this.sentKeys.size,t=>this.sentKeys.has(t));this.lastSentKey=e.at(-1)}bufferPrivately(e){const t=this.truncateReplaySession?.privateRows;if(!t)return!1;for(const n of e)n.type==="delete"?t.delete(n.key):t.set(n.key,n.value);return!0}createStateDiff(e,t){const n=[];for(const[i,r]of e){const o=t.get(i);o===void 0?n.push({type:"delete",key:i,value:r}):K(o,r)||n.push({type:"update",key:i,value:o,previousValue:r})}for(const[i,r]of t)e.has(i)||n.push({type:"insert",key:i,value:r});return n}get isBufferingForTruncate(){return this.truncateReplaySession!==void 0}setReadyIfIdle(){const e=this.truncateReplaySession,t=e&&(e.pendingSetups>0||e.pending.size>0);this.pendingLoadSubsetParticipants.size===0&&!t&&this.setStatus("ready")}isLoadSubsetSessionCurrent(e){return e===this.collection._sync.getLoadSubsetSession()}retireStaleTruncateReplay(e){this.truncateReplaySession===e&&(this.discardTruncateReplay(),this.stalePublishedRows.clear())}discardTruncateReplay(){const e=this.truncateReplaySession;e?.completion.isPending()&&e.completion.reject(new $),this.truncateReplaySession=void 0,this.truncateReplacementPending=!1}resetSnapshotTracking(){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0}createTruncateReplaySession(e,t){return{loadSubsetSession:e,publicationState:{loadedInitialState:this.loadedInitialState,snapshotSent:this.snapshotSent,limitedSnapshotRowCount:this.limitedSnapshotRowCount,lastSentKey:this.lastSentKey},privateRows:this.options.truncateReplayPublication?void 0:t(),pending:new Set,pendingSetups:1,currentAttempt:{pendingCount:0,setupComplete:!1},failures:new Map,completion:mt()}}startTruncateReplayAttempt(e,t,n){for(const i of n)if(this.subsetDemands.includes(i)&&(this.startTruncateReplayDemand(e,t,i),this.truncateReplaySession!==e||e.currentAttempt!==t))break;t.setupComplete=!0,e.pendingSetups--,this.checkTruncateReplayComplete(e)}get hasPendingTruncateReplacement(){return this.truncateReplacementPending}get pendingTruncateReplacement(){const e=this.truncateReplaySession?.completion;return e?.isPending()?e.promise:void 0}get hasFailedTruncateReplacement(){const e=this.truncateReplaySession?.completion;return this.truncateReplacementPending&&e!==void 0&&!e.isPending()}setOrderByIndex(e){this.orderByIndex=e}setStatus(e){if(this.unsubscribed||this._status===e)return;const t=this._status;this._status=e;const n=++this.statusRevision;if(this.emitInnerWhile("status:change",{type:"status:change",subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n),this.statusRevision!==n)return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,subscription:this,previousStatus:t,status:e},()=>this.statusRevision===n)}observeLoadSubsetResult(e,t,n,i,r=()=>!0){if(!(e instanceof Promise))return;const o=this.collection._sync.getLoadSubsetSession(),a={demand:t,promise:e};i&&(this.pendingLoadSubsetParticipants.add(a),this.setStatus("loadingSubset"));const c=()=>{i&&(this.pendingLoadSubsetParticipants.delete(a),this.isLoadSubsetSessionCurrent(o)&&this.setReadyIfIdle())};e.then(c,d=>{this.isLoadSubsetSessionCurrent(o)&&r()&&this.recordLoadSubsetError(n,this.normalizeLoadSubsetPromiseError(e,d)),c()})}normalizeLoadSubsetPromiseError(e,t){const n=this.loadSubsetPromiseErrors.get(e);if(n)return n;const i=W(t);return this.loadSubsetPromiseErrors.set(e,i),i}stopDemandStatusParticipants(e){for(const t of this.pendingLoadSubsetParticipants)t.demand===e&&this.pendingLoadSubsetParticipants.delete(t);this.setReadyIfIdle()}loadSubset(e,t=()=>!0){try{return this.collection._sync.loadSubset(e)}catch(n){const i=W(n);throw t()&&this.recordLoadSubsetError(e,i),i}}createSubsetAcquisition(e){const t=new AbortController,n=e.requestOptions.signal;let i;if(n?.aborted)t.abort(n.reason);else if(n){const r=()=>t.abort(n.reason);n.addEventListener("abort",r,{once:!0}),i=()=>n.removeEventListener("abort",r)}return{options:{...e.requestOptions,signal:t.signal},loadSubsetSession:this.collection._sync.getLoadSubsetSession(),abortController:t,removeRequestAbortListener:i}}releaseAcquisition(e,t=this.primaryFailureDeliveryDepth===0){if(!e.releaseAttempted){e.releaseAttempted=!0;try{e.abortController?.abort(),this.isLoadSubsetSessionCurrent(e.loadSubsetSession)&&this.collection._sync.unloadSubset(e.options)}catch(n){throw t?this.recordLoadSubsetError(e.options,W(n),!0):W(n)}finally{e.removeRequestAbortListener?.()}}}startSubsetDemand(e){const t={requestOptions:e,acquisition:{options:e,loadSubsetSession:this.collection._sync.getLoadSubsetSession()},acquisitionState:"starting"};if(this.collection.status==="cleaned-up"||this.collection.config.syncMode==="on-demand"&&(this.collection.status==="error"||this.collection.status!=="idle"&&this.collection._sync.syncLoadSubsetFn===null)){t.acquisitionState="detached",this.subsetDemands.push(t);const c=se();t.initialResult=c;const d=()=>c.reject(new $);e.signal?.addEventListener("abort",d,{once:!0});const u=()=>{e.signal?.removeEventListener("abort",d),t.initialResult=void 0};return c.promise.then(u,u),{demand:t,result:c.promise,started:!1}}const n=this.createSubsetAcquisition(t);t.acquisition=n;const i=this.truncateReplaySession,r=i?.currentAttempt,o=this.collection._sync.getLoadSubsetSession();this.subsetDemands.push(t);let a;try{a=this.loadSubset(n.options,()=>this.isLoadSubsetSessionCurrent(o)&&this.subsetDemands.includes(t)&&(i===void 0||this.truncateReplaySession===i&&i.currentAttempt===r))}catch(c){const d=this.subsetDemands.indexOf(t);throw d!==-1&&(i&&r&&this.truncateReplaySession===i&&i.currentAttempt===r&&i.failures.set(t,W(c)),this.subsetDemands.splice(d,1)),oe(n),c}if(!this.isLoadSubsetSessionCurrent(o)){const c=this.subsetDemands.indexOf(t);return c!==-1&&this.subsetDemands.splice(c,1),oe(n),{demand:t,result:a,started:!0}}return t.acquisitionState="active",this.subsetDemands.includes(t)?(i&&r&&this.trackTruncateReplayParticipant(i,r,t,a),{demand:t,result:a,started:!0}):(this.releaseAcquisition(n),{demand:t,result:a,started:!0})}isDemandActive(e){return!this.unsubscribed&&this.subsetDemands.includes(e)}recordLoadSubsetError(e,t,n=!1){const i=W(t);if(e.signal?.aborted&&!n)return i;this._lastError=i,this.primaryFailureDeliveryDepth++;try{this.emitInner("loadSubset:error",{type:"loadSubset:error",subscription:this,options:e,error:i})}finally{this.primaryFailureDeliveryDepth--}return i}emitEvents(e){if(this.unsubscribed)return!1;const t=this.filterAndFlipChanges(e);return e.length>0&&t.length===0||this.bufferPrivately(t)?!1:this.filteredCallback(t)}publishSnapshot(e){this.bufferPrivately(e)||this.callback(e)}requestSnapshot(e){if(this.unsubscribed||e?.signal?.aborted||this.loadedInitialState)return!1;const t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if("where"in e){const u=e.where;if(t.where){const h=t.where,l=Le(h,u);t.where=l}else t.where=u}}else this.loadedInitialState=!0;const n={where:t.where,signal:e?.signal,subscription:this,orderBy:e?.orderBy,limit:e?.limit},{demand:i,result:r,started:o}=this.startSubsetDemand(n);if(!this.isDemandActive(i)||(e?.where&&this.requestedSubsetWhere.set(n,e.where),e?.onLoadSubsetResult?.(r,i.acquisition.options,u=>this.releaseDemand(i,u)),!this.isDemandActive(i))||(o&&this.observeLoadSubsetResult(r,i,i.acquisition.options,e?.trackLoadSubsetPromise??!0),!this.isDemandActive(i)))return!1;let a;if(e?.onUnoptimized){if(a=this.collection.currentStateAsChanges({...t,optimizedOnly:!0}),a===void 0){if(e.onUnoptimized(),this.unsubscribed)return!1;a=this.collection.currentStateAsChanges({...t,optimizedOnly:!1})}}else a=this.collection.currentStateAsChanges(t);if(this.unsubscribed||a===void 0)return!1;const c=this.truncateReplaySession?.privateRows??this.publishedRows,d=a.filter(u=>!this.isBufferingForTruncate&&this.stalePublishedRows.has(u.key)||!this.sentKeys.has(u.key)&&!c.has(u.key));for(const u of d)this.sentKeys.add(u.key);return this.snapshotSent=!0,this.publishSnapshot(this.isBufferingForTruncate?d:this.reconcileStalePublishedChanges(d)),!0}releaseSnapshot(e){const t=this.subsetDemands.findIndex(n=>n.requestOptions.where===e||this.requestedSubsetWhere.get(n.requestOptions)===e);t!==-1&&this.releaseDemandAt(t)}releaseDemand(e,t){if(!t){const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n);return}try{this.recordLoadSubsetError(e.acquisition.options,t.error,!0)}finally{const n=this.subsetDemands.indexOf(e);n!==-1&&this.releaseDemandAt(n,!1)}}releaseDemandAt(e,t=this.primaryFailureDeliveryDepth===0){const n=this.subsetDemands[e];if(!n)return;const i=this.truncateReplaySession,r=n.acquisition;this.subsetDemands.splice(e,1),n.initialResult?.reject(new $);const o=[()=>this.removeTruncateReplayParticipant(n),...n.acquisitionState==="active"?[()=>this.releaseAcquisition(r,t)]:[],()=>this.retireEmptyReplay(),()=>{i&&this.checkTruncateReplayComplete(i)},()=>this.stopDemandStatusParticipants(n)];Z(o)}retireEmptyReplay(){this.subsetDemands.length!==0||!this.truncateReplaySession||(this.discardTruncateReplay(),this.stalePublishedRows=new Map(this.publishedRows),this.restorePublishedSnapshotTracking(),this.options.truncateReplayPublication?.succeed())}readOrderedSnapshot(e){const t=[this.options.whereExpression,e.where,e.cursor?.whereFrom].filter(i=>i!==void 0),n=this.collection.currentStateAsChanges({orderBy:e.orderBy,limit:e.limit,where:t.length>0?t.reduce((i,r)=>Le(i,r)):void 0});return Array.isArray(n)?n:[]}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:i,trackLoadSubsetPromise:r=!0,onLoadSubsetResult:o}){if(this.unsubscribed)return;if(!t)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const a=n?Tn(e,n):void 0,c=n!==void 0&&n.length>0,u=n?.[0],h=this.orderByIndex,l=this.options.whereExpression,f=l?te(l):void 0,p=C=>{if(C!==void 0&&this.sentKeys.has(C))return!1;const _=this.collection.get(C);return _===void 0?!1:f?.(_)??!0};let y=u;const w=[];let b=[];if(c){const{expression:C}=e[0],_=this.collection.currentStateAsChanges({where:Lt(C,new Q(u))});if(_){const U=_.map(D=>D.key).filter(D=>!this.sentKeys.has(D)&&p(D));b.push(...U);const R=h.take(t-b.length,u,p);b.push(...R)}else b=h.take(t,u,p)}else b=h.takeFromStart(t,p);const T=()=>Math.max(t-w.length,0),v=()=>b.length===0,k=e[0].expression,A=k.type==="ref"?Ns(new Ot(k.path),!0):null;for(;T()>0&&!v();){for(const C of b){const _=this.collection.get(C);w.push({type:"insert",key:C,value:_}),y=A?A(_):_}b=h.take(T(),y,p)}const E=this.limitedSnapshotRowCount;for(const C of w)this.sentKeys.add(C.key);if(this.publishSnapshot(w),this.unsubscribed)return;this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,E+w.length),w.length>0&&(this.lastSentKey=w[w.length-1].key);let x;if(a&&n){const C=En(e,n);C&&(x={whereFrom:a,whereCurrent:C,lastKey:this.lastSentKey})}const g={where:l,limit:t,orderBy:e,cursor:x,offset:i??E,subscription:this},{demand:S,result:m,started:O}=this.startSubsetDemand(g);this.isDemandActive(S)&&(o?.(m,S.acquisition.options,C=>this.releaseDemand(S,C)),this.isDemandActive(S)&&(O&&this.observeLoadSubsetResult(m,S,S.acquisition.options,r),this.isDemandActive(S)))}filterAndFlipChanges(e){if(e=this.reconcileStalePublishedChanges(e),this.loadedInitialState||this.skipFiltering)return e;const t=this.isBufferingForTruncate,n=[];for(const i of e){let r=i;if(this.sentKeys.has(i.key)){if(i.type==="insert")continue;i.type==="delete"&&this.sentKeys.delete(i.key)}else if(i.type==="update")r={...i,type:"insert",previousValue:void 0},this.sentKeys.add(i.key);else if(i.type==="delete"){if(!t)continue}else this.sentKeys.add(i.key);n.push(r)}return n}reconcileStalePublishedChanges(e){if(this.stalePublishedRows.size===0)return e;const t=[];for(const n of e){const i=this.stalePublishedRows.get(n.key);if(i===void 0){t.push(n);continue}this.stalePublishedRows.delete(n.key),n.type==="delete"?t.push({...n,value:i,previousValue:void 0}):K(i,n.value)||t.push({...n,type:"update",previousValue:i})}if(this.collection.config.syncMode!=="on-demand"&&!this.isBufferingForTruncate)for(const[n,i]of this.stalePublishedRows)this.collection.has(n)||(this.stalePublishedRows.delete(n),t.push({type:"delete",key:n,value:i}));return t}trackPublishedRows(e){for(const t of e)t.type==="delete"?this.publishedRows.delete(t.key):this.publishedRows.set(t.key,t.value)}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(const 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(){if(this.unsubscribed)return;this.unsubscribed=!0,this.statusRevision++;const e=[this.truncateCleanup,this.collectionCleanup,this.collectionRestartCleanup];this.truncateCleanup=void 0,this.collectionCleanup=void 0,this.collectionRestartCleanup=void 0,Z([...e.map(t=>()=>t?.()),()=>{this.discardTruncateReplay(),this.stalePublishedRows.clear();const t=this.subsetDemands.filter(n=>n.acquisitionState==="active").map(n=>n.acquisition);for(const n of this.subsetDemands)n.initialResult?.reject(new $),this.stopDemandStatusParticipants(n),n.acquisitionState==="starting"&&oe(n.acquisition);this.subsetDemands=[],Z(t.map(n=>()=>this.releaseAcquisition(n)))},()=>this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),()=>this.clearListeners()])}}class Dn{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1,this.publicationDeferralDepth=0,this.discardDeferredPublications=!1,this.deferredStateRevision=0,this.deferredLayoutRevision=0,this.deferredPublications=[],this.layoutChangeListeners=new Set,this.stateRevision=0,this.layoutRevision=0}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){yt(()=>{try{Z([...this.changeSubscriptions].map(e=>()=>e.emitEvents([])))}catch(e){pt(e)}})}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1,n=!1){if(e.length>0&&this.stateRevision++,n&&this.layoutRevision++,this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let i=e;if(t){if(this.batchedEvents.length>0){const r=new Map(this.batchedEvents.map(o=>[o.key,o]));for(const o of e){const a=r.get(o.key);r.set(o.key,a?.type==="delete"&&o.type==="insert"?{...o,type:"update",previousValue:a.value}:o)}i=[...r.values()]}this.batchedEvents=[],this.shouldBatchEvents=!1}if(this.publicationDeferralDepth>0){this.deferredPublications.push({changes:i,layoutChanged:n});return}this.publishEvents(i,n)}deferPublication(){this.publicationDeferralDepth===0&&(this.deferredStateRevision=this.stateRevision,this.deferredLayoutRevision=this.layoutRevision),this.publicationDeferralDepth++;let e=!1;const t=n=>{if(e||(e=!0,this.publicationDeferralDepth===0)||(this.discardDeferredPublications||=n,this.publicationDeferralDepth--,this.publicationDeferralDepth>0))return;const i=this.deferredPublications;if(this.deferredPublications=[],this.discardDeferredPublications){this.discardDeferredPublications=!1,this.stateRevision=this.deferredStateRevision,this.layoutRevision=this.deferredLayoutRevision;return}this.publishEvents(i.flatMap(({changes:r})=>r),i.some(({layoutChanged:r})=>r))};return{publish:()=>t(!1),discard:()=>t(!0)}}publishEvents(e,t){if(e.length===0&&!t)return;const n=e.map(o=>this.enrichChangeWithVirtualProps(o)),i=[...this.layoutChangeListeners],r=[...this.changeSubscriptions];yt(()=>{const o=r.map(a=>()=>a.emitEvents(n));e.length===0&&o.unshift(...i);try{Z(o)}catch(a){pt(a)}})}subscribeLayoutChanges(e){return this.layoutChangeListeners.add(e),()=>this.layoutChangeListeners.delete(e)}subscribeChanges(e,t={}){if(t.where&&t.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:n,...i}=t;let r=i.whereExpression;if(n){const c=Mt(),d=n(c);r=L(d)}this.addSubscriber();let o;const a={closed:!1};try{o=new xn(this.collection,e,{...i,whereExpression:r,onUnsubscribe:()=>{a.closed=!0,this.removeSubscriber(),o&&this.changeSubscriptions.delete(o)}}),t.onStatusChange&&o.on("status:change",t.onStatusChange),t.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&o.markAllStateAsSeen(),a.closed||this.changeSubscriptions.add(o)}catch(c){if(o)try{o.unsubscribe()}catch{}else this.removeSubscriber();throw c}return o}addSubscriber(){const e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer();try{(this.lifecycle.status==="cleaned-up"||this.lifecycle.status==="idle")&&this.sync.startSync()}catch(t){throw this.activeSubscribersCount=e,this.activeSubscribersCount===0&&this.lifecycle.startGCTimer(),t}this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new cs;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1,this.deferredPublications=[],this.publicationDeferralDepth=0}}const In=s=>setTimeout(()=>{s({didTimeout:!0,timeRemaining:()=>50})},0),Pn=s=>{clearTimeout(s)},An=typeof window<"u"&&"requestIdleCallback"in window?(s,e)=>window.requestIdleCallback(s,e):(s,e)=>In(s),Pe=typeof window<"u"&&"cancelIdleCallback"in window?s=>window.cancelIdleCallback(s):Pn,$t=class ae{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}schedule(e,t,n){const i=Date.now()+t;this.tasks.set(e,{executeAt:i,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(const n of this.tasks.values())n.executeAt<e&&(e=n.executeAt);const t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;const e=Date.now();for(const[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(i){console.error("Error in CleanupQueue task:",i)}}this.tasks.size>0&&this.updateTimeout()}};$t.instance=null;let Ae=$t;class _n{constructor(e,t){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.statusRevision=0,this.cleaningUp=!1,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)return;if(!{idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["ready","cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(t))throw new os(e,t,this.id)}setStatus(e,t=!1){if(e==="ready"&&!t)throw new ie(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const n=++this.statusRevision,i=this.status;this.status=e,this.events.emitStatusChange(e,i,()=>this.statusRevision===n)}validateCollectionUsable(e){switch(this.status){case"error":throw new rs(e,this.id);case"cleaned-up":this.sync.startSync();break}}markReady(){const e=this.applyReadyTransition();if(e)throw e.error}markReadyDuringSyncStart(){return this.applyReadyTransition()}applyReadyTransition(){if(this.validateStatusTransition(this.status,"ready"),this.status==="loading"||this.status==="error"){this.syncError=void 0;const e=this.statusRevision+1;if(this.setStatus("ready",!0),this.status!=="ready"||this.statusRevision!==e)return;const t=[];this.hasBeenReady||(this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0),t.push(...this.onFirstReadyCallbacks),this.onFirstReadyCallbacks=[]),t.push(()=>this.changes.emitEmptyReadyEvent());try{Z(t)}catch(n){return{error:n}}}}markError(e){this.validateStatusTransition(this.status,"error"),this.syncError=e,this.setStatus("error")}getSyncError(){return this.syncError}assertCanStartSync(){if(this.cleaningUp)throw new ie(`Cannot start collection "${this.id}" during cleanup. Restart after cleanup() completes.`)}startGCTimer(){const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Ae.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Ae.getInstance().cancel(this),this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Pe(this.idleCallbackId),this.idleCallbackId=An(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(this.cleaningUp)return!0;if(!e||e.timeRemaining()>0||e.didTimeout){this.cleaningUp=!0;try{this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Ae.getInstance().cancel(this),this.hasBeenReady=!1,this.syncError=void 0,this.onFirstReadyCallbacks=[]}finally{this.cleaningUp=!1}return this.setStatus("cleaned-up"),this.changes.activeSubscribersCount===0&&this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){return this.hasBeenReady?(e(),()=>{}):(this.onFirstReadyCallbacks.push(e),()=>{const t=this.onFirstReadyCallbacks.indexOf(e);t!==-1&&this.onFirstReadyCallbacks.splice(t,1)})}cleanup(){this.idleCallbackId!==null&&(Pe(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const Mn=Symbol("liveQueryInternal");class Ln{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.loadSubsetOperations=new Set,this.syncStartDeferred=!1,this.syncStartRequested=!1,this.deferredLoadSubsets=[],this.syncEpoch=0,this.loadSubsetSession=0,this.config=e,this.id=t,this.syncMode=e.syncMode??"eager"}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}markLayoutChange(){this.getActivePendingSyncTransaction().layoutChanged=!0}startSync(){if(this.lifecycle.assertCanStartSync(),this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up")return;if(this.syncStartDeferred){this.syncStartRequested=!0;return}const e=++this.syncEpoch,t=()=>e===this.syncEpoch;if(this.lifecycle.setStatus("loading"),!t())return;let n=!0,i;try{const r=Kn(this.config.sync.sync({collection:this.collection,begin:o=>{if(!t())return;const a=se();a.promise.catch(()=>{}),this.state.pendingSyncedTransactions.push({committed:!1,applicationStarted:!1,layoutChanged:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:o?.immediate,applied:a})},write:o=>{if(!t())return;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Ee;if(a.committed)throw new xe;let c;"key"in o?c=o.key:c=this.config.getKey(o.value),this.state.pendingLocalChanges.has(c)&&this.state.pendingLocalOrigins.add(c);let d=o.type;if(o.type==="insert"){const h=this.state.syncedData.has(c),l=a.deletedKeys.has(c),f=a.truncate===!0;if(h&&!l&&!f){const p=this.state.syncedData.get(c);if(p!==void 0&&K(p,o.value)||this.state.hydrationSeedKeys.has(c))d="update";else{const b=this.config.utils?.[Mn];throw new hs(c,this.id,{hasCustomGetKey:b?.hasCustomGetKey??!1,hasJoins:b?.hasJoins??!1,hasDistinct:b?.hasDistinct??!1})}}}const u={...o,type:d,key:c};a.operations.push(u),d==="delete"?(a.deletedKeys.add(c),a.rowMetadataWrites.set(c,{type:"delete"})):d==="insert"?u.metadata!==void 0?a.rowMetadataWrites.set(c,{type:"set",value:u.metadata}):a.rowMetadataWrites.set(c,{type:"delete"}):u.metadata!==void 0&&a.rowMetadataWrites.set(c,{type:"set",value:u.metadata})},commit:o=>{if(!t())return!0;const a=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!a)throw new Ts;if(a.committed)throw new Es;if(o?.aborted)return this.state.cancelPendingSyncedTransaction(a),a.applied.promise;a.committed=!0;const c=()=>{this.state.cancelPendingSyncedTransaction(a)};if(o?.addEventListener("abort",c,{once:!0}),this.state.commitPendingTransactions(),!a.applied.isPending())return o?.removeEventListener("abort",c),!0;const d=a.applied.promise;if(o){const u=()=>{o.removeEventListener("abort",c)};d.then(u,u)}return d},markReady:()=>{t()&&(n?i??=this.lifecycle.markReadyDuringSyncStart():this.lifecycle.markReady())},markError:o=>{t()&&this.lifecycle.markError(o)},truncate:()=>{if(!t())return;const o=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!o)throw new Ee;if(o.committed)throw new xe;o.operations=[],o.deletedKeys.clear(),o.rowMetadataWrites.clear(),o.truncate=!0,o.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi(t)}));if(n=!1,!t()){if(r?.cleanup?.(),i)throw i.error;return}if(this.syncCleanupFn=r?.cleanup??null,this.syncLoadSubsetFn=r?.loadSubset??null,this.syncUnloadSubsetFn=r?.unloadSubset??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new ee(`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(r){throw n=!1,t()&&this.lifecycle.markError(r),r}if(i)throw i.error}deferStart(){return this.lifecycle.status!=="idle"&&this.lifecycle.status!=="cleaned-up"?!1:(this.syncStartDeferred=!0,!0)}resumeStart(){if(!this.syncStartDeferred)return;this.syncStartDeferred=!1;const e=this.syncStartRequested||this.deferredLoadSubsets.length>0;this.syncStartRequested=!1;const t=this.deferredLoadSubsets;this.deferredLoadSubsets=[];const n=this.loadSubsetSession;try{e&&this.startSync()}catch(i){for(const{deferred:r}of t)r.reject(i);throw i}for(const{options:i,deferred:r}of t){const o=this.syncLoadSubsetFn;try{if(n!==this.loadSubsetSession||i.signal?.aborted)throw new $;const a=o?.(i)??!0;a instanceof Promise?a.then(c=>r.resolve(c),c=>r.reject(c)):r.resolve(void 0)}catch(a){r.reject(a)}}}getActivePendingSyncTransaction(){const e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Ee;if(e.committed)throw new xe;return e}createSyncMetadataApi(e){return{row:{get:t=>{if(!e())return;const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],i=n?.rowMetadataWrites.get(t);if(i)return i.type==="delete"?void 0:i.value;if(!n?.truncate)return this.state.syncedMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:"delete"})}},collection:{get:t=>{if(!e())return;const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return i?i.type==="delete"?void 0:i.value:this.state.syncedCollectionMetadata.get(t)},set:(t,n)=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"set",value:n})},delete:t=>{if(!e())return;this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:"delete"})},list:t=>{if(!e())return[];const n=new Map(this.state.syncedCollectionMetadata),i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(i)for(const[r,o]of i.collectionMetadataWrites)o.type==="delete"?n.delete(r):n.set(r,o.value);return Array.from(n.entries()).filter(([r])=>t?r.startsWith(t):!0).map(([r,o])=>({key:r,value:o}))}}}}preload(){try{this.lifecycle.assertCanStartSync()}catch(t){return Promise.reject(t)}if(this.preloadPromise)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.`);const e=new Promise((t,n)=>{if(this.lifecycle.status==="ready"){t();return}if(this.lifecycle.status==="error"){n(this.getPreloadError());return}let i=!1;const r={active:!1,ready:!1};let o=()=>{},a=()=>{};const c=()=>{if(r.active){r.ready=!0;return}i||(i=!0,o(),a(),this.rejectPreload===d&&(this.rejectPreload=void 0),t())},d=u=>{i||(i=!0,o(),a(),this.rejectPreload===d&&(this.rejectPreload=void 0),n(u))};if(this.rejectPreload=d,a=this.lifecycle.onFirstReady(c),o=this.collection.on("status:error",()=>{r.active||d(this.getPreloadError())}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up"){r.active=!0;let u;try{this.startSync()}catch(h){u={error:h}}finally{r.active=!1}this.collection.status==="error"?d(this.getPreloadError()):r.ready?c():u&&d(u.error)}});return this.preloadPromise=e,e.then(void 0,()=>{this.preloadPromise===e&&(this.preloadPromise=null)}),e}getPreloadError(){const e=this.lifecycle.getSyncError();return e===void 0?new as:e}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}beginLoadSubsetOperation(){const e=this.activeLoadSubsetOperation,t={pending:new Set,waiting:!1,completed:!1,hasError:!1};return this.activeLoadSubsetOperation=t,this.loadSubsetOperations.add(t),{wait:()=>this.waitForLoadSubsetOperation(t),cancel:()=>{t.completed=!0,this.loadSubsetOperations.delete(t),this.activeLoadSubsetOperation===t&&(this.activeLoadSubsetOperation=e?.completed?void 0:e)}}}waitForLoadSubsetOperation(e){return e.waiting=!0,e.pending.size===0?(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?Promise.reject(e.error):!0):(e.deferred=se(),e.deferred.promise)}settleLoadSubsetOperation(e,t,n){e.completed||(e.pending.delete(t),!n.ok&&!e.hasError&&(e.hasError=!0,e.error=n.error),!(!e.waiting||e.pending.size>0)&&queueMicrotask(()=>{e.completed||e.pending.size>0||(e.completed=!0,this.loadSubsetOperations.delete(e),this.activeLoadSubsetOperation===e&&(this.activeLoadSubsetOperation=void 0),e.hasError?e.deferred.reject(e.error):e.deferred.resolve())}))}trackLoadSubsetOperationPromise(e){const t=this.activeLoadSubsetOperation;!t||t.pending.has(e)||(t.pending.add(e),e.then(()=>this.settleLoadSubsetOperation(t,e,{ok:!0}),n=>this.settleLoadSubsetOperation(t,e,{ok:!1,error:n})))}trackLoadPromise(e){const t=this.loadSubsetSession,n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),this.trackLoadSubsetOperationPromise(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"});const i=()=>{if(t!==this.loadSubsetSession)return;const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),r&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"})};e.then(i,i)}getLoadSubsetSession(){return this.loadSubsetSession}loadSubset(e){if(e.signal?.aborted)return Promise.reject(new $);if(this.syncMode==="eager")return!0;if(this.syncStartDeferred){this.syncStartRequested=!0;const t=se();return this.deferredLoadSubsets.push({options:e,deferred:t}),this.trackLoadPromise(t.promise),t.promise}if(this.syncLoadSubsetFn){const t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){if(this.syncMode!=="eager"){if(this.syncStartDeferred){this.deferredLoadSubsets=this.deferredLoadSubsets.filter(t=>t.options!==e?!0:(t.deferred.reject(new $),!1));return}this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}}cleanup(){const e=++this.syncEpoch;this.loadSubsetSession++,this.rejectPreload?.(new Ps);const t=this.syncCleanupFn;this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null;try{t?.()}catch(r){this.syncEpoch===e&&(this.syncCleanupFn=t),queueMicrotask(()=>{if(r instanceof Error){const o=new tt(this.id,r);throw o.cause=r,o.stack=r.stack,o}else throw new tt(this.id,r)})}this.preloadPromise=null,this.syncStartDeferred=!1,this.syncStartRequested=!1;const n=this.pendingLoadSubsetPromises.size>0;this.pendingLoadSubsetPromises.clear(),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:"end"}),this.activeLoadSubsetOperation=void 0;for(const r of this.loadSubsetOperations)r.completed||(r.completed=!0,r.pending.clear(),r.hasError=!0,r.error=new $,r.deferred?.reject(r.error));this.loadSubsetOperations.clear();const i=this.deferredLoadSubsets;this.deferredLoadSubsets=[];for(const r of i)r.deferred.reject(new $)}}function Kn(s){if(typeof s=="function")return{cleanup:s};if(typeof s=="object")return s}const gt=1;function ge(s,e){return s===e?0:s<e?-1:1}function Fn(s){return{kind:"constructor",...s.name?{name:s.name}:{}}}function B(s){if(s==null)return s;switch(typeof s){case"string":case"boolean":return s;case"number":return Number.isFinite(s)?s:null;case"bigint":return{__type:"bigint",value:s.toString()};case"function":case"symbol":return;case"undefined":return}if(Array.isArray(s))return s.map(n=>B(n)??null);if(s instanceof Date)return{__type:"date",value:s.toISOString()};if(s instanceof Set)return{__type:"set",values:Array.from(s).map(i=>B(i)??null).sort((i,r)=>ge(J(i),J(r)))};if(s instanceof Map)return{__type:"map",entries:Array.from(s.entries()).map(([i,r])=>({key:B(i)??null,value:B(r)??null})).sort((i,r)=>ge(J(i.key),J(r.key)))};if(s instanceof RegExp)return{__type:"regexp",value:s.toString()};const e={},t=Object.entries(s).sort(([n],[i])=>ge(n,i));for(const[n,i]of t){const r=B(i);r!==void 0&&(e[n]=r)}return e}function J(s){return s===null?"null":Array.isArray(s)?`[${s.map(J).join(",")}]`:typeof s!="object"?JSON.stringify(s):`{${Object.keys(s).sort((n,i)=>ge(n,i)).map(n=>`${JSON.stringify(n)}:${J(s[n])}`).join(",")}}`}function Un(s,e,t,n,i){const r=Fn(n),o=B(e)??null,a=B(i),d=B({signatureVersion:gt,expression:o,options:a??null})??null,u=J(d);return{signatureVersion:gt,signature:u,indexId:s,name:t,expression:e,resolver:r,...a===void 0?{}:{options:a}}}function Ke(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(t=>Ke(t));const e={};for(const[t,n]of Object.entries(s))e[t]=Ke(n);return e}function Vn(s){return JSON.parse(JSON.stringify(s))}class $n{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");const n=++this.indexCounter,i=Mt(),r=e(i),o=L(r),a=t.indexType??this.defaultIndexType;if(!a)throw new ee(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
3
3
  import { BasicIndex } from '@tanstack/db'
4
- createCollection({ defaultIndexType: BasicIndex, ... })`);const c=new a(n,o,t.name,t.options);c.build(this.state.entries()),this.indexes.set(n,c);const u=Ln(n,o,t.name,a,t.options);return this.indexMetadata.set(n,u),this.events.emitIndexAdded(u),c}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");const 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);const i=this.indexMetadata.get(t);return this.indexMetadata.delete(t),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:Kn(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Le(e.options)}}))}updateIndexes(e){for(const t of this.indexes.values())for(const 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);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}const $t=new WeakMap;function Vn(s){return s!==null&&typeof s=="object"?$t.get(s)??s:s}const Un=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),$n=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),zn=new Set(["entries","keys","values","forEach"]);function de(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!z(s)}function qn(s,e,t,n){if(Un.has(s))return function(...i){const r=i[0];if(typeof r!="function")return e.apply(t.copy_,i);const o=(u,d)=>{if(de(u)){const h={tracker:t,prop:String(d)},{proxy:l}=n(u,h);return l}return u},a=function(u,d,h){const l=o(u,d);return r.call(this,l,d,h)};if(s==="reduce"||s==="reduceRight"){const u=function(d,h,l,p){const f=o(h,l);return r.call(this,d,f,l,p)};return e.apply(t.copy_,[u,...i.slice(1)])}const c=e.apply(t.copy_,[a,...i.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const u=t.copy_.indexOf(c);if(u!==-1)return o(c,u)}return s==="filter"&&Array.isArray(c)?c.map(u=>{const d=t.copy_.indexOf(u);return d!==-1?o(u,d):u}):c}}function jn(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const i=t[n];let r=i;if(de(i)){const o={tracker:s,prop:String(n)},{proxy:a}=e(i,o);r=a}return n++,{done:!1,value:r}},[Symbol.iterator](){return this}}}}function gt(s,e,t){return function(...n){const i=s.apply(e.copy_,n);return t(e),i}}function Nn(s,e,t,n,i){if(!(!zn.has(s)&&e!==Symbol.iterator))return(...r)=>{const o=t.copy_,a=o instanceof Map;if(a&&s==="keys")return o.keys();const c=h=>de(h)?i(h,{tracker:t,prop:"",retainIdentity:!0}).proxy:h;if(s==="forEach"){const h=r[0];if(typeof h!="function")throw new TypeError("forEach callback must be a function");return o.forEach((l,p)=>{const f=c(l);h.call(r[1],f,a?p:f,n)})}const u=o.entries(),d=s==="entries"||a&&e===Symbol.iterator;return{next(){const h=u.next();if(h.done)return h;const[l,p]=h.value,f=c(p);return{done:!1,value:d?[a?l:f,f]:f}},[Symbol.iterator](){return this}}}}function U(s,e=new WeakMap){if(s==null||typeof s!="object")return s;if(e.has(s))return e.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s)){const i=[];return e.set(s,i),s.forEach((r,o)=>{i[o]=U(r,e)}),i}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const i=Object.getPrototypeOf(s).constructor,r=new i(s.length);e.set(s,r);for(let o=0;o<s.length;o++)r[o]=s[o];return r}if(s instanceof Map){const i=new Map;return e.set(s,i),s.forEach((r,o)=>{i.set(o,U(r,e))}),i}if(s instanceof Set){const i=new Set;return e.set(s,i),s.forEach(r=>{i.add(U(r,e))}),i}if(z(s))return s;const t={};e.set(s,t);for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=U(s[i],e));const n=Object.getOwnPropertySymbols(s);for(const i of n)t[i]=U(s[i],e);return t}function je(s,e){const t=new Map;function n(l,p){if(t.has(l))return t.get(l);{const f=je(l,p);return t.set(l,f),f}}const i=new Map,r=e?.tracker.valueCopies??new WeakMap,o={valueCopies:r,copy_:e?r.get(s)??s:U(s,r),originalObject:U(s),modified:!1,assigned_:{},parent:e,target:s};function a(l){l.modified||(l.modified=!0),l.parent&&(l.parent.retainIdentity||(l.parent.tracker.copy_[l.parent.prop]=l.copy_,l.parent.tracker.assigned_[l.parent.prop]=!0),a(l.parent.tracker))}function c(l){if(l.copy_ instanceof Map||l.copy_ instanceof Set)return K(Array.from(l.copy_),Array.from(l.originalObject));if(Object.keys(l.assigned_).length===0&&Object.getOwnPropertySymbols(l.assigned_).length===0)return!0;for(const f in l.assigned_)if(l.assigned_[f]===!0){const g=l.copy_[f],w=l.originalObject[f];if(!K(g,w))return!1}else if(l.assigned_[f]===!1)return!1;const p=Object.getOwnPropertySymbols(l.assigned_);for(const f of p)if(l.assigned_[f]===!0){const g=l.copy_[f],w=l.originalObject[f];if(!K(g,w))return!1}else if(l.assigned_[f]===!1)return!1;return!0}function u(l){c(l)&&(l.modified=!1,l.assigned_={},l.parent&&u(l.parent.tracker))}function d(l){if(i.has(l))return i.get(l);const p=new Proxy(l,{get(f,g,w){const b=o.copy_[g]??o.originalObject[g];if(Object.getOwnPropertyDescriptor(f,g)?.get)return b;if(typeof b=="function"){if(Array.isArray(f)){const v=g.toString();if($n.has(v))return gt(b,o,a);const k=qn(v,b,o,n);if(k)return k;if(g===Symbol.iterator)return jn(o,n)}if(f instanceof Map||f instanceof Set){const v=g.toString(),k=T=>{const E=Vn(T);return E!==null&&typeof E=="object"?r.get(E)??E:E};if(v==="has"||v==="delete"||v==="add"||v==="set")return(...T)=>{f instanceof Set?T[0]=k(T[0]):v==="set"&&(T[1]=k(T[1]));const E=b.apply(f,T);return v!=="has"&&a(o),E===f?w:E};if(f instanceof Map&&v==="get")return T=>{const E=f.get(T);return de(E)?n(E,{tracker:o,prop:"",retainIdentity:!0}).proxy:E};if(v==="clear")return gt(b,o,a);const M=Nn(v,g,o,w,n);if(M)return M}return b.bind(f)}if(de(b)){const v={tracker:o,prop:String(g)},{proxy:k}=n(b,v);return i.set(b,k),k}return b},set(f,g,w){const b=o.copy_[g];if(!K(b,w)){const x=o.originalObject[g];K(w,x)?(delete o.assigned_[g.toString()],o.copy_[g]=U(x),c(o)?(o.modified=!1,o.assigned_={},e&&u(e.tracker)):o.modified=!0):(o.copy_[g]=w,o.assigned_[g.toString()]=!0,a(o))}return!0},defineProperty(f,g,w){const b=Reflect.defineProperty(f,g,w);return b&&"value"in w&&(o.copy_[g]=U(w.value),o.assigned_[g.toString()]=!0,a(o)),b},getOwnPropertyDescriptor(f,g){return Reflect.getOwnPropertyDescriptor(f,g)},preventExtensions(f){return Reflect.preventExtensions(f)},isExtensible(f){return Reflect.isExtensible(f)},deleteProperty(f,g){const w=typeof g=="symbol"?g.toString():g;if(w in f){const b=w in o.originalObject,x=Reflect.deleteProperty(f,g);return x&&(b?(o.assigned_[w]=!1,a(o)):(delete o.assigned_[w],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),x}return!0}});return i.set(l,p),$t.set(p,o.copy_),p}return{proxy:d(o.copy_),getChanges:()=>{if(!o.modified)return{};if(typeof o.copy_!="object"||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const l={},p=Object.keys(o.assigned_).some(f=>typeof o.copy_[f]=="object");for(const f in o.copy_){const g=o.copy_[f],w=o.originalObject[f];(o.assigned_[f]===!0||p&&o.copy_[f]!==o.copy_&&!K(g instanceof Set?Array.from(g):g,w instanceof Set?Array.from(w):w))&&f in o.copy_&&(l[f]=o.copy_[f])}return l}}}function Wn(s){const e=s.map(t=>je(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function Bn(s,e){const{proxy:t,getChanges:n}=je(s);return e(t),U(n())}function Hn(s,e){const{proxies:t,getChanges:n}=Wn(s);return e(t),U(n())}class Gn{constructor(){this.transactions=[],this.transactionStack=[],this.sequenceNumber=0}createTransaction(e){const t=new Xn(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.transactionStack.at(-1)}getActiveTransactionForCollection(){const e=this.getActiveTransaction();if(e)return e;if(this!==we)return we.claimActiveTransaction(this)}claimActiveTransaction(e){const t=this.getActiveTransaction();if(!t)return;const n=ce(t);if(n===e)return t;if(n!==this)throw new Error("A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.");return this.removeTransaction(t),e.transactions.push(t),e.transactionStack.push(t),t.sequenceNumber=e.sequenceNumber++,Ne.set(t,e),t}registerTransaction(e){ue.clear(e.id),this.transactionStack.push(e)}unregisterTransaction(e){try{ue.flush(e.id)}finally{this.transactionStack=this.transactionStack.filter(t=>t.id!==e.id)}}removeTransaction(e){const t=this.transactions.findIndex(n=>n.id===e.id);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){for(const n of[...this.transactions])n!==e&&n.state==="pending"&&n.mutations.some(i=>t.has(i.globalKey))&&n.rollback({isSecondaryRollback:!0})}clear(){const e=new Set([...this.transactions.map(t=>t.id),...this.transactionStack.map(t=>t.id)]);for(const t of e)ue.clear(t);this.transactions=[],this.transactionStack=[]}}const we=new Gn,Ne=new WeakMap,zt=new WeakMap;function ce(s){const e=Ne.get(s);if(!e)throw new Error("Transaction is not associated with a TransactionScope.");return e}function Yn(s){const e=zt.get(s);if(!e)throw new Error("Transaction is not associated with an ambient scope.");return e}function Jn(s,e){switch(`${s.type}-${e.type}`){case"insert-update":return{...s,type:"insert",original:{},modified:e.modified,changes:{...s.changes,...e.changes},key:s.key,globalKey:s.globalKey,metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:s.original,changes:{...s.changes,...e.changes},metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const t=`${s.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${t}`)}}}function Qn(s){return we.createTransaction(s)}function Zn(){return we.getActiveTransaction()}class Xn{constructor(e,t,n){if(typeof e.mutationFn>"u")throw new bs;this.id=e.id??le(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=se(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Ne.set(this,t),zt.set(this,t)}setState(e){this.state=e,(e==="completed"||e==="failed")&&ce(this).removeTransaction(this)}mutate(e){if(this.state!=="pending")throw new ws;const t=ce(this),n=new Set([t,Yn(this)]);for(const i of n)i.registerTransaction(this);try{e()}finally{n.add(ce(this));for(const i of n)i.unregisterTransaction(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){const t=new Map;for(const n of this.mutations)t.set(n.globalKey,n);for(const n of e){const i=t.get(n.globalKey);if(i){const r=Jn(i,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}this.mutations.length=0;for(const n of t.values())this.mutations.push(n)}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new vs;if(this.state==="failed")return this;if(this.setState("failed"),!t){const n=new Set(this.mutations.map(i=>i.globalKey));ce(this).rollbackConflictingTransactions(this,n)}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const 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 ks;if(this.setState("persisting"),this.mutations.length===0)return this.setState("completed"),this.isPersisted.resolve(this),this;try{if(await this.mutationFn({transaction:this}),this.state!=="persisting")return this;this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){if(this.state!=="persisting")return this;const t=W(e);throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){const t=this.createdAt.getTime()-e.createdAt.getTime();return t!==0?t:this.sequenceNumber-e.sequenceNumber}}class ei{constructor(e,t){this.insert=(n,i)=>{this.lifecycle.validateCollectionUsable("insert");const r=this.state,o=this.getActiveTransaction();if(!o&&!this.config.onInsert)throw new ms;const a=Array.isArray(n)?n:[n],c=[],u=new Set;if(a.forEach(d=>{const h=this.validateData(d,"insert"),l=this.config.getKey(h);if(this.state.has(l)||u.has(l))throw new cs(l);u.add(l);const p=this.generateGlobalKey(l,d),f={mutationId:le(),original:{},modified:h,changes:Object.fromEntries(Object.keys(d).map(g=>[g,h[g]])),globalKey:p,key:l,metadata:i?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:i?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(f)}),o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;{const d=this.createTransaction({metadata:{[ye]:!0},mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return d.applyMutations(c),this.markPendingLocalOrigins(c),d.commit().catch(()=>{}),r.transactions.set(d.id,d),r.scheduleTransactionCleanup(d),r.recomputeOptimisticState(!0),d}},this.delete=(n,i)=>{const r=this.state;this.lifecycle.validateCollectionUsable("delete");const o=this.getActiveTransaction();if(!o&&!this.config.onDelete)throw new Ss;if(Array.isArray(n)&&n.length===0)throw new ps;const a=Array.isArray(n)?n:[n],c=[];for(const d of a){if(!this.state.has(d))throw new ys(d);const h=this.generateGlobalKey(d,this.state.get(d)),l={mutationId:le(),original:this.state.get(d),modified:this.state.get(d),changes:this.state.get(d),globalKey:h,key:d,metadata:i?.metadata,syncMetadata:r.syncedMetadata.get(d)||{},optimistic:i?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(l)}if(o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;const u=this.createTransaction({autoCommit:!0,metadata:{[ye]:!0},mutationFn:async d=>this.config.onDelete({transaction:d.transaction,collection:this.collection})});return u.applyMutations(c),this.markPendingLocalOrigins(c),u.commit().catch(()=>{}),r.transactions.set(u.id,u),r.scheduleTransactionCleanup(u),r.recomputeOptimisticState(!0),u},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.transactionScope=e}getActiveTransaction(){return this.transactionScope?this.transactionScope.getActiveTransactionForCollection():Zn()}createTransaction(e){return this.transactionScope?this.transactionScope.createTransaction(e):Qn(e)}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new ts}validateData(e,t,n){if(!this.config.schema)return e;const i=this.ensureStandardSchema(this.config.schema);if(t==="update"&&n){const o=this.state.get(n);if(o&&e&&typeof e=="object"&&typeof o=="object"){const a=Object.assign({},o,e),c=i["~standard"].validate(a);if(c instanceof Promise)throw new Xe;if("issues"in c&&c.issues){const l=c.issues.map(p=>({message:p.message,path:p.path?.map(f=>String(f))}));throw new Ze(t,l)}const u=c.value,d=Object.keys(e);return Object.fromEntries(d.map(l=>[l,u[l]]))}}const r=i["~standard"].validate(e);if(r instanceof Promise)throw new Xe;if("issues"in r&&r.issues){const o=r.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new Ze(t,o)}return r.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new os(t):new as(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(const t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(typeof e>"u")throw new us;const i=this.state;this.lifecycle.validateCollectionUsable("update");const r=this.getActiveTransaction();if(!r&&!this.config.onUpdate)throw new gs;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new ds;const c=typeof t=="function"?t:n,u=typeof t=="function"?{}:t,d=a.map(f=>{const g=this.state.get(f);if(!g)throw new hs(f);return g});let h;o?h=Hn(d,c):h=[Bn(d[0],c)];const l=a.map((f,g)=>{const w=h[g];if(!w||Object.keys(w).length===0)return null;const b=d[g],x=this.validateData(w,"update",f),v=Object.assign({},b,x),k=this.config.getKey(b),M=this.config.getKey(v);if(k!==M)throw new fs(k,M);const T=this.generateGlobalKey(M,v);return{mutationId:le(),original:b,modified:v,changes:Object.fromEntries(Object.keys(w).map(E=>[E,v[E]])),globalKey:T,key:f,metadata:u.metadata,syncMetadata:i.syncedMetadata.get(f)||{},optimistic:u.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(l.length===0){const f=this.createTransaction({mutationFn:async()=>{}});return f.commit().catch(()=>{}),i.scheduleTransactionCleanup(f),f}if(r)return r.applyMutations(l),i.transactions.set(r.id,r),i.scheduleTransactionCleanup(r),i.recomputeOptimisticState(!0),r;const p=this.createTransaction({metadata:{[ye]:!0},mutationFn:async f=>this.config.onUpdate({transaction:f.transaction,collection:this.collection})});return p.applyMutations(l),this.markPendingLocalOrigins(l),p.commit().catch(()=>{}),i.transactions.set(p.id,p),i.scheduleTransactionCleanup(p),i.recomputeOptimisticState(!0),p}}class ti extends Ft{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e},n),!n())return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,collection:this.collection,previousStatus:t,status:e},n)}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 si(s){const e=new ni(s);return s.utils?e.utils=s.utils:e.utils={},e}class ni{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new Xt;if(!e.sync)throw new es;if(e.id?this.id=e.id:this.id=le(),this.config={...e,autoIndex:e.autoIndex??"off"},this.config.autoIndex==="eager"&&!e.defaultIndexType)throw new ee(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
4
+ createCollection({ defaultIndexType: BasicIndex, ... })`);const c=new a(n,o,t.name,t.options);c.build(this.state.entries()),this.indexes.set(n,c);const d=Un(n,o,t.name,a,t.options);return this.indexMetadata.set(n,d),this.events.emitIndexAdded(d),c}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");const 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);const i=this.indexMetadata.get(t);return this.indexMetadata.delete(t),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:Vn(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:Ke(e.options)}}))}updateIndexes(e){for(const t of this.indexes.values())for(const 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);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}const zt=new WeakMap;function zn(s){return s!==null&&typeof s=="object"?zt.get(s)??s:s}const jn=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),qn=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),Nn=new Set(["entries","keys","values","forEach"]);function de(s){return s!==null&&typeof s=="object"&&!(s instanceof Date)&&!(s instanceof RegExp)&&!z(s)}function Wn(s,e,t,n){if(jn.has(s))return function(...i){const r=i[0];if(typeof r!="function")return e.apply(t.copy_,i);const o=(d,u)=>{if(de(d)){const h={tracker:t,prop:String(u)},{proxy:l}=n(d,h);return l}return d},a=function(d,u,h){const l=o(d,u);return r.call(this,l,u,h)};if(s==="reduce"||s==="reduceRight"){const d=function(u,h,l,f){const p=o(h,l);return r.call(this,u,p,l,f)};return e.apply(t.copy_,[d,...i.slice(1)])}const c=e.apply(t.copy_,[a,...i.slice(1)]);if((s==="find"||s==="findLast")&&c&&typeof c=="object"){const d=t.copy_.indexOf(c);if(d!==-1)return o(c,d)}return s==="filter"&&Array.isArray(c)?c.map(d=>{const u=t.copy_.indexOf(d);return u!==-1?o(d,u):d}):c}}function Bn(s,e){return function(){const t=s.copy_;let n=0;return{next(){if(n>=t.length)return{done:!0,value:void 0};const i=t[n];let r=i;if(de(i)){const o={tracker:s,prop:String(n)},{proxy:a}=e(i,o);r=a}return n++,{done:!1,value:r}},[Symbol.iterator](){return this}}}}function St(s,e,t){return function(...n){const i=s.apply(e.copy_,n);return t(e),i}}function Hn(s,e,t,n,i){if(!(!Nn.has(s)&&e!==Symbol.iterator))return(...r)=>{const o=t.copy_,a=o instanceof Map;if(a&&s==="keys")return o.keys();const c=h=>de(h)?i(h,{tracker:t,prop:"",retainIdentity:!0}).proxy:h;if(s==="forEach"){const h=r[0];if(typeof h!="function")throw new TypeError("forEach callback must be a function");return o.forEach((l,f)=>{const p=c(l);h.call(r[1],p,a?f:p,n)})}const d=o.entries(),u=s==="entries"||a&&e===Symbol.iterator;return{next(){const h=d.next();if(h.done)return h;const[l,f]=h.value,p=c(f);return{done:!1,value:u?[a?l:p,p]:p}},[Symbol.iterator](){return this}}}}function V(s,e=new WeakMap){if(s==null||typeof s!="object")return s;if(e.has(s))return e.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s)){const i=[];return e.set(s,i),s.forEach((r,o)=>{i[o]=V(r,e)}),i}if(ArrayBuffer.isView(s)&&!(s instanceof DataView)){const i=Object.getPrototypeOf(s).constructor,r=new i(s.length);e.set(s,r);for(let o=0;o<s.length;o++)r[o]=s[o];return r}if(s instanceof Map){const i=new Map;return e.set(s,i),s.forEach((r,o)=>{i.set(o,V(r,e))}),i}if(s instanceof Set){const i=new Set;return e.set(s,i),s.forEach(r=>{i.add(V(r,e))}),i}if(z(s))return s;const t={};e.set(s,t);for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=V(s[i],e));const n=Object.getOwnPropertySymbols(s);for(const i of n)t[i]=V(s[i],e);return t}function We(s,e){const t=new Map;function n(l,f){if(t.has(l))return t.get(l);{const p=We(l,f);return t.set(l,p),p}}const i=new Map,r=e?.tracker.valueCopies??new WeakMap,o={valueCopies:r,copy_:e?r.get(s)??s:V(s,r),originalObject:V(s),modified:!1,assigned_:{},parent:e,target:s};function a(l){l.modified||(l.modified=!0),l.parent&&(l.parent.retainIdentity||(l.parent.tracker.copy_[l.parent.prop]=l.copy_,l.parent.tracker.assigned_[l.parent.prop]=!0),a(l.parent.tracker))}function c(l){if(l.copy_ instanceof Map||l.copy_ instanceof Set)return K(Array.from(l.copy_),Array.from(l.originalObject));if(Object.keys(l.assigned_).length===0&&Object.getOwnPropertySymbols(l.assigned_).length===0)return!0;for(const p in l.assigned_)if(l.assigned_[p]===!0){const y=l.copy_[p],w=l.originalObject[p];if(!K(y,w))return!1}else if(l.assigned_[p]===!1)return!1;const f=Object.getOwnPropertySymbols(l.assigned_);for(const p of f)if(l.assigned_[p]===!0){const y=l.copy_[p],w=l.originalObject[p];if(!K(y,w))return!1}else if(l.assigned_[p]===!1)return!1;return!0}function d(l){c(l)&&(l.modified=!1,l.assigned_={},l.parent&&d(l.parent.tracker))}function u(l){if(i.has(l))return i.get(l);const f=new Proxy(l,{get(p,y,w){const b=o.copy_[y]??o.originalObject[y];if(Object.getOwnPropertyDescriptor(p,y)?.get)return b;if(typeof b=="function"){if(Array.isArray(p)){const v=y.toString();if(qn.has(v))return St(b,o,a);const k=Wn(v,b,o,n);if(k)return k;if(y===Symbol.iterator)return Bn(o,n)}if(p instanceof Map||p instanceof Set){const v=y.toString(),k=E=>{const x=zn(E);return x!==null&&typeof x=="object"?r.get(x)??x:x};if(v==="has"||v==="delete"||v==="add"||v==="set")return(...E)=>{p instanceof Set?E[0]=k(E[0]):v==="set"&&(E[1]=k(E[1]));const x=b.apply(p,E);return v!=="has"&&a(o),x===p?w:x};if(p instanceof Map&&v==="get")return E=>{const x=p.get(E);return de(x)?n(x,{tracker:o,prop:"",retainIdentity:!0}).proxy:x};if(v==="clear")return St(b,o,a);const A=Hn(v,y,o,w,n);if(A)return A}return b.bind(p)}if(de(b)){const v={tracker:o,prop:String(y)},{proxy:k}=n(b,v);return i.set(b,k),k}return b},set(p,y,w){const b=o.copy_[y];if(!K(b,w)){const T=o.originalObject[y];K(w,T)?(delete o.assigned_[y.toString()],o.copy_[y]=V(T),c(o)?(o.modified=!1,o.assigned_={},e&&d(e.tracker)):o.modified=!0):(o.copy_[y]=w,o.assigned_[y.toString()]=!0,a(o))}return!0},defineProperty(p,y,w){const b=Reflect.defineProperty(p,y,w);return b&&"value"in w&&(o.copy_[y]=V(w.value),o.assigned_[y.toString()]=!0,a(o)),b},getOwnPropertyDescriptor(p,y){return Reflect.getOwnPropertyDescriptor(p,y)},preventExtensions(p){return Reflect.preventExtensions(p)},isExtensible(p){return Reflect.isExtensible(p)},deleteProperty(p,y){const w=typeof y=="symbol"?y.toString():y;if(w in p){const b=w in o.originalObject,T=Reflect.deleteProperty(p,y);return T&&(b?(o.assigned_[w]=!1,a(o)):(delete o.assigned_[w],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),T}return!0}});return i.set(l,f),zt.set(f,o.copy_),f}return{proxy:u(o.copy_),getChanges:()=>{if(!o.modified)return{};if(typeof o.copy_!="object"||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const l={},f=Object.keys(o.assigned_).some(p=>typeof o.copy_[p]=="object");for(const p in o.copy_){const y=o.copy_[p],w=o.originalObject[p];(o.assigned_[p]===!0||f&&o.copy_[p]!==o.copy_&&!K(y instanceof Set?Array.from(y):y,w instanceof Set?Array.from(w):w))&&p in o.copy_&&(l[p]=o.copy_[p])}return l}}}function Gn(s){const e=s.map(t=>We(t));return{proxies:e.map(t=>t.proxy),getChanges:()=>e.map(t=>t.getChanges())}}function Yn(s,e){const{proxy:t,getChanges:n}=We(s);return e(t),V(n())}function Jn(s,e){const{proxies:t,getChanges:n}=Gn(s);return e(t),V(n())}class Qn{constructor(){this.transactions=[],this.transactionStack=[],this.sequenceNumber=0}createTransaction(e){const t=new si(e,this,this.sequenceNumber++);return this.transactions.push(t),t}getActiveTransaction(){return this.transactionStack.at(-1)}getActiveTransactionForCollection(){const e=this.getActiveTransaction();if(e)return e;if(this!==we)return we.claimActiveTransaction(this)}claimActiveTransaction(e){const t=this.getActiveTransaction();if(!t)return;const n=ce(t);if(n===e)return t;if(n!==this)throw new Error("A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.");return this.removeTransaction(t),e.transactions.push(t),e.transactionStack.push(t),t.sequenceNumber=e.sequenceNumber++,Be.set(t,e),t}registerTransaction(e){ue.clear(e.id),this.transactionStack.push(e)}unregisterTransaction(e){try{ue.flush(e.id)}finally{this.transactionStack=this.transactionStack.filter(t=>t.id!==e.id)}}removeTransaction(e){const t=this.transactions.findIndex(n=>n.id===e.id);t!==-1&&this.transactions.splice(t,1)}rollbackConflictingTransactions(e,t){for(const n of[...this.transactions])n!==e&&n.state==="pending"&&n.mutations.some(i=>t.has(i.globalKey))&&n.rollback({isSecondaryRollback:!0})}clear(){const e=new Set([...this.transactions.map(t=>t.id),...this.transactionStack.map(t=>t.id)]);for(const t of e)ue.clear(t);this.transactions=[],this.transactionStack=[]}}const we=new Qn,Be=new WeakMap,jt=new WeakMap;function ce(s){const e=Be.get(s);if(!e)throw new Error("Transaction is not associated with a TransactionScope.");return e}function Zn(s){const e=jt.get(s);if(!e)throw new Error("Transaction is not associated with an ambient scope.");return e}function Xn(s,e){switch(`${s.type}-${e.type}`){case"insert-update":return{...s,type:"insert",original:{},modified:e.modified,changes:{...s.changes,...e.changes},key:s.key,globalKey:s.globalKey,metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:s.original,changes:{...s.changes,...e.changes},metadata:e.metadata??s.metadata,syncMetadata:{...s.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const t=`${s.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${t}`)}}}function ei(s){return we.createTransaction(s)}function ti(){return we.getActiveTransaction()}class si{constructor(e,t,n){if(typeof e.mutationFn>"u")throw new ks;this.id=e.id??le(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=se(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=n,this.metadata=e.metadata??{},Be.set(this,t),jt.set(this,t)}setState(e){this.state=e,(e==="completed"||e==="failed")&&ce(this).removeTransaction(this)}mutate(e){if(this.state!=="pending")throw new Cs;const t=ce(this),n=new Set([t,Zn(this)]);for(const i of n)i.registerTransaction(this);try{e()}finally{n.add(ce(this));for(const i of n)i.unregisterTransaction(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){const t=new Map;for(const n of this.mutations)t.set(n.globalKey,n);for(const n of e){const i=t.get(n.globalKey);if(i){const r=Xn(i,n);r===null?t.delete(n.globalKey):t.set(n.globalKey,r)}else t.set(n.globalKey,n)}this.mutations.length=0;for(const n of t.values())this.mutations.push(n)}rollback(e){const t=e?.isSecondaryRollback??!1;if(this.state==="completed")throw new Rs;if(this.state==="failed")return this;if(this.setState("failed"),!t){const n=new Set(this.mutations.map(i=>i.globalKey));ce(this).rollbackConflictingTransactions(this,n)}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const 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 Os;if(this.setState("persisting"),this.mutations.length===0)return this.setState("completed"),this.isPersisted.resolve(this),this;try{if(await this.mutationFn({transaction:this}),this.state!=="persisting")return this;this.setState("completed"),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){if(this.state!=="persisting")return this;const t=W(e);throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){const t=this.createdAt.getTime()-e.createdAt.getTime();return t!==0?t:this.sequenceNumber-e.sequenceNumber}}class ni{constructor(e,t){this.insert=(n,i)=>{this.lifecycle.validateCollectionUsable("insert");const r=this.state,o=this.getActiveTransaction();if(!o&&!this.config.onInsert)throw new bs;const a=Array.isArray(n)?n:[n],c=[],d=new Set;if(a.forEach(u=>{const h=this.validateData(u,"insert"),l=this.config.getKey(h);if(this.state.has(l)||d.has(l))throw new ds(l);d.add(l);const f=this.generateGlobalKey(l,u),p={mutationId:le(),original:{},modified:h,changes:Object.fromEntries(Object.keys(u).map(y=>[y,h[y]])),globalKey:f,key:l,metadata:i?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:i?.optimistic??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(p)}),o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;{const u=this.createTransaction({metadata:{[ye]:!0},mutationFn:async h=>await this.config.onInsert({transaction:h.transaction,collection:this.collection})});return u.applyMutations(c),this.markPendingLocalOrigins(c),u.commit().catch(()=>{}),r.transactions.set(u.id,u),r.scheduleTransactionCleanup(u),r.recomputeOptimisticState(!0),u}},this.delete=(n,i)=>{const r=this.state;this.lifecycle.validateCollectionUsable("delete");const o=this.getActiveTransaction();if(!o&&!this.config.onDelete)throw new vs;if(Array.isArray(n)&&n.length===0)throw new gs;const a=Array.isArray(n)?n:[n],c=[];for(const u of a){if(!this.state.has(u))throw new Ss(u);const h=this.generateGlobalKey(u,this.state.get(u)),l={mutationId:le(),original:this.state.get(u),modified:this.state.get(u),changes:this.state.get(u),globalKey:h,key:u,metadata:i?.metadata,syncMetadata:r.syncedMetadata.get(u)||{},optimistic:i?.optimistic??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};c.push(l)}if(o)return o.applyMutations(c),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;const d=this.createTransaction({autoCommit:!0,metadata:{[ye]:!0},mutationFn:async u=>this.config.onDelete({transaction:u.transaction,collection:this.collection})});return d.applyMutations(c),this.markPendingLocalOrigins(c),d.commit().catch(()=>{}),r.transactions.set(d.id,d),r.scheduleTransactionCleanup(d),r.recomputeOptimisticState(!0),d},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}setTransactionScope(e){this.transactionScope=e}getActiveTransaction(){return this.transactionScope?this.transactionScope.getActiveTransactionForCollection():ti()}createTransaction(e){return this.transactionScope?this.transactionScope.createTransaction(e):ei(e)}ensureStandardSchema(e){if(e&&"~standard"in e)return e;throw new is}validateData(e,t,n){if(!this.config.schema)return e;const i=this.ensureStandardSchema(this.config.schema);if(t==="update"&&n){const o=this.state.get(n);if(o&&e&&typeof e=="object"&&typeof o=="object"){const a=Object.assign({},o,e),c=i["~standard"].validate(a);if(c instanceof Promise)throw new et;if("issues"in c&&c.issues){const l=c.issues.map(f=>({message:f.message,path:f.path?.map(p=>String(p))}));throw new Xe(t,l)}const d=c.value,u=Object.keys(e);return Object.fromEntries(u.map(l=>[l,d[l]]))}}const r=i["~standard"].validate(e);if(r instanceof Promise)throw new et;if("issues"in r&&r.issues){const o=r.issues.map(a=>({message:a.message,path:a.path?.map(c=>String(c))}));throw new Xe(t,o)}return r.value}generateGlobalKey(e,t){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new ls(t):new us(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(const t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(typeof e>"u")throw new fs;const i=this.state;this.lifecycle.validateCollectionUsable("update");const r=this.getActiveTransaction();if(!r&&!this.config.onUpdate)throw new ws;const o=Array.isArray(e),a=o?e:[e];if(o&&a.length===0)throw new ps;const c=typeof t=="function"?t:n,d=typeof t=="function"?{}:t,u=a.map(p=>{const y=this.state.get(p);if(!y)throw new ys(p);return y});let h;o?h=Jn(u,c):h=[Yn(u[0],c)];const l=a.map((p,y)=>{const w=h[y];if(!w||Object.keys(w).length===0)return null;const b=u[y],T=this.validateData(w,"update",p),v=Object.assign({},b,T),k=this.config.getKey(b),A=this.config.getKey(v);if(k!==A)throw new ms(k,A);const E=this.generateGlobalKey(A,v);return{mutationId:le(),original:b,modified:v,changes:Object.fromEntries(Object.keys(w).map(x=>[x,v[x]])),globalKey:E,key:p,metadata:d.metadata,syncMetadata:i.syncedMetadata.get(p)||{},optimistic:d.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(l.length===0){const p=this.createTransaction({mutationFn:async()=>{}});return p.commit().catch(()=>{}),i.scheduleTransactionCleanup(p),p}if(r)return r.applyMutations(l),i.transactions.set(r.id,r),i.scheduleTransactionCleanup(r),i.recomputeOptimisticState(!0),r;const f=this.createTransaction({metadata:{[ye]:!0},mutationFn:async p=>this.config.onUpdate({transaction:p.transaction,collection:this.collection})});return f.applyMutations(l),this.markPendingLocalOrigins(l),f.commit().catch(()=>{}),i.transactions.set(f.id,f),i.scheduleTransactionCleanup(f),i.recomputeOptimisticState(!0),f}}class ii extends Ut{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t,n){if(this.emitInnerWhile("status:change",{type:"status:change",collection:this.collection,previousStatus:t,status:e},n),!n())return;const i=`status:${e}`;this.emitInnerWhile(i,{type:i,collection:this.collection,previousStatus:t,status:e},n)}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 ri(s){const e=new oi(s);return s.utils?e.utils=s.utils:e.utils={},e}class oi{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(t,n)=>this._mutations.insert(t,n),this.delete=(t,n)=>this._mutations.delete(t,n),!e)throw new ss;if(!e.sync)throw new ns;if(e.id?this.id=e.id:this.id=le(),this.config={...e,autoIndex:e.autoIndex??"off"},this.config.autoIndex==="eager"&&!e.defaultIndexType)throw new ee(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
5
5
  import { BasicIndex } from '@tanstack/db'
6
- createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);Qt(this),this._changes=new Tn,this._events=new ti,this._indexes=new Fn,this._lifecycle=new Pn(e,this.id),this._mutations=new ei(e,this.id),this._state=new fn(e),this._sync=new An(e,this.id),this.comparisonOpts=ii(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}get _stateRevision(){return this._changes.stateRevision}get _layoutRevision(){return this._changes.layoutRevision}_subscribeLayoutChanges(e){return this._changes.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this._changes.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status==="ready"}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_setTransactionScope(e){this._mutations.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}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(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,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(){const e=new Map;for(const[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 un(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 ii(s){if(s.defaultStringCollation){const e=s.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}function ri(s){const e=s.getMapping(),t=new Map;for(const[n,i]of Object.entries(e.columns))i.predicate!=="@id"&&t.set(n,i.predicate);return t}function We(s,e){const t=new Map;for(const[i,r]of ri(e))t.set(r,i);const n=new Map;for(const[i,r]of Object.entries(s.fields))n.set(i,{field:i,descriptor:r,column:t.get(r.predicate)});return n}function oi(s){return Wt(s.storage.resourceIdPattern)}function ai(s,e){const t=e.getType();if(s.class!==t)throw new F("mapping_class_mismatch",`descriptor ${s.uri} declares class ${s.class} but table ${e.config.name} reads ${t}`)}function Be(s){return new Set(Object.entries(s.fields).filter(([,e])=>e.secret===!0).map(([e])=>e))}function qt(s){const e=Be(s);return Object.entries(s.fields).filter(([t])=>!e.has(t)).sort(([,t],[,n])=>t.predicate<n.predicate?-1:t.predicate>n.predicate?1:0).map(([t])=>t)}function ci(s){return typeof s=="object"&&s!==null&&typeof s.termType=="string"&&typeof s.value=="string"}function li(s){const e=s.datatype;if(e)return typeof e=="string"?e:e.value}function St(s,e){if(e==null||e==="")return;const t=ci(e)?e:void 0,n=t?t.value:e,i=t?li(t):void 0;switch(s.type){case"uri":return t&&t.termType!=="NamedNode",String(n);case"string":case"text":return String(n);case"number":{if(typeof n=="number")return n;const r=Number(n);return Number.isFinite(r)?r:void 0}case"boolean":return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:!!n;case"timestamp":{const r=n instanceof Date?n:new Date(String(n));return Number.isNaN(r.getTime())?void 0:r}case"json":{if(!t)return e;if(i&&!/#json(Array)?$/u.test(i)&&n==="")return;try{return JSON.parse(String(n))}catch{return n}}default:return n}}function ui(s,e){if(s.array){if(e==null)return;const n=(Array.isArray(e)?e:[e]).map(i=>St(s,i)).filter(i=>i!==void 0);return n.length>0?n:void 0}return St(s,e)}function di(s,e,t){const n=We(s,e),i=oi(s),r=Be(s),o=[];for(const a of t){const c=Nt(s,a);if(c===void 0)continue;const u={id:c};i!=="id"&&(u[i]=c);const d=a["@id"]??a.uri??a.subject;typeof d=="string"&&(u["@id"]=d);for(const h of n.values()){if(r.has(h.field)||h.column===void 0)continue;const l=ui(h.descriptor,a[h.column]);l!==void 0&&(u[h.field]=l)}o.push(u)}return o}function hi(s,e,t,n){const i=We(s,e),r={id:n.resourceId};for(const[o,a]of Object.entries(t)){if(o==="id"||o==="@id")continue;const c=i.get(o);!c||c.column===void 0||n.includeField&&!n.includeField(o)||(r[c.column]=a)}return r}function He(s){return s.array===!0&&s.type==="uri"}async function fi(s,e){return typeof s.isInitialized!="function"||s.isInitialized()||await e.init?.(s),await e.select().from(s).execute()}async function pi(s,e={}){return{etag:void 0,subjects:(await fi(s.table,s.database)).filter(n=>Bt(s.descriptor,s.document,s.podUrl,n))}}function yi(s){const t=s.getDialect?.()?.config?.session?.fetch;return typeof t=="function"?t:void 0}const mi=new Set;function ne(s){const e=s,t={};for(const[n,i]of Object.entries(e))n.startsWith("$")||(t[n]=i);return t}function X(s){if(s instanceof Date)return s.toISOString();if(Array.isArray(s))return s.map(e=>X(e));if(s&&typeof s=="object"){if(s instanceof Set)return[...s].map(t=>X(t));const e=Object.entries(s).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0);return Object.fromEntries(e.map(([t,n])=>[t,X(n)]))}return s}function jt(s,e){const t=ne(s),n={};t.id!==void 0&&(n.id=X(t.id));for(const i of e)t[i]!==void 0&&(n[i]=X(t[i]));return JSON.stringify(n)}function gi(s,e){return s===void 0||e===void 0?s===e:JSON.stringify(X(s))===JSON.stringify(X(e))}function Si(s,e,t=mi){if(s===void 0)return!1;const n=ne(s),i=ne(e);for(const[r,o]of Object.entries(i))if(!(r==="@id"||o===void 0)&&!t.has(r)&&!gi(n[r],o))return!1;return!0}function bi(s){const e=new Set(s.presentKeys),t=[],n=[],i=[],r=o=>{const a=s.knownHash(o);if(a!==void 0)return a;const c=s.presentRow?.(o);return c===void 0?void 0:s.hashOf(c)};for(const[o,a]of s.next){if(s.pendingKeys.has(o)){e.has(o)&&r(o)!==s.hashOf(a)&&n.push({key:o,row:a});continue}if(!e.has(o)){t.push({key:o,row:a});continue}r(o)!==s.hashOf(a)&&n.push({key:o,row:a})}for(const o of e){if(s.next.has(o)||s.pendingKeys.has(o))continue;const a=s.presentRow?.(o);a!==void 0&&i.push({key:o,row:a})}return{inserts:t,updates:n,deletes:i}}function wi(){let s;return{promise:new Promise(t=>{s=()=>t()}),resolve:s}}function vi(s){const e=new Set,t=new Map,n=[],i=a=>{e.delete(a),t.delete(a)};return{keys:e,entries:t,conflicts:n,register:a=>{i(a.key);const c=wi(),u={...a,settled:!1,error:void 0,settledPromise:c.promise,resolveSettled:c.resolve};return t.set(a.key,u),e.add(a.key),u},clear:i,settle:(a,c)=>{a.settled||(a.error=c,a.settled=!0,a.resolveSettled())},isConfirmed:a=>t.get(a)?.settled===!0&&t.get(a)?.error===void 0,recordConflict:a=>{n.push(a),s?.(a)}}}function bt(s,e,t){s.recordConflict({key:e.key,server:t,local:e.localRow??e.intent??t,at:Date.now()}),s.settle(e,new F("write_conflict",`row ${e.key} was changed by someone else; server wins`))}function ki(s,e,t,n=Ci){for(const i of s.entries.values()){if(i.settled)continue;const r=e.get(i.key);if(i.intent===void 0){if(r===void 0){s.settle(i);continue}i.beforeHash!==void 0&&t(r)!==i.beforeHash&&bt(s,i,r);continue}if(Si(r,i.intent,n)){s.settle(i);continue}if(r!==void 0&&t(r)!==i.beforeHash){bt(s,i,r);continue}r===void 0&&i.beforeHash!==void 0&&s.settle(i,new F("write_conflict",`row ${i.key} disappeared before the write was confirmed; server wins`))}}const Ci=new Set;function wt(s,e){if(!(typeof s!="string"||s.length===0))return/^[a-z][a-z0-9+.-]*:/iu.test(s)?s:new URL(s,e).toString()}async function Ri(s,e,t){const n=s.descriptor.fields[e];if(!n||!He(n))throw new F("write_field_not_uri_array",`field ${e} is not array+uri; it must go through the ORM`);const i=Ht(s.document),r=(Array.isArray(t.previous)?t.previous:[t.previous]).map(h=>wt(h,i)).filter(h=>h!==void 0),o=(Array.isArray(t.next)?t.next:[t.next]).map(h=>wt(h,i)).filter(h=>h!==void 0),a=h=>h.map(l=>`<${t.subjectIri}> <${n.predicate}> <${l}> .`).join(`
7
- `),c=[r.length>0?`DELETE DATA { ${a(r)} }`:void 0,o.length>0?`INSERT DATA { ${a(o)} }`:void 0].filter(h=>h!==void 0);if(c.length===0)return;const u=s.authenticatedFetch??yi(s.database);if(!u)throw new F("write_field_no_fetch","array+uri fields need an authenticated fetch (SolidAuthSession.fetch); none available");const d=await u(i,{method:"PATCH",headers:{"content-type":"application/sparql-update"},body:c.join(`;
8
- `)});if(!d.ok)throw new F("write_field_rejected",`SPARQL PATCH for ${e} failed with HTTP ${d.status}`)}function Oi(s){const{descriptor:e,table:t,pending:n}=s,i=qt(e),r=d=>jt(d,i),o=new Set(Object.entries(e.fields).filter(([,d])=>He(d)).map(([d])=>d)),a=We(e,t),c=d=>a.get(d)?.column,u=async(d,h)=>{try{await h()}catch(l){throw n.clear(d),l instanceof Error?l:new F("write_failed",String(l),{cause:l})}try{await s.confirm(d)}finally{n.clear(d)}};return{onInsert:async({transaction:d})=>{for(const h of d.mutations){const l=h.modified,p=String(h.key),f=Oe(e,s.document,s.podUrl,p),g=Ge(e,s.document,p);n.register({key:p,intent:l,localRow:l,beforeHash:void 0}),await u(p,async()=>{const w=hi(e,t,l,{resourceId:f,includeField:b=>!o.has(b)});await s.database.insert(t).values(w).execute(),await vt(s,l,g,void 0,l)})}},onUpdate:async({transaction:d})=>{for(const h of d.mutations){const l=String(h.key),p=h.original,f=h.modified,g=h.changes,w=Oe(e,s.document,s.podUrl,l),b=Ge(e,s.document,l),x=p&&Object.keys(p).length>0?r(p):void 0;n.register({key:l,intent:f,localRow:f,beforeHash:x}),await u(l,async()=>{const v={};for(const[k,M]of Object.entries(g)){if(o.has(k))continue;const T=c(k);T!==void 0&&(v[T]=M)}if(Object.keys(v).length>0&&!await s.database.updateById(t,w,v))throw new F("write_rejected",`drizzle-solid did not update ${w}`);await vt(s,g,b,p,f)})}},onDelete:async({transaction:d})=>{for(const h of d.mutations){const l=String(h.key),p=h.original,f=Oe(e,s.document,s.podUrl,l);n.register({key:l,intent:void 0,localRow:p,beforeHash:p&&Object.keys(p).length>0?r(p):void 0}),await u(l,async()=>{await s.database.deleteById(t,f)})}}}}async function vt(s,e,t,n,i){for(const[r,o]of Object.entries(s.descriptor.fields))He(o)&&r in e&&await Ri(s,r,{subjectIri:t,previous:n?.[r],next:i?.[r]})}const Ae={available:!1,unsubscribe:()=>{}};function Ti(s,e,t){if(!s||typeof s.watch!="function")return Ae;try{const n=s.watch(e,t);if(typeof n!="function")return Ae;let i=!0;return{available:!0,unsubscribe:()=>{i&&(i=!1,n())}}}catch{return Ae}}const xi=75,Ei=2;function Di(s){return new Promise(e=>{setTimeout(e,s)})}function Pi(s){const{descriptor:e,table:t,database:n,document:i,podUrl:r,pending:o}=s,a=s.coalesceMs??xi,c=s.confirmRetries??Ei,u=qt(e),d=Be(e),h=R=>jt(R,u);let l,p,f=!1,g=!1,w=!1,b="initializing",x,v=[],k,M=!1,T=!1,E;async function m(){if(l)return l;const R=s.collection();if(!R)throw new F("sync_not_started","collection has not started syncing yet");if(await R.preload(),!l)throw new F("sync_not_started","collection sync did not start");return l}function S(){T||x!==void 0||(x=setTimeout(()=>{x=void 0,y().catch(()=>{b="degraded"})},a))}function y(){if(k)return M=!0,k;const R=(async()=>{try{do M=!1,await O();while(M&&!T)}finally{k=void 0}})();return k=R,R}async function O(){const R=await m();if(T)return;let D;try{D=await pi({descriptor:e,table:t,database:n,document:i,podUrl:r},{ifNoneMatch:E})}catch(P){b="degraded",!g&&!w&&(w=!0,R.markError(P));return}D.etag!==void 0&&(E=D.etag);const Y=di(e,t,D.subjects),re=new Map(Y.map(P=>[String(P.id),P])),Ce=[...R.collection.keys()].map(P=>String(P)),Re=P=>R.metadata?.row.get(P)?.hash,N=bi({next:re,presentKeys:Ce,pendingKeys:o.keys,knownHash:Re,hashOf:h,presentRow:P=>R.collection.get(P)});if(N.inserts.length+N.updates.length+N.deletes.length>0){R.begin({immediate:!0});for(const P of N.inserts)R.write({type:"insert",value:ne(P.row)});for(const P of N.updates)R.write({type:"update",value:ne(P.row)});for(const P of N.deletes)R.write({type:"delete",key:P.key,value:ne(P.row)});for(const P of[...N.inserts,...N.updates])R.metadata?.row.set(P.key,{hash:h(P.row)});await R.commit()}g||(g=!0,w=!1,R.markReady()),ki(o,re,h,d),b=f?"live":"unavailable"}async function C(R){const D=o.entries.get(R);if(D)for(let Y=0;;Y+=1){if(await y(),D.settled){if(D.error)throw D.error;return}if(Y>=c)throw new F("write_unconfirmed",`write to ${R} was not visible in the document after ${c+1} reads`);await Di(a)}}const A=R=>T?()=>{}:(l=R,p=Ti(s.feed,i,()=>{if(!g){v.push({topic:i});return}S()}),f=p.available,y().then(()=>{if(T)return;const D=v;v=[],D.length>0&&S()}).catch(()=>{b="degraded"}),()=>{V()});function V(){T||(T=!0,x!==void 0&&(clearTimeout(x),x=void 0),p?.unsubscribe(),p=void 0,v=[])}return{sync:A,refresh:()=>y(),confirmPending:C,state:()=>b,dispose:V,truncate:()=>{!l||T||(l.begin({immediate:!0}),l.truncate(),Promise.resolve(l.commit()).catch(()=>{}))}}}function Ii(s,e){ai(s,e.table);const t=Ct(s,{podUrl:e.podUrl,document:e.document,scope:e.scope}),n=vi(e.onConflict);let i;const r=Pi({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,feed:e.feed,coalesceMs:e.coalesceMs,confirmRetries:e.confirmRetries,pending:n,collection:()=>i}),o=Oi({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,pending:n,confirm:c=>r.confirmPending(c)}),a=si({id:`pod-collection:${s.uri}:${t}`,getKey:c=>c.id,sync:{sync:r.sync,rowUpdateMode:"full"},startSync:!0,onInsert:o.onInsert,onUpdate:o.onUpdate,onDelete:o.onDelete});return i=a,Object.assign(a,{tableDocument:t,pendingKeys:n.keys,conflicts:n.conflicts,refresh:()=>r.refresh(),syncState:()=>r.state(),dispose:()=>r.dispose(),truncateForTest:()=>r.truncate()})}function kt(s){const e=s;if(typeof e.syncState!="function"||typeof e.dispose!="function")throw new F("collection_not_from_define","collection was not created by definePodCollection()");return e}function Mi(s){const e=new Map,t=new Set;let n;const i=()=>{for(const a of[...t])a()},r=(a,c)=>`${a.uri}\0${c}`,o=(a,c)=>{const u=Ct(a,{podUrl:s.podUrl,document:c.document,scope:c.scope}),d=r(a,u),h=e.get(d);if(h)return h;const l=Ii(a,{...c,database:s.database,podUrl:s.podUrl,feed:s.feed});return e.set(d,l),l.preload().then(i,i),l};return{define:o,async load(a,c){return o(a,c)},syncState(a){return kt(a).syncState()},subscribeSyncState(a){return t.add(a),t.size===1&&typeof s.feed?.subscribeState=="function"&&(n=s.feed.subscribeState(i)),()=>{t.delete(a),t.size===0&&(n?.(),n=void 0)}},dispose(){for(const a of e.values())kt(a).dispose();e.clear(),n?.(),n=void 0,i()}}}export{Mi as createPodCollectionsCapability};
6
+ createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);es(this),this._changes=new Dn,this._events=new ii,this._indexes=new $n,this._lifecycle=new _n(e,this.id),this._mutations=new ni(e,this.id),this._state=new mn(e),this._sync=new Ln(e,this.id),this.comparisonOpts=ai(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}get _stateRevision(){return this._changes.stateRevision}get _layoutRevision(){return this._changes.layoutRevision}_subscribeLayoutChanges(e){return this._changes.subscribeLayoutChanges(e)}_markLayoutChange(){this._sync.markLayoutChange()}_deferPublication(){return this._changes.deferPublication()}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status==="ready"}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}_setTransactionScope(e){this._mutations.setTransactionScope(e)}_hasHydratedKey(e){return this._state.hydratedKeys.has(e)}_deferSyncStart(){return this._sync.deferStart()}_resumeSyncStart(){this._sync.resumeStart()}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(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(const e of this._state.keys()){const t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(const[n,i]of this.entries())e(i,n,t++)}map(e){const t=[];let n=0;for(const[i,r]of this.entries())t.push(e(r,i,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(){const e=new Map;for(const[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 fn(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 ai(s){if(s.defaultStringCollation){const e=s.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}const qt=/^[a-z][a-z0-9+.-]*:/iu;function ci(s){const e=s.getMapping(),t=new Map;for(const[n,i]of Object.entries(e.columns))i.predicate!=="@id"&&t.set(n,i.predicate);return t}function Ce(s,e){const t=new Map;for(const[i,r]of ci(e))t.set(r,i);const n=new Map;for(const[i,r]of Object.entries(s.fields))n.set(i,{field:i,descriptor:r,column:t.get(r.predicate)});return n}function li(s){return Gt(s.storage.resourceIdPattern)}function ui(s,e){const t=e.getType();if(s.class!==t)throw new F("mapping_class_mismatch",`descriptor ${s.uri} declares class ${s.class} but table ${e.config.name} reads ${t}`)}function He(s){return new Set(Object.entries(s.fields).filter(([,e])=>e.secret===!0).map(([e])=>e))}function Nt(s){const e=He(s);return Object.entries(s.fields).filter(([t])=>!e.has(t)).sort(([,t],[,n])=>t.predicate<n.predicate?-1:t.predicate>n.predicate?1:0).map(([t])=>t)}function di(s){return typeof s=="object"&&s!==null&&typeof s.termType=="string"&&typeof s.value=="string"}function hi(s){const e=s.datatype;if(e)return typeof e=="string"?e:e.value}function bt(s,e){if(e==null||e==="")return;const t=di(e)?e:void 0,n=t?t.value:e,i=t?hi(t):void 0;switch(s.type){case"uri":return t&&t.termType!=="NamedNode",String(n);case"string":case"text":return String(n);case"number":{if(typeof n=="number")return n;const r=Number(n);return Number.isFinite(r)?r:void 0}case"boolean":return typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:!!n;case"timestamp":{const r=n instanceof Date?n:new Date(String(n));return Number.isNaN(r.getTime())?void 0:r}case"json":{if(!t)return e;if(i&&!/#json(Array)?$/u.test(i)&&n==="")return;try{return JSON.parse(String(n))}catch{return n}}default:return n}}function fi(s,e){if(s.array){if(e==null)return;const n=(Array.isArray(e)?e:[e]).map(i=>bt(s,i)).filter(i=>i!==void 0);return n.length>0?n:void 0}return bt(s,e)}function pi(s,e,t){const n=Ce(s,e),i=li(s),r=He(s),o=[];for(const a of t){const c=Ht(s,a);if(c===void 0)continue;const d={id:c};i!=="id"&&(d[i]=c);const u=a["@id"]??a.uri??a.subject;typeof u=="string"&&(d["@id"]=u);for(const h of n.values()){if(r.has(h.field)||h.column===void 0)continue;const l=fi(h.descriptor,a[h.column]);l!==void 0&&(d[h.field]=l)}o.push(d)}return o}function Wt(s,e,t,n){const i=Ce(s,e),r={id:n.resourceId};for(const[o,a]of Object.entries(t)){if(o==="id"||o==="@id")continue;const c=i.get(o);!c||c.column===void 0||n.includeField&&!n.includeField(o)||(r[c.column]=a)}return r}function Ge(s){return s.array===!0&&s.type==="uri"}function Fe(s,e){return(Array.isArray(s)?s:[s]).filter(t=>typeof t=="string"&&t.length>0).map(t=>qt.test(t)?t:new URL(t,e).toString())}function wt(s,e,t,n){const i={...t},r=Wt(s,e,t,{resourceId:n.resourceId}),o=Ce(s,e),a=new Set([e]);for(const u of Object.values(n.database.schema??{}))u&&typeof u=="object"&&"config"in u&&"columns"in u&&a.add(u);const c=new Map,d=new Map;for(const u of a){c.set(u.config.name,u);const h=u.getType();d.set(h,[...d.get(h)??[],u])}for(const[u,h]of o){const l=i[u];if(h.descriptor.type!=="uri"||l===void 0||l===null)continue;if(h.descriptor.array){i[u]=Fe(l,n.document);continue}if(!h.column||typeof l!="string"||!l||qt.test(l))continue;const f=n.database.getDialect().getUriResolver();i[u]=f.resolveLink(l,e.columns[h.column],{baseUri:n.podUrl,tableRegistry:d,tableNameRegistry:c,currentTable:e,record:r})}return i}async function yi(s,e){return typeof s.isInitialized!="function"||s.isInitialized()||await e.init?.(s),await e.select().from(s).execute()}async function mi(s,e={}){return{etag:void 0,subjects:(await yi(s.table,s.database)).filter(n=>Yt(s.descriptor,s.document,s.podUrl,n))}}function gi(s){const t=s.getDialect?.()?.config?.session?.fetch;return typeof t=="function"?t:void 0}const Si=new Set;function ne(s){const e=s,t={};for(const[n,i]of Object.entries(e))n.startsWith("$")||(t[n]=i);return t}function X(s){if(s instanceof Date)return s.toISOString();if(Array.isArray(s))return s.map(e=>X(e));if(s&&typeof s=="object"){if(s instanceof Set)return[...s].map(t=>X(t));const e=Object.entries(s).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0);return Object.fromEntries(e.map(([t,n])=>[t,X(n)]))}return s}function Bt(s,e){const t=ne(s),n={};t.id!==void 0&&(n.id=X(t.id));for(const i of e)t[i]!==void 0&&(n[i]=X(t[i]));return JSON.stringify(n)}function bi(s,e){return s===void 0||e===void 0?s===e:JSON.stringify(X(s))===JSON.stringify(X(e))}function wi(s,e,t=Si){if(s===void 0)return!1;const n=ne(s),i=ne(e);for(const[r,o]of Object.entries(i))if(!(r==="@id"||o===void 0)&&!t.has(r)&&!bi(n[r],o))return!1;return!0}function vi(s){const e=new Set(s.presentKeys),t=[],n=[],i=[],r=o=>{const a=s.knownHash(o);if(a!==void 0)return a;const c=s.presentRow?.(o);return c===void 0?void 0:s.hashOf(c)};for(const[o,a]of s.next){if(s.pendingKeys.has(o)){e.has(o)&&r(o)!==s.hashOf(a)&&n.push({key:o,row:a});continue}if(!e.has(o)){t.push({key:o,row:a});continue}r(o)!==s.hashOf(a)&&n.push({key:o,row:a})}for(const o of e){if(s.next.has(o)||s.pendingKeys.has(o))continue;const a=s.presentRow?.(o);a!==void 0&&i.push({key:o,row:a})}return{inserts:t,updates:n,deletes:i}}function ki(){let s;return{promise:new Promise(t=>{s=()=>t()}),resolve:s}}function Ci(s){const e=new Set,t=new Map,n=[],i=a=>{e.delete(a),t.delete(a)};return{keys:e,entries:t,conflicts:n,register:a=>{i(a.key);const c=ki(),d={...a,settled:!1,error:void 0,settledPromise:c.promise,resolveSettled:c.resolve};return t.set(a.key,d),e.add(a.key),d},clear:i,settle:(a,c)=>{a.settled||(a.error=c,a.settled=!0,a.resolveSettled())},isConfirmed:a=>t.get(a)?.settled===!0&&t.get(a)?.error===void 0,recordConflict:a=>{n.push(a),s?.(a)}}}function vt(s,e,t){s.recordConflict({key:e.key,server:t,local:e.localRow??e.intent??t,at:Date.now()}),s.settle(e,new F("write_conflict",`row ${e.key} was changed by someone else; server wins`))}function Ri(s,e,t,n=Oi){for(const i of s.entries.values()){if(i.settled)continue;const r=e.get(i.key);if(i.intent===void 0){if(r===void 0){s.settle(i);continue}i.beforeHash!==void 0&&t(r)!==i.beforeHash&&vt(s,i,r);continue}if(wi(r,i.intent,n)){s.settle(i);continue}if(r!==void 0&&t(r)!==i.beforeHash){vt(s,i,r);continue}r===void 0&&i.beforeHash!==void 0&&s.settle(i,new F("write_conflict",`row ${i.key} disappeared before the write was confirmed; server wins`))}}const Oi=new Set;async function Ti(s,e,t){const n=s.descriptor.fields[e];if(!n||!Ge(n))throw new F("write_field_not_uri_array",`field ${e} is not array+uri; it must go through the ORM`);const i=Jt(s.document),r=Fe(t.previous,i),o=Fe(t.next,i),a=h=>h.map(l=>`<${t.subjectIri}> <${n.predicate}> <${l}> .`).join(`
7
+ `),c=[r.length>0?`DELETE DATA { ${a(r)} }`:void 0,o.length>0?`INSERT DATA { ${a(o)} }`:void 0].filter(h=>h!==void 0);if(c.length===0)return;const d=s.authenticatedFetch??gi(s.database);if(!d)throw new F("write_field_no_fetch","array+uri fields need an authenticated fetch (SolidAuthSession.fetch); none available");const u=await d(i,{method:"PATCH",headers:{"content-type":"application/sparql-update"},body:c.join(`;
8
+ `)});if(!u.ok)throw new F("write_field_rejected",`SPARQL PATCH for ${e} failed with HTTP ${u.status}`)}function Ei(s){const{descriptor:e,table:t,pending:n}=s,i=Nt(e),r=u=>Bt(u,i),o=new Set(Object.entries(e.fields).filter(([,u])=>Ge(u)).map(([u])=>u)),a=Ce(e,t),c=u=>a.get(u)?.column,d=async(u,h)=>{try{await h()}catch(l){throw n.clear(u),l instanceof Error?l:new F("write_failed",String(l),{cause:l})}try{await s.confirm(u)}finally{n.clear(u)}};return{onInsert:async({transaction:u})=>{for(const h of u.mutations){const l=String(h.key),f=Te(e,s.document,s.podUrl,l),p=Ye(e,s.document,l),y=wt(e,t,h.modified,{database:s.database,podUrl:s.podUrl,document:s.document,resourceId:f});Object.assign(h.modified,y),n.register({key:l,intent:y,localRow:y,beforeHash:void 0}),await d(l,async()=>{const w=Wt(e,t,y,{resourceId:f,includeField:b=>!o.has(b)});await s.database.insert(t).values(w).execute(),await kt(s,y,p,void 0,y)})}},onUpdate:async({transaction:u})=>{for(const h of u.mutations){const l=String(h.key),f=h.original,p=h.changes,y=Te(e,s.document,s.podUrl,l),w=Ye(e,s.document,l),b=wt(e,t,h.modified,{database:s.database,podUrl:s.podUrl,document:s.document,resourceId:y});Object.assign(h.modified,b);const T=f&&Object.keys(f).length>0?r(f):void 0;n.register({key:l,intent:b,localRow:b,beforeHash:T}),await d(l,async()=>{const v={};for(const k of Object.keys(p)){if(o.has(k))continue;const A=c(k);A!==void 0&&(v[A]=b[k])}if(Object.keys(v).length>0&&!await s.database.updateById(t,y,v))throw new F("write_rejected",`drizzle-solid did not update ${y}`);await kt(s,p,w,f,b)})}},onDelete:async({transaction:u})=>{for(const h of u.mutations){const l=String(h.key),f=h.original,p=Te(e,s.document,s.podUrl,l);n.register({key:l,intent:void 0,localRow:f,beforeHash:f&&Object.keys(f).length>0?r(f):void 0}),await d(l,async()=>{await s.database.deleteById(t,p)})}}}}async function kt(s,e,t,n,i){for(const[r,o]of Object.entries(s.descriptor.fields))Ge(o)&&r in e&&await Ti(s,r,{subjectIri:t,previous:n?.[r],next:i?.[r]})}const _e={available:!1,unsubscribe:()=>{}};function xi(s,e,t){if(!s||typeof s.watch!="function")return _e;try{const n=s.watch(e,t);if(typeof n!="function")return _e;let i=!0;return{available:!0,unsubscribe:()=>{i&&(i=!1,n())}}}catch{return _e}}const Di=75,Ii=2;function Pi(s){return new Promise(e=>{setTimeout(e,s)})}function Ai(s){const{descriptor:e,table:t,database:n,document:i,podUrl:r,pending:o}=s,a=s.coalesceMs??Di,c=s.confirmRetries??Ii,d=Nt(e),u=He(e),h=R=>Bt(R,d);let l,f,p=!1,y=!1,w=!1,b="initializing",T,v=[],k,A=!1,E=!1,x;async function g(){if(l)return l;const R=s.collection();if(!R)throw new F("sync_not_started","collection has not started syncing yet");if(await R.preload(),!l)throw new F("sync_not_started","collection sync did not start");return l}function S(){E||T!==void 0||(T=setTimeout(()=>{T=void 0,m().catch(()=>{b="degraded"})},a))}function m(){if(k)return A=!0,k;const R=(async()=>{try{do A=!1,await O();while(A&&!E)}finally{k=void 0}})();return k=R,R}async function O(){const R=await g();if(E)return;let D;try{D=await mi({descriptor:e,table:t,database:n,document:i,podUrl:r},{ifNoneMatch:x})}catch(I){b="degraded",!y&&!w&&(w=!0,R.markError(I));return}D.etag!==void 0&&(x=D.etag);const Y=pi(e,t,D.subjects),re=new Map(Y.map(I=>[String(I.id),I])),Re=[...R.collection.keys()].map(I=>String(I)),Oe=I=>R.metadata?.row.get(I)?.hash,N=vi({next:re,presentKeys:Re,pendingKeys:o.keys,knownHash:Oe,hashOf:h,presentRow:I=>R.collection.get(I)});if(N.inserts.length+N.updates.length+N.deletes.length>0){R.begin({immediate:!0});for(const I of N.inserts)R.write({type:"insert",value:ne(I.row)});for(const I of N.updates)R.write({type:"update",value:ne(I.row)});for(const I of N.deletes)R.write({type:"delete",key:I.key,value:ne(I.row)});for(const I of[...N.inserts,...N.updates])R.metadata?.row.set(I.key,{hash:h(I.row)});await R.commit()}y||(y=!0,w=!1,R.markReady()),Ri(o,re,h,u),b=p?"live":"unavailable"}async function C(R){const D=o.entries.get(R);if(D)for(let Y=0;;Y+=1){if(await m(),D.settled){if(D.error)throw D.error;return}if(Y>=c)throw new F("write_unconfirmed",`write to ${R} was not visible in the document after ${c+1} reads`);await Pi(a)}}const _=R=>E?()=>{}:(l=R,f=xi(s.feed,i,()=>{if(!y){v.push({topic:i});return}S()}),p=f.available,m().then(()=>{if(E)return;const D=v;v=[],D.length>0&&S()}).catch(()=>{b="degraded"}),()=>{U()});function U(){E||(E=!0,T!==void 0&&(clearTimeout(T),T=void 0),f?.unsubscribe(),f=void 0,v=[])}return{sync:_,refresh:()=>m(),confirmPending:C,state:()=>b,dispose:U,truncate:()=>{!l||E||(l.begin({immediate:!0}),l.truncate(),Promise.resolve(l.commit()).catch(()=>{}))}}}function _i(s,e){ui(s,e.table);const t=Rt(s,{podUrl:e.podUrl,document:e.document,scope:e.scope}),n=Ci(e.onConflict);let i;const r=Ai({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,feed:e.feed,coalesceMs:e.coalesceMs,confirmRetries:e.confirmRetries,pending:n,collection:()=>i}),o=Ei({descriptor:s,table:e.table,database:e.database,podUrl:e.podUrl,document:t,pending:n,confirm:c=>r.confirmPending(c)}),a=ri({id:`pod-collection:${s.uri}:${t}`,getKey:c=>c.id,sync:{sync:r.sync,rowUpdateMode:"full"},startSync:!0,onInsert:o.onInsert,onUpdate:o.onUpdate,onDelete:o.onDelete});return i=a,Object.assign(a,{tableDocument:t,pendingKeys:n.keys,conflicts:n.conflicts,refresh:()=>r.refresh(),syncState:()=>r.state(),dispose:()=>r.dispose(),truncateForTest:()=>r.truncate()})}function Ct(s){const e=s;if(typeof e.syncState!="function"||typeof e.dispose!="function")throw new F("collection_not_from_define","collection was not created by definePodCollection()");return e}function Ki(s){const e=new Map,t=new Set;let n;const i=()=>{for(const a of[...t])a()},r=(a,c)=>`${a.uri}\0${c}`,o=(a,c)=>{const d=Rt(a,{podUrl:s.podUrl,document:c.document,scope:c.scope}),u=r(a,d),h=e.get(u);if(h)return h;const l=_i(a,{...c,database:s.database,podUrl:s.podUrl,feed:s.feed});return e.set(u,l),l.preload().then(i,i),l};return{define:o,async load(a,c){return o(a,c)},syncState(a){return Ct(a).syncState()},subscribeSyncState(a){return t.add(a),t.size===1&&typeof s.feed?.subscribeState=="function"&&(n=s.feed.subscribeState(i)),()=>{t.delete(a),t.size===0&&(n?.(),n=void 0)}},dispose(){for(const a of e.values())Ct(a).dispose();e.clear(),n?.(),n=void 0,i()}}}export{Ki as createPodCollectionsCapability};