@membank/dashboard 0.7.1 → 0.9.0

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 (36) hide show
  1. package/dist/bin.mjs +25 -6
  2. package/dist/client/assets/WorkspaceMemoryDetail-BFpMjQWu.js +1 -0
  3. package/dist/client/assets/_projectId-Cs170Emi.js +40 -0
  4. package/dist/client/assets/_projectId-p99W0TrB.js +4 -0
  5. package/dist/client/assets/_projectId._memoryId-B8g4zsrH.js +1 -0
  6. package/dist/client/assets/_projectId.index-jEbJri1I.js +1 -0
  7. package/dist/client/assets/collections-Bj4kWtiN.js +19 -0
  8. package/dist/client/assets/index-DwfCB-hG.js +10 -0
  9. package/dist/client/assets/index-JriiD5q1.css +2 -0
  10. package/dist/client/assets/routes-uvB1fUgz.js +1 -0
  11. package/dist/client/assets/typeColors-C2x_OYRB.js +1 -0
  12. package/dist/client/index.html +4 -7
  13. package/dist/index.cjs +24 -5
  14. package/dist/index.d.cts +2 -2
  15. package/dist/index.d.mts +2 -2
  16. package/dist/index.mjs +25 -6
  17. package/package.json +2 -2
  18. package/dist/client/assets/WorkspaceCenter-F8ctl0ZL.js +0 -1
  19. package/dist/client/assets/WorkspaceMemoryDetail-BLFoEX3q.js +0 -1
  20. package/dist/client/assets/_projectId-D3UHHv9-.js +0 -1
  21. package/dist/client/assets/_projectId._memoryId-CZOJ7L4F.js +0 -1
  22. package/dist/client/assets/_projectId.index-Dc3jTh6p.js +0 -1
  23. package/dist/client/assets/collections-y7eMFwFc.js +0 -19
  24. package/dist/client/assets/empty-C4Q9vAt-.js +0 -1
  25. package/dist/client/assets/global-BZgjloNm.js +0 -1
  26. package/dist/client/assets/global._memoryId-DbiHUsW4.js +0 -1
  27. package/dist/client/assets/global.index-w6voN-YE.js +0 -1
  28. package/dist/client/assets/index-B3Ej81eU.js +0 -10
  29. package/dist/client/assets/index-DHtBroPC.css +0 -2
  30. package/dist/client/assets/input-BdBFU9te.js +0 -1
  31. package/dist/client/assets/preload-helper-DYD3iRAO.js +0 -1
  32. package/dist/client/assets/routes-DdtLVWUF.js +0 -1
  33. package/dist/client/assets/schemas-jSuIeSIL.js +0 -39
  34. package/dist/client/assets/skeleton-BDvkvqhf.js +0 -1
  35. package/dist/client/assets/types-DT_fBrSI.js +0 -1
  36. package/dist/client/assets/useRenderElement-DhejdWAQ.js +0 -1
@@ -0,0 +1,19 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),l=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u<e.length;u++)a=e[u],s=l+j(a,u),c+=N(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+j(a,u++),c+=N(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return N(M(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function P(e,t,n){if(e==null)return e;var r=[],i=0;return N(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ee(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var F=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},te={map:P,forEach:function(e,t,n){P(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return P(e,function(){t++}),t},toArray:function(e){return P(e,function(e){return e})||[]},only:function(e){if(!O(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=te,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return w.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!T.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return E(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)T.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return E(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=O,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ee}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=w.T,n={};w.T=n;try{var r=e(),i=w.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(C,F)}catch(e){F(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),w.T=t}},e.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()},e.use=function(e){return w.H.use(e)},e.useActionState=function(e,t,n){return w.H.useActionState(e,t,n)},e.useCallback=function(e,t){return w.H.useCallback(e,t)},e.useContext=function(e){return w.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return w.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return w.H.useEffect(e,t)},e.useEffectEvent=function(e){return w.H.useEffectEvent(e)},e.useId=function(){return w.H.useId()},e.useImperativeHandle=function(e,t,n){return w.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return w.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return w.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return w.H.useMemo(e,t)},e.useOptimistic=function(e,t){return w.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return w.H.useReducer(e,t,n)},e.useRef=function(e){return w.H.useRef(e)},e.useState=function(e){return w.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return w.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return w.H.useTransition()},e.version=`19.2.5`})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),f=o(((e,t)=>{t.exports=d()})),p=o((e=>{var t=u();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),m=o(((e,t)=>{t.exports=p()})),h=o((e=>{var t=u(),n=m();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),g=o(((e,t)=>{t.exports=h()})),_=g(),v=c(u(),1),y=v.use,b=typeof window<`u`?v.useLayoutEffect:v.useEffect;function x(e){let t=v.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function S(e,t,n={},r={}){v.useEffect(()=>{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function C(e){let t=v.useRef(null);return v.useImperativeHandle(e,()=>t.current,[]),t}function w(e){return e[e.length-1]}function T(e){return typeof e==`function`}function E(e,t){return T(e)?e(t):e}var D=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable,k=()=>Object.create(null),A=(e,t)=>j(e,t,k);function j(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=ee(e)&&ee(i);if(!a&&!(N(e)&&N(i)))return i;let o=a?e:M(e);if(!o)return i;let s=a?i:M(i);if(!s)return i;let c=o.length,l=s.length,u=a?Array(l):n(),d=0;for(let t=0;t<l;t++){let o=a?t:s[t],l=e[o],f=i[o];if(l===f){u[o]=l,(a?t<c:D.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=j(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function M(e){let t=Object.getOwnPropertyNames(e);for(let n of t)if(!O.call(e,n))return!1;let n=Object.getOwnPropertySymbols(e);if(n.length===0)return t;let r=t;for(let t of n){if(!O.call(e,t))return!1;r.push(t)}return r}function N(e){if(!P(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!P(n)||!n.hasOwnProperty(`isPrototypeOf`))}function P(e){return Object.prototype.toString.call(e)===`[object Object]`}function ee(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function F(e,t,n){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(!F(e[r],t[r],n))return!1;return!0}if(N(e)&&N(t)){let r=n?.ignoreUndefined??!0;if(n?.partial){for(let i in t)if((!r||t[i]!==void 0)&&!F(e[i],t[i],n))return!1;return!0}let i=0;if(!r)i=Object.keys(e).length;else for(let t in e)e[t]!==void 0&&i++;let a=0;for(let o in t)if((!r||t[o]!==void 0)&&(a++,a>i||!F(e[o],t[o],n)))return!1;return i===a}return!1}function te(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function ne(e){return typeof e?.message==`string`?e.message.startsWith(`Failed to fetch dynamically imported module`)||e.message.startsWith(`error loading dynamically imported module`)||e.message.startsWith(`Importing a module script failed`):!1}function re(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function ie(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function I(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return ie(t)}var L=[`http:`,`https:`,`mailto:`,`tel:`];function ae(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function oe(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=I(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=I(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function R(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function se(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function z(){throw Error(`Invariant failed`)}function ce(e){let t=new Map,n,r,i=e=>{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var B=4,V=5;function le(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function ue(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=le(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2<a.length&&a.charCodeAt(r+2)===36){let e=r+3,a=s;if(e<a)return n[0]=3,n[1]=t+r,n[2]=t+e,n[3]=t+a,n[4]=t+s+1,n[5]=i,n}}else if(c===36){let a=r+1,o=r+2;return o===s?(n[0]=2,n[1]=t+r,n[2]=t+a,n[3]=t+o,n[4]=t+s+1,n[5]=e.length,n):(n[0]=1,n[1]=t+r,n[2]=t+o,n[3]=t+s,n[4]=t+s+1,n[5]=i,n)}}return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n}function de(e,t,n,r,i,a,o){o?.(n);let s=r;{let r=n.fullPath??n.from,o=r.length,c=n.options?.caseSensitive??e,l=!!(n.options?.params?.parse&&n.options?.skipRouteOnParseError?.params);for(;s<o;){let e=ue(r,s,t),o,u=s,d=e[5];switch(s=d+1,a++,e[0]){case 0:{let t=r.substring(e[2],e[3]);if(c){let e=i.static?.get(t);if(e)o=e;else{i.static??=new Map;let e=me(n.fullPath??n.from);e.parent=i,e.depth=a,o=e,i.static.set(t,e)}}else{let e=t.toLowerCase(),r=i.staticInsensitive?.get(e);if(r)o=r;else{i.staticInsensitive??=new Map;let t=me(n.fullPath??n.from);t.parent=i,t.depth=a,o=t,i.staticInsensitive.set(e,t)}}break}case 1:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.dynamic?.find(e=>!e.skipOnParamError&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=he(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.skipOnParamError&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=he(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=he(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=me(n.fullPath??n.from);e.kind=V,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=me(n.fullPath??n.from);e.kind=B,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=n.options?.params?.parse??null,i.skipOnParamError=l,i.parsingPriority=n.options?.skipRouteOnParseError?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)de(e,t,r,s,i,a,o)}function fe(e,t){if(e.skipOnParamError&&!t.skipOnParamError)return-1;if(!e.skipOnParamError&&t.skipOnParamError)return 1;if(e.skipOnParamError&&t.skipOnParamError&&(e.parsingPriority||t.parsingPriority))return t.parsingPriority-e.parsingPriority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function pe(e){if(e.pathless)for(let t of e.pathless)pe(t);if(e.static)for(let t of e.static.values())pe(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())pe(t);if(e.dynamic?.length){e.dynamic.sort(fe);for(let t of e.dynamic)pe(t)}if(e.optional?.length){e.optional.sort(fe);for(let t of e.optional)pe(t)}if(e.wildcard?.length){e.wildcard.sort(fe);for(let t of e.wildcard)pe(t)}}function me(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,skipOnParamError:!1,parsingPriority:0}}function he(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,skipOnParamError:!1,parsingPriority:0,caseSensitive:n,prefix:r,suffix:i}}function ge(e,t){let n=me(`/`),r=new Uint16Array(6);for(let t of e)de(!1,r,t,1,n,0);pe(n),t.masksTree=n,t.flatCache=ce(1e3)}function _e(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=Se(e,t.masksTree);return t.flatCache.set(e,r),r}function ve(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=me(`/`),de(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),Se(r,o,n)}function ye(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=Se(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=we(a.route)),t.matchCache.set(r,a),a}function be(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function xe(e,t=!1,n){let r=me(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return de(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&z(),a[e.id]=e,s!==0&&e.path){let t=be(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),pe(r),{processedTree:{segmentTree:r,singleCache:ce(1e3),matchCache:ce(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function Se(e,t,n=!1){let r=e.split(`/`),i=Ee(e,r,t,n);if(!i)return null;let[a]=Ce(e,r,i);return{route:i.node.route,rawParams:a,parsedParams:i.parsedParams}}function Ce(e,t,n){let r=Te(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s<r.length;o++,s++,c++,l++){let u=r[s];if(u.kind===B)break;if(u.kind===V){l--,o--,c--;continue}let d=t[o],f=c;if(d&&(c+=d.length),u.kind===1){i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0;if(e.charCodeAt(t)===123){let n=u.suffix?.length??0,r=e.substring(t+2,e.length-n-1),i=d.substring(t,d.length-n);a[r]=decodeURIComponent(i)}else{let t=e.substring(1);a[t]=decodeURIComponent(d)}}else if(u.kind===3){if(n.skipped&1<<s){o--,c=f-1;continue}i??=n.node.fullPath.split(`/`);let e=i[l],t=u.prefix?.length??0,r=u.suffix?.length??0,p=e.substring(t+3,e.length-r-1),m=u.suffix||u.prefix?d.substring(t,d.length-r):d;m&&(a[p]=decodeURIComponent(m))}else if(u.kind===2){let t=u,n=e.substring(f+(t.prefix?.length??0),e.length-(t.suffix?.length??0)),r=decodeURIComponent(n);a[`*`]=r,a._splat=r;break}}return n.rawParams&&Object.assign(a,n.rawParams),[a,{part:o,node:s,path:c,segment:l}]}function we(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function Te(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Ee(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!w(t),a=i&&e!==`/`,o=t.length-+!!i,s=[{node:n,index:1,skipped:0,depth:1,statics:0,dynamics:0,optionals:0}],c=null,l=null;for(;s.length;){let n=s.pop(),{node:i,index:u,skipped:d,depth:f,statics:p,dynamics:m,optionals:h}=n,{extract:g,rawParams:_,parsedParams:v}=n;if(i.kind===2&&i.route&&!Ae(l,n))continue;if(i.skipOnParamError){if(!ke(e,t,n))continue;_=n.rawParams,g=n.extract,v=n.parsedParams}r&&i.route&&i.kind!==B&&Ae(c,n)&&(c=n);let y=u===o;if(y&&(i.route&&(!a||i.kind===B||i.kind===2)&&Ae(l,n)&&(l=n),!i.optional&&!i.wildcard&&!i.index&&!i.pathless))continue;let b=y?void 0:t[u],x;if(y&&i.index){let n={node:i.index,index:u,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v},r=!0;if(i.index.skipOnParamError&&(ke(e,t,n)||(r=!1)),r){if(!m&&!h&&!d&&Oe(p,o))return n;Ae(l,n)&&(l=n)}}if(i.wildcard)for(let e=i.wildcard.length-1;e>=0;e--){let n=i.wildcard[e],{prefix:r,suffix:a}=n;if(!(r&&(y||!(n.caseSensitive?b:x??=b.toLowerCase()).startsWith(r)))){if(a){if(y)continue;let e=t.slice(u).join(`/`).slice(-a.length);if((n.caseSensitive?e:e.toLowerCase())!==a)continue}s.push({node:n,index:o,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}}if(i.optional){let e=d|1<<f,t=f+1;for(let n=i.optional.length-1;n>=0;n--){let r=i.optional[n];s.push({node:r,index:u,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:a}=n;if(r||a){let e=n.caseSensitive?b:x??=b.toLowerCase();if(r&&!e.startsWith(r)||a&&!e.endsWith(a))continue}s.push({node:n,index:u+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+De(o,u),extract:g,rawParams:_,parsedParams:v})}}if(!y&&i.dynamic&&b)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?b:x??=b.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}s.push({node:t,index:u+1,skipped:d,depth:f+1,statics:p,dynamics:m+De(o,u),optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y&&i.staticInsensitive){let e=i.staticInsensitive.get(x??=b.toLowerCase());e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+De(o,u),dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(!y&&i.static){let e=i.static.get(b);e&&s.push({node:e,index:u+1,skipped:d,depth:f+1,statics:p+De(o,u),dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];s.push({node:n,index:u,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_,parsedParams:v})}}}if(l)return l;if(r&&c){let n=c.index;for(let e=0;e<c.index;e++)n+=t[e].length;let r=n===e.length?`/`:e.slice(n);return c.rawParams??=Object.create(null),c.rawParams[`**`]=decodeURIComponent(r),c}return null}function De(e,t){return 2**(e-t-1)}function Oe(e,t){return e===2**(t-1)-1}function ke(e,t,n){try{let[r,i]=Ce(e,t,n);n.rawParams=r,n.extract=i;let a=n.node.parse(r);return n.parsedParams=Object.assign(Object.create(null),n.parsedParams,a),!0}catch{return null}}function Ae(e,t){return e?t.statics>e.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===B)>(e.node.kind===B)||t.node.kind===B==(e.node.kind===B)&&t.depth>e.depth))):!0}function je(e){return Me(e.filter(e=>e!==void 0).join(`/`))}function Me(e){return e.replace(/\/{2,}/g,`/`)}function Ne(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Pe(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Fe(e){return Pe(Ne(e))}function Ie(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Le(e,t,n){return Ie(e,n)===Ie(t,n)}function Re({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),a=!i&&t===`.`,o;if(r){o=i?t:a?e:e+`\0`+t;let n=r.get(o);if(n)return n}let s;if(a)s=e.split(`/`);else if(i)s=t.split(`/`);else{for(s=e.split(`/`);s.length>1&&w(s)===``;)s.pop();let n=t.split(`/`);for(let e=0,t=n.length;e<t;e++){let r=n[e];r===``?e?e===t-1&&s.push(r):s=[r]:r===`..`?s.pop():r===`.`||s.push(r)}}s.length>1&&(w(s)===``?n===`never`&&s.pop():n===`always`&&s.push(``));let c,l=``;for(let e=0;e<s.length;e++){e>0&&(l+=`/`);let t=s[e];if(!t)continue;c=ue(t,0,c);let n=c[0];if(n===0){l+=t;continue}let r=c[5],i=t.substring(0,c[1]),a=t.substring(c[4],r),o=t.substring(c[2],c[3]);n===1?l+=i||a?`${i}{$${o}}${a}`:`$${o}`:n===2?l+=i||a?`${i}{$}${a}`:`$`:l+=`${i}{-$${o}}${a}`}l=Me(l);let u=l||`/`;return o&&r&&r.set(o,u),u}function ze(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function Be(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>He(e,n)).join(`/`):He(r,n):r}function Ve({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s<o;){let r=s;c=ue(e,r,c);let o=c[5];if(s=o+1,r===o)continue;let u=c[0];if(u===0){l+=`/`+e.substring(r,o);continue}if(u===2){let s=t._splat;a._splat=s,a[`*`]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o);if(!s){i=!0,(u||d)&&(l+=`/`+u+d);continue}let f=Be(`_splat`,t,n);l+=`/`+u+f+d;continue}if(u===1){let s=e.substring(c[2],c[3]);!i&&!(s in t)&&(i=!0),a[s]=t[s];let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Be(s,t,n)??`undefined`;l+=`/`+u+f+d;continue}if(u===3){let i=e.substring(c[2],c[3]),s=t[i];if(s==null)continue;a[i]=s;let u=e.substring(r,c[1]),d=e.substring(c[4],o),f=Be(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function He(e,t){let n=encodeURIComponent(e);return t?.(n)??n}var Ue=`Error preloading route! ☝️`,We=f();function Ge({children:e,fallback:t=null}){return Ke()?(0,We.jsx)(v.Fragment,{children:e}):(0,We.jsx)(v.Fragment,{children:t})}function Ke(){return v.useSyncExternalStore(qe,()=>!0,()=>!1)}function qe(){return()=>{}}var Je=v.createContext(null);function Ye(e){return v.useContext(Je)}function Xe(e,t){return e===t}function Ze(e,t,n=Xe){let r=(0,v.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,v.useCallback)(()=>e?.get(),[e]);return(0,_.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Qe=o((e=>{var t=u();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`);function o(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var s=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function c(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return o(e,t,null,r)},e.flushSync=function(e){var t=s.T,n=i.p;try{if(s.T=null,i.p=2,e)return e()}finally{s.T=t,i.p=n,i.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`)if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=c(t.as,t.crossOrigin);i.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??i.d.M(e)},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin);i.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`)if(t){var n=c(t.as,t.crossOrigin);i.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else i.d.m(e)},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return s.H.useFormState(e,t,n)},e.useFormStatus=function(){return s.H.useHostTransitionStatus()},e.version=`19.2.5`})),$e=o(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=Qe()})),et=c($e(),1);function tt(e,t){let n=Ye(),r=C(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:s,preload:c,preloadDelay:l,preloadIntentProximity:u,hashScrollIntoView:d,replace:f,startTransition:p,resetScroll:m,viewTransition:h,children:g,target:_,disabled:y,style:b,className:x,onClick:w,onBlur:T,onFocus:D,onMouseEnter:O,onMouseLeave:k,onTouchStart:A,ignoreBlocker:j,params:M,search:N,hash:P,state:ee,mask:te,reloadDocument:ne,unsafeRelative:re,from:ie,_fromLocation:I,...L}=e,oe=Ke(),R=v.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),se=Ze(n.stores.location,e=>e,(e,t)=>e.href===t.href),z=v.useMemo(()=>{let e={_fromLocation:se,...R};return n.buildLocation(e)},[n,se,R]),ce=z.maskedLocation?z.maskedLocation.publicHref:z.publicHref,B=z.maskedLocation?z.maskedLocation.external:z.external,V=v.useMemo(()=>ut(ce,B,n.history,y),[y,B,ce,n.history]),le=v.useMemo(()=>{if(V?.external)return ae(V.href,n.protocolAllowlist)?void 0:V.href;if(!dt(s)&&!(typeof s!=`string`||s.indexOf(`:`)===-1))try{return new URL(s),ae(s,n.protocolAllowlist)?void 0:s}catch{}},[s,V,n.protocolAllowlist]),ue=v.useMemo(()=>{if(le)return!1;if(o?.exact){if(!Le(se.pathname,z.pathname,n.basepath))return!1}else{let e=Ie(se.pathname,n.basepath),t=Ie(z.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!F(se.search,z.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:o?.includeHash?oe&&se.hash===z.hash:!0},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,se,le,oe,z.hash,z.pathname,z.search,n.basepath]),de=ue?E(i,{})??rt:nt,fe=ue?nt:E(a,{})??nt,pe=[x,de.className,fe.className].filter(Boolean).join(` `),me=(b||de.style||fe.style)&&{...b,...de.style,...fe.style},[he,ge]=v.useState(!1),_e=v.useRef(!1),ve=e.reloadDocument||le?!1:c??n.options.defaultPreload,ye=l??n.options.defaultPreloadDelay??0,be=v.useCallback(()=>{n.preloadRoute({...R,_builtLocation:z}).catch(e=>{console.warn(e),console.warn(Ue)})},[n,R,z]);S(r,v.useCallback(e=>{e?.isIntersecting&&be()},[be]),ct,{disabled:!!y||ve!==`viewport`}),v.useEffect(()=>{_e.current||!y&&ve===`render`&&(be(),_e.current=!0)},[y,be,ve]);let xe=e=>{let t=e.currentTarget.getAttribute(`target`),r=_===void 0?t:_;if(!y&&!mt(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,et.flushSync)(()=>{ge(!0)});let t=n.subscribe(`onResolved`,()=>{t(),ge(!1)});n.navigate({...R,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:j})}};if(le)return{...L,ref:r,href:le,...g&&{children:g},..._&&{target:_},...y&&{disabled:y},...b&&{style:b},...x&&{className:x},...w&&{onClick:w},...T&&{onBlur:T},...D&&{onFocus:D},...O&&{onMouseEnter:O},...k&&{onMouseLeave:k},...A&&{onTouchStart:A}};let Se=e=>{if(y||ve!==`intent`)return;if(!ye){be();return}let t=e.currentTarget;if(st.has(t))return;let n=setTimeout(()=>{st.delete(t),be()},ye);st.set(t,n)},Ce=e=>{y||ve!==`intent`||be()},we=e=>{if(y||!ve||!ye)return;let t=e.currentTarget,n=st.get(t);n&&(clearTimeout(n),st.delete(t))};return{...L,...de,...fe,href:V?.href,ref:r,onClick:lt([w,xe]),onBlur:lt([T,we]),onFocus:lt([D,Se]),onMouseEnter:lt([O,Se]),onMouseLeave:lt([k,we]),onTouchStart:lt([A,Ce]),disabled:!!y,target:_,...me&&{style:me},...pe&&{className:pe},...y&&it,...ue&&at,...oe&&he&&ot}}var nt={},rt={className:`active`},it={role:`link`,"aria-disabled":!0},at={"data-status":`active`,"aria-current":`page`},ot={"data-transitioning":`transitioning`},st=new WeakMap,ct={rootMargin:`100px`},lt=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function ut(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function dt(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}function ft(e){return v.forwardRef(function(t,n){return(0,We.jsx)(pt,{...t,_asChild:e,ref:n})})}var pt=v.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=tt(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return v.createElement(`a`,t,o)}return v.createElement(n,a,o)});function mt(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var ht=o((e=>{var t=u().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),gt=o(((e,t)=>{t.exports=ht()})),_t={};function vt(e,t){let n=v.useRef(_t);return n.current===_t&&(n.current=e(t)),n}var yt=typeof document<`u`?v.useLayoutEffect:()=>{};function bt(e,t){return function(n,...r){let i=new URL(e);return i.searchParams.set(`code`,n.toString()),r.forEach(e=>i.searchParams.append(`args[]`,e)),`${t} error #${n}; visit ${i} for the full message.`}}var xt=bt(`https://base-ui.com/production-error`,`Base UI`),St=[];function Ct(e){v.useEffect(e,St)}function wt(){}var Tt=Object.freeze([]),Et=Object.freeze({}),Dt=`none`,Ot=`trigger-press`,kt=`trigger-hover`,At=`trigger-focus`,jt=`outside-press`,Mt=`escape-key`,Nt=`disabled`,Pt=`imperative-action`;function Ft(e,t,n,r){let i=!1,a=!1,o=r??Et;return{reason:e,event:t??new Event(`base-ui`),cancel(){i=!0},allowPropagation(){a=!0},get isCanceled(){return i},get isPropagationAllowed(){return a},trigger:n,...o}}function It(){return typeof window<`u`}function Lt(e){return Bt(e)?(e.nodeName||``).toLowerCase():`#document`}function Rt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function zt(e){return((Bt(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function Bt(e){return It()?e instanceof Node||e instanceof Rt(e).Node:!1}function Vt(e){return It()?e instanceof Element||e instanceof Rt(e).Element:!1}function Ht(e){return It()?e instanceof HTMLElement||e instanceof Rt(e).HTMLElement:!1}function Ut(e){return!It()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof Rt(e).ShadowRoot}function Wt(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=tn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function Gt(e){return/^(table|td|th)$/.test(Lt(e))}function Kt(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var qt=/transform|translate|scale|rotate|perspective|filter/,Jt=/paint|layout|strict|content/,Yt=e=>!!e&&e!==`none`,Xt;function Zt(e){let t=Vt(e)?tn(e):e;return Yt(t.transform)||Yt(t.translate)||Yt(t.scale)||Yt(t.rotate)||Yt(t.perspective)||!$t()&&(Yt(t.backdropFilter)||Yt(t.filter))||qt.test(t.willChange||``)||Jt.test(t.contain||``)}function Qt(e){let t=rn(e);for(;Ht(t)&&!en(t);){if(Zt(t))return t;if(Kt(t))return null;t=rn(t)}return null}function $t(){return Xt??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),Xt}function en(e){return/^(html|body|#document)$/.test(Lt(e))}function tn(e){return Rt(e).getComputedStyle(e)}function nn(e){return Vt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function rn(e){if(Lt(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Ut(e)&&e.host||zt(e);return Ut(t)?t.host:t}function an(e){let t=rn(e);return en(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ht(t)&&Wt(t)?t:an(t)}function on(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=an(e),i=r===e.ownerDocument?.body,a=Rt(r);if(i){let e=sn(a);return t.concat(a,a.visualViewport||[],Wt(r)?r:[],e&&n?on(e):[])}else return t.concat(r,on(r,[],n))}function sn(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function cn(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function ln(e,t,n,r){let i=vt(dn).current;return fn(i,e,t,n,r)&&mn(i,[e,t,n,r]),i.callback}function un(e){let t=vt(dn).current;return pn(t,e)&&mn(t,e),t.callback}function dn(){return{callback:null,cleanup:null,refs:[]}}function fn(e,t,n,r,i){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==i}function pn(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}function mn(e,t){if(e.refs=t,t.every(e=>e==null)){e.callback=null;return}e.callback=n=>{if(e.cleanup&&=(e.cleanup(),null),n!=null){let r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){let i=t[e];if(i!=null)switch(typeof i){case`function`:{let t=i(n);typeof t==`function`&&(r[e]=t);break}case`object`:i.current=n;break;default:}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){let n=t[e];if(n!=null)switch(typeof n){case`function`:{let t=r[e];typeof t==`function`?t():n(null);break}case`object`:n.current=null;break;default:}}}}}}var hn=v[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0,-3)],gn=hn&&hn!==v.useLayoutEffect?hn:e=>e();function _n(e){let t=vt(vn).current;return t.next=e,gn(t.effect),t.trampoline}function vn(){let e={next:void 0,callback:yn,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function yn(){}var bn=null;globalThis.requestAnimationFrame;var xn=new class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=e=>{this.isScheduled=!1;let t=this.callbacks,n=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,n>0)for(let n=0;n<t.length;n+=1)t[n]?.(e)};request(e){let t=this.nextId;return this.nextId+=1,this.callbacks.push(e),this.callbacksCount+=1,this.isScheduled||=(requestAnimationFrame(this.tick),!0),t}cancel(e){let t=e-this.startId;t<0||t>=this.callbacks.length||(this.callbacks[t]=null,--this.callbacksCount)}},Sn=class e{static create(){return new e}static request(e){return xn.request(e)}static cancel(e){return xn.cancel(e)}currentId=bn;request(e){this.cancel(),this.currentId=xn.request(()=>{this.currentId=bn,e()})}cancel=()=>{this.currentId!==bn&&(xn.cancel(this.currentId),this.currentId=bn)};disposeEffect=()=>this.cancel};function Cn(){let e=vt(Sn.create).current;return Ct(e.disposeEffect),e}function wn(e){return e?.ownerDocument||document}function Tn(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function En(e,t){if(!e||!t)return!1;let n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&Ut(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function Dn(e){return`composedPath`in e?e.composedPath()[0]:e.target}var On={...v},kn=0;function An(e,t=`mui`){let[n,r]=v.useState(e),i=e||n;return v.useEffect(()=>{n??(kn+=1,r(`${t}-${kn}`))},[n,t]),i}var jn=On.useId;function Mn(e,t){if(jn!==void 0){let n=jn();return e??(t?`${t}-${n}`:n)}return An(e,t)}var Nn=19;function Pn(e){return Nn>=e}function Fn(e){if(!v.isValidElement(e))return null;let t=e,n=t.props;return(Pn(19)?n?.ref:t.ref)??null}function In(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}function Ln(e,t){let n={};for(let r in e){let i=e[r];if(t?.hasOwnProperty(r)){let e=t[r](i);e!=null&&Object.assign(n,e);continue}i===!0?n[`data-${r.toLowerCase()}`]=``:i&&(n[`data-${r.toLowerCase()}`]=i.toString())}return n}function Rn(e,t){return typeof e==`function`?e(t):e}function zn(e,t){return typeof e==`function`?e(t):e}var Bn={};function Vn(e,t,n,r,i){if(!n&&!r&&!i&&!e)return Un(t);let a=Un(e);return t&&(a=Wn(a,t)),n&&(a=Wn(a,n)),r&&(a=Wn(a,r)),i&&(a=Wn(a,i)),a}function Hn(e){if(e.length===0)return Bn;if(e.length===1)return Un(e[0]);let t=Un(e[0]);for(let n=1;n<e.length;n+=1)t=Wn(t,e[n]);return t}function Un(e){return Jn(e)?{...Yn(e,Bn)}:Gn(e)}function Wn(e,t){return Jn(t)?Yn(t,e):Kn(e,t)}function Gn(e){let t={...e};for(let e in t){let n=t[e];qn(e,n)&&(t[e]=Zn(n))}return t}function Kn(e,t){if(!t)return e;for(let n in t){let r=t[n];switch(n){case`style`:e[n]=In(e.style,r);break;case`className`:e[n]=$n(e.className,r);break;default:qn(n,r)?e[n]=Xn(e[n],r):e[n]=r}}return e}function qn(e,t){let n=e.charCodeAt(0),r=e.charCodeAt(1),i=e.charCodeAt(2);return n===111&&r===110&&i>=65&&i<=90&&(typeof t==`function`||t===void 0)}function Jn(e){return typeof e==`function`}function Yn(e,t){return Jn(e)?e(t):e??Bn}function Xn(e,t){return t?e?(...n)=>{let r=n[0];if(er(r)){let i=r;Qn(i);let a=t(...n);return i.baseUIHandlerPrevented||e?.(...n),a}let i=t(...n);return e?.(...n),i}:Zn(t):e}function Zn(e){return e&&((...t)=>{let n=t[0];return er(n)&&Qn(n),e(...t)})}function Qn(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function $n(e,t){return t?e?t+` `+e:t:e}function er(e){return typeof e==`object`&&!!e&&`nativeEvent`in e}function tr(e,t,n={}){let r=t.render,i=nr(t,n);return n.enabled===!1?null:ar(e,r,i,n.state??Et)}function nr(e,t={}){let{className:n,style:r,render:i}=e,{state:a=Et,ref:o,props:s,stateAttributesMapping:c,enabled:l=!0}=t,u=l?Rn(n,a):void 0,d=l?zn(r,a):void 0,f=l?Ln(a,c):Et,p=l&&s?rr(s):void 0,m=l?In(f,p)??{}:Et;return typeof document<`u`&&(l?Array.isArray(o)?m.ref=un([m.ref,Fn(i),...o]):m.ref=ln(m.ref,Fn(i),o):ln(null,null)),l?(u!==void 0&&(m.className=$n(m.className,u)),d!==void 0&&(m.style=In(m.style,d)),m):Et}function rr(e){return Array.isArray(e)?Hn(e):Vn(void 0,e)}var ir=Symbol.for(`react.lazy`);function ar(e,t,n,r){if(t){if(typeof t==`function`)return t(n,r);let e=Vn(n,t.props);e.ref=n.ref;let i=t;return i?.$$typeof===ir&&(i=v.Children.toArray(t)[0]),v.cloneElement(i,e)}if(e&&typeof e==`string`)return or(e,n);throw Error(xt(8))}function or(e,t){return e===`button`?(0,v.createElement)(`button`,{type:`button`,...t,key:t.key}):e===`img`?(0,v.createElement)(`img`,{alt:``,...t,key:t.key}):v.createElement(e,t)}function sr(e){return e==null?e:`current`in e?e.current:e}function cr(e,t=!1,n=!1){let[r,i]=v.useState(e&&t?`idle`:void 0),[a,o]=v.useState(e);return e&&!a&&(o(!0),i(`starting`)),!e&&a&&r!==`ending`&&!n&&i(`ending`),!e&&!a&&r===`ending`&&i(void 0),yt(()=>{if(!e&&a&&r!==`ending`&&n){let e=Sn.request(()=>{i(`ending`)});return()=>{Sn.cancel(e)}}},[e,a,r,n]),yt(()=>{if(!e||t)return;let n=Sn.request(()=>{i(void 0)});return()=>{Sn.cancel(n)}},[t,e]),yt(()=>{if(!e||!t)return;e&&a&&r!==`idle`&&i(`starting`);let n=Sn.request(()=>{i(`idle`)});return()=>{Sn.cancel(n)}},[t,e,a,r]),{mounted:a,setMounted:o,transitionStatus:r}}var lr=function(e){return e.startingStyle=`data-starting-style`,e.endingStyle=`data-ending-style`,e}({}),ur={[lr.startingStyle]:``},dr={[lr.endingStyle]:``},fr={transitionStatus(e){return e===`starting`?ur:e===`ending`?dr:null}};function pr(e,t=!1,n=!0){let r=Cn();return _n((i,a=null)=>{r.cancel();let o=sr(e);if(o==null)return;let s=o,c=()=>{et.flushSync(i)};if(typeof s.getAnimations!=`function`||globalThis.BASE_UI_ANIMATIONS_DISABLED){i();return}function l(){Promise.all(s.getAnimations().map(e=>e.finished)).then(()=>{a?.aborted||c()}).catch(()=>{if(n){a?.aborted||c();return}let e=s.getAnimations();!a?.aborted&&e.length>0&&e.some(e=>e.pending||e.playState!==`finished`)&&l()})}if(t){let e=lr.startingStyle;if(!s.hasAttribute(e)){r.request(l);return}let t=new MutationObserver(()=>{s.hasAttribute(e)||(t.disconnect(),l())});t.observe(s,{attributes:!0,attributeFilter:[e]}),a?.addEventListener(`abort`,()=>t.disconnect(),{once:!0});return}r.request(l)})}function mr(e){let{enabled:t=!0,open:n,ref:r,onComplete:i}=e,a=_n(i),o=pr(r,n,!1);v.useEffect(()=>{if(!t)return;let e=new AbortController;return o(a,e.signal),()=>{e.abort()}},[t,n,a,o])}function hr(e){return Mn(e,`base-ui`)}function gr(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=gr(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function _r(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=gr(e))&&(r&&(r+=` `),r+=t);return r}var vr=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t<e.length;t++)n[t]=e[t];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},yr=(e,t)=>({classGroupId:e,validator:t}),br=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),xr=`-`,Sr=[],Cr=`arbitrary..`,wr=e=>{let t=Dr(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return Er(e);let n=e.split(xr);return Tr(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?vr(i,t):t:i||Sr}return n[e]||Sr}}},Tr=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=Tr(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(xr):e.slice(t).join(xr),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},Er=e=>e.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?Cr+r:void 0})(),Dr=e=>{let{theme:t,classGroups:n}=e;return Or(n,t)},Or=(e,t)=>{let n=br();for(let r in e){let i=e[r];kr(i,n,r,t)}return n},kr=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];Ar(i,t,n,r)}},Ar=(e,t,n,r)=>{if(typeof e==`string`){jr(e,t,n);return}if(typeof e==`function`){Mr(e,t,n,r);return}Nr(e,t,n,r)},jr=(e,t,n)=>{let r=e===``?t:Pr(t,e);r.classGroupId=n},Mr=(e,t,n,r)=>{if(Fr(e)){kr(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(yr(n,e))},Nr=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];kr(o,Pr(t,a),n,r)}},Pr=(e,t)=>{let n=e,r=t.split(xr),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=br(),n.nextPart.set(t,i)),n=i}return n},Fr=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,Ir=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Lr=`!`,Rr=`:`,zr=[],Br=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Vr=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;s<o;s++){let o=e[s];if(n===0&&r===0){if(o===Rr){t.push(e.slice(i,s)),i=s+1;continue}if(o===`/`){a=s;continue}}o===`[`?n++:o===`]`?n--:o===`(`?r++:o===`)`&&r--}let s=t.length===0?e:e.slice(i),c=s,l=!1;s.endsWith(Lr)?(c=s.slice(0,-1),l=!0):s.startsWith(Lr)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return Br(t,l,c,u)};if(t){let e=t+Rr,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Br(zr,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Hr=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=a[0]===`[`,s=t.has(a);o||s?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Ur=e=>({cache:Ir(e.cacheSize),parseClassName:Vr(e),sortModifiers:Hr(e),...wr(e)}),Wr=/\s+/,Gr=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a}=t,o=[],s=e.trim().split(Wr),c=``;for(let e=s.length-1;e>=0;--e){let t=s[e],{isExternal:l,modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:p}=n(t);if(l){c=t+(c.length>0?` `+c:c);continue}let m=!!p,h=r(m?f.substring(0,p):f);if(!h){if(!m){c=t+(c.length>0?` `+c:c);continue}if(h=r(f),!h){c=t+(c.length>0?` `+c:c);continue}m=!1}let g=u.length===0?``:u.length===1?u[0]:a(u).join(`:`),_=d?g+Lr:g,v=_+h;if(o.indexOf(v)>-1)continue;o.push(v);let y=i(h,m);for(let e=0;e<y.length;++e){let t=y[e];o.push(_+t)}c=t+(c.length>0?` `+c:c)}return c},Kr=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=qr(n))&&(i&&(i+=` `),i+=r);return i},qr=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=qr(e[r]))&&(n&&(n+=` `),n+=t);return n},Jr=(e,...t)=>{let n,r,i,a,o=o=>(n=Ur(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=Gr(e,n);return i(e,a),a};return a=o,(...e)=>a(Kr(...e))},Yr=[],H=e=>{let t=t=>t[e]||Yr;return t.isThemeGetter=!0,t},Xr=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Zr=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Qr=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,$r=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ei=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ti=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ni=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ri=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ii=e=>Qr.test(e),U=e=>!!e&&!Number.isNaN(Number(e)),ai=e=>!!e&&Number.isInteger(Number(e)),oi=e=>e.endsWith(`%`)&&U(e.slice(0,-1)),si=e=>$r.test(e),ci=()=>!0,li=e=>ei.test(e)&&!ti.test(e),ui=()=>!1,di=e=>ni.test(e),fi=e=>ri.test(e),pi=e=>!W(e)&&!G(e),mi=e=>ki(e,Ni,ui),W=e=>Xr.test(e),hi=e=>ki(e,Pi,li),gi=e=>ki(e,Fi,U),_i=e=>ki(e,Li,ci),vi=e=>ki(e,Ii,ui),yi=e=>ki(e,ji,ui),bi=e=>ki(e,Mi,fi),xi=e=>ki(e,Ri,di),G=e=>Zr.test(e),Si=e=>Ai(e,Pi),Ci=e=>Ai(e,Ii),wi=e=>Ai(e,ji),Ti=e=>Ai(e,Ni),Ei=e=>Ai(e,Mi),Di=e=>Ai(e,Ri,!0),Oi=e=>Ai(e,Li,!0),ki=(e,t,n)=>{let r=Xr.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Ai=(e,t,n=!1)=>{let r=Zr.exec(e);return r?r[1]?t(r[1]):n:!1},ji=e=>e===`position`||e===`percentage`,Mi=e=>e===`image`||e===`url`,Ni=e=>e===`length`||e===`size`||e===`bg-size`,Pi=e=>e===`length`,Fi=e=>e===`number`,Ii=e=>e===`family-name`,Li=e=>e===`number`||e===`weight`,Ri=e=>e===`shadow`,zi=Jr(()=>{let e=H(`color`),t=H(`font`),n=H(`text`),r=H(`font-weight`),i=H(`tracking`),a=H(`leading`),o=H(`breakpoint`),s=H(`container`),c=H(`spacing`),l=H(`radius`),u=H(`shadow`),d=H(`inset-shadow`),f=H(`text-shadow`),p=H(`drop-shadow`),m=H(`blur`),h=H(`perspective`),g=H(`aspect`),_=H(`ease`),v=H(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),G,W],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[G,W,c],T=()=>[ii,`full`,`auto`,...w()],E=()=>[ai,`none`,`subgrid`,G,W],D=()=>[`auto`,{span:[`full`,ai,G,W]},ai,G,W],O=()=>[ai,`auto`,G,W],k=()=>[`auto`,`min`,`max`,`fr`,G,W],A=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],j=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],M=()=>[`auto`,...w()],N=()=>[ii,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],P=()=>[ii,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],ee=()=>[ii,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,G,W],te=()=>[...b(),wi,yi,{position:[G,W]}],ne=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],re=()=>[`auto`,`cover`,`contain`,Ti,mi,{size:[G,W]}],ie=()=>[oi,Si,hi],I=()=>[``,`none`,`full`,l,G,W],L=()=>[``,U,Si,hi],ae=()=>[`solid`,`dashed`,`dotted`,`double`],oe=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],R=()=>[U,oi,wi,yi],se=()=>[``,`none`,m,G,W],z=()=>[`none`,U,G,W],ce=()=>[`none`,U,G,W],B=()=>[U,G,W],V=()=>[ii,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[si],breakpoint:[si],color:[ci],container:[si],"drop-shadow":[si],ease:[`in`,`out`,`in-out`],font:[pi],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[si],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[si],shadow:[si],spacing:[`px`,U],text:[si],"text-shadow":[si],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,ii,W,G,g]}],container:[`container`],columns:[{columns:[U,W,G,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[ai,`auto`,G,W]}],basis:[{basis:[ii,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[U,ii,`auto`,`initial`,`none`,W]}],grow:[{grow:[``,U,G,W]}],shrink:[{shrink:[``,U,G,W]}],order:[{order:[ai,`first`,`last`,`none`,G,W]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":k()}],"auto-rows":[{"auto-rows":k()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...A(),`normal`]}],"justify-items":[{"justify-items":[...j(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...j()]}],"align-content":[{content:[`normal`,...A()]}],"align-items":[{items:[...j(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...j(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":A()}],"place-items":[{"place-items":[...j(),`baseline`]}],"place-self":[{"place-self":[`auto`,...j()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:M()}],mx:[{mx:M()}],my:[{my:M()}],ms:[{ms:M()}],me:[{me:M()}],mbs:[{mbs:M()}],mbe:[{mbe:M()}],mt:[{mt:M()}],mr:[{mr:M()}],mb:[{mb:M()}],ml:[{ml:M()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:N()}],"inline-size":[{inline:[`auto`,...P()]}],"min-inline-size":[{"min-inline":[`auto`,...P()]}],"max-inline-size":[{"max-inline":[`none`,...P()]}],"block-size":[{block:[`auto`,...ee()]}],"min-block-size":[{"min-block":[`auto`,...ee()]}],"max-block-size":[{"max-block":[`none`,...ee()]}],w:[{w:[s,`screen`,...N()]}],"min-w":[{"min-w":[s,`screen`,`none`,...N()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...N()]}],h:[{h:[`screen`,`lh`,...N()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...N()]}],"max-h":[{"max-h":[`screen`,`lh`,...N()]}],"font-size":[{text:[`base`,n,Si,hi]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Oi,_i]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,oi,W]}],"font-family":[{font:[Ci,vi,t]}],"font-features":[{"font-features":[W]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,G,W]}],"line-clamp":[{"line-clamp":[U,`none`,G,gi]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,G,W]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,G,W]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...ae(),`wavy`]}],"text-decoration-thickness":[{decoration:[U,`from-font`,`auto`,G,hi]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[U,`auto`,G,W]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,G,W]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,G,W]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:ne()}],"bg-size":[{bg:re()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},ai,G,W],radial:[``,G,W],conic:[ai,G,W]},Ei,bi]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:ie()}],"gradient-via-pos":[{via:ie()}],"gradient-to-pos":[{to:ie()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:L()}],"border-w-x":[{"border-x":L()}],"border-w-y":[{"border-y":L()}],"border-w-s":[{"border-s":L()}],"border-w-e":[{"border-e":L()}],"border-w-bs":[{"border-bs":L()}],"border-w-be":[{"border-be":L()}],"border-w-t":[{"border-t":L()}],"border-w-r":[{"border-r":L()}],"border-w-b":[{"border-b":L()}],"border-w-l":[{"border-l":L()}],"divide-x":[{"divide-x":L()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":L()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ae(),`hidden`,`none`]}],"divide-style":[{divide:[...ae(),`hidden`,`none`]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ae(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[U,G,W]}],"outline-w":[{outline:[``,U,Si,hi]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,Di,xi]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,Di,xi]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:L()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[U,hi]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":L()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,Di,xi]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[U,G,W]}],"mix-blend":[{"mix-blend":[...oe(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":oe()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[U]}],"mask-image-linear-from-pos":[{"mask-linear-from":R()}],"mask-image-linear-to-pos":[{"mask-linear-to":R()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":R()}],"mask-image-t-to-pos":[{"mask-t-to":R()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":R()}],"mask-image-r-to-pos":[{"mask-r-to":R()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":R()}],"mask-image-b-to-pos":[{"mask-b-to":R()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":R()}],"mask-image-l-to-pos":[{"mask-l-to":R()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":R()}],"mask-image-x-to-pos":[{"mask-x-to":R()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":R()}],"mask-image-y-to-pos":[{"mask-y-to":R()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[G,W]}],"mask-image-radial-from-pos":[{"mask-radial-from":R()}],"mask-image-radial-to-pos":[{"mask-radial-to":R()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[U]}],"mask-image-conic-from-pos":[{"mask-conic-from":R()}],"mask-image-conic-to-pos":[{"mask-conic-to":R()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:ne()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,G,W]}],filter:[{filter:[``,`none`,G,W]}],blur:[{blur:se()}],brightness:[{brightness:[U,G,W]}],contrast:[{contrast:[U,G,W]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Di,xi]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,U,G,W]}],"hue-rotate":[{"hue-rotate":[U,G,W]}],invert:[{invert:[``,U,G,W]}],saturate:[{saturate:[U,G,W]}],sepia:[{sepia:[``,U,G,W]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,G,W]}],"backdrop-blur":[{"backdrop-blur":se()}],"backdrop-brightness":[{"backdrop-brightness":[U,G,W]}],"backdrop-contrast":[{"backdrop-contrast":[U,G,W]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,U,G,W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[U,G,W]}],"backdrop-invert":[{"backdrop-invert":[``,U,G,W]}],"backdrop-opacity":[{"backdrop-opacity":[U,G,W]}],"backdrop-saturate":[{"backdrop-saturate":[U,G,W]}],"backdrop-sepia":[{"backdrop-sepia":[``,U,G,W]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,G,W]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[U,`initial`,G,W]}],ease:[{ease:[`linear`,`initial`,_,G,W]}],delay:[{delay:[U,G,W]}],animate:[{animate:[`none`,v,G,W]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,G,W]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:z()}],"rotate-x":[{"rotate-x":z()}],"rotate-y":[{"rotate-y":z()}],"rotate-z":[{"rotate-z":z()}],scale:[{scale:ce()}],"scale-x":[{"scale-x":ce()}],"scale-y":[{"scale-y":ce()}],"scale-z":[{"scale-z":ce()}],"scale-3d":[`scale-3d`],skew:[{skew:B()}],"skew-x":[{"skew-x":B()}],"skew-y":[{"skew-y":B()}],transform:[{transform:[G,W,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:V()}],"translate-x":[{"translate-x":V()}],"translate-y":[{"translate-y":V()}],"translate-z":[{"translate-z":V()}],"translate-none":[`translate-none`],accent:[{accent:F()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,G,W]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,G,W]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[U,Si,hi,gi]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function Bi(...e){return zi(_r(e))}function Vi(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Hi(e){let t=Date.now()-new Date(e).getTime(),n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}var Ui=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Wi=_r,Gi=(e,t)=>n=>{if(t?.variants==null)return Wi(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Ui(t)||Ui(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Wi(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)};function Ki(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var qi=e=>{switch(e){case`success`:return Xi;case`info`:return Qi;case`warning`:return Zi;case`error`:return $i;default:return null}},Ji=Array(12).fill(0),Yi=({visible:e,className:t})=>v.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},v.createElement(`div`,{className:`sonner-spinner`},Ji.map((e,t)=>v.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Xi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),Zi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),Qi=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),$i=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},v.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),ea=v.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},v.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),v.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),ta=()=>{let[e,t]=v.useState(document.hidden);return v.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},na=1,ra=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:na++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],v.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(aa(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!v.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||na++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},ia=(e,t)=>{let n=t?.id||na++;return ra.addToast({title:e,...t,id:n}),n},aa=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,oa=Object.assign(ia,{success:ra.success,info:ra.info,warning:ra.warning,error:ra.error,custom:ra.custom,message:ra.message,promise:ra.promise,dismiss:ra.dismiss,loading:ra.loading},{getHistory:()=>ra.toasts,getToasts:()=>ra.getActiveToasts()});Ki(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function sa(e){return e.label!==void 0}var ca=3,la=`24px`,ua=`16px`,da=4e3,fa=356,pa=14,ma=45,ha=200;function ga(...e){return e.filter(Boolean).join(` `)}function _a(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var va=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:y=``,duration:b,position:x,gap:S,expandByDefault:C,classNames:w,icons:T,closeButtonAriaLabel:E=`Close toast`}=e,[D,O]=v.useState(null),[k,A]=v.useState(null),[j,M]=v.useState(!1),[N,P]=v.useState(!1),[ee,F]=v.useState(!1),[te,ne]=v.useState(!1),[re,ie]=v.useState(!1),[I,L]=v.useState(0),[ae,oe]=v.useState(0),R=v.useRef(n.duration||b||da),se=v.useRef(null),z=v.useRef(null),ce=c===0,B=c+1<=o,V=n.type,le=n.dismissible!==!1,ue=n.className||``,de=n.descriptionClassName||``,fe=v.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),pe=v.useMemo(()=>n.closeButton??p,[n.closeButton,p]),me=v.useMemo(()=>n.duration||b||da,[n.duration,b]),he=v.useRef(0),ge=v.useRef(0),_e=v.useRef(0),ve=v.useRef(null),[ye,be]=x.split(`-`),xe=v.useMemo(()=>s.reduce((e,t,n)=>n>=fe?e:e+t.height,0),[s,fe]),Se=ta(),Ce=n.invert||t,we=V===`loading`;ge.current=v.useMemo(()=>fe*S+xe,[fe,xe]),v.useEffect(()=>{R.current=me},[me]),v.useEffect(()=>{M(!0)},[]),v.useEffect(()=>{let e=z.current;if(e){let t=e.getBoundingClientRect().height;return oe(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),v.useLayoutEffect(()=>{if(!j)return;let e=z.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,oe(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[j,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let Te=v.useCallback(()=>{P(!0),L(ge.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},ha)},[n,d,a,ge]);v.useEffect(()=>{if(n.promise&&V===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||Se?(()=>{if(_e.current<he.current){let e=new Date().getTime()-he.current;R.current-=e}_e.current=new Date().getTime()})():R.current!==1/0&&(he.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),Te()},R.current)),()=>clearTimeout(e)},[u,i,n,V,Se,Te]),v.useEffect(()=>{n.delete&&(Te(),n.onDismiss==null||n.onDismiss.call(n,n))},[Te,n.delete]);function Ee(){return T?.loading?v.createElement(`div`,{className:ga(w?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":V===`loading`},T.loading):v.createElement(Yi,{className:ga(w?.loader,n?.classNames?.loader),visible:V===`loading`})}let De=n.icon||T?.[V]||qi(V);return v.createElement(`li`,{tabIndex:0,ref:z,className:ga(_,ue,w?.toast,n?.classNames?.toast,w?.default,w?.[V],n?.classNames?.[V]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":j,"data-promise":!!n.promise,"data-swiped":re,"data-removed":N,"data-visible":B,"data-y-position":ye,"data-x-position":be,"data-index":c,"data-front":ce,"data-swiping":ee,"data-dismissible":le,"data-type":V,"data-invert":Ce,"data-swipe-out":te,"data-swipe-direction":k,"data-expanded":!!(u||C&&j),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${N?I:ge.current}px`,"--initial-height":C?`auto`:`${ae}px`,...m,...n.style},onDragEnd:()=>{F(!1),O(null),ve.current=null},onPointerDown:e=>{e.button!==2&&(we||!le||(se.current=new Date,L(ge.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),ve.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(te||!le)return;ve.current=null;let e=Number(z.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(z.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-se.current?.getTime(),i=D===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=ma||a>.11){L(ge.current),n.onDismiss==null||n.onDismiss.call(n,n),A(D===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Te(),ne(!0);return}else{var o,s;(o=z.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=z.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}ie(!1),F(!1),O(null)},onPointerMove:t=>{var n,r;if(!ve.current||!le||window.getSelection()?.toString().length>0)return;let i=t.clientY-ve.current.y,a=t.clientX-ve.current.x,o=e.swipeDirections??_a(x);!D&&(Math.abs(a)>1||Math.abs(i)>1)&&O(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(D===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)<Math.abs(i)?e:i}}else if(D===`x`&&(o.includes(`left`)||o.includes(`right`)))if(o.includes(`left`)&&a<0||o.includes(`right`)&&a>0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)<Math.abs(a)?e:a}(Math.abs(s.x)>0||Math.abs(s.y)>0)&&ie(!0),(n=z.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=z.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},pe&&!n.jsx&&V!==`loading`?v.createElement(`button`,{"aria-label":E,"data-disabled":we,"data-close-button":!0,onClick:we||!le?()=>{}:()=>{Te(),n.onDismiss==null||n.onDismiss.call(n,n)},className:ga(w?.closeButton,n?.classNames?.closeButton)},T?.close??ea):null,(V||n.icon||n.promise)&&n.icon!==null&&(T?.[V]!==null||n.icon)?v.createElement(`div`,{"data-icon":``,className:ga(w?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Ee():null,n.type===`loading`?null:De):null,v.createElement(`div`,{"data-content":``,className:ga(w?.content,n?.classNames?.content)},v.createElement(`div`,{"data-title":``,className:ga(w?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?v.createElement(`div`,{"data-description":``,className:ga(y,de,w?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),v.isValidElement(n.cancel)?n.cancel:n.cancel&&sa(n.cancel)?v.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{sa(n.cancel)&&le&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Te())},className:ga(w?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,v.isValidElement(n.action)?n.action:n.action&&sa(n.action)?v.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{sa(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Te())},className:ga(w?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function ya(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function ba(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?ua:la;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var xa=v.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=ca,toastOptions:g,dir:_=ya(),gap:y=pa,icons:b,containerAriaLabel:x=`Notifications`}=e,[S,C]=v.useState([]),w=v.useMemo(()=>n?S.filter(e=>e.toasterId===n):S.filter(e=>!e.toasterId),[S,n]),T=v.useMemo(()=>Array.from(new Set([i].concat(w.filter(e=>e.position).map(e=>e.position)))),[w,i]),[E,D]=v.useState([]),[O,k]=v.useState(!1),[A,j]=v.useState(!1),[M,N]=v.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),P=v.useRef(null),ee=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=v.useRef(null),te=v.useRef(!1),ne=v.useCallback(e=>{C(t=>(t.find(t=>t.id===e.id)?.delete||ra.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return v.useEffect(()=>ra.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{C(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{et.flushSync(()=>{C(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[S]),v.useEffect(()=>{if(d!==`system`){N(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?N(`dark`):N(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{N(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{N(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),v.useEffect(()=>{S.length<=1&&k(!1)},[S]),v.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;k(!0),(t=P.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===P.current||P.current?.contains(document.activeElement))&&k(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),v.useEffect(()=>{if(P.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,te.current=!1)}},[P.current]),v.createElement(`section`,{ref:t,"aria-label":`${x} ${ee}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},T.map((t,n)=>{let[i,a]=t.split(`-`);return w.length?v.createElement(`ol`,{key:t,dir:_===`auto`?ya():_,tabIndex:-1,ref:P,className:c,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${E[0]?.height||0}px`,"--width":`${fa}px`,"--gap":`${y}px`,...m,...ba(l,u)},onBlur:e=>{te.current&&!e.currentTarget.contains(e.relatedTarget)&&(te.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||te.current||(te.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>k(!0),onMouseMove:()=>k(!0),onMouseLeave:()=>{A||k(!1)},onDragEnd:()=>k(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j(!0)},onPointerUp:()=>j(!1)},w.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>v.createElement(va,{key:n.id,icons:b,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:A,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:ne,toasts:w.filter(e=>e.position==n.position),heights:E.filter(e=>e.position==n.position),setHeights:D,expandByDefault:o,gap:y,expanded:O,swipeDirections:e.swipeDirections}))):null}))}),Sa=`__includes_scalar__`,Ca=class{},wa=class extends Ca{constructor(e,t){super(),this.collection=e,this.alias=t,this.type=`collectionRef`}},Ta=class extends Ca{constructor(e,t){super(),this.query=e,this.alias=t,this.type=`queryRef`}},K=class extends Ca{constructor(e){super(),this.path=e,this.type=`ref`}},Ea=class extends Ca{constructor(e){super(),this.value=e,this.type=`val`}},Da=class extends Ca{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},Oa=class extends Ca{constructor(e,t){super(),this.name=e,this.args=t,this.type=`agg`}},ka=class extends Ca{constructor(e,t,n,r,i,a,o=`collection`,s){super(),this.query=e,this.correlationField=t,this.childCorrelationField=n,this.fieldName=r,this.parentFilters=i,this.parentProjection=a,this.materialization=o,this.scalarField=s,this.type=`includesSubquery`}};function Aa(e){return e instanceof Oa||e instanceof Da||e instanceof K||e instanceof Ea||e instanceof ka}function ja(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Ma(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Na(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function Pa(e){return{expression:e,residual:!0}}function Fa(e,t){if(e.from.alias===t)return e.from;for(let n of e.join||[])if(n.from.alias===t)return n.from}function Ia(e,t,n){if(t.path.length!==0){if(t.path.length===1){let r=t.path[0];if(e.select){let t=e.select[r];if(t&&t.type===`ref`)return Ia(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Fa(e,r);return a?a.type===`queryRef`?Ia(a.query,new K(i),n):{collection:a.collection,path:i}:void 0}}}var La=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},Ra=class extends La{constructor(e,t,n){let r=`${e===`insert`?`Insert`:`Update`} validation failed: ${t.map(e=>`
2
+ - ${e.message} - path: ${e.path}`).join(``)}`;super(n||r),this.name=`SchemaValidationError`,this.type=e,this.issues=t}},za=class extends La{constructor(e){super(e),this.name=`CollectionConfigurationError`}},Ba=class extends za{constructor(){super(`Collection requires a config`)}},Va=class extends za{constructor(){super(`Collection requires a sync config`)}},Ha=class extends za{constructor(){super(`Schema must implement the standard-schema interface`)}},Ua=class extends za{constructor(){super(`Schema validation must be synchronous`)}},Wa=class extends La{constructor(e){super(e),this.name=`CollectionStateError`}},Ga=class extends Wa{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},Ka=class extends Wa{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},qa=class extends Wa{constructor(){super(`Collection is in error state`)}},Ja=class extends Wa{constructor(){super(`Active subscribers count is negative - this should never happen`)}},Ya=class extends La{constructor(e){super(e),this.name=`CollectionOperationError`}},Xa=class extends Ya{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},Za=class extends Ya{constructor(e,t){super(`getKey returned an invalid key type. Expected string or number, but got ${e===null?`null`:typeof e}: ${JSON.stringify(e)}. Item: ${JSON.stringify(t)}`)}},Qa=class extends Ya{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},$a=class extends Ya{constructor(e,t,n){let r=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${t}"`;n?.hasCustomGetKey&&n.hasDistinct?super(`${r}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):n?.hasCustomGetKey&&n.hasJoins?super(`${r}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(r)}},eo=class extends Ya{constructor(){super(`The first argument to update is missing`)}},to=class extends Ya{constructor(){super(`No keys were passed to update`)}},no=class extends Ya{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},ro=class extends Ya{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.`)}},io=class extends Ya{constructor(){super(`No keys were passed to delete`)}},ao=class extends Ya{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},oo=class extends La{constructor(e){super(e),this.name=`MissingHandlerError`}},so=class extends oo{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},co=class extends oo{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},lo=class extends oo{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},uo=class extends La{constructor(e){super(e),this.name=`TransactionError`}},fo=class extends uo{constructor(){super(`mutationFn is required when creating a transaction`)}},po=class extends uo{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},mo=class extends uo{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},ho=class extends uo{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},go=class extends uo{constructor(){super(`No pending sync transaction to write to`)}},_o=class extends uo{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},vo=class extends uo{constructor(){super(`No pending sync transaction to commit`)}},yo=class extends uo{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},bo=class extends La{constructor(e){super(e),this.name=`QueryBuilderError`}},xo=class extends bo{constructor(e){super(`Only one source is allowed in the ${e}`)}},So=class extends bo{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}},Co=class extends bo{constructor(e){super(`Invalid source for live query: The value provided for alias "${e}" is not a Collection or subquery. Live queries only accept Collection instances or subqueries. Please ensure you're passing a valid Collection or QueryBuilder, not a plain array or other data type.`)}},wo=class extends bo{constructor(e,t){super(`Invalid source for ${e}: Expected an object with a single key-value pair like { alias: collection }. For example: .from({ todos: todosCollection }). Got: ${t}`)}},To=class extends bo{constructor(){super(`Join condition must be an equality expression`)}},Eo=class extends bo{constructor(){super(`Query must have a from clause`)}},Do=class extends bo{constructor(e){super(`Invalid where() expression: Expected a query expression, but received a ${e}. This usually happens when using JavaScript's comparison operators (===, !==, <, >, etc.) directly. Instead, use the query builder functions:
3
+
4
+ ❌ .where(({ user }) => user.id === 'abc')
5
+ ✅ .where(({ user }) => eq(user.id, 'abc'))
6
+
7
+ Available comparison functions: eq, gt, gte, lt, lte, and, or, not, like, ilike, isNull, isUndefined`)}},Oo=class extends La{constructor(e){super(e),this.name=`QueryCompilationError`}},ko=class extends Oo{constructor(){super(`DISTINCT requires a SELECT clause.`)}},Ao=class extends Oo{constructor(){super(`fn.select() cannot be used with groupBy(). groupBy requires the compiler to statically analyze aggregate functions (count, sum, max, etc.) in the SELECT clause, which is not possible with fn.select() since it is an opaque function. Use .select() instead of .fn.select() when combining with groupBy().`)}},jo=class extends Oo{constructor(){super(`Top-level scalar select() is not supported by createLiveQueryCollection() or queryOnce(). Return an object from .select(), or use the scalar query inside toArray(...) or concat(toArray(...)).`)}},Mo=class extends Oo{constructor(){super(`HAVING clause requires GROUP BY clause`)}},No=class extends Oo{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}},Po=class extends Oo{constructor(e,t,n){let r=t?`alias "${e}" (collection "${t}")`:`collection "${e}"`,i=n?.length?`. Available keys: ${n.join(`, `)}`:``;super(`Input for ${r} not found in inputs map${i}`)}},Fo=class extends Oo{constructor(e,t){super(`Subquery uses alias "${e}" which is already used in the parent query. Each alias must be unique across parent and subquery contexts. Parent query aliases: ${t.join(`, `)}. Please rename "${e}" in either the parent query or subquery to avoid conflicts.`)}},Io=class extends Oo{constructor(e){super(`Unsupported FROM type: ${e}`)}},Lo=class extends Oo{constructor(e){super(`Unknown expression type: ${e}`)}},Ro=class extends Oo{constructor(){super(`Reference path cannot be empty`)}},zo=class extends Oo{constructor(e){super(`Unknown function: ${e}`)}},Bo=class extends Oo{constructor(e){super(`Collection "${e}" not found during compilation of join`)}},Vo=class extends La{constructor(e){super(e),this.name=`JoinError`}},Ho=class extends Vo{constructor(e){super(`Unsupported join type: ${e}`)}},Uo=class extends Vo{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}},Wo=class extends Vo{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}},Go=class extends Vo{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}},Ko=class extends Vo{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}},qo=class extends Vo{constructor(){super(`Invalid join condition`)}},Jo=class extends Vo{constructor(e){super(`Unsupported join source type: ${e}`)}},Yo=class extends La{constructor(e){super(e),this.name=`GroupByError`}},Xo=class extends Yo{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}},Zo=class extends Yo{constructor(e){super(`Unsupported aggregate function: ${e}`)}},Qo=class extends Yo{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}},$o=class extends Yo{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}},es=class extends La{constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Collection "${e}" sync cleanup function threw an error: ${n}`),this.name=`SyncCleanupError`}},ts=class extends La{constructor(e){super(e),this.name=`QueryOptimizerError`}},ns=class extends ts{constructor(){super(`Cannot combine empty expression list`)}},rs=class extends Oo{constructor(e,t,n,r){super(`Internal error: subscription for alias '${e}' (remapped from '${t}', collection '${n}') is missing in join pipeline. Available aliases: ${r.join(`, `)}. This indicates a bug in alias tracking.`)}},is=class extends Oo{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}},as=class extends Oo{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}};function os(e,t){return ss(e,t,new Map)}function ss(e,t,n){if(e===t)return!0;if(e==null||t==null||typeof e!=typeof t)return!1;if(e instanceof Date)return t instanceof Date?e.getTime()===t.getTime():!1;if(t instanceof Date)return!1;if(e instanceof RegExp)return t instanceof RegExp?e.source===t.source&&e.flags===t.flags:!1;if(t instanceof RegExp)return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Array.from(e.entries()).every(([e,r])=>t.has(e)&&ss(r,t.get(e),n));return n.delete(e),r}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Array.from(e),i=Array.from(t);if(r.every(e=>typeof e!=`object`))return n.delete(e),r.every(e=>t.has(e));let a=r.length===i.length;return n.delete(e),a}if(t instanceof Set)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)&&!(e instanceof DataView)&&!(t instanceof DataView)){let n=e,r=t;if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!1;return!0}if(ArrayBuffer.isView(t)&&!(t instanceof DataView)&&!ArrayBuffer.isView(e))return!1;if(ls(e)&&ls(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(ls(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;if(n.has(e))return n.get(e)===t;n.set(e,t);let r=e.every((e,r)=>ss(e,t[r],n));return n.delete(e),r}if(Array.isArray(t))return!1;if(typeof e==`object`){if(n.has(e))return n.get(e)===t;n.set(e,t);let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return n.delete(e),!1;let a=r.every(r=>r in t&&ss(e[r],t[r],n));return n.delete(e),a}return!1}var cs=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function ls(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&cs.has(t)}var us={direction:`asc`,nulls:`first`,stringSort:`locale`},ds=new WeakMap,fs=1;function ps(e){if(ds.has(e))return ds.get(e);let t=fs++;return ds.set(e,t),t}var ms=(e,t,n)=>{let{nulls:r}=n;if(e==null&&t==null)return 0;if(e==null)return r===`first`?-1:1;if(t==null)return r===`first`?1:-1;if(typeof e==`string`&&typeof t==`string`&&n.stringSort===`locale`)return e.localeCompare(t,n.locale,n.localeOptions);if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<Math.min(e.length,t.length);r++){let i=ms(e[r],t[r],n);if(i!==0)return i}return e.length-t.length}if(e instanceof Date&&t instanceof Date)return e.getTime()-t.getTime();if(ls(e)&&ls(t)){let n=e.toString(),r=t.toString();return n<r?-1:+(n>r)}let i=typeof e==`object`,a=typeof t==`object`;if(i||a){if(i&&a)return ps(e)-ps(t);if(i)return 1;if(a)return-1}return e<t?-1:+(e>t)},hs=(e,t,n)=>ms(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function gs(e){return(t,n)=>e.direction===`asc`?ms(t,n,e):hs(t,n,e)}var _s=gs({direction:`asc`,nulls:`first`,stringSort:`locale`});function vs(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}var ys=128;function bs(e){return e instanceof Date?e.getTime():ls(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=ys?`__u8__${Array.from(e).join(`,`)}`:e}function xs(e,t){if(e===t)return!0;let n=typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array,r=typeof Buffer<`u`&&t instanceof Buffer||t instanceof Uint8Array;return n&&r?vs(e,t):!1}function q(e){return e==null}function Ss(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e==`string`||typeof e==`number`){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Cs(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function ws(e){return e===!0}function J(e,t=!1){return Es(e,t)}function Ts(e){return Es(e,!0)}function Es(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?Os(e):Ds(e);case`func`:return ks(e,t);default:throw new Lo(e.type)}}function Ds(e){let[t,...n]=e.path;if(!t)throw new Ro;if(t===`$selected`){if(n.length===0)return e=>e.$selected;if(n.length===1){let e=n[0];return t=>t.$selected?.[e]}else return e=>{let t=e.$selected;if(t===void 0)return;let r=t;for(let e of n){if(r==null)return r;r=r[e]}return r}}let r=t;if(n.length===0)return e=>e[r];if(n.length===1){let e=n[0];return t=>t[r]?.[e]}else return e=>{let t=e[r];if(t===void 0)return;let i=t;for(let e of n){if(i==null)return i;i=i[e]}return i}}function Os(e){let t=e.path;return e=>{let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}}function ks(e,t){let n=e.args.map(e=>Es(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=bs(e(n)),i=bs(t(n));return q(r)||q(i)?null:xs(r,i)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r>i}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r>=i}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r<i}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:r<=i}}case`and`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!1)return!1;q(n)&&(t=!0)}return t?null:!0};case`or`:return e=>{let t=!1;for(let r of n){let n=r(e);if(n===!0)return!0;q(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return q(n)?null:!n}}case`in`:{let e=n[0],t=n[1];return n=>{let r=bs(e(n)),i=t(n);return q(r)?null:Array.isArray(i)?i.some(e=>bs(e)===r):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:As(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return q(r)||q(i)?null:As(r,i,!0)}}case`upper`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toUpperCase():n}}case`lower`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`?n.toLowerCase():n}}case`length`:{let e=n[0];return t=>{let n=e(t);return typeof n==`string`||Array.isArray(n)?n.length:0}}case`concat`:return e=>n.map(t=>{let n=t(e);try{return String(n??``)}catch{try{return JSON.stringify(n)||``}catch{return`[object]`}}}).join(``);case`coalesce`:return e=>{for(let t of n){let n=t(e);if(n!=null)return n}return null};case`add`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)+(i??0)}}case`subtract`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)-(i??0)}}case`multiply`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return(r??0)*(i??0)}}case`divide`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n)??0;return i===0?null:(r??0)/i}}case`date`:{let e=n[0];return t=>{let n=Ss(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=Ss(e(t));return n?n.toISOString():null}}case`strftime`:{let e=n[0],t=n[1];return n=>{let r=e(n);if(typeof r!=`string`)return null;let i=Ss(t(n));return i?Cs(r,i):null}}case`isUndefined`:{let e=n[0];return t=>e(t)===void 0}case`isNull`:{let e=n[0];return t=>e(t)===null}default:throw new zo(e.name)}}function As(e,t,n){if(typeof e!=`string`||typeof t!=`string`)return!1;let r=n?e.toLowerCase():e,i=(n?t.toLowerCase():t).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return i=i.replace(/%/g,`.*`),i=i.replace(/_/g,`.`),RegExp(`^${i}$`,`s`).test(r)}var js=class{constructor(e){this.originalIndex=e}lookup(e,t){let n=e===`gt`?`lt`:e===`gte`?`lte`:e===`lt`?`gt`:e===`lte`?`gte`:e;return this.originalIndex.lookup(n,t)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,t,n){return this.originalIndex.takeReversed(e,t,n)}takeFromStart(e,t){return this.originalIndex.takeReversedFromEnd(e,t)}takeReversed(e,t,n){return this.originalIndex.take(e,t,n)}takeReversedFromEnd(e,t){return this.originalIndex.takeFromStart(e,t)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(e){return this.originalIndex.supports(e)}matchesField(e){return this.originalIndex.matchesField(e)}matchesCompareOptions(e){return this.originalIndex.matchesCompareOptions(e)}matchesDirection(e){return this.originalIndex.matchesDirection(e)}getStats(){return this.originalIndex.getStats()}add(e,t){this.originalIndex.add(e,t)}remove(e,t){this.originalIndex.remove(e,t)}update(e,t,n){this.originalIndex.update(e,t,n)}build(e){this.originalIndex.build(e)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(e){return this.originalIndex.equalityLookup(e)}inArrayLookup(e){return this.originalIndex.inArrayLookup(e)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}};function Ms(e,t,n,r,i){let a=e;return{...e,$synced:a.$synced??r(),$origin:a.$origin??i(),$key:a.$key??t,$collectionId:a.$collectionId??n}}var Ns=[`$synced`,`$origin`,`$key`,`$collectionId`];function Ps(e){return Ns.includes(e)}function Fs(e){return e.some(e=>Ps(e))}function Is(e,t,n){if(Fs(t))return;let r=n??{...us,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new js(n)}function Ls(e){if(e.length===0)return new Set;if(e.length===1)return new Set(e[0]);let t=new Set(e[0]);for(let n=1;n<e.length;n++){let r=new Set;for(let i of t)e[n].has(i)&&r.add(i);t=r}return t}function Rs(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function zs(e,t){return Bs(e,t)}function Bs(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return Hs(e,t);case`and`:return Us(e,t);case`or`:return Ws(e,t);case`in`:return Gs(e,t)}return{canOptimize:!1,matchingKeys:new Set}}function Vs(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=new Map;for(let t of e.args)if(t.type===`func`&&[`gt`,`gte`,`lt`,`lte`].includes(t.name)){let e=t;if(e.args.length===2){let t=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(t.type===`ref`&&r.type===`val`)i=t,a=r;else if(t.type===`val`&&r.type===`ref`)switch(i=r,a=t,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`;break}if(i&&a){let e=i.path.join(`.`),t=a.value;n.has(e)||n.set(e,[]),n.get(e).push({operation:o,value:t})}}}for(let[e,r]of n)if(r.length>=2){let n=Is(t,e.split(`.`));if(n&&n.supports(`gt`)&&n.supports(`lt`)){let e,t,i=!0,a=!0;for(let{operation:n,value:o}of r)switch(n){case`gt`:(e===void 0||o>e)&&(e=o,i=!1);break;case`gte`:(e===void 0||o>e)&&(e=o,i=!0);break;case`lt`:(t===void 0||o<t)&&(t=o,a=!1);break;case`lte`:(t===void 0||o<t)&&(t=o,a=!0);break}return{canOptimize:!0,matchingKeys:n.rangeQuery({from:e,to:t,fromInclusive:i,toInclusive:a})}}}return{canOptimize:!1,matchingKeys:new Set}}function Hs(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};let n=e.args[0],r=e.args[1],i=null,a=null,o=e.name;if(n.type===`ref`&&r.type===`val`)i=n,a=r;else if(n.type===`val`&&r.type===`ref`)switch(i=r,a=n,o){case`gt`:o=`lt`;break;case`gte`:o=`lte`;break;case`lt`:o=`gt`;break;case`lte`:o=`gte`;break}if(i&&a){let e=i.path,n=Is(t,e);if(n){let e=a.value,t=o;return n.supports(t)?{canOptimize:!0,matchingKeys:n.lookup(t,e)}:{canOptimize:!1,matchingKeys:new Set}}}return{canOptimize:!1,matchingKeys:new Set}}function Us(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=Vs(e,t);if(n.canOptimize)return n;let r=[];for(let n of e.args){let e=Bs(n,t);e.canOptimize&&r.push(e)}return r.length>0?{canOptimize:!0,matchingKeys:Ls(r.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function Ws(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=[];for(let r of e.args){let e=Bs(r,t);e.canOptimize&&n.push(e)}return n.length>0?{canOptimize:!0,matchingKeys:Rs(n.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function Gs(e,t){if(e.type!==`func`||e.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};let n=e.args[0],r=e.args[1];if(n.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){let e=n.path,i=r.value,a=Is(t,e);if(a){if(a.supports(`in`))return{canOptimize:!0,matchingKeys:a.lookup(`in`,i)};if(a.supports(`eq`)){let e=new Set;for(let t of i){let n=a.lookup(`eq`,t);for(let t of n)e.add(t)}return{canOptimize:!0,matchingKeys:e}}}}return{canOptimize:!1,matchingKeys:new Set}}var Ks={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function qs(){return Ks.enabled&&!1}function Js(e){if(qs())if(Ks.onSuggestion)try{Ks.onSuggestion(e)}catch{}else console.warn(`[TanStack DB] Index suggestion for "${e.collectionId}":
8
+ ${e.message}
9
+ Field: ${e.fieldPath.join(`.`)}
10
+ Add index: collection.createIndex((row) => row.${e.fieldPath.join(`.`)})`)}function Ys(e,t,n){qs()&&t>Ks.collectionSizeThreshold&&Js({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function Xs(e){return e.config.autoIndex===`eager`}function Zs(e,t,n,r,i){if(Fs(t)||!Xs(n))return;let a=r??{...us,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){qs()&&Ys(n.id||`unknown`,n.size,t);try{n.createIndex(e=>{let n=e;for(let e of t)n=n[e];return n},{name:`auto:${t.join(`.`)}`,options:i?{compareFn:i,compareOptions:a}:{}})}catch(e){console.warn(`${n.id?`[${n.id}] `:``}Failed to create auto-index for field path "${t.join(`.`)}":`,e)}}}function Qs(e,t){if(!Xs(t))return;let n=$s(e);for(let{fieldName:e,fieldPath:r}of n)Zs(e,r,t)}function $s(e){let t=[];function n(e){if(e.type!==`func`)return;let r=e;if(r.name===`and`){for(let e of r.args)n(e);return}if(![`eq`,`gt`,`gte`,`lt`,`lte`,`in`].includes(r.name)||r.args.length<1||r.args[0].type!==`ref`)return;let i=r.args[0].path;if(i.length===0)return;let a=i.join(`_`);t.push({fieldName:a,fieldPath:i})}return n(e),t}var ec=class extends Map{constructor(e,t){super(t),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,t){let n=t(this.get(e));return this.set(e,n),n}},tc=3e4;function nc(e,t){if(t.length<=tc)e.push(...t);else for(let n=0;n<t.length;n+=tc){let r=t.slice(n,n+tc);e.push(...r)}}function rc(e,t,n){let r=0,i=e.length;for(;r<i;){let a=Math.floor((r+i)/2),o=n(e[a],t);if(o<0)r=a+1;else if(o>0)i=a;else return a}return r}var ic=new class{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!=`object`||!e){let t=String(e),n=0;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n=(n<<5)-n+r,n&=n}return n}return this.objectIds.has(e)||this.objectIds.set(e,this.nextId++),this.objectIds.get(e)}getStringId(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`obj_${this.getId(e)}`:`str_${String(e)}`}};function ac(e,t){let[n,r]=e,[i,a]=t;return{onlyInA:[...oc(n,Math.min(r,i)),...oc(Math.max(n,a),r)],onlyInB:[...oc(i,Math.min(a,n)),...oc(Math.max(i,r),a)]}}function oc(e,t){let n=[];for(let r=e;r<t;r++)n.push(r);return n}function sc(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function cc(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t instanceof Date?t.toISOString():t)}var lc=Y(),uc=Y(),dc=Y(),fc=Y(),pc=Y();function Y(){return Math.random()*(2**31-1)>>>0}var mc=new ArrayBuffer(8),hc=new DataView(mc),gc=new Uint8Array(mc),_c=class{constructor(){this.hash=lc,this.length=0,this.carry=0,this.carryBytes=0}_mix(e){e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+3864292196}writeByte(e){this.carry|=(e&255)<<8*this.carryBytes,this.carryBytes++,this.length++,this.carryBytes===4&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}update(e){switch(typeof e){case`symbol`:{this.update(pc);let t=e.description;if(!t)return;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);this.writeByte(n&255),this.writeByte(n>>>8&255)}return}case`string`:this.update(uc);for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);this.writeByte(n&255),this.writeByte(n>>>8&255)}return;case`number`:hc.setFloat64(0,e,!0),this.writeByte(gc[0]),this.writeByte(gc[1]),this.writeByte(gc[2]),this.writeByte(gc[3]),this.writeByte(gc[4]),this.writeByte(gc[5]),this.writeByte(gc[6]),this.writeByte(gc[7]);return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(fc)):this.update(dc);t>0n;)this.writeByte(Number(t&255n)),t>>=8n;e===0n&&this.writeByte(0);return}default:throw TypeError(`Unsupported input type: ${typeof e}`)}}digest(){if(this.carryBytes>0){let e=this.carry>>>0;e=Math.imul(e,3432918353),e=e<<15|e>>>17,e=Math.imul(e,461845907),this.hash^=e}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,2246822507),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,3266489909),this.hash^=this.hash>>>16,this.hash>>>0}},vc=Y(),yc=Y(),bc=Y(),xc=Y(),Sc=Y(),Cc=Y(),wc=Y(),Tc=Y(),Ec=Y(),Dc=Y(),Oc=Y(),kc=Y(),Ac=Y(),jc=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Mc(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&jc.has(t)}var Nc=128,Pc=new WeakMap;function Fc(e){let t=new _c;return Vc(t,e),t.digest()}function Ic(e){let t=Pc.get(e);if(t!==void 0)return t;let n;if(e instanceof Date)n=Lc(e);else if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)if(e.byteLength<=Nc)n=Rc(e);else return Wc(e);else if(e instanceof File)return Wc(e);else if(Mc(e))n=zc(e);else{let t=e,r=Tc;e instanceof Array&&(r=Ec),e instanceof Map&&(r=Dc,t=[...e.entries()]),e instanceof Set&&(r=Oc,t=[...e.entries()]),n=Bc(t,r)}return Pc.set(e,n),n}function Lc(e){let t=new _c;return t.update(wc),t.update(e.getTime()),t.digest()}function Rc(e){let t=new _c;t.update(kc),t.update(e.byteLength);for(let n=0;n<e.byteLength;n++)t.writeByte(e[n]);return t.digest()}function zc(e){let t=new _c;return t.update(Ac),t.update(e[Symbol.toStringTag]),t.update(e.toString()),t.digest()}function Bc(e,t){let n=new _c;n.update(t);let r=Object.keys(e);r.sort(Gc);for(let t of r)n.update(Sc),n.update(t),Vc(n,e[t]);return n.digest()}function Vc(e,t){if(t===null){e.update(bc);return}switch(typeof t){case`undefined`:e.update(xc);return;case`boolean`:e.update(t?vc:yc);return;case`number`:e.update(isNaN(t)?NaN:t===0?0:t);return;case`bigint`:case`string`:case`symbol`:e.update(t);return;case`object`:e.update(Hc(t));return;case`function`:e.update(Wc(t));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof t} which is not supported`)}}function Hc(e){let t=Pc.get(e);return t===void 0&&(t=Ic(e)),t}var Uc=1;function Wc(e){let t=Pc.get(e);return t===void 0&&(t=Uc^Cc,Uc++,Pc.set(e,t)),t}function Gc(e,t){return e.localeCompare(t)}var Kc=class e{#e;constructor(e=[]){this.#e=e}toString(e=!1){return`MultiSet(${JSON.stringify(this.#e,null,e?2:void 0)})`}toJSON(){return JSON.stringify(Array.from(this.getInner()))}static fromJSON(t){return new e(JSON.parse(t))}map(t){return new e(this.#e.map(([e,n])=>[t(e),n]))}filter(t){return new e(this.#e.filter(([e,n])=>t(e)))}negate(){return new e(this.#e.map(([e,t])=>[e,-t]))}concat(t){let n=[];return nc(n,this.#e),nc(n,t.getInner()),new e(n)}consolidate(){if(this.#e.length>0){let e=this.#e[0]?.[0];if(Array.isArray(e)&&e.length===2)return this.#t()}return this.#n()}#t(){let t=new Map,n=new Map,r=e=>{if(e.length!==2)throw Error(`Expected tuple of length 2`);let[t,n]=e;return`${ic.getStringId(t)}|${ic.getStringId(n)}`};for(let[e,i]of this.#e){if(!Array.isArray(e)||e.length!==2)return this.#n();let[a,o]=e;if(typeof a!=`string`&&typeof a!=`number`)return this.#n();let s;s=Array.isArray(o)&&o.length===2?r(o):ic.getStringId(o);let c=a+`|`+s;t.set(c,(t.get(c)||0)+i),n.has(c)||n.set(c,e)}let i=[];for(let[e,r]of t)r!==0&&i.push([n.get(e),r]);return new e(i)}#n(){let t=new ec(()=>0),n=new Map,r=!1,i=!1,a=!1;for(let[e,t]of this.#e)if(typeof e==`string`)r=!0;else if(typeof e==`number`)i=!0;else{a=!0;break}let o=a||r&&i;for(let[e,r]of this.#e){let i=o?Fc(e):e;o&&!n.has(i)&&n.set(i,e),t.update(i,e=>e+r)}let s=[];for(let[e,r]of t.entries())if(r!==0){let t=o?n.get(e):e;s.push([t,r])}return new e(s)}extend(t){let n=t instanceof e?t.getInner():t;nc(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}},qc=class{#e;constructor(e){this.#e=e}drain(){let e=[...this.#e].reverse();return this.#e.length=0,e}isEmpty(){return this.#e.length===0}},Jc=class{#e=[];sendData(e){e instanceof Kc||(e=new Kc(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new qc(e)}},Yc=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},Xc=class extends Yc{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},Zc=class extends Yc{constructor(e,t,n,r){super(e,[t,n],r),this.id=e}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}},Qc=class extends Xc{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},$c=class{#e=[];#t=0;#n=!1;constructor(){}#r(){if(this.#n)throw Error(`Graph already finalized`)}getNextOperatorId(){return this.#r(),this.#t++}newInput(){this.#r();let e=new Jc;return new tl(this,e)}addOperator(e){this.#r(),this.#e.push(e)}finalize(){this.#r(),this.#n=!0}step(){if(!this.#n)throw Error(`Graph not finalized`);for(let e of this.#e)e.run()}pendingWork(){return this.#e.some(e=>e.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}},el=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}connectReader(){return this.#t.newReader()}get writer(){return this.#t}get graph(){return this.#e}pipe(...e){return e.reduce((e,t)=>t(e),this)}},tl=class extends el{sendData(e){this.writer.sendData(e)}},nl=class extends Xc{run(){let e=this.inputMessages();if(e.length===0)return;let t=new Kc;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function rl(){return e=>{let t=new el(e.graph,new Jc),n=new nl(e.graph.getNextOperatorId(),e.connectReader(),t.writer);return e.graph.addOperator(n),t}}var il=Symbol(`NO_PREFIX`),al=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=cl(e),r=this.get(n);if(ll(r)){let[i,a]=r;if(cl(i)!==n)throw Error(`Mismatching prefixes, this should never happen`);if(i===e||Fc(i)===Fc(e)){let r=a+t;r===0?this.delete(n):this.set(n,[e,r])}else{let a=new ol;a.set(Fc(i),r),a.set(Fc(e),[e,t]),this.set(n,a)}}else r===void 0?this.set(n,[e,t]):r.addValue(e,t)&&this.delete(n);return this.size===0}},ol=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=Fc(e),r=this.get(n);if(r){let[,i]=r,a=i+t;a===0?this.delete(n):this.set(n,[e,a])}else this.set(n,[e,t]);return this.size===0}},sl=class e{#e;#t=new Map;constructor(){this.#e=new Map}static fromMultiSets(t){let n=new e;for(let e of t)for(let[t,r]of e.getInner()){let[e,i]=t;n.addValue(e,[i,r])}return n}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return this.#e.size}has(e){return this.#e.has(e)}hasPresence(e){return(this.#t.get(e)||0)!==0}getConsolidatedMultiplicity(e){return this.#t.get(e)||0}getPresenceKeys(){return this.#t.keys()}get(e){return[...this.getIterator(e)]}*getIterator(e){let t=this.#e.get(e);if(ll(t))yield t;else if(t===void 0)return;else if(t instanceof ol)for(let e of t.values())yield e;else for(let e of t.values())if(ll(e))yield e;else for(let t of e.values())yield t}*entries(){for(let e of this.#e.keys())for(let t of this.getIterator(e))yield[e,t]}*entriesIterators(){for(let e of this.#e.keys())yield[e,this.getIterator(e)]}addValue(e,t){let[n,r]=t;if(r===0)return;let i=(this.#t.get(e)||0)+r;i===0?this.#t.delete(e):this.#t.set(e,i);let a=this.#e.get(e);if(a===void 0){this.#e.set(e,t);return}if(ll(a)){this.#n(e,a,n,r);return}if(a instanceof ol){let i=cl(n);if(i!==il){let n=new al;n.set(il,a),n.set(i,t),this.#e.set(e,n)}else a.addValue(n,r)&&this.#e.delete(e)}else a.addValue(n,r)&&this.#e.delete(e)}#n(e,t,n,r){let[i,a]=t;if(i===n){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}let o=cl(n),s=cl(i);if(s===o&&(i===n||Fc(i)===Fc(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}if(s===il&&o===il){let a=new ol;a.set(Fc(i),t),a.set(Fc(n),[n,r]),this.#e.set(e,a)}else{let a=new al;if(s===o){let e=new ol;e.set(Fc(i),t),e.set(Fc(n),[n,r]),a.set(s,e)}else a.set(s,t),a.set(o,[n,r]);this.#e.set(e,a)}}append(e){for(let[t,n]of e.entries())this.addValue(t,n)}join(e){let t=[];if(this.size<=e.size)for(let[n,r]of this.entriesIterators()){if(!e.has(n))continue;let i=e.get(n);for(let[e,a]of r)for(let[r,o]of i)a!==0&&o!==0&&t.push([[n,[e,r]],a*o])}else for(let[n,r]of e.entriesIterators()){if(!this.has(n))continue;let e=this.get(n);for(let[i,a]of r)for(let[r,o]of e)o!==0&&a!==0&&t.push([[n,[r,i]],o*a])}return new Kc(t)}};function cl(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:il}function ll(e){return Array.isArray(e)}var ul=class extends Xc{#e=new sl;#t=new sl;#n;constructor(e,t,n,r){super(e,t,n),this.#n=r}run(){let e=new Set;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.#e.addValue(t,[i,r]),e.add(t)}let t=[];for(let n of e){let e=this.#e.get(n),r=this.#t.get(n),i=this.#n(e),a=new Map,o=new Map;for(let[e,t]of i){let n=a.get(e)??0;a.set(e,n+t)}for(let[e,t]of r){let n=o.get(e)??0;o.set(e,n+t)}for(let[e,r]of o)a.has(e)||(t.push([[n,e],-r]),this.#t.addValue(n,[e,-r]));for(let[e,r]of a)o.has(e)||r!==0&&(t.push([[n,e],r]),this.#t.addValue(n,[e,r]));for(let[e,r]of a){let i=o.get(e);if(i!==void 0){let a=r-i;a!==0&&(t.push([[n,e],a]),this.#t.addValue(n,[e,a]))}}}t.length>0&&this.output.sendData(new Kc(t))}};function dl(e){return t=>{let n=new el(t.graph,new Jc),r=new ul(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var fl=class extends Xc{#e;#t;constructor(e,t,n,r=e=>e){super(e,t,n),this.#e=r,this.#t=new Map}run(){let e=new Map;for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let t=Fc(this.#e(n)),i=(e.get(t)?.[0]??this.#t.get(t)??0)+r;e.set(t,[i,n])}let t=[];for(let[n,[r,i]]of e.entries()){let e=this.#t.get(n)??0;r===0?this.#t.delete(n):this.#t.set(n,r),e<=0&&r>0?t.push([[Fc(this.#e(i)),i[1]],1]):e>0&&r<=0&&t.push([[Fc(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new Kc(t))}};function pl(e=e=>e){return t=>{let n=new el(t.graph,new Jc),r=new fl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var ml=class extends Qc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function hl(e){return t=>{let n=new el(t.graph,new Jc),r=new ml(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var gl=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function _l(e,t,n){let r=n[0];if(t!=null&&e>=t)throw Error(e+` >= `+t);if(e.slice(-1)===r||t&&t.slice(-1)===r)throw Error(`trailing zero`);if(t){let i=0;for(;(e[i]||r)===t[i];)i++;if(i>0)return t.slice(0,i)+_l(e.slice(i),t.slice(i),n)}let i=e?n.indexOf(e[0]):0,a=t==null?n.length:n.indexOf(t[0]);return a-i>1?n[Math.round(.5*(i+a))]:t&&t.length>1?t.slice(0,1):n[i]+_l(e.slice(1),null,n)}function vl(e){if(e.length!==yl(e[0]))throw Error(`invalid integer part of order key: `+e)}function yl(e){if(e>=`a`&&e<=`z`)return e.charCodeAt(0)-97+2;if(e>=`A`&&e<=`Z`)return 90-e.charCodeAt(0)+2;throw Error(`invalid order key head: `+e)}function bl(e){let t=yl(e[0]);if(t>e.length)throw Error(`invalid order key: `+e);return e.slice(0,t)}function xl(e,t){if(e===`A`+t[0].repeat(26))throw Error(`invalid order key: `+e);let n=bl(e);if(e.slice(n.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function Sl(e,t){vl(e);let[n,...r]=e.split(``),i=!0;for(let e=r.length-1;i&&e>=0;e--){let n=t.indexOf(r[e])+1;n===t.length?r[e]=t[0]:(r[e]=t[n],i=!1)}if(i){if(n===`Z`)return`a`+t[0];if(n===`z`)return null;let e=String.fromCharCode(n.charCodeAt(0)+1);return e>`a`?r.push(t[0]):r.pop(),e+r.join(``)}else return n+r.join(``)}function Cl(e,t){vl(e);let[n,...r]=e.split(``),i=!0;for(let e=r.length-1;i&&e>=0;e--){let n=t.indexOf(r[e])-1;n===-1?r[e]=t.slice(-1):(r[e]=t[n],i=!1)}if(i){if(n===`a`)return`Z`+t.slice(-1);if(n===`A`)return null;let e=String.fromCharCode(n.charCodeAt(0)-1);return e<`Z`?r.push(t.slice(-1)):r.pop(),e+r.join(``)}else return n+r.join(``)}function wl(e,t,n=gl){if(e!=null&&xl(e,n),t!=null&&xl(t,n),e!=null&&t!=null&&e>=t)throw Error(e+` >= `+t);if(e==null){if(t==null)return`a`+n[0];let e=bl(t),r=t.slice(e.length);if(e===`A`+n[0].repeat(26))return e+_l(``,r,n);if(e<t)return e;let i=Cl(e,n);if(i==null)throw Error(`cannot decrement any more`);return i}if(t==null){let t=bl(e),r=e.slice(t.length);return Sl(t,n)??t+_l(r,null,n)}let r=bl(e),i=e.slice(r.length),a=bl(t),o=t.slice(a.length);if(r===a)return r+_l(i,o,n);let s=Sl(r,n);if(s==null)throw Error(`cannot increment any more`);return s<t?s:r+_l(i,null,n)}function Tl(e,t){return[e,t]}function El(e){return e[0]}function Dl(e){return e[1]}function Ol(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?sc(t,r):a}}var kl=class{#e=[];#t;#n;#r;constructor(e,t,n){this.#n=e,this.#r=e+t,this.#t=n}get size(){let e=this.#n,t=this.#r-this.#n,n=this.#e.length-e;return Math.max(0,Math.min(t,n))}move({offset:e,limit:t}){let n=this.#n,r=this.#r-this.#n,i=[this.#n,this.#r===1/0?this.#n+this.size:this.#r];this.#n=e??n,this.#r=this.#n+(t??r);let{onlyInA:a,onlyInB:o}=ac(i,[this.#n,this.#r===1/0?Math.max(this.#n+this.size,i[1]):this.#r]),s=[];o.forEach(e=>{let t=this.#e[e];t&&s.push(t)});let c=[];return a.forEach(e=>{let t=this.#e[e];t&&c.push(t)}),{moveIns:s,moveOuts:c,changes:a.length+o.length>0}}insert(e){let t={moveIn:null,moveOut:null},n=this.#i(e),r=Tl(e,wl(n===0?null:Dl(this.#e[n-1]),n===this.#e.length?null:Dl(this.#e[n])));if(this.#e.splice(n,0,r),n<this.#r){let e=Math.max(n,this.#n);e<this.#e.length&&(t.moveIn=this.#e[e],this.#r<this.#e.length&&(t.moveOut=this.#e[this.#r]))}return t}delete(e){let t={moveIn:null,moveOut:null},n=this.#i(e),[r]=this.#e.splice(n,1);if(n<this.#r){if(t.moveOut=r,n<this.#n){let e=this.#n-1;e<this.#e.length?t.moveOut=this.#e[e]:t.moveOut=null}let e=this.#r-1;e<this.#e.length&&(t.moveIn=this.#e[e])}return t}#i(e){return rc(this.#e,Tl(e,``),(e,t)=>this.#t(El(e),El(t)))}},Al=class{#e=new Map;#t;constructor(e){this.#t=e}get size(){return this.#t.size}get isEmpty(){return this.#e.size===0&&this.#t.size===0}processElement(e,t,n){let{oldMultiplicity:r,newMultiplicity:i}=this.#n(e,n);return r<=0&&i>0?this.#t.insert([e,t]):r>0&&i<=0?this.#t.delete([e,t]):{moveIn:null,moveOut:null}}move(e){if(!(this.#t instanceof kl))throw Error(`Cannot move B+-tree implementation of TopK with fractional index`);return this.#t.move(e)}#n(e,t){if(t===0){let t=this.#e.get(e)??0;return{oldMultiplicity:t,newMultiplicity:t}}let n=this.#e.get(e)??0,r=n+t;return r===0?this.#e.delete(e):this.#e.set(e,r),{oldMultiplicity:n,newMultiplicity:r}}};function jl(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],1])}}function Ml(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],-1])}}var Nl=class extends Xc{#e=new Map;#t;#n;#r;#i;constructor(e,t,n,r,i){super(e,t,n),this.#t=i.groupKeyFn,this.#i=i.limit??1/0,this.#r=i.offset??0,this.#n=Ol(r),i.setSizeCallback?.(()=>this.#a()),i.setWindowFn?.(this.#c.bind(this))}createTopK(e,t,n){return new kl(e,t,n)}#a(){let e=0;for(let t of this.#e.values())e+=t.size;return e}#o(e){let t=this.#e.get(e);return t||(t=new Al(this.createTopK(this.#r,this.#i,this.#n)),this.#e.set(e,t)),t}#s(e,t){t.isEmpty&&this.#e.delete(e)}#c({offset:e,limit:t}){e!==void 0&&(this.#r=e),t!==void 0&&(this.#i=t);let n=[],r=!1;for(let e of this.#e.values()){let t=e.move({offset:this.#r,limit:this.#i});t.moveIns.forEach(e=>jl(e,n)),t.moveOuts.forEach(e=>Ml(e,n)),t.changes&&(r=!0)}r&&this.output.sendData(new Kc(n))}run(){let e=[];for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.#l(t,i,r,e)}e.length>0&&this.output.sendData(new Kc(e))}#l(e,t,n,r){let i=this.#t(e,t),a=this.#o(i),o=a.processElement(e,t,n);jl(o.moveIn,r),Ml(o.moveOut,r),this.#s(i,a)}};function Pl(e,t){return n=>{let r=new el(n.graph,new Jc),i=new Nl(n.graph.getNextOperatorId(),n.connectReader(),r.writer,e,t);return n.graph.addOperator(i),r}}var Fl=class extends Zc{#e=new sl;#t=new sl;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=sl.fromMultiSets(this.inputAMessages()),t=sl.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new Kc;this.#n!==`anti`&&this.emitInnerResults(e,t,n),(this.#n===`left`||this.#n===`full`||this.#n===`anti`)&&this.emitLeftOuterResults(e,t,n),(this.#n===`right`||this.#n===`full`)&&this.emitRightOuterResults(e,t,n),this.#e.append(e),this.#t.append(t),n.getInner().length>0&&this.output.sendData(n)}emitInnerResults(e,t,n){e.size>0&&n.extend(e.join(this.#t)),t.size>0&&n.extend(this.#e.join(t)),e.size>0&&t.size>0&&n.extend(e.join(t))}emitLeftOuterResults(e,t,n){if(e.size>0){for(let[r,i]of e.entriesIterators())if(this.#t.getConsolidatedMultiplicity(r)+t.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[e,null]],t)}if(t.size>0)for(let e of t.getPresenceKeys()){let r=this.#t.getConsolidatedMultiplicity(e),i=t.getConsolidatedMultiplicity(e);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[t,r]of this.#e.getIterator(e))r!==0&&n.add([e,[t,null]],o?-r:+r)}}emitRightOuterResults(e,t,n){if(t.size>0){for(let[r,i]of t.entriesIterators())if(this.#e.getConsolidatedMultiplicity(r)+e.getConsolidatedMultiplicity(r)===0)for(let[e,t]of i)t!==0&&n.add([r,[null,e]],t)}if(e.size>0)for(let t of e.getPresenceKeys()){let r=this.#e.getConsolidatedMultiplicity(t),i=e.getConsolidatedMultiplicity(t);if(i===0)continue;let a=r+i;if(r===0==(a===0))continue;let o=r===0;for(let[e,r]of this.#t.getIterator(t))r!==0&&n.add([t,[null,e]],o?-r:+r)}}};function Il(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new el(n.graph,new Jc),i=new Fl(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var Ll=class extends Qc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}};function X(e){return t=>{let n=new el(t.graph,new Jc),r=new Ll(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Rl=class extends Xc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}run(){for(let e of this.inputMessages())this.#e(e),this.output.sendData(e)}};function zl(e){return t=>{let n=new el(t.graph,new Jc),r=new Rl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Bl=class extends Qc{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function Vl(e){return t=>{let n=new el(t.graph,new Jc),r=new Bl(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Hl=class extends Xc{#e;constructor(e,t,n,r,i){super(e,t,n);let a=i.limit??1/0,o=i.offset??0,s=this.createTopK(o,a,Ol(r));this.#e=new Al(s),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new kl(e,t,n)}moveTopK({offset:e,limit:t}){let n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(e=>jl(e,n)),r.moveOuts.forEach(e=>Ml(e,n)),r.changes&&this.output.sendData(new Kc(n))}run(){let e=[];for(let t of this.inputMessages())for(let[n,r]of t.getInner()){let[t,i]=n;this.processElement(t,i,r,e)}e.length>0&&this.output.sendData(new Kc(e))}processElement(e,t,n,r){let i=this.#e.processElement(e,t,n);jl(i.moveIn,r),Ml(i.moveOut,r)}};function Ul(e,t){let n=t||{};return t=>{let r=new el(t.graph,new Jc),i=new Hl(t.graph.getNextOperatorId(),t.connectReader(),r.writer,e,n);return t.graph.addOperator(i),r}}function Wl(e){return`pipe`in e}function Gl(e,t={}){let n=Object.fromEntries(Object.entries(t).filter(([e,t])=>!Wl(t)));return Object.fromEntries(Object.entries(t).filter(([e,t])=>Wl(t))),t=>{let r=`__original_key__`;return t.pipe(X(t=>{let i=e(t),a=cc(i),o={};o[r]=i;for(let[e,r]of Object.entries(n))o[e]=r.preMap(t);return[a,o]})).pipe(dl(e=>{let t=0;for(let[n,r]of e)t+=r;if(t<=0)return[];let i={};i[r]=e[0]?.[0]?.[r];for(let[t,r]of Object.entries(n)){let n=e.map(([e,n])=>[e[t],n]);i[t]=r.reduce(n)}return[[i,1]]})).pipe(X(([e,t])=>{let i=t[r],a={};Object.assign(a,i);for(let[e,r]of Object.entries(n))r.postMap?a[e]=r.postMap(t[e]):a[e]=t[e];return[e,a]}))}}function Kl(e=e=>e){return{preMap:t=>e(t),reduce:e=>{let t=0;for(let[n,r]of e)t+=n*r;return t}}}function ql(e=e=>e){return{preMap:t=>e(t)==null?0:1,reduce:e=>{let t=0;for(let[n,r]of e)t+=n*r;return t}}}function Jl(e=e=>e){return{preMap:t=>({sum:e(t),count:0}),reduce:e=>{let t=0,n=0;for(let[r,i]of e)t+=r.sum*i,n+=i;return{sum:t,count:n}},postMap:e=>e.sum/e.count}}function Yl(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[n,r]of e)(!t||n&&n<t)&&(t=n);return t}}}function Xl(e){let t=e??(e=>e);return{preMap:e=>t(e),reduce:e=>{let t;for(let[n,r]of e)(!t||n&&n>t)&&(t=n);return t}}}function Zl(e=e=>e){return{preMap:t=>[e(t)],reduce:e=>{let t=[];for(let[n,r]of e)for(let e of n)for(let n=0;n<r;n++)t.push(e);return t.length===0?[]:(t.sort((e,t)=>e-t),t)},postMap:e=>{if(e.length===0)return 0;let t=Math.floor(e.length/2);return e.length%2==0?(e[t-1]+e[t])/2:e[t]}}}function Ql(e=e=>e){return{preMap:t=>{let n=e(t),r=new Map;return r.set(n,1),r},reduce:e=>{let t=new Map;for(let[n,r]of e)for(let[e,i]of n.entries()){let n=t.get(e)||0;t.set(e,n+i*r)}return t},postMap:e=>{if(e.size===0)return 0;let t=0,n=0;for(let[r,i]of e.entries())i>n&&(n=i,t=r);return t}}}var $l={sum:Kl,count:ql,avg:Jl,min:Yl,max:Xl,median:Zl,mode:Ql};function eu(e,t){let n=t.limit??1/0,r=t.offset??0,i=t.setSizeCallback,a=t.setWindowFn,o=t.groupKeyFn,s=t.comparator??((e,t)=>e===t?0:e<t?-1:1);return t=>t.pipe(Pl((t,n)=>s(e(t),e(n)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:a,groupKeyFn:o}),rl())}function tu(e,t,n){let r=n?.limit??1/0,i=n?.offset??0,a=n?.setSizeCallback,o=n?.setWindowFn,s=n?.comparator??((e,t)=>e===t?0:e<t?-1:1);return n=>n.pipe(e((e,n)=>s(t(e),t(n)),{limit:r,offset:i,setSizeCallback:a,setWindowFn:o}),rl())}function nu(e,t){return tu(Ul,e,t)}var ru=`__virtual_synced__`,iu=`__virtual_has_local__`;function au(e){let t=!1,n=!0,r=!1;for(let[i,a]of Object.entries(e)){if(i===`$selected`)continue;let e=a,o=`$synced`in e,s=`$origin`in e;!o&&!s||(t=!0,e.$synced===!1&&(n=!1),e.$origin===`local`&&(r=!0))}return{synced:t?n:!0,hasLocal:r}}var{sum:ou,count:su,avg:cu,min:lu,max:uu}=$l;function du(e,t){let n=new Map,r=[...e];if(!t)return{selectToGroupByIndex:n,groupByExpressions:r};for(let[e,i]of Object.entries(t)){if(i.type===`agg`||_u(i))continue;let t=r.findIndex(e=>pu(i,e));if(t===-1)throw new Xo(e);n.set(e,t)}return{selectToGroupByIndex:n,groupByExpressions:r}}function fu(e,t,n,r,i,a,o){let s={[ru]:{preMap:([,e])=>au(e).synced,reduce:e=>{for(let[t,n]of e)if(!t&&n>0)return!1;return!0}},[iu]:{preMap:([,e])=>au(e).hasLocal,reduce:e=>{for(let[t,n]of e)if(t&&n>0)return!0;return!1}}};if(t.length===0){let t=s,c={},l={value:0};if(r){for(let[e,n]of Object.entries(r))if(n.type===`agg`)t[e]=mu(n);else if(_u(n)){let{transformed:r,extracted:i}=vu(n,l);for(let[e,n]of Object.entries(i))t[e]=mu(n);c[e]=J(r)}}let u=o?([,e])=>({__singleGroup:!0,__correlationKey:e?.[o]?.__correlationKey}):()=>({__singleGroup:!0});if(e=e.pipe(Gl(u,t)),e=e.pipe(X(([,e])=>{let t={...e.$selected||{}};if(r){for(let[n,i]of Object.entries(r))i.type===`agg`&&(t[n]=e[n]);gu(t,e,c)}let n=o?e.__correlationKey:void 0,i=n===void 0?`single_group`:`single_group_${cc(n)}`,s={...e,$selected:t},l=e[ru],u=e[iu];return s.$synced=l??!0,s.$origin=u?`local`:`remote`,s.$key=i,s.$collectionId=a??s.$collectionId,o&&n!==void 0&&(s[o]={__correlationKey:n}),[i,s]})),n&&n.length>0)for(let t of n){let n=J(hu(Ma(t),r||{},`$selected`));e=e.pipe(hl(([,e])=>ws(n({$selected:e.$selected}))))}if(i&&i.length>0)for(let t of i)e=e.pipe(hl(([,e])=>ws(t({$selected:e.$selected}))));return e}let c=du(t,r),l=t.map(e=>J(e)),u=([,e])=>{let n={...e};delete n.$selected;let r={};for(let e=0;e<t.length;e++){let t=l[e],i=t(n);r[`__key_${e}`]=i}return o&&(r.__correlationKey=e?.[o]?.__correlationKey),r},d=s,f={},p={value:0};if(r){for(let[e,t]of Object.entries(r))if(t.type===`agg`)d[e]=mu(t);else if(_u(t)){let{transformed:n,extracted:r}=vu(t,p);for(let[e,t]of Object.entries(r))d[e]=mu(t);f[e]=J(n)}}if(e=e.pipe(Gl(u,d)),e=e.pipe(X(([,e])=>{let n=e.$selected||{},i={};if(r){for(let[t,a]of Object.entries(r))if(a.type===`agg`)i[t]=e[t];else if(!f[t]){let r=c.selectToGroupByIndex.get(t);r===void 0?i[t]=n[t]:i[t]=e[`__key_${r}`]}gu(i,e,f)}else for(let n=0;n<t.length;n++)i[`__key_${n}`]=e[`__key_${n}`];let s=o?e.__correlationKey:void 0,l=[];for(let n=0;n<t.length;n++)l.push(e[`__key_${n}`]);s!==void 0&&l.push(s);let u=l.length===1?l[0]:cc(l),d={...e,$selected:i},p=e[ru],m=e[iu];return d.$synced=p??!0,d.$origin=m?`local`:`remote`,d.$key=u,d.$collectionId=a??d.$collectionId,o&&s!==void 0&&(d[o]={__correlationKey:s}),[u,d]})),n&&n.length>0)for(let t of n){let n=J(hu(Ma(t),r||{}));e=e.pipe(hl(([,e])=>n({$selected:e.$selected})))}if(i&&i.length>0)for(let t of i)e=e.pipe(hl(([,e])=>ws(t({$selected:e.$selected}))));return e}function pu(e,t){if(!e||!t||e.type!==t.type)return!1;switch(e.type){case`ref`:return!e.path||!t.path||e.path.length!==t.path.length?!1:e.path.every((e,n)=>e===t.path[n]);case`val`:return e.value===t.value;case`func`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>pu(e,t.args[n]));case`agg`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>pu(e,t.args[n]));default:return!1}}function mu(e){let t=J(e.args[0]),n=([,e])=>{let n=t(e);return typeof n==`number`?n:n==null?0:Number(n)},r=([,e])=>{let n=t(e);return typeof n==`number`||typeof n==`string`||typeof n==`bigint`||n instanceof Date?n:n==null?0:Number(n)},i=([,e])=>t(e);switch(e.name.toLowerCase()){case`sum`:return ou(n);case`count`:return su(i);case`avg`:return cu(n);case`min`:return lu(r);case`max`:return uu(r);default:throw new Zo(e.name)}}function hu(e,t,n=`$selected`){switch(e.type){case`agg`:{let r=e;for(let[e,i]of Object.entries(t))if(i.type===`agg`&&yu(r,i))return new K([n,e]);throw new Qo(r.name)}case`func`:{let n=e,r=n.args.map(e=>hu(e,t));return new Da(n.name,r)}case`ref`:return e;case`val`:return e;default:throw new $o(e.type)}}function gu(e,t,n){for(let n of Object.keys(t))n.startsWith(`__agg_`)&&(e[n]=t[n]);for(let[t,r]of Object.entries(n))e[t]=r({$selected:e});for(let t of Object.keys(e))t.startsWith(`__agg_`)&&delete e[t]}function _u(e){return Aa(e)?e.type===`agg`?!0:e.type===`func`&&`args`in e?e.args.some(e=>_u(e)):!1:!1}function vu(e,t){if(e.type===`agg`){let n=`__agg_${t.value++}`;return{transformed:new K([`$selected`,n]),extracted:{[n]:e}}}if(e.type===`func`){let n={},r=e.args.map(e=>{let r=vu(e,t);return Object.assign(n,r.extracted),r.transformed});return{transformed:new Da(e.name,r),extracted:n}}return{transformed:e,extracted:{}}}function yu(e,t){return e.name===t.name&&e.args.length===t.args.length&&e.args.every((e,n)=>pu(e,t.args[n]))}function bu(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>({compiledExpression:J(hu(e.expression,r,`$selected`)),compareOptions:xu(e,i)})),d=e=>{let t=e;return n.length>1?u.map(e=>e.compiledExpression(t)):n.length===1?u[0].compiledExpression(t):null},f=(e,t)=>{if(n.length>1){let r=e,i=t;for(let e=0;e<n.length;e++){let t=u[e],n=gs(t.compareOptions)(r[e],i[e]);if(n!==0)return n}return r.length-i.length}if(n.length===1){let n=u[0];return gs(n.compareOptions)(e,t)}return _s(e,t)},p,m;if(s&&!l){let t,r,o,l=e.from.alias,u=n[0],d=u.expression;if(d.type===`ref`){let n=Ia(e,d,i);if(n){r=n.collection;let i=n.path[0],a=xu(u,r);if(i){let e=gs(a);Zs(i,n.path,r,a,e)}if(o=J(new K(n.path),!0),t=Is(r,n.path,a),t?.supports(`gt`)||(t=void 0),!t){let e=r.id,t=n.path.join(`.`);console.warn(`[TanStack DB]${e?` [${e}]`:``} orderBy with limit requires an index on "${t}" for efficient lazy loading. Falling back to loading all data. Consider creating an index on the collection with collection.createIndex((row) => row.${t}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`)}l=d.path.length>1?String(d.path[0]):e.from.alias}}if(o){let u=n.every(e=>e.expression.type===`ref`)?n.map(t=>{let n=t.expression,r=Ia(e,n,i);return J(r?new K(r.path):t.expression,!0)}):void 0;m={alias:l,offset:c??0,limit:s,comparator:(e,t)=>{if(n.length===1)return f(e&&o(e),t&&o(t));if(u){let n=e=>e&&u.map(t=>t(e));return f(n(e),n(t))}return 0},valueExtractorForRawRow:e=>{if(n.length===1)return o(e);if(u)return u.map(t=>t(e))},firstColumnValueExtractor:o,index:t,orderBy:n};let d=r?.id??i.id;a[d]=m,t&&(p=e=>{a[d].dataNeeded=()=>{let t=e();return Math.max(0,m.limit-t)}})}}return l?t.pipe(eu(d,{limit:s,offset:c,comparator:f,setSizeCallback:p,groupKeyFn:l,setWindowFn:e=>{o(t=>{e(t),m&&(m.offset=t.offset??m.offset,m.limit=t.limit??m.limit)})}})):t.pipe(nu(d,{limit:s,offset:c,comparator:f,setSizeCallback:p,setWindowFn:e=>{o(t=>{e(t),m&&(m.offset=t.offset??m.offset,m.limit=t.limit??m.limit)})}}))}function xu(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function Su(e,t={}){let n=t=>{let n=[];for(let[r,i]of e.entries())(t?.(i)??!0)&&n.push({type:`insert`,key:r,value:i});return n};if(t.limit!==void 0&&!t.orderBy)throw Error(`limit cannot be used without orderBy`);if(t.orderBy){let n=t.where?Cu(t.where):void 0,r=Tu(e,t.orderBy,t.limit,n,t.optimizedOnly);if(r===void 0)return;let i=[];for(let t of r){let n=e.get(t);n!==void 0&&i.push({type:`insert`,key:t,value:n})}return i}if(!t.where)return n();try{let r=t.where,i=zs(r,e);if(i.canOptimize){let t=[];for(let n of i.matchingKeys){let r=e.get(n);r!==void 0&&t.push({type:`insert`,key:n,value:r})}return t}else return t.optimizedOnly?void 0:n(Cu(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=Cu(t.where);return t.optimizedOnly?void 0:n(i)}}function Cu(e){let t=Ts(e);return e=>{try{return ws(t(e))}catch{return!1}}}function wu(e,t){let n=Cu(t.whereExpression);return t=>{let r=[];for(let e of t)if(e.type===`insert`)n(e.value)&&r.push(e);else if(e.type===`update`){let t=n(e.value),i=e.previousValue?n(e.previousValue):!1;t&&i?r.push(e):t&&!i?r.push({...e,type:`insert`}):!t&&i&&r.push({...e,type:`delete`,value:e.previousValue})}else n(e.value)&&r.push(e);(r.length>0||t.length===0)&&e(r)}}function Tu(e,t,n,r,i){if(t.length===1){let i=t[0],a=i.expression;if(a.type===`ref`){let t=a.path,o=xu(i,e);Zs(t[0],t,e,o);let s=Is(e,t,o);if(s&&s.supports(`gt`))return s.takeFromStart(n??s.keyCount,t=>{let n=e.get(t);return n===void 0?!1:r?.(n)??!0})}}if(i)return;let a=[];for(let[t,n]of e.entries())(r?.(n)??!0)&&a.push({key:t,value:n});a.sort((e,n)=>{for(let r of t){let t=gs(r.compareOptions)(Eu(e.value,r.expression),Eu(n.value,r.expression));if(t!==0)return t}return 0});let o=a.map(e=>e.key);return n===void 0?o:o.slice(0,n)}function Eu(e,t){if(t.type===`ref`){let n=t,r=e;for(let e of n.path)r=r?.[e];return r}else if(t.type===`val`)return t.value;else return Ts(t)(e)}var Du=class{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,t){let n=0,r=this.sortedKeys.length;if(!this.comparator){for(;n<r;){let t=Math.floor((n+r)/2),i=this.sortedKeys[t],a=sc(e,i);if(a<0)r=t;else if(a>0)n=t+1;else return t}return n}for(;n<r;){let i=Math.floor((n+r)/2),a=this.sortedKeys[i],o=this.map.get(a),s=this.comparator(t,o);if(s<0)r=i;else if(s>0)n=i+1;else{let t=sc(e,a);if(t<0)r=i;else if(t>0)n=i+1;else return i}}return n}set(e,t){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);this.sortedKeys.splice(n,1)}let n=this.indexOf(e,t);return this.sortedKeys.splice(n,0,e),this.map.set(e,t),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){let t=this.map.get(e),n=this.indexOf(e,t);return this.sortedKeys.splice(n,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(let e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(let e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(let t of this.sortedKeys)e(this.map.get(t),t,this.map)}},Ou=`__tanstack_db_direct`,ku=class{constructor(e){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let e=!1;for(let t of this.transactions.values())if(t.state===`persisting`){e=!0;break}let{committedSyncedTransactions:t,uncommittedSyncedTransactions:n,hasTruncateSync:r,hasImmediateSync:i}=this.pendingSyncedTransactions.reduce((e,t)=>(t.committed?(e.committedSyncedTransactions.push(t),t.truncate&&(e.hasTruncateSync=!0),t.immediate&&(e.hasImmediateSync=!0)):e.uncommittedSyncedTransactions.push(t),e),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!e||r||i){this.isCommittingSyncTransactions=!0;let e=new Map(this.rowOrigins),i=new Map(this.optimisticUpserts),a=new Set(this.optimisticDeletes),o=r?t.find(e=>e.truncate)?.optimisticSnapshot:null,s,c,l=new Set;for(let e of t){for(let t of e.operations)l.add(t.key);for(let[t]of e.rowMetadataWrites)l.add(t)}let u=this.preSyncVisibleState;if(u.size===0){u=new Map;for(let e of l){let t=this.get(e);t!==void 0&&u.set(e,t)}}let d=[],f=this.config.sync.rowUpdateMode||`partial`,p=new Map;for(let e of this.transactions.values())if(e.state===`completed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&t.optimistic&&p.set(t.key,{type:t.type,value:t.modified});for(let e of t){if(e.truncate){let e=new Set([...this.syncedData.keys(),...o?.upserts.keys()||[]]);for(let t of e){if(o?.deletes.has(t))continue;let e=o?.upserts.get(t)||this.syncedData.get(t);e!==void 0&&d.push({type:`delete`,key:t,value:e})}s=new Set(this.pendingLocalChanges),c=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(let e of l)u.delete(e);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(let t of e.operations){let e=t.key;this.syncedKeys.add(e);let n=this.isLocalOnly||this.pendingLocalChanges.has(e)||this.pendingLocalOrigins.has(e)||s?.has(e)===!0||c?.has(e)===!0?`local`:`remote`;switch(t.type){case`insert`:this.syncedData.set(e,t.value),this.rowOrigins.set(e,n),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break;case`update`:if(f===`partial`){let n=Object.assign({},this.syncedData.get(e),t.value);this.syncedData.set(e,n)}else this.syncedData.set(e,t.value);this.rowOrigins.set(e,n),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break;case`delete`:this.syncedData.delete(e),this.syncedMetadata.delete(e),this.rowOrigins.delete(e),this.pendingLocalChanges.delete(e),this.pendingLocalOrigins.delete(e),this.pendingOptimisticUpserts.delete(e),this.pendingOptimisticDeletes.delete(e),this.pendingOptimisticDirectUpserts.delete(e),this.pendingOptimisticDirectDeletes.delete(e);break}}for(let[t,n]of e.rowMetadataWrites){if(n.type===`delete`){this.syncedMetadata.delete(t);continue}this.syncedMetadata.set(t,n.value)}for(let[t,n]of e.collectionMetadataWrites){if(n.type===`delete`){this.syncedCollectionMetadata.delete(t);continue}this.syncedCollectionMetadata.set(t,n.value)}}if(r){let e=new Set;for(let n of t)for(let t of n.operations)(t.type===`insert`||t.type===`update`)&&e.add(t.key);let n=new Map(o.upserts),r=new Set(o.deletes);for(let[t,i]of n)if(!r.has(t))if(e.has(t)){let e=!1;for(let n=d.length-1;n>=0;n--){let r=d[n];if(r.key===t&&r.type===`insert`){r.value=i,e=!0;break}}e||d.push({type:`insert`,key:t,value:i})}else d.push({type:`insert`,key:t,value:i});if(d.length>0&&r.size>0){let e=[];for(let t of d)t.type===`insert`&&r.has(t.key)||e.push(t);d.length=0,d.push(...e)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&o){for(let[e,t]of o.upserts)this.optimisticUpserts.set(e,t);for(let e of o.deletes)this.optimisticDeletes.add(e)}for(let e of this.transactions.values())if(![`completed`,`failed`].includes(e.state)){for(let t of e.mutations)if(this.isThisCollection(t.collection)&&t.optimistic)switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key);break}}for(let t of l){let n=u.get(t),r=this.get(t),o=this.getVirtualPropsSnapshotForState(t,{rowOrigins:e,optimisticUpserts:i,optimisticDeletes:a,completedOptimisticKeys:p}),s=this.getVirtualPropsSnapshotForState(t),c=o.$synced!==s.$synced||o.$origin!==s.$origin,l=n===void 0?void 0:Ms(n,t,this.collection.id,()=>o.$synced,()=>o.$origin),f=p.get(t),m=!1;f&&(f.type===`delete`&&n!==void 0&&r===void 0&&os(f.value,n)||r!==void 0&&os(f.value,r))&&(m=!0);let h=c&&n!==void 0&&r!==void 0&&os(n,r);if(!(m&&!h))if(n===void 0&&r!==void 0){let e=p.get(t);if(e){let n=e.value,i=Ms(n,t,this.collection.id,()=>o.$synced,()=>o.$origin);d.push({type:`update`,key:t,value:r,previousValue:i})}else d.push({type:`insert`,key:t,value:r})}else n!==void 0&&r===void 0?d.push({type:`delete`,key:t,value:l??n}):n!==void 0&&r!==void 0&&(!os(n,r)||h)&&d.push({type:`update`,key:t,value:r,previousValue:l??n})}this.size=this.calculateSize(),d.length>0&&this.indexes.updateIndexes(d),this.changes.emitEvents(d,!0),this.pendingSyncedTransactions=n,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||=!0}},this.config=e,this.transactions=new Du((e,t)=>e.compareCreatedAt(t)),this.syncedData=new Du(e.compare)}setDeps(e){this.collection=e.collection,this.lifecycle=e.lifecycle,this.changes=e.changes,this.indexes=e.indexes,this._events=e.events}isRowSynced(e){return this.isLocalOnly?!0:!this.optimisticUpserts.has(e)&&!this.optimisticDeletes.has(e)}getRowOrigin(e){return this.isLocalOnly||this.optimisticUpserts.has(e)||this.optimisticDeletes.has(e)?`local`:this.rowOrigins.get(e)??`remote`}createVirtualPropsSnapshot(e,t){return{$synced:t?.$synced??this.isRowSynced(e),$origin:t?.$origin??this.getRowOrigin(e),$key:t?.$key??e,$collectionId:t?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(e,t){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:`local`});let n=t?.optimisticUpserts??this.optimisticUpserts,r=t?.optimisticDeletes??this.optimisticDeletes,i=n.has(e)||r.has(e)||t?.completedOptimisticKeys?.has(e)===!0;return this.createVirtualPropsSnapshot(e,{$synced:!i,$origin:i?`local`:(t?.rowOrigins??this.rowOrigins).get(e)??`remote`})}enrichWithVirtualPropsSnapshot(e,t){let n=e,r=n.$synced??t.$synced,i=n.$origin??t.$origin,a=n.$key??t.$key,o=n.$collectionId??t.$collectionId,s=this.virtualPropsCache.get(e);if(s&&s.synced===r&&s.origin===i&&s.key===a&&s.collectionId===o)return s.enriched;let c={...e,$synced:r,$origin:i,$key:a,$collectionId:o};return this.virtualPropsCache.set(e,{synced:r,origin:i,key:a,collectionId:o,enriched:c}),c}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,t){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(t))}enrichChangeMessage(e){let{__virtualProps:t}=e,n=t?.value?this.enrichWithVirtualPropsSnapshot(e.value,t.value):this.enrichWithVirtualProps(e.value,e.key),r=e.previousValue?t?.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,t.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:n,previousValue:r,metadata:e.metadata}}getWithVirtualProps(e){let t=this.get(e);if(t!==void 0)return this.enrichWithVirtualProps(t,e)}get(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;if(!t.has(e))return n.has(e)?n.get(e):r.get(e)}has(e){let{optimisticDeletes:t,optimisticUpserts:n,syncedData:r}=this;return t.has(e)?!1:n.has(e)?!0:r.has(e)}*keys(){let{syncedData:e,optimisticDeletes:t,optimisticUpserts:n}=this;for(let n of e.keys())t.has(n)||(yield n);for(let r of n.keys())!e.has(r)&&!t.has(r)&&(yield r)}*values(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){for(let[e,t]of this.entries())yield[e,t]}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;let t=new Map(this.optimisticUpserts),n=new Set(this.optimisticDeletes),r=new Map(this.rowOrigins);for(let e of this.transactions.values()){let t=e.metadata[Ou]===!0;if(e.state===`completed`){for(let n of e.mutations)if(this.isThisCollection(n.collection)&&(this.pendingLocalOrigins.add(n.key),n.optimistic))switch(n.type){case`insert`:case`update`:this.pendingOptimisticUpserts.set(n.key,n.modified),this.pendingOptimisticDeletes.delete(n.key),t?(this.pendingOptimisticDirectUpserts.add(n.key),this.pendingOptimisticDirectDeletes.delete(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key));break;case`delete`:this.pendingOptimisticUpserts.delete(n.key),this.pendingOptimisticDeletes.add(n.key),t?(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.add(n.key)):(this.pendingOptimisticDirectUpserts.delete(n.key),this.pendingOptimisticDirectDeletes.delete(n.key));break}}else if(e.state===`failed`)for(let t of e.mutations)this.isThisCollection(t.collection)&&(this.pendingLocalOrigins.delete(t.key),t.optimistic&&(this.pendingOptimisticUpserts.delete(t.key),this.pendingOptimisticDeletes.delete(t.key),this.pendingOptimisticDirectUpserts.delete(t.key),this.pendingOptimisticDirectDeletes.delete(t.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();let i=new Set;for(let e of this.pendingSyncedTransactions)for(let t of e.operations)i.add(t.key);let a=[];for(let[e,t]of this.pendingOptimisticUpserts)i.has(e)||this.pendingOptimisticDirectUpserts.has(e)?this.optimisticUpserts.set(e,t):a.push(e);for(let e of a)this.pendingOptimisticUpserts.delete(e),this.pendingLocalOrigins.delete(e);let o=[];for(let e of this.pendingOptimisticDeletes)i.has(e)||this.pendingOptimisticDirectDeletes.has(e)?this.optimisticDeletes.add(e):o.push(e);for(let e of o)this.pendingOptimisticDeletes.delete(e),this.pendingLocalOrigins.delete(e);let s=[];for(let e of this.transactions.values())[`completed`,`failed`].includes(e.state)||s.push(e);for(let e of s)for(let t of e.mutations)if(this.isThisCollection(t.collection)&&(this.pendingLocalChanges.add(t.key),t.optimistic))switch(t.type){case`insert`:case`update`:this.optimisticUpserts.set(t.key,t.modified),this.optimisticDeletes.delete(t.key);break;case`delete`:this.optimisticUpserts.delete(t.key),this.optimisticDeletes.add(t.key);break}this.size=this.calculateSize();let c=[];this.collectOptimisticChanges(t,n,r,c);let l=c.filter(t=>!!(!this.recentlySyncedKeys.has(t.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){let t=new Set;for(let e of this.pendingSyncedTransactions)for(let n of e.operations)t.add(n.key);let n=l.filter(e=>!(e.type===`delete`&&t.has(e.key)&&!s.some(t=>t.mutations.some(t=>this.isThisCollection(t.collection)&&t.key===e.key))));n.length>0&&this.indexes.updateIndexes(n),this.changes.emitEvents(n,e)}else l.length>0&&this.indexes.updateIndexes(l),this.changes.emitEvents(l,e)}calculateSize(){let e=this.syncedData.size,t=Array.from(this.optimisticDeletes).filter(e=>this.syncedData.has(e)&&!this.optimisticUpserts.has(e)).length,n=Array.from(this.optimisticUpserts.keys()).filter(e=>!this.syncedData.has(e)).length;return e-t+n}collectOptimisticChanges(e,t,n,r){let i=new Set([...e.keys(),...this.optimisticUpserts.keys(),...t,...this.optimisticDeletes]);for(let a of i){let i=this.get(a),o=this.getPreviousValue(a,e,t),s=this.getVirtualPropsSnapshotForState(a,{rowOrigins:n,optimisticUpserts:e,optimisticDeletes:t}),c=this.getVirtualPropsSnapshotForState(a);o!==void 0&&i===void 0?r.push({type:`delete`,key:a,value:o,__virtualProps:{value:s}}):o===void 0&&i!==void 0?r.push({type:`insert`,key:a,value:i,__virtualProps:{value:c}}):o!==void 0&&i!==void 0&&o!==i&&r.push({type:`update`,key:a,value:i,previousValue:o,__virtualProps:{value:c,previousValue:s}})}}getPreviousValue(e,t,n){if(!n.has(e))return t.has(e)?t.get(e):this.syncedData.get(e)}scheduleTransactionCleanup(e){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;let e=new Set;for(let t of this.pendingSyncedTransactions)for(let n of t.operations)e.add(n.key);for(let t of e)this.recentlySyncedKeys.add(t);for(let t of e)if(!this.preSyncVisibleState.has(t)){let e=this.get(t);e!==void 0&&this.preSyncVisibleState.set(t,e)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}};function Au(){let e=new Map;function t(n){let r=n.join(`.`);if(e.has(r))return e.get(r);let i=new Proxy({},{get(e,r,i){if(r===`__refProxy`)return!0;if(r===`__path`)return n;if(r!==`__type`)return typeof r==`symbol`?Reflect.get(e,r,i):t([...n,String(r)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?!0:Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return e.set(r,i),i}return t([])}function ju(e){let t=new Map,n=0;function r(e){let i=e.join(`.`);if(t.has(i))return t.get(i);let a=new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return e;if(n!==`__type`)return typeof n==`symbol`?Reflect.get(t,n,i):r([...e,String(n)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?!0:Reflect.has(e,t)},ownKeys(t){let r=++n,i=`__SPREAD_SENTINEL__${e.join(`.`)}__${r}`;return Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(t)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return t.set(i,a),a}return new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return[];if(n===`__type`)return;if(typeof n==`symbol`)return Reflect.get(t,n,i);let a=String(n);if(e.includes(a))return r([a])},has(t,n){return n===`__refProxy`||n===`__path`||n===`__type`||typeof n==`string`&&e.includes(n)?!0:Reflect.has(t,n)},ownKeys(t){return[...e,`__refProxy`,`__path`,`__type`]},getOwnPropertyDescriptor(t,n){if(n===`__refProxy`||n===`__path`||n===`__type`)return{enumerable:!1,configurable:!0};if(typeof n==`string`&&e.includes(n))return{enumerable:!0,configurable:!0}}})}function Mu(e){let t=ju(e),n=new Map;function r(e){let t=e.join(`.`);if(n.has(t))return n.get(t);let i=new Proxy({},{get(t,n,i){if(n===`__refProxy`)return!0;if(n===`__path`)return[`$selected`,...e];if(n!==`__type`)return typeof n==`symbol`?Reflect.get(t,n,i):r([...e,String(n)])},has(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?!0:Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return t===`__refProxy`||t===`__path`||t===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(e,t)}});return n.set(t,i),i}let i=r([]);return new Proxy(t,{get(e,t,n){return t===`$selected`?i:Reflect.get(e,t,n)},has(e,t){return t===`$selected`?!0:Reflect.has(e,t)},ownKeys(e){return[...Reflect.ownKeys(e),`$selected`]},getOwnPropertyDescriptor(e,t){return t===`$selected`?{enumerable:!0,configurable:!0,value:i}:Reflect.getOwnPropertyDescriptor(e,t)}})}function Z(e){if(Nu(e))return new K(e.__path);if(e&&typeof e==`object`&&(e.__brand===`ToArrayWrapper`||e.__brand===`ConcatToArrayWrapper`)){let t=e.__brand===`ToArrayWrapper`?`toArray()`:`concat(toArray())`;throw Error(`${t} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${t} directly as a select field value instead.`)}return e&&typeof e==`object`&&`type`in e&&(e.type===`func`||e.type===`ref`||e.type===`val`||e.type===`agg`)?e:new Ea(e)}function Nu(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Pu(e,t){return new Da(`eq`,[Z(e),Z(t)])}function Fu(e,t){return new Da(`gt`,[Z(e),Z(t)])}function Iu(e,t){return new Da(`gte`,[Z(e),Z(t)])}function Lu(e,t){return new Da(`lt`,[Z(e),Z(t)])}function Ru(e,t,...n){return new Da(`and`,[e,t,...n].map(e=>Z(e)))}function zu(e,t,...n){return new Da(`or`,[e,t,...n].map(e=>Z(e)))}function Bu(e,t){return new Da(`in`,[Z(e),Z(t)])}var Vu=class{constructor(e){this.query=e,this.__brand=`ToArrayWrapper`}},Hu=class{constructor(e){this.query=e,this.__brand=`ConcatToArrayWrapper`}},Uu=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}once(e,t){let n=this.on(e,e=>{t(e),n()});return n}off(e,t){this.listeners.get(e)?.delete(t)}waitFor(e,t){return new Promise((n,r)=>{let i,a=this.on(e,e=>{i&&=(clearTimeout(i),void 0),n(e),a()});t&&(i=setTimeout(()=>{i=void 0,a(),r(Error(`Timeout waiting for event ${String(e)}`))},t))})}emitInner(e,t){this.listeners.get(e)?.forEach(e=>{try{e(t)}catch(e){queueMicrotask(()=>{throw e})}})}clearListeners(){this.listeners.clear()}};function Wu(e,t){if(t.length===0||e.length===0)return;if(e.length===1){let{expression:n,compareOptions:r}=e[0];return(r.direction===`asc`?Fu:Lu)(n,new Ea(t[0]))}let n=[];for(let r=0;r<e.length&&r<t.length;r++){let i=e[r],a=t[r],o=[];for(let n=0;n<r;n++){let r=e[n],i=t[n];o.push(Pu(r.expression,new Ea(i)))}let s=(i.compareOptions.direction===`asc`?Fu:Lu)(i.expression,new Ea(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>Ru(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>zu(e,t))}var Gu=class extends Uu{constructor(e,t,n){super(),this.collection=e,this.callback=t,this.options=n,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,n.onUnsubscribe&&this.on(`unsubscribed`,e=>n.onUnsubscribe(e)),n.whereExpression&&Qs(n.whereExpression,this.collection);let r=e=>{t(e),this.trackSentKeys(e)};this.callback=r,this.filteredCallback=n.whereExpression?wu(this.callback,n):this.callback,this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){let e=[...this.loadedSubsets],t=this.collection._sync.syncLoadSubsetFn!==null;if(e.length===0||!t){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(let t of e){let e=this.collection._sync.loadSubset(t);this.loadedSubsets.push(t),this.trackLoadSubsetPromise(e),e instanceof Promise&&(this.pendingTruncateRefetches.add(e),e.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(e),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;let e=this.truncateBuffer.flat();e.length>0&&this.filteredCallback(e),this.truncateBuffer=[]}setOrderByIndex(e){this.orderByIndex=e}hasOrderByIndex(){return this.orderByIndex!==void 0}setStatus(e){if(this._status===e)return;let t=this._status;this._status=e,this.emitInner(`status:change`,{type:`status:change`,subscription:this,previousStatus:t,status:e});let n=`status:${e}`;this.emitInner(n,{type:n,subscription:this,previousStatus:t,status:e})}trackLoadSubsetPromise(e){e instanceof Promise&&(this.pendingLoadSubsetPromises.add(e),this.setStatus(`loadingSubset`),e.finally(()=>{this.pendingLoadSubsetPromises.delete(e),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`)}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(e){let t=this.filterAndFlipChanges(e);this.isBufferingForTruncate?t.length>0&&this.truncateBuffer.push(t):this.filteredCallback(t)}requestSnapshot(e){if(this.loadedInitialState)return!1;let t={where:this.options.whereExpression,optimizedOnly:e?.optimizedOnly??!1};if(e){if(`where`in e){let n=e.where;if(t.where){let e=t.where;t.where=Ru(e,n)}else t.where=n}}else this.loadedInitialState=!0;let n={where:t.where,subscription:this,orderBy:e?.orderBy,limit:e?.limit},r=this.collection._sync.loadSubset(n);e?.onLoadSubsetResult?.(r),this.loadedSubsets.push(n),(e?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(r);let i=this.collection.currentStateAsChanges(t);if(i===void 0)return!1;let a=i.filter(e=>!this.sentKeys.has(e.key));for(let e of a)this.sentKeys.add(e.key);return this.snapshotSent=!0,this.callback(a),!0}requestLimitedSnapshot({orderBy:e,limit:t,minValues:n,offset:r,trackLoadSubsetPromise:i=!0,onLoadSubsetResult:a}){if(!t)throw Error(`limit is required`);if(!this.orderByIndex)throw Error(`Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`);let o=n!==void 0&&n.length>0,s=n?.[0],c=this.orderByIndex,l=this.options.whereExpression,u=l?Cu(l):void 0,d=e=>{if(e!==void 0&&this.sentKeys.has(e))return!1;let t=this.collection.get(e);return t===void 0?!1:u?.(t)??!0},f=s,p=[],m=[];if(o){let{expression:n}=e[0],r=this.collection.currentStateAsChanges({where:Pu(n,new Ea(s))});if(r){let e=r.map(e=>e.key).filter(e=>!this.sentKeys.has(e)&&d(e));m.push(...e);let n=c.take(t-m.length,s,d);m.push(...n)}else m=c.take(t,s,d)}else m=c.takeFromStart(t,d);let h=()=>Math.max(t-p.length,0),g=()=>m.length===0,_=e[0].expression,v=_.type===`ref`?J(new K(_.path),!0):null;for(;h()>0&&!g();){let e=new Set;for(let t of m){let n=this.collection.get(t);p.push({type:`insert`,key:t,value:n}),f=v?v(n):n,e.add(t)}m=c.take(h(),f,d)}let y=this.limitedSnapshotRowCount;for(let e of p)this.sentKeys.add(e.key);this.callback(p),this.limitedSnapshotRowCount+=p.length,p.length>0&&(this.lastSentKey=p[p.length-1].key);let b;if(n!==void 0&&n.length>0){let t=Wu(e,n);if(t){let{expression:r}=e[0],i=n[0],a;if(i instanceof Date){let e=new Date(i.getTime()+1);a=Ru(Iu(r,new Ea(i)),Lu(r,new Ea(e)))}else a=Pu(r,new Ea(i));b={whereFrom:t,whereCurrent:a,lastKey:this.lastSentKey}}}let x={where:l,limit:t,orderBy:e,cursor:b,offset:r??y,subscription:this},S=this.collection._sync.loadSubset(x);a?.(S),this.loadedSubsets.push(x),i&&this.trackLoadSubsetPromise(S)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;let t=this.isBufferingForTruncate,n=[];for(let r of e){let e=r;if(!this.sentKeys.has(r.key)){if(r.type===`update`)e={...r,type:`insert`,previousValue:void 0};else if(r.type===`delete`&&!t)continue;this.sentKeys.add(r.key)}else if(r.type===`insert`)continue;else r.type===`delete`&&this.sentKeys.delete(r.key);n.push(e)}return n}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(let t of e)t.type===`delete`?this.sentKeys.delete(t.key):this.sentKeys.add(t.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(let e of this.loadedSubsets)this.collection._sync.unloadSubset(e);this.loadedSubsets=[],this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),this.clearListeners()}},Ku=class{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(e){this.lifecycle=e.lifecycle,this.sync=e.sync,this.events=e.events,this.collection=e.collection,this.state=e.state}emitEmptyReadyEvent(){for(let e of this.changeSubscriptions)e.emitEvents([])}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,t=!1){if(this.shouldBatchEvents&&!t){this.batchedEvents.push(...e);return}let n=e;if(t&&(this.batchedEvents.length>0&&(n=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),n.length===0)return;let r=n.map(e=>this.enrichChangeWithVirtualProps(e));for(let e of this.changeSubscriptions)e.emitEvents(r)}subscribeChanges(e,t={}){if(this.addSubscriber(),t.where&&t.whereExpression)throw Error(`Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`);let{where:n,...r}=t,i=r.whereExpression;n&&(i=Z(n(Au())));let a=new Gu(this.collection,e,{...r,whereExpression:i,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(a)}});return t.onStatusChange&&a.on(`status:change`,t.onStatusChange),t.includeInitialState?a.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:t.orderBy,limit:t.limit,onLoadSubsetResult:t.onLoadSubsetResult}):t.includeInitialState===!1&&a.markAllStateAsSeen(),this.changeSubscriptions.add(a),a}addSubscriber(){let e=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,e)}removeSubscriber(){let e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new Ja;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}},qu=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),Ju=e=>{clearTimeout(e)},Yu=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>qu(e),Xu=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):Ju,Zu=class e{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return e.instance||=new e,e.instance}schedule(e,t,n){let r=Date.now()+t;this.tasks.set(e,{executeAt:r,callback:n}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(let t of this.tasks.values())t.executeAt<e&&(e=t.executeAt);let t=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),t)}process(){this.timeoutId=null;let e=Date.now();for(let[t,n]of this.tasks.entries())if(e>=n.executeAt){this.tasks.delete(t);try{n.callback()}catch(e){console.error(`Error in CleanupQueue task:`,e)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){e.instance&&=(e.instance.timeoutId!==null&&clearTimeout(e.instance.timeoutId),null)}};Zu.instance=null;var Qu=Zu,$u=class{constructor(e,t){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=e,this.id=t}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,t){if(e!==t&&!{idle:[`loading`,`error`,`cleaned-up`],loading:[`ready`,`error`,`cleaned-up`],ready:[`cleaned-up`,`error`],error:[`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[e].includes(t))throw new Ka(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new Wa(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);let n=this.status;this.status=e,this.events.emitStatusChange(e,n)}validateCollectionUsable(e){switch(this.status){case`error`:throw new Ga(e,this.id);case`cleaned-up`:this.sync.startSync();break}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`){if(this.setStatus(`ready`,!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||=!0;let e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(e=>e())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){let e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Qu.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Qu.getInstance().cancel(this),this.idleCallbackId!==null&&(Xu(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Xu(this.idleCallbackId),this.idleCallbackId=Yu(e=>{this.changes.activeSubscribersCount===0?this.performCleanup(e)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(e){if(!e||e.timeRemaining()>0||e.didTimeout){this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Qu.getInstance().cancel(this),this.hasBeenReady=!1;let e=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],e.forEach(e=>{try{e()}catch(e){console.error(`${this.config.id?`[${this.config.id}] `:``}Error in onFirstReady callback during cleanup:`,e)}}),this.setStatus(`cleaned-up`),this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(e){if(this.hasBeenReady){e();return}this.onFirstReadyCallbacks.push(e)}cleanup(){this.idleCallbackId!==null&&(Xu(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}},ed=Symbol(`liveQueryInternal`),td=class{constructor(e,t){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.config=e,this.id=t,this.syncMode=e.syncMode??`eager`}setDeps(e){this.collection=e.collection,this.state=e.state,this.lifecycle=e.lifecycle,this._events=e.events}startSync(){if(!(this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)){this.lifecycle.setStatus(`loading`);try{let e=nd(this.config.sync.sync({collection:this.collection,begin:e=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:e?.immediate})},write:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new go;if(t.committed)throw new _o;let n;n=`key`in e?e.key:this.config.getKey(e.value),this.state.pendingLocalChanges.has(n)&&this.state.pendingLocalOrigins.add(n);let r=e.type;if(e.type===`insert`){let i=this.state.syncedData.has(n),a=t.deletedKeys.has(n),o=t.truncate===!0;if(i&&!a&&!o){let t=this.state.syncedData.get(n);if(t!==void 0&&os(t,e.value))r=`update`;else{let e=this.config.utils[ed];throw new $a(n,this.id,{hasCustomGetKey:e?.hasCustomGetKey??!1,hasJoins:e?.hasJoins??!1,hasDistinct:e?.hasDistinct??!1})}}}let i={...e,type:r,key:n};t.operations.push(i),r===`delete`?(t.deletedKeys.add(n),t.rowMetadataWrites.set(n,{type:`delete`})):r===`insert`?i.metadata===void 0?t.rowMetadataWrites.set(n,{type:`delete`}):t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata}):i.metadata!==void 0&&t.rowMetadataWrites.set(n,{type:`set`,value:i.metadata})},commit:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new vo;if(e.committed)throw new yo;e.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new go;if(e.committed)throw new _o;e.operations=[],e.deletedKeys.clear(),e.rowMetadataWrites.clear(),e.truncate=!0,e.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}));if(this.syncCleanupFn=e?.cleanup??null,this.syncLoadSubsetFn=e?.loadSubset??null,this.syncUnloadSubsetFn=e?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new za(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(e){throw this.lifecycle.setStatus(`error`),e}}}getActivePendingSyncTransaction(){let e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new go;if(e.committed)throw new _o;return e}createSyncMetadataApi(){return{row:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],n=t?.rowMetadataWrites.get(e);if(n)return n.type===`delete`?void 0:n.value;if(!t?.truncate)return this.state.syncedMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:`delete`})}},collection:{get:e=>{let t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(e);return t?t.type===`delete`?void 0:t.value:this.state.syncedCollectionMetadata.get(e)},set:(e,t)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`set`,value:t})},delete:e=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:`delete`})},list:e=>{let t=new Map(this.state.syncedCollectionMetadata),n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(n)for(let[e,r]of n.collectionMetadataWrites)r.type===`delete`?t.delete(e):t.set(e,r.value);return Array.from(t.entries()).filter(([t])=>e?t.startsWith(e):!0).map(([e,t])=>({key:e,value:t}))}}}}preload(){return this.preloadPromise?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.`),this.preloadPromise=new Promise((e,t)=>{if(this.lifecycle.status===`ready`){e();return}if(this.lifecycle.status===`error`){t(new qa);return}if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`)try{this.startSync()}catch(e){t(e);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){let t=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`}),e.finally(()=>{let t=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),t&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})})}loadSubset(e){if(this.syncMode===`eager`)return!0;if(this.syncLoadSubsetFn){let t=this.syncLoadSubsetFn(e);if(t instanceof Promise)return this.trackLoadPromise(t),t}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&=(this.syncCleanupFn(),null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){let t=new es(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new es(this.id,e)})}this.preloadPromise=null}};function nd(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var rd=1;function id(e,t){return e===t?0:e<t?-1:1}function ad(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function od(e){if(e==null)return e;switch(typeof e){case`string`:case`boolean`:return e;case`number`:return Number.isFinite(e)?e:null;case`bigint`:return{__type:`bigint`,value:e.toString()};case`function`:case`symbol`:return;case`undefined`:return}if(Array.isArray(e))return e.map(e=>od(e)??null);if(e instanceof Date)return{__type:`date`,value:e.toISOString()};if(e instanceof Set)return{__type:`set`,values:Array.from(e).map(e=>od(e)??null).sort((e,t)=>id(sd(e),sd(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:od(e)??null,value:od(t)??null})).sort((e,t)=>id(sd(e.key),sd(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>id(e,t));for(let[e,r]of n){let n=od(r);n!==void 0&&(t[e]=n)}return t}function sd(e){return e===null?`null`:Array.isArray(e)?`[${e.map(sd).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>id(e,t)).map(t=>`${JSON.stringify(t)}:${sd(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function cd(e,t,n,r,i){let a=ad(r),o=od(t)??null,s=od(i);return{signatureVersion:rd,signature:sd(od({signatureVersion:rd,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function ld(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>ld(e));let t={};for(let[n,r]of Object.entries(e))t[n]=ld(r);return t}function ud(e){return JSON.parse(JSON.stringify(e))}var dd=class{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(e){this.state=e.state,this.lifecycle=e.lifecycle,this.defaultIndexType=e.defaultIndexType,this.events=e.events}createIndex(e,t={}){this.lifecycle.validateCollectionUsable(`createIndex`);let n=++this.indexCounter,r=Z(e(Au())),i=t.indexType??this.defaultIndexType;if(!i)throw new za(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
11
+ import { BasicIndex } from '@tanstack/db'
12
+ createCollection({ defaultIndexType: BasicIndex, ... })`);let a=new i(n,r,t.name,t.options);a.build(this.state.entries()),this.indexes.set(n,a);let o=cd(n,r,t.name,i,t.options);return this.indexMetadata.set(n,o),this.events.emitIndexAdded(o),a}removeIndex(e){this.lifecycle.validateCollectionUsable(`removeIndex`);let t=typeof e==`number`?e:e.id,n=this.indexes.get(t);if(!n||typeof e!=`number`&&n!==e)return!1;this.indexes.delete(t);let r=this.indexMetadata.get(t);return this.indexMetadata.delete(t),r&&this.events.emitIndexRemoved(r),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,t)=>e.indexId-t.indexId).map(e=>({...e,expression:ud(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:ld(e.options)}}))}updateIndexes(e){for(let t of this.indexes.values())for(let n of e)switch(n.type){case`insert`:t.add(n.key,n.value);break;case`update`:n.previousValue?t.update(n.key,n.previousValue,n.value):t.add(n.key,n.value);break;case`delete`:t.remove(n.key,n.value);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}},fd=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),pd=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),md=new Set([`set`,`delete`,`clear`,`add`]),hd=new Set([`entries`,`keys`,`values`,`forEach`]);function gd(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!ls(e)}function _d(e,t,n,r){if(fd.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(gd(e)){let{proxy:i}=r(e,{tracker:n,prop:String(t)});return i}return e},s=function(e,t,n){let r=o(e,t);return a.call(this,r,t,n)};if(e===`reduce`||e===`reduceRight`)return t.apply(n.copy_,[function(e,t,n,r){let i=o(t,n);return a.call(this,e,i,n,r)},...i.slice(1)]);let c=t.apply(n.copy_,[s,...i.slice(1)]);if((e===`find`||e===`findLast`)&&c&&typeof c==`object`){let e=n.copy_.indexOf(c);if(e!==-1)return o(c,e)}return e===`filter`&&Array.isArray(c)?c.map(e=>{let t=n.copy_.indexOf(e);return t===-1?e:o(e,t)}):c}}function vd(e,t){return function(){let n=e.copy_,r=0;return{next(){if(r>=n.length)return{done:!0,value:void 0};let i=n[r],a=i;if(gd(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function yd(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function bd(e,t,n,r,i,a,o){if(hd.has(e)||t===Symbol.iterator)return function(...s){let c=n.apply(i.copy_,s);if(e===`forEach`){let e=s[0];if(typeof e==`function`)return n.apply(r,[function(t,n,r){let a=e.call(this,t,n,r);return o(i),a},...s.slice(1)])}if(e===`entries`||e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator){let n=c,o=new Map;if(e===`values`&&r instanceof Map)for(let[e,t]of i.copy_.entries())o.set(t,e);let s=new Map;if(r instanceof Set)for(let e of i.copy_.values())s.set(e,e);return{next(){let c=n.next();if(!c.done&&c.value&&typeof c.value==`object`){if(e===`entries`&&Array.isArray(c.value)&&c.value.length===2){if(c.value[1]&&typeof c.value[1]==`object`){let e=c.value[0],t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value[1],t);c.value[1]=n}}else if(e===`values`||e===Symbol.iterator.toString()||t===Symbol.iterator)if(e===`values`&&r instanceof Map){let e=o.get(c.value);if(e!==void 0){let t={tracker:i,prop:e,updateMap:t=>{i.copy_ instanceof Map&&i.copy_.set(e,t)}},{proxy:n}=a(c.value,t);c.value=n}}else if(r instanceof Set){let e=c.value,t={tracker:i,prop:e,updateSet:t=>{i.copy_ instanceof Set&&(i.copy_.delete(e),i.copy_.add(t),s.set(e,t))}},{proxy:n}=a(c.value,t);c.value=n}else{let e=Symbol(`iterator-value`),{proxy:t}=a(c.value,{tracker:i,prop:e});c.value=t}}return c},[Symbol.iterator](){return this}}}return c}}function Q(...e){let t=typeof window<`u`&&typeof localStorage<`u`;(t&&localStorage.getItem(`DEBUG`)===`true`||!t&&typeof process<`u`&&{}.DEBUG===`true`)&&console.log(`[proxy]`,...e)}function xd(e,t=new WeakMap){if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e)){let n=[];return t.set(e,n),e.forEach((e,r)=>{n[r]=xd(e,t)}),n}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)){let n=Object.getPrototypeOf(e).constructor,r=new n(e.length);t.set(e,r);for(let t=0;t<e.length;t++)r[t]=e[t];return r}if(e instanceof Map){let n=new Map;return t.set(e,n),e.forEach((e,r)=>{n.set(r,xd(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(xd(e,t))}),n}if(ls(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=xd(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=xd(e[i],t);return n}var Sd=0;function Cd(){return Sd+=1,Sd}function wd(e,t){let n=new Map;function r(e,t){if(Q(`Object ID:`,e.constructor.name),n.has(e))return n.get(e);{let r=wd(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:xd(e),originalObject:xd(e),proxyCount:Cd(),modified:!1,assigned_:{},parent:t,target:e};Q(`createChangeProxy called for target`,e,a.proxyCount);function o(e){e.modified||=!0,e.parent&&(Q(`propagating change to parent`),`updateMap`in e.parent?e.parent.updateMap(e.copy_):`updateSet`in e.parent?e.parent.updateSet(e.copy_):(e.parent.tracker.copy_[e.parent.prop]=e.copy_,e.parent.tracker.assigned_[e.parent.prop]=!0),o(e.parent.tracker))}function s(e){if(Q(`checkIfReverted called with assigned keys:`,Object.keys(e.assigned_)),Object.keys(e.assigned_).length===0&&Object.getOwnPropertySymbols(e.assigned_).length===0)return Q(`No assigned properties, returning true`),!0;for(let t in e.assigned_)if(e.assigned_[t]===!0){let n=e.copy_[t],r=e.originalObject[t];if(Q(`Checking property ${String(t)}, current:`,n,`original:`,r),!os(n,r))return Q(`Property ${String(t)} is different, returning false`),!1}else if(e.assigned_[t]===!1)return Q(`Property ${String(t)} was deleted, returning false`),!1;let t=Object.getOwnPropertySymbols(e.assigned_);for(let n of t)if(e.assigned_[n]===!0){let t=e.copy_[n],r=e.originalObject[n];if(!os(t,r))return Q(`Symbol property is different, returning false`),!1}else if(e.assigned_[n]===!1)return Q(`Symbol property was deleted, returning false`),!1;return Q(`All properties match original values, returning true`),!0}function c(e,t){Q(`checkParentStatus called for child prop:`,t);let n=s(e);Q(`Parent checkIfReverted returned:`,n),n&&(Q(`Parent is fully reverted, clearing tracking`),e.modified=!1,e.assigned_={},e.parent&&(Q(`Continuing up the parent chain`),c(e.parent.tracker,e.parent.prop)))}function l(e){if(Q(`createObjectProxy`,e),i.has(e))return Q(`proxyCache found match`),i.get(e);let n=new Proxy(e,{get(e,t){Q(`get`,e,t);let n=a.copy_[t]??a.originalObject[t],s=a.originalObject[t];if(Q(`value (at top of proxy get)`,n),Object.getOwnPropertyDescriptor(e,t)?.get)return n;if(typeof n==`function`){if(Array.isArray(e)){let e=t.toString();if(pd.has(e))return yd(n,a,o);let i=_d(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return vd(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(md.has(i))return yd(n,a,o);let s=bd(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(gd(n)){let{proxy:e}=r(s,{tracker:a,prop:String(t)});return i.set(n,e),e}return n},set(e,n,r){let i=a.copy_[n];if(Q(`set called for property ${String(n)}, current:`,i,`new:`,r),os(i,r))Q(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=os(r,e);if(Q(`value:`,r,`original:`,e,`isRevertToOriginal:`,i),i){Q(`Reverting property ${String(n)} to original value`),delete a.assigned_[n.toString()],Q(`Updating copy with original value for ${String(n)}`),a.copy_[n]=xd(e),Q(`Checking if all properties reverted`);let r=s(a);Q(`All reverted:`,r),r?(Q(`All properties reverted, clearing tracking`),a.modified=!1,a.assigned_={},t&&(Q(`Updating parent for property:`,t.prop),c(t.tracker,t.prop))):(Q(`Some properties still changed, keeping modified flag`),a.modified=!0)}else Q(`Setting new value for property ${String(n)}`),a.copy_[n]=r,a.assigned_[n.toString()]=!0,Q(`Marking object and ancestors as modified`,a),o(a)}return!0},defineProperty(e,t,n){let r=Reflect.defineProperty(e,t,n);return r&&`value`in n&&(a.copy_[t]=xd(n.value),a.assigned_[t.toString()]=!0,o(a)),r},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(e,t)},preventExtensions(e){return Reflect.preventExtensions(e)},isExtensible(e){return Reflect.isExtensible(e)},deleteProperty(e,t){Q(`deleteProperty`,e,t);let n=typeof t==`symbol`?t.toString():t;if(n in e){let r=n in a.originalObject,i=Reflect.deleteProperty(e,t);return i&&(r?(a.assigned_[n]=!1,o(a)):(delete a.assigned_[n],Object.keys(a.assigned_).length===0&&Object.getOwnPropertySymbols(a.assigned_).length===0?a.modified=!1:a.modified=!0)),i}return!0}});return i.set(e,n),n}return{proxy:l(a.copy_),getChanges:()=>{if(Q(`getChanges called, modified:`,a.modified),Q(a),!a.modified)return Q(`Object not modified, returning empty object`),{};if(typeof a.copy_!=`object`||Array.isArray(a.copy_)||Object.keys(a.assigned_).length===0)return a.copy_;let e={};for(let t in a.copy_)a.assigned_[t]===!0&&t in a.copy_&&(e[t]=a.copy_[t]);return Q(`Returning copy:`,e),e}}}function Td(e){let t=e.map(e=>wd(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Ed(e,t){let{proxy:n,getChanges:r}=wd(e);return t(n),r()}function Dd(e,t){let{proxies:n,getChanges:r}=Td(e);return t(n),r()}function Od(){let e,t,n=!0;return{promise:new Promise((r,i)=>{e=e=>{n=!1,r(e)},t=e=>{n=!1,i(e)}}),resolve:e,reject:t,isPending:()=>n}}function kd(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var Ad=new class{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let t=this.contexts.get(e);return t||(t={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,t)),t}schedule({contextId:e,jobId:t,dependencies:n,run:r}){if(e===void 0){r();return}let i=this.getOrCreateContext(e);if(i.jobs.has(t)||i.queue.push(t),i.jobs.set(t,r),n){let e=new Set(n);e.delete(t),i.dependencies.set(t,e)}else i.dependencies.has(t)||i.dependencies.set(t,new Set);i.completed.delete(t)}flush(e){let t=this.contexts.get(e);if(!t)return;let{queue:n,jobs:r,dependencies:i,completed:a}=t;for(;n.length>0;){let t=!1,o=n.length;for(let s=0;s<o;s++){let o=n.shift(),s=r.get(o);if(!s){i.delete(o),a.delete(o);continue}let c=i.get(o),l=!c;if(c){l=!0;for(let t of c){if(t===o)continue;let n=kd(t)&&t.hasPendingGraphRun(e);if(r.has(t)&&!a.has(t)||!r.has(t)&&n){l=!1;break}}}l?(r.delete(o),i.delete(o),s(),a.add(o),t=!0):n.push(o)}if(!t)throw Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(let e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(t=>t(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){let t=this.contexts.get(e);return!!t&&t.jobs.size>0}clearJob(e,t){let n=this.contexts.get(e);n&&(n.jobs.delete(t),n.dependencies.delete(t),n.completed.delete(t),n.queue=n.queue.filter(e=>e!==t),n.jobs.size===0&&this.contexts.delete(e))}},jd=[],Md=[],Nd=0;function Pd(e,t){switch(`${e.type}-${t.type}`){case`insert-update`:return{...e,type:`insert`,original:{},modified:t.modified,changes:{...e.changes,...t.changes},key:e.key,globalKey:e.globalKey,metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case`insert-delete`:return null;case`update-delete`:return t;case`update-update`:return{...t,original:e.original,changes:{...e.changes,...t.changes},metadata:t.metadata??e.metadata,syncMetadata:{...e.syncMetadata,...t.syncMetadata}};case`delete-delete`:case`insert-insert`:return t;default:{let n=`${e.type}-${t.type}`;throw Error(`Unhandled mutation combination: ${n}`)}}}function Fd(e){let t=new Bd(e);return jd.push(t),t}function Id(){if(Md.length>0)return Md.slice(-1)[0]}function Ld(e){Ad.clear(e.id),Md.push(e)}function Rd(e){try{Ad.flush(e.id)}finally{Md=Md.filter(t=>t.id!==e.id)}}function zd(e){let t=jd.findIndex(t=>t.id===e.id);t!==-1&&jd.splice(t,1)}var Bd=class{constructor(e){if(e.mutationFn===void 0)throw new fo;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Od(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Nd++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e===`completed`||e===`failed`)&&zd(this)}mutate(e){if(this.state!==`pending`)throw new po;Ld(this);try{e()}finally{Rd(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){for(let t of e){let e=this.mutations.findIndex(e=>e.globalKey===t.globalKey);if(e>=0){let n=this.mutations[e],r=Pd(n,t);r===null?this.mutations.splice(e,1):this.mutations[e]=r}else this.mutations.push(t)}}rollback(e){let t=e?.isSecondaryRollback??!1;if(this.state===`completed`)throw new mo;if(this.setState(`failed`),!t){let e=new Set;this.mutations.forEach(t=>e.add(t.globalKey));for(let t of jd)t.state===`pending`&&t.mutations.some(t=>e.has(t.globalKey))&&t.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){let e=new Set;for(let t of this.mutations)e.has(t.collection.id)||(t.collection._state.onTransactionStateChange(),t.collection._state.pendingSyncedTransactions.length>0&&t.collection._state.commitPendingTransactions(),e.add(t.collection.id))}async commit(){if(this.state!==`pending`)throw new ho;if(this.setState(`persisting`),this.mutations.length===0)return this.setState(`completed`),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState(`completed`),this.touchCollection(),this.isPersisted.resolve(this)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.error={message:t.message,error:t},this.rollback(),t}return this}compareCreatedAt(e){let t=this.createdAt.getTime()-e.createdAt.getTime();return t===0?this.sequenceNumber-e.sequenceNumber:t}},Vd=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=Id();if(!r&&!this.config.onInsert)throw new so;let i=Array.isArray(e)?e:[e],a=[],o=new Set;if(i.forEach(e=>{let n=this.validateData(e,`insert`),r=this.config.getKey(n);if(this.state.has(r)||o.has(r))throw new Qa(r);o.add(r);let i=this.generateGlobalKey(r,e),s={mutationId:crypto.randomUUID(),original:{},modified:n,changes:Object.fromEntries(Object.keys(e).map(e=>[e,n[e]])),globalKey:i,key:r,metadata:t?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:t?.optimistic??!0,type:`insert`,createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(s)}),r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;{let e=Fd({metadata:{[Ou]:!0},mutationFn:async e=>await this.config.onInsert({transaction:e.transaction,collection:this.collection})});return e.applyMutations(a),this.markPendingLocalOrigins(a),e.commit().catch(()=>void 0),n.transactions.set(e.id,e),n.scheduleTransactionCleanup(e),n.recomputeOptimisticState(!0),e}},this.delete=(e,t)=>{let n=this.state;this.lifecycle.validateCollectionUsable(`delete`);let r=Id();if(!r&&!this.config.onDelete)throw new lo;if(Array.isArray(e)&&e.length===0)throw new io;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new ao(e);let r=this.generateGlobalKey(e,this.state.get(e)),i={mutationId:crypto.randomUUID(),original:this.state.get(e),modified:this.state.get(e),changes:this.state.get(e),globalKey:r,key:e,metadata:t?.metadata,syncMetadata:n.syncedMetadata.get(e)||{},optimistic:t?.optimistic??!0,type:`delete`,createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(i)}if(r)return r.applyMutations(a),n.transactions.set(r.id,r),n.scheduleTransactionCleanup(r),n.recomputeOptimisticState(!0),r;let o=Fd({autoCommit:!0,metadata:{[Ou]:!0},mutationFn:async e=>this.config.onDelete({transaction:e.transaction,collection:this.collection})});return o.applyMutations(a),this.markPendingLocalOrigins(a),o.commit().catch(()=>void 0),n.transactions.set(o.id,o),n.scheduleTransactionCleanup(o),n.recomputeOptimisticState(!0),o},this.id=t,this.config=e}setDeps(e){this.lifecycle=e.lifecycle,this.state=e.state,this.collection=e.collection}ensureStandardSchema(e){if(e&&`~standard`in e)return e;throw new Ha}validateData(e,t,n){if(!this.config.schema)return e;let r=this.ensureStandardSchema(this.config.schema);if(t===`update`&&n){let i=this.state.get(n);if(i&&e&&typeof e==`object`&&typeof i==`object`){let n=Object.assign({},i,e),a=r[`~standard`].validate(n);if(a instanceof Promise)throw new Ua;if(`issues`in a&&a.issues)throw new Ra(t,a.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));let o=a.value;return Object.fromEntries(Object.keys(e).map(e=>[e,o[e]]))}}let i=r[`~standard`].validate(e);if(i instanceof Promise)throw new Ua;if(`issues`in i&&i.issues)throw new Ra(t,i.issues.map(e=>({message:e.message,path:e.path?.map(e=>String(e))})));return i.value}generateGlobalKey(e,t){if(typeof e!=`string`&&typeof e!=`number`)throw e===void 0?new Xa(t):new Za(e,t);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(let t of e)this.state.pendingLocalOrigins.add(t.key)}update(e,t,n){if(e===void 0)throw new eo;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=Id();if(!i&&!this.config.onUpdate)throw new co;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new to;let s=typeof t==`function`?t:n,c=typeof t==`function`?{}:t,l=o.map(e=>{let t=this.state.get(e);if(!t)throw new no(e);return t}),u;u=a?Dd(l,s):[Ed(l[0],s)];let d=o.map((e,t)=>{let n=u[t];if(!n||Object.keys(n).length===0)return null;let i=l[t],a=this.validateData(n,`update`,e),o=Object.assign({},i,a),s=this.config.getKey(i),d=this.config.getKey(o);if(s!==d)throw new ro(s,d);let f=this.generateGlobalKey(d,o);return{mutationId:crypto.randomUUID(),original:i,modified:o,changes:Object.fromEntries(Object.keys(n).map(e=>[e,o[e]])),globalKey:f,key:e,metadata:c.metadata,syncMetadata:r.syncedMetadata.get(e)||{},optimistic:c.optimistic??!0,type:`update`,createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(d.length===0){let e=Fd({mutationFn:async()=>{}});return e.commit().catch(()=>void 0),r.scheduleTransactionCleanup(e),e}if(i)return i.applyMutations(d),r.transactions.set(i.id,i),r.scheduleTransactionCleanup(i),r.recomputeOptimisticState(!0),i;let f=Fd({metadata:{[Ou]:!0},mutationFn:async e=>this.config.onUpdate({transaction:e.transaction,collection:this.collection})});return f.applyMutations(d),this.markPendingLocalOrigins(d),f.commit().catch(()=>void 0),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}},Hd=class extends Uu{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,t){this.emitInner(e,t)}emitStatusChange(e,t){this.emit(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:t,status:e});let n=`status:${e}`;this.emit(n,{type:n,collection:this.collection,previousStatus:t,status:e})}emitSubscribersChange(e,t){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:t,subscriberCount:e})}emitIndexAdded(e){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:e})}emitIndexRemoved(e){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:e})}cleanup(){this.clearListeners()}};function Ud(e){let t=new Wd(e);return e.utils?t.utils=e.utils:t.utils={},t}var Wd=class{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(e,t)=>this._mutations.insert(e,t),this.delete=(e,t)=>this._mutations.delete(e,t),!e)throw new Ba;if(!e.sync)throw new Va;if(e.id?this.id=e.id:this.id=crypto.randomUUID(),this.config={...e,autoIndex:e.autoIndex??`off`},this.config.autoIndex===`eager`&&!e.defaultIndexType)throw new za(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
13
+ import { BasicIndex } from '@tanstack/db'
14
+ createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new Ku,this._events=new Hd,this._indexes=new dd,this._lifecycle=new $u(e,this.id),this._mutations=new Vd(e,this.id),this._state=new ku(e),this._sync=new td(e,this.id),this.comparisonOpts=Gd(e),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:e.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),e.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(e){return this._lifecycle.onFirstReady(e)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(e){return this._state.getWithVirtualProps(e)}has(e){return this._state.has(e)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield t)}}*entries(){for(let e of this._state.keys()){let t=this.get(e);t!==void 0&&(yield[e,t])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let t=0;for(let[n,r]of this.entries())e(r,n,t++)}map(e){let t=[],n=0;for(let[r,i]of this.entries())t.push(e(i,r,n++));return t}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,t={}){return this._indexes.createIndex(e,t)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,t,n){return this._mutations.validateData(e,t,n)}get compareOptions(){return{...this.comparisonOpts}}update(e,t,n){return this._mutations.update(e,t,n)}get state(){let e=new Map;for(let[t,n]of this.entries())e.set(t,n);return e}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(e={}){return Su(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 Gd(e){if(e.defaultStringCollation){let t=e.defaultStringCollation;return{stringSort:t.stringSort??`locale`,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}}else return{stringSort:`locale`}}function Kd(e){let t=qd(e),n=e,r,i=0;for(;i<10&&!os(n,r);)r=n,n=Xd(n),i++;return{optimizedQuery:Qd(n),sourceWhereClauses:t}}function qd(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=af(tf(e.where).map(e=>rf(e))),r=Yd(e);for(let[i,a]of n.singleSource)Jd(e,i)&&!r.has(i)&&t.set(i,a);return t}function Jd(e,t){if(e.from.alias===t)return e.from.type===`collectionRef`;if(e.join){for(let n of e.join)if(n.from.alias===t)return n.from.type===`collectionRef`}return!1}function Yd(e){let t=new Set;if(e.join){let n=e.from.alias;for(let r of e.join){let e=r.from.alias;(r.type===`left`||r.type===`full`)&&t.add(e),(r.type===`right`||r.type===`full`)&&t.add(n)}}return t}function Xd(e){return Zd({...e,from:e.from.type===`queryRef`?new Ta(Xd(e.from.query),e.from.alias):e.from,join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new Ta(Xd(e.from.query),e.from.alias):e.from}))})}function Zd(e){if(!e.where||e.where.length===0)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=yf(tf(e.where));return{...e,where:[t]}}return e}let t=of(e,af(tf(e.where.filter(e=>!Na(e))).map(e=>rf(e)))),n=e.where.filter(e=>Na(e));return n.length>0&&(t.where=[...t.where||[],...n]),t}function Qd(e){return{...e,from:$d(e.from),join:e.join?.map(e=>({...e,from:$d(e.from)}))}}function $d(e){if(e.type===`collectionRef`)return e;let t=Qd(e.query);if(ef(t)){let n=$d(t.from);return n.type===`collectionRef`?new wa(n.collection,e.alias):new Ta(n.query,e.alias)}return new Ta(t,e.alias)}function ef(e){return(!e.where||e.where.length===0)&&!e.select&&(!e.groupBy||e.groupBy.length===0)&&(!e.having||e.having.length===0)&&(!e.orderBy||e.orderBy.length===0)&&(!e.join||e.join.length===0)&&e.limit===void 0&&e.offset===void 0&&!e.fnSelect&&(!e.fnWhere||e.fnWhere.length===0)&&(!e.fnHaving||e.fnHaving.length===0)}function tf(e){let t=[];for(let n of e){let e=ja(n);t.push(...nf(e))}return t}function nf(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...nf(n));return t}else return[e]}function rf(e){let t=new Set,n=!1;function r(e){switch(e.type){case`ref`:if(e.path&&e.path.length>0){let r=e.path[0];r&&(t.add(r),e.path.length===1&&(n=!0))}break;case`func`:e.args&&e.args.forEach(r);break;case`val`:break;case`agg`:e.args&&e.args.forEach(r);break}}return r(e),{expression:e,touchedSources:t,hasNamespaceOnlyRef:n}}function af(e){let t=new Map,n=[];for(let r of e)if(r.touchedSources.size===1&&!r.hasNamespaceOnlyRef){let e=Array.from(r.touchedSources)[0];t.has(e)||t.set(e,[]),t.get(e).push(r.expression)}else (r.touchedSources.size>1||r.hasNamespaceOnlyRef)&&n.push(r.expression);let r=new Map;for(let[e,n]of t)r.set(e,yf(n));return{singleSource:r,multiSource:n.length>0?yf(n):void 0}}function of(e,t){let n=new Set,r=Yd(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=cf(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:cf(e.from,i,n)})):void 0,s=[];t.multiSource&&s.push(t.multiSource);let c=r.size>0;for(let[e,r]of t.singleSource)n.has(e)?c&&s.push(Pa(r)):s.push(r);let l=s.length>1?[yf(s.flatMap(e=>nf(ja(e))))]:s;return{select:e.select,groupBy:e.groupBy?[...e.groupBy]:void 0,having:e.having?[...e.having]:void 0,orderBy:e.orderBy?[...e.orderBy]:void 0,limit:e.limit,offset:e.offset,distinct:e.distinct,fnSelect:e.fnSelect,fnWhere:e.fnWhere?[...e.fnWhere]:void 0,fnHaving:e.fnHaving?[...e.fnHaving]:void 0,from:a,join:o,where:l.length>0?l:[]}}function sf(e){return{from:e.from.type===`collectionRef`?new wa(e.from.collection,e.from.alias):new Ta(sf(e.from.query),e.from.alias),select:e.select,join:e.join?e.join.map(e=>({type:e.type,left:e.left,right:e.right,from:e.from.type===`collectionRef`?new wa(e.from.collection,e.from.alias):new Ta(sf(e.from.query),e.from.alias)})):void 0,where:e.where?[...e.where]:void 0,groupBy:e.groupBy?[...e.groupBy]:void 0,having:e.having?[...e.having]:void 0,orderBy:e.orderBy?[...e.orderBy]:void 0,limit:e.limit,offset:e.offset,fnSelect:e.fnSelect,fnWhere:e.fnWhere?[...e.fnWhere]:void 0,fnHaving:e.fnHaving?[...e.fnHaving]:void 0}}function cf(e,t,n){let r=t.get(e.alias);if(!r)return e.type===`collectionRef`?new wa(e.collection,e.alias):new Ta(sf(e.query),e.alias);if(e.type===`collectionRef`){let t={from:new wa(e.collection,e.alias),where:[r]};return n.add(e.alias),new Ta(t,e.alias)}if(!mf(e.query,r,e.alias)||vf(e.query,r,e.alias))return new Ta(sf(e.query),e.alias);let i=e.query.where||[],a={...sf(e.query),where:[...i,r]};return n.add(e.alias),new Ta(a,e.alias)}function lf(e,t,n){return e.select?hf(e.select)||_f(e.select,t,n):!1}function uf(e){return e.groupBy&&e.groupBy.length>0}function df(e){return e.having&&e.having.length>0}function ff(e){return e.orderBy&&e.orderBy.length>0&&(e.limit!==void 0||e.offset!==void 0)}function pf(e){return e.fnSelect||e.fnWhere&&e.fnWhere.length>0||e.fnHaving&&e.fnHaving.length>0}function mf(e,t,n){return!(lf(e,t,n)||uf(e)||df(e)||ff(e)||pf(e))}function hf(e){for(let t of Object.values(e))if(typeof t==`object`){let e=t;if(e.type===`agg`||!(`type`in e)&&hf(e))return!0}return!1}function gf(e){let t=[];if(typeof e!=`object`||!e)return t;switch(e.type){case`ref`:t.push(e);break;case`func`:case`agg`:for(let n of e.args??[])t.push(...gf(n));break}return t}function _f(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof K||r.add(t);let i=gf(t);for(let e of i){let t=e.path;if(!Array.isArray(t)||t.length<2)continue;let i=t[0],a=t[1];if(i===n&&r.has(a))return!0}return!1}function vf(e,t,n){let r=gf(t);if(r.every(e=>e.path[0]!==n))return!1;if(e.fnSelect)return!0;let i=e.select;if(!i)return!1;for(let t of r){let r=t.path;if(r.length<2||r[0]!==n)continue;let a=i[r[1]];if(!a)continue;if(!(a instanceof K)||a.path.length<2)return!0;let[o,s]=a.path;if(o!==n&&o!==e.from.alias||s!==r[1])return!0}return!1}function yf(e){if(e.length===0)throw new ns;return e.length===1?e[0]:new Da(`and`,e)}function bf(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e;for(let e of t)y=xf(y,e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v);return y}function xf(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=t.from.type===`collectionRef`,{alias:b,input:x,collectionId:S}=wf(t.from,a,c,l,u,d,f,p,o,s,h,g,_,v);n[b]=x,y&&(g[b]=S);let C=c[r],w=c[S];if(!C)throw new Bo(r);if(!w)throw new Bo(S);let{activeSource:T,lazySource:E}=Ef(t.type,C,w),D=Object.keys(n),{mainExpr:O,joinedExpr:k}=Sf(t.left,t.right,D,b),A=J(O),j=J(k),M=e.pipe(X(([e,t])=>[bs(A(t)),[e,t]])),N=x.pipe(X(([e,t])=>{let n={[b]:t};return[bs(j(n)),[e,n]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new Ho(t.type);if(T){let e=T===`main`?t.from:m.from,n=e.type===`queryRef`&&(e.query.limit||e.query.offset),r=O.type===`func`||k.type===`func`;if(!n&&!r){let e=T===`main`?b:i;d.add(e);let t=T===`main`?M:N,n=Ia(m,T===`main`?k:O,E),r=n.collection,a=n.path[0];a&&Zs(a,n.path,r);let o=t.pipe(Vl(t=>{let i=_[e]||e,a=l[i];if(!a)throw new rs(i,e,E.id,Object.keys(l));if(a.hasLoadedInitialState())return;let o=[...new Set(t.getInner().map(([[e]])=>e).filter(e=>e!=null))];if(o.length===0)return;let s=new K(n.path);if(!a.requestSnapshot({where:Bu(s,o),optimizedOnly:!0})){let e=r.id,t=n.path.join(`.`);console.warn(`[TanStack DB]${e?` [${e}]`:``} Join requires an index on "${t}" for efficient loading. Falling back to loading all data. Consider creating an index on the collection with collection.createIndex((row) => row.${t}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`),a.requestSnapshot()}}));T===`main`?M=o:N=o}}return M.pipe(Il(N,t.type),Tf(t.type))}function Sf(e,t,n,r){let i=n.filter(e=>e!==r),a=Cf(e),o=Cf(t);if(a&&i.includes(a)&&o===r)return{mainExpr:e,joinedExpr:t};if(a===r&&o&&i.includes(o))return{mainExpr:t,joinedExpr:e};throw!a||!o?new Wo:a===o?new Uo(a):i.includes(a)?o===r?new qo:new Ko(r):new Go(a)}function Cf(e){switch(e.type){case`ref`:return e.path[0]||null;case`func`:{let t=new Set;for(let n of e.args){let e=Cf(n);e&&t.add(e)}return t.size===1?Array.from(t)[0]:null}default:return null}}function wf(e,t,n,r,i,a,o,s,c,l,u,d,f,p){switch(e.type){case`collectionRef`:{let n=t[e.alias];if(!n)throw new Po(e.alias,e.collection.id,Object.keys(t));return d[e.alias]=e.collection.id,{alias:e.alias,input:n,collectionId:e.collection.id}}case`queryRef`:{let m=u(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l);Object.assign(d,m.aliasToCollectionId),Object.assign(f,m.aliasRemapping);let h=l.has(e.query),g=e.query.from.alias;if(!(!h&&e.alias===g))for(let[e,t]of m.sourceWhereClauses)p.set(e,t);let _=Object.keys(m.aliasToCollectionId).find(e=>m.aliasToCollectionId[e]===m.collectionId);_&&_!==e.alias&&(f[e.alias]=_);let v=m.pipeline.pipe(X(e=>{let[t,[n,r]]=e;return[t,n]}));return{alias:e.alias,input:v,collectionId:m.collectionId}}default:throw new Jo(e.type)}}function Tf(e){return function(t){return t.pipe(hl(t=>{let[n,[r,i]]=t,a=r?.[1],o=i?.[1];return e===`inner`?!!(a&&o):e===`left`?!!a:e===`right`?!!o:!0}),X(e=>{let[t,[n,r]]=e,i=n?.[0],a=n?.[1],o=r?.[0],s=r?.[1],c={};return a&&Object.assign(c,a),s&&Object.assign(c,s),[`[${i},${o}]`,c]}))}}function Ef(e,t,n){switch(e){case`left`:return{activeSource:`main`,lazySource:n};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return t.size<n.size?{activeSource:`main`,lazySource:n}:{activeSource:`joined`,lazySource:t};default:return{activeSource:void 0,lazySource:void 0}}}function Df(e){return e instanceof Ea?e.value:e}function Of(e,t,n){let r=e.source(t);if(r&&typeof r==`object`){let t=n,i=e.targetPath;if(i.length===0)for(let[e,t]of Object.entries(r))n[e]=Df(t);else for(let e=0;e<i.length;e++){let n=i[e];if(e===i.length-1){let e=t[n]??={};if(typeof e==`object`)for(let[t,n]of Object.entries(r))e[t]=Df(n)}else{let e=t[n];(typeof e!=`object`||!e)&&(t[n]={}),t=t[n]}}}}function kf(e,t,n){let r=e.alias.split(`.`);if(r.length===1)n[e.alias]=e.compiled(t);else{let i=n;for(let e=0;e<r.length-1;e++){let t=r[e],n=i[t];(typeof n!=`object`||!n)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=Df(e.compiled(t))}}function Af([e,t],n){let r={};for(let e of n)e.kind===`merge`?Of(e,t,r):kf(e,t,r);return[e,{...t,$selected:r}]}function jf(e,t,n){let r=[];return Pf([],t,r),e.pipe(X(e=>Af(e,r)))}function Mf(e){return e.type===`agg`}function Nf(e){return e&&typeof e==`object`&&!Aa(e)}function Pf(e,t,n){for(let[r,i]of Object.entries(t)){if(r.startsWith(`__SPREAD_SENTINEL__`)){let t=r.slice(19),a=t.lastIndexOf(`__`),o=a>=0?t.slice(0,a):t,s=i&&typeof i==`object`&&`type`in i&&i.type===`ref`;if(o.includes(`.`)||s){let t=[...e],r=J(s?i:new K(o.split(`.`)));n.push({kind:`merge`,targetPath:t,source:r})}else{let t=o,r=[...e];n.push({kind:`merge`,targetPath:r,source:e=>e[t]})}continue}let t=i;if(t&&t.type===`includesSubquery`){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});continue}if(Nf(t)){Pf([...e,r],t,n);continue}if(Mf(t)||_u(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else{if(t===void 0||!Aa(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});continue}if(t instanceof Ea){let i=t.value;n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>i})}else n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:J(t)})}}}var Ff=Symbol(`includesRouting`);function If(e,t,n,r,i,a,o,s,c=new WeakMap,l=new WeakMap,u,d){let f=c.get(e);if(f)return f;Rf(e);let{optimizedQuery:p,sourceWhereClauses:m}=Kd(e),h=p;l.set(h,e),Uf(h,e,l);let g={...t},_={},v={},y={},{alias:b,input:x,collectionId:S}=zf(h.from,g,n,r,i,a,o,s,c,l,_,v,m);y[b]=x;let C=x;if(u&&d){let e=d.path.slice(1);C=x.pipe(X(([t,n])=>[Xf(n,e),[t,n]])).pipe(Il(u,`inner`)).pipe(hl(([e,[t]])=>t!=null),X(([e,[t,n]])=>{let[r,i]=t,a={...i,__correlationKey:e};return n!=null&&(a.__parentContext=n),[n==null?r:`${String(r)}::${JSON.stringify(n)}`,a]})),y[b]=C}let w=C.pipe(X(([e,t])=>{let{__parentContext:n,...r}=t,i={[b]:r};return n&&(Object.assign(i,n),i.__parentContext=n),[e,i]}));if(h.join&&h.join.length>0&&(w=bf(w,h.join,y,S,b,g,c,l,n,r,i,a,o,s,e,If,_,v,m)),h.where&&h.where.length>0)for(let e of h.where){let t=J(ja(e));w=w.pipe(hl(([e,n])=>ws(t(n))))}if(h.fnWhere&&h.fnWhere.length>0)for(let e of h.fnWhere)w=w.pipe(hl(([t,n])=>ws(e(n))));let T=[],E=[];if(h.select){let e=Kf(h.select);e.length>0&&(h={...h,select:{...h.select}});for(let{key:t,subquery:u}of e){let e=J(u.correlationField),d;if(u.parentProjection&&u.parentProjection.length>0){let t=u.parentProjection.map(e=>({alias:e.path[0],field:e.path.slice(1),compiled:J(e)}));d=w.pipe(X(([n,r])=>{let i={};for(let e of t){i[e.alias]||(i[e.alias]={});let t=e.compiled(r),n=i[e.alias];for(let t=0;t<e.field.length-1;t++)n[e.field[t]]||(n[e.field[t]]={}),n=n[e.field[t]];n[e.field[e.field.length-1]]=t}return[e(r),i]}))}else d=w.pipe(X(([t,n])=>[e(n),null]));d=d.pipe(dl(e=>e.map(([e,t])=>[e,+(t>0)])));let f=u.childCorrelationField.path[0],p=u.query.from.type===`collectionRef`?u.query.from.collection:null,y=Gf(u.query,u.childCorrelationField,p);if(y){let e=y.collection,t=y.path,n=t[0];a.add(f),n&&Zs(n,t,e),d=d.pipe(Vl(e=>{let n=r[v[f]||f];if(!n||n.hasLoadedInitialState())return;let i=[...new Set(e.getInner().map(([[e]])=>e).filter(e=>e!=null))];if(i.length===0)return;let a=new K(t);n.requestSnapshot({where:Bu(a,i)})}))}let b=If(u.parentFilters&&u.parentFilters.length>0?{...u.query,where:[...u.query.where||[],...u.parentFilters]}:u.query,g,n,r,i,a,o,s,c,l,d,u.childCorrelationField);Object.assign(_,b.aliasToCollectionId),Object.assign(v,b.aliasRemapping);for(let[e,t]of b.sourceWhereClauses)m.set(e,t);if(T.push({pipeline:b.pipeline,fieldName:u.fieldName,correlationField:u.correlationField,childCorrelationField:u.childCorrelationField,hasOrderBy:!!(u.query.orderBy&&u.query.orderBy.length>0),childCompilationResult:b,parentProjection:u.parentProjection,materialization:u.materialization,scalarField:u.scalarField}),u.parentProjection&&u.parentProjection.length>0){let t=u.parentProjection.map(e=>({alias:e.path[0],field:e.path.slice(1),compiled:J(e)})),n=e;E.push({fieldName:u.fieldName,getRouting:e=>{let r={};for(let n of t){r[n.alias]||(r[n.alias]={});let t=n.compiled(e),i=r[n.alias];for(let e=0;e<n.field.length-1;e++)i[n.field[e]]||(i[n.field[e]]={}),i=i[n.field[e]];i[n.field[n.field.length-1]]=t}return{correlationKey:n(e),parentContext:r}}})}else E.push({fieldName:u.fieldName,getRouting:t=>({correlationKey:e(t),parentContext:null})});Yf(h.select,t)}}if(h.distinct&&!h.fnSelect&&!h.select)throw new ko;if(h.fnSelect&&h.groupBy&&h.groupBy.length>0)throw new Ao;w=h.fnSelect?w.pipe(X(([e,t])=>{let n=h.fnSelect(t);return[e,{...t,$selected:n}]})):h.select?jf(w,h.select):w.pipe(X(([e,t])=>{let n=!h.join&&!h.groupBy?t[b]:t;return[e,{...t,$selected:n}]})),E.length>0&&(w=w.pipe(X(([e,t])=>{let n={};for(let{fieldName:e,getRouting:r}of E)n[e]=r(t);return t.$selected[Ff]=n,[e,t]})));let D=u?b:void 0;if(h.groupBy&&h.groupBy.length>0?w=fu(w,h.groupBy,h.having,h.select,h.fnHaving,S,D):h.select&&Object.values(h.select).some(e=>e.type===`agg`||_u(e))&&(w=fu(w,[],h.having,h.select,h.fnHaving,S,D)),h.having&&(!h.groupBy||h.groupBy.length===0)&&!(h.select&&Object.values(h.select).some(e=>e.type===`agg`)))throw new Mo;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(let e of h.fnHaving)w=w.pipe(hl(([t,n])=>e(n)));if(h.distinct&&(w=w.pipe(pl(([e,t])=>t.$selected))),h.orderBy&&h.orderBy.length>0){let t=u&&(h.limit!==void 0||h.offset!==void 0)?(e,t)=>{let n=t?.[b]?.__correlationKey,r=t?.__parentContext;return r==null?n:JSON.stringify([n,r])}:void 0,r={collectionId:S,pipeline:bu(e,w,h.orderBy,h.select||{},n[S],o,s,h.limit,h.offset,t).pipe(X(([e,[t,n]])=>{let r=t.$selected,i=Hf(Vf(r),t);if(u){let r=t[b]?.__correlationKey,a=t.__parentContext??null;return delete i.__correlationKey,delete i.__parentContext,[e,[i,n,r,a]]}return[e,[i,n]]})),sourceWhereClauses:m,aliasToCollectionId:_,aliasRemapping:v,includes:T.length>0?T:void 0};return c.set(e,r),r}else if(h.limit!==void 0||h.offset!==void 0)throw new No;let O={collectionId:S,pipeline:w.pipe(X(([e,t])=>{let n=t.$selected,r=Hf(Vf(n),t);if(u){let n=t[b]?.__correlationKey,i=t.__parentContext??null;return delete r.__correlationKey,delete r.__parentContext,[e,[r,void 0,n,i]]}return[e,[r,void 0]]})),sourceWhereClauses:m,aliasToCollectionId:_,aliasRemapping:v,includes:T.length>0?T:void 0};return c.set(e,O),O}function Lf(e){let t=new Set;if(e.from.type===`collectionRef`&&t.add(e.from.alias),e.join)for(let n of e.join)n.from.type===`collectionRef`&&t.add(n.from.alias);return t}function Rf(e,t=new Set){let n=Lf(e);for(let e of n)if(t.has(e))throw new Fo(e,Array.from(t));let r=new Set([...t,...n]);if(e.from.type===`queryRef`&&Rf(e.from.query,r),e.join)for(let t of e.join)t.from.type===`queryRef`&&Rf(t.from.query,r)}function zf(e,t,n,r,i,a,o,s,c,l,u,d,f){switch(e.type){case`collectionRef`:{let n=t[e.alias];if(!n)throw new Po(e.alias,e.collection.id,Object.keys(t));return u[e.alias]=e.collection.id,{alias:e.alias,input:n,collectionId:e.collection.id}}case`queryRef`:{let p=If(l.get(e.query)||e.query,t,n,r,i,a,o,s,c,l);Object.assign(u,p.aliasToCollectionId),Object.assign(d,p.aliasRemapping);let m=l.has(e.query),h=e.query.from.alias;if(!(!m&&e.alias===h))for(let[e,t]of p.sourceWhereClauses)f.set(e,t);let g=Object.keys(p.aliasToCollectionId).find(e=>p.aliasToCollectionId[e]===p.collectionId);g&&g!==e.alias&&(d[e.alias]=g);let _=p.pipeline.pipe(X(e=>{let[t,[n,r]]=e;return[t,Vf(n)]}));return{alias:e.alias,input:_,collectionId:p.collectionId}}default:throw new Io(e.type)}}function Bf(e){return e instanceof Ea||e&&typeof e==`object`&&`type`in e&&e.type===`val`}function Vf(e){return Bf(e)?e.value:e}function Hf(e,t){if(!e||typeof e!=`object`)return e;let n=!1;for(let r of Ns)if(e[r]==null&&r in t){n=!0;break}if(!n)return e;for(let n of Ns)e[n]==null&&n in t&&(e[n]=t[n]);return e}function Uf(e,t,n){if(e.from.type===`queryRef`&&t.from.type===`queryRef`&&(n.set(e.from.query,t.from.query),Uf(e.from.query,t.from.query,n)),e.join&&t.join)for(let r=0;r<e.join.length&&r<t.join.length;r++){let i=e.join[r],a=t.join[r];i.from.type===`queryRef`&&a.from.type===`queryRef`&&(n.set(i.from.query,a.from.query),Uf(i.from.query,a.from.query,n))}}function Wf(e,t){if(e.from.alias===t)return e.from;for(let n of e.join||[])if(n.from.alias===t)return n.from}function Gf(e,t,n){if(t.path.length!==0){if(t.path.length===1){let r=t.path[0];if(e.select){let t=e.select[r];if(t&&t.type===`ref`)return Gf(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Wf(e,r);return a?a.type===`queryRef`?Gf(a.query,new K(i),n):{collection:a.collection,path:i}:void 0}}}function Kf(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(r instanceof ka?t.push({key:n,subquery:r}):qf(r)&&Jf(r,n));return t}function qf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type!=`string`}function Jf(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof ka)throw Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${t}.${n}".`);qf(r)&&Jf(r,`${t}.${n}`)}}function Yf(e,t){e[t]=new Ea(null)}function Xf(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}function Zf(e,t){let n=e.type;if(n===`val`)return new Ea(e.value);if(n===`ref`){let n=e.path;if(Array.isArray(n)){if(n[0]===t&&n.length>1)return new K(n.slice(1));if(n.length===1&&n[0]!==void 0)return new K([n[0]])}return new K(Array.isArray(n)?n:[String(n)])}else{let n=[];for(let r of e.args){let e=Zf(r,t);n.push(e)}return new Da(e.name,n)}}function Qf(e,t){return e.map(e=>{let n=Zf(e.expression,t);return{...e,expression:n}})}var $f=new WeakMap;function ep(e){return e.utils?.[ed]?.getBuilder?.()}function tp(e,t){$f.set(e,t)}function np(e){return $f.get(e)}var rp=class e{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(t,n){let r;try{r=Object.keys(t)}catch{throw new wo(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new wo(n,`array`);if(r.length!==1)throw r.length===0?new wo(n,`empty object`):r.every(e=>!isNaN(Number(e)))?new wo(n,`string`):new xo(n);let i=r[0],a=t[i],o;if(a instanceof Wd)o=new wa(a,i);else if(a instanceof e){let e=a._getQuery();if(!e.from)throw new So(n);o=new Ta(e,i)}else throw new Co(i);return[i,o]}from(t){let[,n]=this._createRefForSource(t,`from clause`);return new e({...this.query,from:n})}join(t,n,r=`left`){let[i,a]=this._createRefForSource(t,`join clause`),o=n(ju([...this._getCurrentAliases(),i])),s,c;if(o.type===`func`&&o.name===`eq`&&o.args.length===2)s=o.args[0],c=o.args[1];else throw new To;let l={from:a,type:r,left:s,right:c},u=this.query.join||[];return new e({...this.query,join:[...u,l]})}leftJoin(e,t){return this.join(e,t,`left`)}rightJoin(e,t){return this.join(e,t,`right`)}innerJoin(e,t){return this.join(e,t,`inner`)}fullJoin(e,t){return this.join(e,t,`full`)}where(t){let n=t(ju(this._getCurrentAliases())),r=Nu(n)?Z(n):n;if(!Aa(r))throw new Do(ip(r));let i=this.query.where||[];return new e({...this.query,where:[...i,r]})}having(t){let n=this._getCurrentAliases(),r=t(this.query.select||this.query.fnSelect?Mu(n):ju(n)),i=Nu(r)?Z(r):r;if(!Aa(i))throw new Do(ip(i));let a=this.query.having||[];return new e({...this.query,having:[...a,i]})}select(t){let n=this._getCurrentAliases(),r=t(ju(n));Nu(r)&&r.__path.length===1&&(r={[`__SPREAD_SENTINEL__${r.__path[0]}__0`]:!0});let i=sp(r,n);return new e({...this.query,select:i,fnSelect:void 0})}orderBy(t,n=`asc`){let r=this._getCurrentAliases(),i=t(this.query.select||this.query.fnSelect?Mu(r):ju(r)),a=typeof n==`string`?{direction:n,nulls:`first`}:{direction:n.direction??`asc`,nulls:n.nulls??`first`,stringSort:n.stringSort,locale:n.stringSort===`locale`?n.locale:void 0,localeOptions:n.stringSort===`locale`?n.localeOptions:void 0},o=e=>({expression:Z(e),compareOptions:a}),s=Array.isArray(i)?i.map(e=>o(e)):[o(i)],c=this.query.orderBy||[];return new e({...this.query,orderBy:[...c,...s]})}groupBy(t){let n=t(ju(this._getCurrentAliases())),r=Array.isArray(n)?n.map(e=>Z(e)):[Z(n)],i=this.query.groupBy||[];return new e({...this.query,groupBy:[...i,...r]})}limit(t){return new e({...this.query,limit:t})}offset(t){return new e({...this.query,offset:t})}distinct(){return new e({...this.query,distinct:!0})}findOne(){return new e({...this.query,singleResult:!0})}_getCurrentAliases(){let e=[];if(this.query.from&&e.push(this.query.from.alias),this.query.join)for(let t of this.query.join)e.push(t.from.alias);return e}get fn(){let t=this;return{select(n){return new e({...t.query,select:void 0,fnSelect:n})},where(n){return new e({...t.query,fnWhere:[...t.query.fnWhere||[],n]})},having(n){return new e({...t.query,fnHaving:[...t.query.fnHaving||[],n]})}}}_getQuery(){if(!this.query.from)throw new Eo;return this.query}};function ip(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`object`:typeof e}function ap(e){return e===void 0?Z(null):e instanceof Oa||e instanceof Da||e instanceof K||e instanceof Ea?e:Z(e)}function op(e){return typeof e==`object`&&!!e&&!Aa(e)&&!e.__refProxy}function sp(e,t=[]){if(!op(e))return ap(e);let n={};for(let[r,i]of Object.entries(e)){if(typeof r==`string`&&r.startsWith(`__SPREAD_SENTINEL__`)){n[r]=i;continue}if(i instanceof rp){n[r]=up(i,r,t,`collection`);continue}if(i instanceof Vu){if(!(i.query instanceof rp))throw Error(`toArray() must wrap a subquery builder`);n[r]=up(i.query,r,t,`array`);continue}if(i instanceof Hu){if(!(i.query instanceof rp))throw Error(`concat(toArray(...)) must wrap a subquery builder`);n[r]=up(i.query,r,t,`concat`);continue}n[r]=sp(i,t)}return n}function cp(e){let t=[];switch(e.type){case`ref`:t.push(e);break;case`func`:for(let n of e.args??[])t.push(...cp(n));break}return t}function lp(e,t){return cp(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0]))}function up(e,t,n,r){let i=e._getQuery(),a=[i.from.alias];if(i.join)for(let e of i.join)a.push(e.from.alias);let o,s,c=-1,l=-1;if(i.where)for(let e=0;e<i.where.length;e++){let t=i.where[e],r=typeof t==`object`&&`expression`in t?t.expression:t;if(r.type===`func`&&r.name===`eq`&&r.args.length===2){let t=dp(r.args[0],r.args[1],n,a);if(t){o=t.parentRef,s=t.childRef,c=e;break}}if(r.type===`func`&&r.name===`and`&&r.args.length>=2){for(let t=0;t<r.args.length;t++){let i=r.args[t];if(i.type===`func`&&i.name===`eq`&&i.args.length===2){let r=dp(i.args[0],i.args[1],n,a);if(r){o=r.parentRef,s=r.childRef,c=e,l=t;break}}}if(o)break}}if(!o||!s||c===-1)throw Error(`Includes subquery for "${t}" must have a WHERE clause with an eq() condition that correlates a parent field with a child field. Example: .where(({child}) => eq(child.parentId, parent.id))`);let u=[...i.where];if(l>=0){let e=u[c],t=(typeof e==`object`&&`expression`in e?e.expression:e).args.filter((e,t)=>t!==l);if(t.length===1)u[c]=typeof e==`object`&&`expression`in e&&e.residual?{expression:t[0],residual:!0}:t[0];else{let n=new Da(`and`,t);u[c]=typeof e==`object`&&`expression`in e&&e.residual?{expression:n,residual:!0}:n}}else u.splice(c,1);let d=[],f=[];for(let e of u)lp(e,n)?f.push(e):d.push(e);let p;if(f.length>0){let e=new Set;p=[];for(let t of f){let r=typeof t==`object`&&`expression`in t?t.expression:t;for(let t of cp(r))t.path[0]!=null&&n.includes(t.path[0])&&!e.has(t.path.join(`.`))&&(e.add(t.path.join(`.`)),p.push(t))}}let m={...i,where:d.length>0?d:void 0},h=m.select,g=h===void 0||op(h),_=m,v;if(r===`concat`&&(h===void 0||g))throw Error(`concat(toArray(...)) for "${t}" requires the subquery to select a scalar value`);if(!g){if(r===`collection`)throw Error(`Includes subquery for "${t}" must select an object when materializing as a Collection`);v=Sa,_={...m,select:{[v]:h}}}return new ka(_,o,s,t,f.length>0?f:void 0,p,r,v)}function dp(e,t,n,r){if(e.type===`ref`&&t.type===`ref`){let i=e.path[0],a=t.path[0];if(i&&a&&n.includes(i)&&r.includes(a))return{parentRef:e,childRef:t};if(i&&a&&n.includes(a)&&r.includes(i))return{parentRef:t,childRef:e}}}function fp(e){return pp(e(new rp))}function pp(e){return e._getQuery()}function mp(e){let t={};function n(e){e.type===`collectionRef`?t[e.collection.id]=e.collection:e.type===`queryRef`&&r(e.query)}function r(e){if(e.from&&n(e.from),e.join&&Array.isArray(e.join))for(let t of e.join)t.from&&n(t.from);e.select&&i(e.select)}function i(e){for(let[t,n]of Object.entries(e))typeof t==`string`&&t.startsWith(`__SPREAD_SENTINEL__`)||(n instanceof ka?r(n.query):_p(n)&&i(n))}return r(e),t}function hp(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return hp(t.query);throw Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(e)}`)}function gp(e){let t=new Map;function n(e){if(e)if(e.type===`collectionRef`){let{id:n}=e.collection,r=t.get(n);r?r.add(e.alias):t.set(n,new Set([e.alias]))}else e.type===`queryRef`&&i(e.query)}function r(e){for(let[t,n]of Object.entries(e))typeof t==`string`&&t.startsWith(`__SPREAD_SENTINEL__`)||(n instanceof ka?i(n.query):_p(n)&&r(n))}function i(e){if(e){if(n(e.from),e.join)for(let t of e.join)n(t.from);e.select&&r(e.select)}}return i(e),t}function _p(e){return!(typeof e!=`object`||!e||e instanceof ka||`type`in e&&typeof e.type==`string`||e.__refProxy)}function vp(e){let t=typeof e.query==`function`?fp(e.query):pp(e.query);if(e.requireObjectResult&&t.select&&!_p(t.select))throw new jo;return t}function yp(e,t,n){let r=[];for(let e of t){let t=n(e.value);e.type===`insert`?r.push([[t,e.value],1]):e.type===`update`?(r.push([[t,e.previousValue],-1]),r.push([[t,e.value],1])):r.push([[t,e.value],-1])}return r.length!==0&&e.sendData(new Kc(r)),r.length}function*bp(e){for(let t of e)t.type===`update`?(yield{type:`delete`,key:t.key,value:t.previousValue},yield{type:`insert`,key:t.key,value:t.value}):yield t}function xp(e,t){let n=[];for(let r of e){if(r.type===`insert`){if(t.has(r.key))continue;t.add(r.key)}else r.type===`delete`&&t.delete(r.key);n.push(r)}return n}function Sp(e,t,n,r){let i=t,a=!1;for(let t of e){if(t.type===`delete`)continue;let e=!n.has(t.key);i===void 0||r(i,t.value)<0?(i=t.value,a=!0):e&&(a=!0)}return{biggest:i,shouldResetLoadKey:a}}function Cp(e,t){let{orderBy:n,limit:r,offset:i}=e,a=r!==void 0&&i!==void 0?r+i:r,o=n?Qf(n,t):void 0,s=o?.every(e=>{let t=e.expression;if(t.type!==`ref`)return!1;let n=t.path;return Array.isArray(n)&&n.length===1})??!1;return{orderBy:s?o:void 0,limit:s?a:void 0}}function wp(e,t,n,r,i){let{orderBy:a,valueExtractorForRawRow:o,offset:s}=e,c=t?o(t):void 0,l;c!==void 0&&(l=Array.isArray(c)?c:[c]);let u=cc({minValues:l??null,offset:s,limit:i});if(n===u)return;let d=Qf(a,r);return{minValues:l,normalizedOrderBy:d,loadRequestKey:u}}var Tp=Symbol.for(`@tanstack/db.collection-config-builder`),Ep=class{constructor(e,t,n,r){this.alias=e,this.collectionId=t,this.collection=n,this.collectionConfigBuilder=r,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){let e=this.getWhereClauseForAlias();if(e){let t=Zf(e,this.alias);return this.subscribeToChanges(t)}return this.subscribeToChanges()}subscribeToChanges(e){let t=this.getOrderByInfo(),n=e=>{e instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(e)},r=e=>{let t=e.subscription;if(e.status===`loadingSubset`)this.ensureLoadingPromise(t);else{let e=this.subscriptionLoadingPromises.get(t);e&&(this.subscriptionLoadingPromises.delete(t),e.resolve())}},i;if(t)i=this.subscribeToOrderedChanges(e,t,r,n);else{let t=!this.collectionConfigBuilder.isLazyAlias(this.alias);i=this.subscribeToMatchingChanges(e,t,r)}return i.status===`loadingSubset`&&this.ensureLoadingPromise(i),this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(()=>{let e=this.subscriptionLoadingPromises.get(i);e&&(this.subscriptionLoadingPromises.delete(i),e.resolve()),i.unsubscribe()}),i}sendChangesToPipeline(e,t){let n=xp(Array.isArray(e)?e:[...e],this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],i=yp(r,n,this.collection.config.getKey)>0?t:void 0;this.collectionConfigBuilder.scheduleGraphRun(i,{alias:this.alias})}subscribeToMatchingChanges(e,t,n){let r=e=>{this.sendChangesToPipeline(e)},i=Cp(this.collectionConfigBuilder.query,this.alias),a=t?e=>{e instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(e)}:void 0;return this.collection.subscribeChanges(r,{...t&&{includeInitialState:t},whereExpression:e,onStatusChange:n,orderBy:i.orderBy,limit:i.limit,onLoadSubsetResult:a})}subscribeToOrderedChanges(e,t,n,r){let{orderBy:i,offset:a,limit:o,index:s}=t,c=e=>{e instanceof Promise&&(this.pendingOrderedLoadPromise=e,e.finally(()=>{this.pendingOrderedLoadPromise===e&&(this.pendingOrderedLoadPromise=void 0)})),r(e)};this.orderedLoadSubsetResult=c;let l={},u=this.collection.subscribeChanges(e=>{let n=Array.isArray(e)?e:[...e];this.trackSentValues(n,t.comparator);let r=bp(n);this.sendChangesToPipelineWithTracking(r,l.current)},{whereExpression:e,onStatusChange:n});l.current=u;let d=this.collection.on(`truncate`,()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});u.on(`unsubscribed`,()=>{d()});let f=Qf(i,this.alias);return s?(u.setOrderByIndex(s),u.requestLimitedSnapshot({limit:a+o,orderBy:f,trackLoadSubsetPromise:!1,onLoadSubsetResult:c})):u.requestSnapshot({orderBy:f,limit:a+o,trackLoadSubsetPromise:!1,onLoadSubsetResult:c}),u}loadMoreIfNeeded(e){let t=this.getOrderByInfo();if(!t)return!0;let{dataNeeded:n,index:r}=t;if(!n||!r||this.pendingOrderedLoadPromise)return!0;let i=n();return i>0&&this.loadNextItems(i,e),!0}sendChangesToPipelineWithTracking(e,t){if(!this.getOrderByInfo()){this.sendChangesToPipeline(e);return}let n=t;n[Tp]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,n[Tp])}loadNextItems(e,t){let n=this.getOrderByInfo();if(!n)return;let r=wp(n,this.biggest,this.lastLoadRequestKey,this.alias,e);r&&(this.lastLoadRequestKey=r.loadRequestKey,t.requestLimitedSnapshot({orderBy:r.normalizedOrderBy,limit:e,minValues:r.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}))}getWhereClauseForAlias(){let e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.alias)}getOrderByInfo(){let e=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(e&&e.alias===this.alias)return e}trackSentValues(e,t){let n=Sp(e,this.biggest,this.sentToD2Keys,t);this.biggest=n.biggest,n.shouldResetLoadKey&&(this.lastLoadRequestKey=void 0)}ensureLoadingPromise(e){if(this.subscriptionLoadingPromises.has(e))return;let t,n=new Promise(e=>{t=e});this.subscriptionLoadingPromises.set(e,{resolve:t}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(n)}},Dp=0,Op=class{constructor(e){this.config=e,this.compiledAliasToCollectionId={},this.resultKeys=new WeakMap,this.orderByIndices=new WeakMap,this.isGraphRunning=!1,this.runCount=0,this.isInErrorState=!1,this.aliasDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.optimizableOrderByCollections={},this.id=e.id||`live-query-${++Dp}`,this.query=vp({query:e.query,requireObjectResult:!0}),this.collections=mp(this.query);let t=gp(this.query);this.collectionByAlias={};for(let[e,n]of t.entries()){let t=this.collections[e];if(t)for(let e of n)this.collectionByAlias[e]=t}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=kp(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??hp(this.query).compareOptions,this.compileBasePipeline()}hasJoins(e){return!!(e.join&&e.join.length>0||e.from.type===`queryRef`&&this.hasJoins(e.from.query))}getConfig(){return{id:this.id,getKey:this.config.getKey||(e=>this.resultKeys.get(e)??e.$key),sync:this.getSyncConfig(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime||5e3,schema:this.config.schema,onInsert:this.config.onInsert,onUpdate:this.config.onUpdate,onDelete:this.config.onDelete,startSync:this.config.startSync,singleResult:this.query.singleResult,utils:{getRunCount:this.getRunCount.bind(this),setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[ed]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new as;return this.currentWindow=e,this.windowFn(e),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(e=>{let t=this.liveQueryCollection.on(`loadingSubset:change`,n=>{n.isLoadingSubset||(t(),e())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(e){let t=this.compiledAliasToCollectionId[e];if(t)return t;let n=this.collectionByAlias[e];if(n)return n.id;throw Error(`Unknown source alias "${e}"`)}isLazyAlias(e){return this.lazySources.has(e)}maybeRunGraph(e){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw Error(`maybeRunGraph called without active sync session. This should not happen.`);this.isGraphRunning=!0;try{let{begin:t,commit:n}=this.currentSyncConfig,r=this.currentSyncState;if(this.isInErrorState)return;if(r.subscribedToAllCollections){let i=!1;for(;r.graph.pendingWork();)r.graph.run(),r.flushPendingChanges?.(),e?.(),i=!0;i||e?.(),r.messagesCount===0&&(t(),n()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,t){let n=t?.contextId??Id()?.id,r=t?.jobId??this,i=(()=>{if(t?.dependencies)return t.dependencies;let e=new Set(this.builderDependencies);if(t?.alias){let n=this.aliasDependencies[t.alias];if(n)for(let t of n)e.add(t)}return e.delete(this),Array.from(e)})();if(n)for(let e of i)typeof e.scheduleGraphRun==`function`&&e.scheduleGraphRun(void 0,{contextId:n});if(!this.currentSyncConfig||!this.currentSyncState)throw Error(`scheduleGraphRun called without active sync session. This should not happen.`);let a=n?this.pendingGraphRuns.get(n):void 0;a||(a={loadCallbacks:new Set},n&&this.pendingGraphRuns.set(n,a)),e&&a.loadCallbacks.add(e);let o=n?void 0:a;Ad.schedule({contextId:n,jobId:r,dependencies:i,run:()=>this.executeGraphRun(n,o)})}clearPendingGraphRun(e){this.pendingGraphRuns.delete(e)}hasPendingGraphRun(e){return this.pendingGraphRuns.has(e)}executeGraphRun(e,t){let n=t??(e?this.pendingGraphRuns.get(e):void 0);e&&this.pendingGraphRuns.delete(e),!(!n||!this.currentSyncConfig||!this.currentSyncState)&&(this.incrementRunCount(),this.maybeRunGraph(()=>{let e=!0,t;if(n.loadCallbacks.forEach(n=>{try{e=n()&&e}catch(n){e=!1,t??=n}}),t)throw t;return e}))}getSyncConfig(){return{rowUpdateMode:`full`,sync:this.syncFn.bind(this)}}incrementRunCount(){this.runCount++}getRunCount(){return this.runCount}syncFn(e){this.liveQueryCollection=e.collection,this.currentSyncConfig=e;let t={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},n=this.extendPipelineWithChangeProcessing(e,t);this.currentSyncState=n,this.unsubscribeFromSchedulerClears=Ad.onClear(e=>{this.clearPendingGraphRun(e)});let r=e.collection.on(`loadingSubset:change`,t=>{t.isLoadingSubset||this.updateLiveQueryStatus(e)});t.unsubscribeCallbacks.add(r);let i=this.subscribeToAllCollections(e,n);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(i),this.scheduleGraphRun(i),()=>{t.unsubscribeCallbacks.forEach(e=>e()),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.includesCache=void 0,this.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(e=>delete this.subscriptions[e]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new $c,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(e=>[e,this.graphCache.newInput()]));let e=If(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,e=>{this.windowFn=e});this.pipelineCache=e.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId,this.includesCache=e.includes;let t=Object.keys(this.compiledAliasToCollectionId).filter(e=>!Object.hasOwn(this.inputsCache,e));if(t.length>0)throw new is(t)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(e,t){let{begin:n,commit:r}=e,{graph:i,inputs:a,pipeline:o}=this.maybeCompileBasePipeline(),s=new Map;o.pipe(zl(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(Up,s)}));let c=this.setupIncludesOutput(this.includesCache,t);return t.flushPendingChanges=()=>{let t=s.size>0,i=Vp(c);if(!t&&!i)return;let a=s;if(this.config.getKey){let e=new Map;for(let[,t]of s){let n=this.config.getKey(t.value),r=e.get(n);r?(r.inserts+=t.inserts,r.deletes+=t.deletes,t.inserts>0&&(r.value=t.value,t.orderByIndex!==void 0&&(r.orderByIndex=t.orderByIndex))):e.set(n,{...t})}a=e}t&&(n(),a.forEach(this.applyChanges.bind(this,e)),r()),s=new Map,Bp(c,e.collection,this.id,t?a:null,e)},i.finalize(),t.graph=i,t.inputs=a,t.pipeline=o,t}setupIncludesOutput(e,t){return!e||e.length===0?[]:e.map(e=>{let n={fieldName:e.fieldName,childCorrelationField:e.childCorrelationField,hasOrderBy:e.hasOrderBy,materialization:e.materialization,scalarField:e.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return e.pipeline.pipe(zl(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Rp(o,s),l=n.pendingChildChanges.get(c);l||(l=new Map,n.pendingChildChanges.set(c,l));let u=l.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:a};i<0?u.deletes+=Math.abs(i):i>0&&(u.inserts+=i,u.value=r),l.set(e,u)}})),e.childCompilationResult.includes&&(n.nestedSetups=Mp(e.childCompilationResult.includes,t),n.nestedRoutingIndex=new Map,n.nestedRoutingReverseIndex=new Map),n})}applyChanges(e,t,n){let{write:r,collection:i}=e,{deletes:a,inserts:o,value:s,orderByIndex:c}=t;if(this.resultKeys.set(s,n),c!==void 0&&this.orderByIndices.set(s,c),o&&a===0)r({value:s,type:`insert`});else if(o>a||o===a&&i.has(i.getKeyFromItem(s)))r({value:s,type:`update`});else if(a>0)r({value:s,type:`delete`});else throw Error(`Could not apply changes: ${JSON.stringify(t)}. This should never happen.`)}handleSourceStatusChange(e,t,n){let{status:r}=n;if(r===`error`){this.transitionToError(`Source collection '${t}' entered error state`);return}if(r===`cleaned-up`){this.transitionToError(`Source collection '${t}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.`);return}this.updateLiveQueryStatus(e)}updateLiveQueryStatus(e){let{markReady:t}=e;if(this.isInErrorState)return;let n=this.currentSyncState?.subscribedToAllCollections,r=this.allCollectionsReady(),i=this.liveQueryCollection?.isLoadingSubset;n&&r&&!i&&t()}transitionToError(e){this.isInErrorState=!0,console.error(`[Live Query Error] ${e}`),this.liveQueryCollection?._lifecycle.setStatus(`error`)}allCollectionsReady(){return Object.values(this.collections).every(e=>e.isReady())}subscribeToAllCollections(e,t){let n=Object.entries(this.compiledAliasToCollectionId);if(n.length===0)throw Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);let r=n.map(([n,r])=>{let i=this.collectionByAlias[n]??this.collections[r],a=np(i);a&&a!==this?(this.aliasDependencies[n]=[a],this.builderDependencies.add(a)):this.aliasDependencies[n]=[];let o=new Ep(n,r,i,this),s=i.on(`status:change`,t=>{this.handleSourceStatusChange(e,r,t)});t.unsubscribeCallbacks.add(s);let c=o.subscribe();return this.subscriptions[n]=c,o.loadMoreIfNeeded.bind(o,c)});return t.subscribedToAllCollections=!0,()=>(r.map(e=>e()),!0)}};function kp(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function Ap(e){return e.materialization!==`collection`}function jp(e,t){if(!t)return e.materialization===`array`?[]:e.materialization===`concat`?``:void 0;if(e.materialization===`collection`)return t.collection;let n=[...t.collection.toArray],r=e.scalarField?n.map(t=>t?.[e.scalarField]):n;return e.materialization===`array`?r:r.map(e=>String(e??``)).join(``)}function Mp(e,t){return e.map(e=>{let n=new Map;e.pipeline.pipe(zl(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Rp(o,s),l=n.get(c);l||(l=new Map,n.set(c,l));let u=l.get(e)||{deletes:0,inserts:0,value:r,orderByIndex:a};i<0?u.deletes+=Math.abs(i):i>0&&(u.inserts+=i,u.value=r),l.set(e,u)}}));let r={compilationResult:e,buffer:n};return e.childCompilationResult.includes&&(r.nestedSetups=Mp(e.childCompilationResult.includes,t)),r})}function Np(e){return e.map(e=>{let t={fieldName:e.compilationResult.fieldName,childCorrelationField:e.compilationResult.childCorrelationField,hasOrderBy:e.compilationResult.hasOrderBy,materialization:e.compilationResult.materialization,scalarField:e.compilationResult.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return e.nestedSetups&&(t.nestedSetups=e.nestedSetups,t.nestedRoutingIndex=new Map,t.nestedRoutingReverseIndex=new Map),t})}function Pp(e){let t=new Set;if(!e.nestedSetups)return t;for(let n=0;n<e.nestedSetups.length;n++){let r=e.nestedSetups[n],i=[];for(let[a,o]of r.buffer){let r=e.nestedRoutingIndex.get(a);if(r===void 0)continue;let s=e.childRegistry.get(r);if(!s||!s.includesStates)continue;let c=s.includesStates[n];for(let[e,t]of o){let n=c.pendingChildChanges.get(a);n||(n=new Map,c.pendingChildChanges.set(a,n));let r=n.get(e);r?(r.inserts+=t.inserts,r.deletes+=t.deletes,t.inserts>0&&(r.value=t.value,t.orderByIndex!==void 0&&(r.orderByIndex=t.orderByIndex))):n.set(e,{...t})}t.add(r),i.push(a)}for(let e of i)r.buffer.delete(e)}return t}function Fp(e,t,n){if(e.nestedSetups){for(let r of e.nestedSetups)for(let[,i]of n)if(i.inserts>0){let n=i.value[Ff]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Rp(a,n?.parentContext??null);if(a!=null){e.nestedRoutingIndex.set(o,t);let n=e.nestedRoutingReverseIndex.get(t);n||(n=new Set,e.nestedRoutingReverseIndex.set(t,n)),n.add(o)}}else if(i.deletes>0&&i.inserts===0){let n=i.value[Ff]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Rp(a,n?.parentContext??null);if(a!=null){e.nestedRoutingIndex.delete(o);let n=e.nestedRoutingReverseIndex.get(t);n&&(n.delete(o),n.size===0&&e.nestedRoutingReverseIndex.delete(t))}}}}function Ip(e,t){if(!e.nestedRoutingReverseIndex)return;let n=e.nestedRoutingReverseIndex.get(t);if(n){for(let t of n)e.nestedRoutingIndex.delete(t);e.nestedRoutingReverseIndex.delete(t)}}function Lp(e){for(let t of e)if(t.buffer.size>0||t.nestedSetups&&Lp(t.nestedSetups))return!0;return!1}function Rp(e,t){return t==null?e:JSON.stringify([e,t])}function zp(e,t,n,r,i){let a=new WeakMap,o=r?new WeakMap:null,s=null,c=o?kp(o):void 0,l={collection:Ud({id:`__child-collection:${e}-${t}-${cc(n)}`,getKey:e=>a.get(e),compare:c,sync:{rowUpdateMode:`full`,sync:e=>(s=e,()=>{s=null})},startSync:!0,gcTime:0}),get syncMethods(){return s},resultKeys:a,orderByIndices:o};return i&&(l.includesStates=Np(i)),l}function Bp(e,t,n,r,i){for(let a of e){if(r){for(let[e,i]of r)if(i.inserts>0){let r=i.value,o=r[Ff]?.[a.fieldName],s=o?.correlationKey,c=Rp(s,o?.parentContext??null);if(s!=null){if(!a.childRegistry.has(c)){let e=zp(n,a.fieldName,c,a.hasOrderBy,a.nestedSetups);a.childRegistry.set(c,e)}let i=a.correlationToParentKeys.get(c);i||(i=new Set,a.correlationToParentKeys.set(c,i)),i.add(e);let o=jp(a,a.childRegistry.get(c));r[a.fieldName]=o;let s=t.get(e);s&&s!==r&&(s[a.fieldName]=o)}}}let e=Ap(a)?new Set(a.pendingChildChanges.keys()):null,o=new Map;if(a.pendingChildChanges.size>0){for(let[e,r]of a.pendingChildChanges){let i=a.childRegistry.get(e);if(i||(i=zp(n,a.fieldName,e,a.hasOrderBy,a.nestedSetups),a.childRegistry.set(e,i)),a.materialization===`collection`&&Hp(t,a.fieldName,e,a.correlationToParentKeys,i.collection),i.syncMethods){i.syncMethods.begin();for(let[e,t]of r)i.resultKeys.set(t.value,e),i.orderByIndices&&t.orderByIndex!==void 0&&i.orderByIndices.set(t.value,t.orderByIndex),t.inserts>0&&t.deletes===0?i.syncMethods.write({value:t.value,type:`insert`}):t.inserts>t.deletes||t.inserts===t.deletes&&i.syncMethods.collection.has(i.syncMethods.collection.getKeyFromItem(t.value))?i.syncMethods.write({value:t.value,type:`update`}):t.deletes>0&&i.syncMethods.write({value:t.value,type:`delete`});i.syncMethods.commit()}Fp(a,e,r),o.set(e,{entry:i,childChanges:r})}a.pendingChildChanges.clear()}let s=Pp(a);for(let[,{entry:e,childChanges:t}]of o)e.includesStates&&Bp(e.includesStates,e.collection,e.collection.id,t,e.syncMethods);for(let e of s){if(o.has(e))continue;let t=a.childRegistry.get(e);t?.includesStates&&Bp(t.includesStates,t.collection,t.collection.id,null,t.syncMethods)}let c=new Set;if(a.nestedSetups)for(let[e,t]of a.childRegistry)o.has(e)||s.has(e)||t.includesStates&&Vp(t.includesStates)&&(Bp(t.includesStates,t.collection,t.collection.id,null,t.syncMethods),c.add(e));let l=Ap(a)?new Set([...e||[],...s,...c]):null;if(i&&l&&l.size>0){let e=[];for(let n of l){let r=a.correlationToParentKeys.get(n);if(!r)continue;let o=a.childRegistry.get(n);for(let n of r){let r=t.get(n);if(r){let t=i.collection.getKeyFromItem(r),n={...r};r[a.fieldName]=jp(a,o),e.push({type:`update`,key:t,value:r,previousValue:n})}}}e.length>0&&t._changes.emitEvents(e,!0)}if(r){for(let[e,t]of r)if(t.deletes>0&&t.inserts===0){let n=t.value[Ff]?.[a.fieldName],r=n?.correlationKey,i=Rp(r,n?.parentContext??null);if(r!=null){let t=a.correlationToParentKeys.get(i);t&&(t.delete(e),t.size===0&&(Ip(a,i),a.childRegistry.delete(i),a.correlationToParentKeys.delete(i)))}}}}if(r)for(let[,e]of r)delete e.value[Ff]}function Vp(e){for(let t of e)if(t.pendingChildChanges.size>0||t.nestedSetups&&Lp(t.nestedSetups))return!0;return!1}function Hp(e,t,n,r,i){let a=r.get(n);if(a)for(let n of a){let r=e.get(n);r&&(r[t]=i)}}function Up(e,[[t,n],r]){let[i,a]=n,o=e.get(t)||{deletes:0,inserts:0,value:i,orderByIndex:a};return r<0?o.deletes+=Math.abs(r):r>0&&(o.inserts+=r,o.value=i,a!==void 0&&(o.orderByIndex=a)),e.set(t,o),e}function Wp(e){return new Op(e).getConfig()}function Gp(e){if(typeof e==`function`)return Kp(Wp({query:e}));{let t=e,n=Wp(t);return t.utils&&(n.utils={...n.utils,...t.utils}),Kp(n)}}function Kp(e){let t=Ud(e),n=ep(e);return n&&tp(t,n),t}var qp=1;function Jp(e,t=[]){let n=e&&typeof e==`object`&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`,r=(0,v.useRef)(null),i=(0,v.useRef)(null),a=(0,v.useRef)(null),o=(0,v.useRef)(0),s=(0,v.useRef)(null),c=!r.current||n&&a.current!==e||!n&&(i.current===null||i.current.length!==t.length||i.current.some((e,n)=>e!==t[n]));if(c)if(n)e.config?.syncMode===`on-demand`&&console.warn(`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.
15
+
16
+ Instead, use a query builder function:
17
+ const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c))
18
+
19
+ Or switch to syncMode "eager" if you want all data to sync automatically.`),e.startSyncImmediate(),r.current=e,a.current=e;else if(typeof e==`function`){let n=e(new rp);if(n==null)r.current=null;else if(n instanceof Wd)n.startSyncImmediate(),r.current=n;else if(n instanceof rp)r.current=Gp({query:e,startSync:!0,gcTime:qp});else if(n&&typeof n==`object`)r.current=Gp({startSync:!0,gcTime:qp,...n});else throw Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof n}`);i.current=[...t]}else r.current=Gp({startSync:!0,gcTime:qp,...e}),i.current=[...t];c&&(o.current=0,s.current=null);let l=(0,v.useRef)(null);(!l.current||c)&&(l.current=e=>{if(!r.current)return()=>{};let t=r.current.subscribeChanges(()=>{o.current+=1,e()});return r.current.status===`ready`&&(o.current+=1,e()),()=>{t.unsubscribe()}});let u=(0,v.useRef)(null);(!u.current||c)&&(u.current=()=>{let e=o.current,t=r.current;return(!s.current||s.current.version!==e||s.current.collection!==t)&&(s.current={collection:t,version:e}),s.current});let d=(0,v.useSyncExternalStore)(l.current,u.current),f=(0,v.useRef)(null),p=(0,v.useRef)(null);if(!f.current||f.current.version!==d.version||f.current.collection!==d.collection){if(!d.collection)p.current={state:void 0,data:void 0,collection:void 0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1};else{let e=Array.from(d.collection.entries()),t=d.collection.config.singleResult,n=null,r=null;p.current={get state(){return n||=new Map(e),n},get data(){return r||=e.map(([,e])=>e),t?r[0]:r},collection:d.collection,status:d.collection.status,isLoading:d.collection.status===`loading`,isReady:d.collection.status===`ready`,isIdle:d.collection.status===`idle`,isError:d.collection.status===`error`,isCleanedUp:d.collection.status===`cleaned-up`,isEnabled:!0}}f.current=d}return p.current}var Yp=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Xp=new class extends Yp{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Zp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Qp=new class{#e=Zp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function $p(e){setTimeout(e,0)}var em=typeof window>`u`||`Deno`in globalThis;function tm(){}function nm(e,t){return typeof e==`function`?e(t):e}function rm(e){return typeof e==`number`&&e>=0&&e!==1/0}function im(e,t){return Math.max(e+(t||0)-Date.now(),0)}function am(e,t){return typeof e==`function`?e(t):e}function om(e,t){return typeof e==`function`?e(t):e}function sm(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==lm(o,t.options))return!1}else if(!dm(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function cm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(um(t.options.mutationKey)!==um(a))return!1}else if(!dm(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function lm(e,t){return(t?.queryKeyHashFn||um)(e)}function um(e){return JSON.stringify(e,(e,t)=>gm(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function dm(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>dm(e[n],t[n])):!1}var fm=Object.prototype.hasOwnProperty;function pm(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=hm(e)&&hm(t);if(!r&&!(gm(e)&&gm(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:fm.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=pm(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function mm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function hm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function gm(e){if(!_m(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!_m(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function _m(e){return Object.prototype.toString.call(e)===`[object Object]`}function vm(e){return new Promise(t=>{Qp.setTimeout(t,e)})}function ym(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:pm(e,t)}function bm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function xm(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Sm=Symbol();function Cm(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Sm?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function wm(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Tm=(()=>{let e=()=>em;return{isServer(){return e()},setIsServer(t){e=t}}})();function Em(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var Dm=$p;function Om(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Dm,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var $=Om(),km=new class extends Yp{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Am(e){return Math.min(1e3*2**e,3e4)}function jm(e){return(e??`online`)===`online`?km.isOnline():!0}var Mm=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Nm(e){let t=!1,n=0,r,i=Em(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new Mm(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Xp.isFocused()&&(e.networkMode===`always`||km.isOnline())&&e.canRun(),u=()=>jm(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(Tm.isServer()?0:3),o=e.retryDelay??Am,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),vm(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var Pm=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),rm(this.gcTime)&&(this.#e=Qp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Tm.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Qp.clearTimeout(this.#e),this.#e=void 0)}};function Fm(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{wm(e,()=>t.signal,()=>n=!0)},u=Cm(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?xm:bm;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?Lm:Im,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Im(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Im(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Lm(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var Rm=class extends Pm{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Vm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Vm(this.options);e.data!==void 0&&(this.setState(Bm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ym(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(tm).catch(tm):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>om(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Sm||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>am(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!im(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Cm(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Fm(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=Nm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Mm&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Mm){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...zm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Bm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),$.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function zm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:jm(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Bm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Vm(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Hm=class extends Yp{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=Em(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Wm(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gm(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gm(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof om(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!mm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Km(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||om(this.options.enabled,this.#t)!==om(t.enabled,this.#t)||am(this.options.staleTime,this.#t)!==am(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||om(this.options.enabled,this.#t)!==om(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Jm(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(tm)),t}#g(){this.#b();let e=am(this.options.staleTime,this.#t);if(Tm.isServer()||this.#r.isStale||!rm(e))return;let t=im(this.#r.dataUpdatedAt,e)+1;this.#d=Qp.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(Tm.isServer()||om(this.options.enabled,this.#t)===!1||!rm(this.#p)||this.#p===0)&&(this.#f=Qp.setInterval(()=>{(this.options.refetchIntervalInBackground||Xp.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Qp.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Qp.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Wm(e,t),o=i&&Km(e,n,t,r);(a||o)&&(l={...l,...zm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=ym(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=ym(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:qm(e,t),refetch:this.refetch,promise:this.#o,isEnabled:om(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=Em())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!mm(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){$.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function Um(e,t){return om(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&om(t.retryOnMount,e)===!1)}function Wm(e,t){return Um(e,t)||e.state.data!==void 0&&Gm(e,t,t.refetchOnMount)}function Gm(e,t,n){if(om(t.enabled,e)!==!1&&am(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&qm(e,t)}return!1}function Km(e,t,n,r){return(e!==t||om(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&qm(e,n)}function qm(e,t){return om(t.enabled,e)!==!1&&e.isStaleByTime(am(t.staleTime,e))}function Jm(e,t){return!mm(e.getCurrentResult(),t)}var Ym=class extends Pm{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Xm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Nm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),$.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Xm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Zm=class extends Yp{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Ym({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=Qm(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){$.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>cm(t,e))}findAll(e={}){return this.getAll().filter(t=>cm(e,t))}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return $.batch(()=>Promise.all(e.map(e=>e.continue().catch(tm))))}};function Qm(e){return e.options.scope?.id}var $m=class extends Yp{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??lm(r,t),a=this.get(i);return a||(a=new Rm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){$.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>sm(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>sm(e,t)):t}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){$.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){$.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},eh=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new $m,this.#t=e.mutationCache||new Zm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Xp.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=km.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(am(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=nm(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return $.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;$.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return $.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=$.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(tm).catch(tm)}invalidateQueries(e,t={}){return $.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=$.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(tm)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(tm)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(am(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(tm).catch(tm)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(tm).catch(tm)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return km.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(um(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{dm(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(um(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{dm(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=lm(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===Sm&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},th=class extends La{constructor(e){super(e),this.name=`QueryCollectionError`}},nh=class extends th{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},rh=class extends th{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},ih=class extends th{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},ah=class extends th{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},oh=class extends th{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},sh=class extends th{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},ch=class extends th{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},lh=class extends th{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},uh=new WeakMap;function dh(e,t){let n=Array.isArray(e)?e:[e],r=[];for(let e of n)if(e.type===`delete`){let t=Array.isArray(e.key)?e.key:[e.key];for(let e of t)r.push({type:`delete`,key:e})}else{let n=Array.isArray(e.data)?e.data:[e.data];for(let i of n){let n;if(e.type===`update`)n=t.getKey(i);else{let r=t.collection.validateData(i,e.type===`upsert`?`insert`:e.type);n=t.getKey(r)}r.push({type:e.type,key:n,data:i})}}return r}function fh(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new sh(r.key);if(n.add(r.key),r.type===`update`){if(!t.collection._state.syncedData.has(r.key))throw new ch(r.key)}else if(r.type===`delete`&&!t.collection._state.syncedData.has(r.key))throw new lh(r.key)}}function ph(e,t){let n=dh(e,t);fh(n,t),t.begin({immediate:!0});for(let e of n)switch(e.type){case`insert`:{let n=t.collection.validateData(e.data,`insert`);t.write({type:`insert`,value:n});break}case`update`:{let n={...t.collection._state.syncedData.get(e.key),...e.data},r=t.collection.validateData(n,`update`,e.key);t.write({type:`update`,value:r});break}case`delete`:{let n=t.collection._state.syncedData.get(e.key);t.write({type:`delete`,value:n});break}case`upsert`:{let n=t.collection._state.syncedData.has(e.key),r=t.collection.validateData(e.data,n?`update`:`insert`,e.key);n?t.write({type:`update`,value:r}):t.write({type:`insert`,value:r});break}}t.commit();let r=Array.from(t.collection._state.syncedData.values());t.updateCacheData?t.updateCacheData(r):t.queryClient.setQueryData(t.queryKey,r)}function mh(e){function t(){let t=e();if(!t)throw new oh;return t}return{writeInsert(e){let n={type:`insert`,data:e},r=t(),i=uh.get(r);if(i?.isActive){i.operations.push(n);return}ph(n,r)},writeUpdate(e){let n={type:`update`,data:e},r=t(),i=uh.get(r);if(i?.isActive){i.operations.push(n);return}ph(n,r)},writeDelete(e){let n={type:`delete`,key:e},r=t(),i=uh.get(r);if(i?.isActive){i.operations.push(n);return}ph(n,r)},writeUpsert(e){let n={type:`upsert`,data:e},r=t(),i=uh.get(r);if(i?.isActive){i.operations.push(n);return}ph(n,r)},writeBatch(e){let n=t();if(uh.get(n)?.isActive)throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let r={operations:[],isActive:!0};uh.set(n,r);try{let t=e();if(t&&typeof t==`object`&&`then`in t&&typeof t.then==`function`)throw Error(`writeBatch does not support async callbacks. The callback must be synchronous.`);r.operations.length>0&&ph(r.operations,n)}finally{r.isActive=!1,uh.delete(n)}}}}function hh(e){if(!e)return;let t={};return e.where&&(t.where=gh(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:gh(e.expression),direction:e.compareOptions.direction,nulls:e.compareOptions.nulls,stringSort:e.compareOptions.stringSort};return e.compareOptions.stringSort===`locale`?{...t,locale:e.compareOptions.locale,localeOptions:e.compareOptions.localeOptions}:t})),e.limit!==void 0&&(t.limit=e.limit),e.offset!==void 0&&(t.offset=e.offset),Object.keys(t).length===0?void 0:JSON.stringify(t)}function gh(e){if(!e)return null;switch(e.type){case`val`:return{type:`val`,value:_h(e.value)};case`ref`:return{type:`ref`,path:[...e.path]};case`func`:return{type:`func`,name:e.name,args:e.args.map(e=>gh(e))};default:return null}}function _h(e){if(e===void 0)return{__type:`undefined`};if(typeof e==`number`){if(Number.isNaN(e))return{__type:`nan`};if(e===1/0)return{__type:`infinity`,sign:1};if(e===-1/0)return{__type:`infinity`,sign:-1}}return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:e instanceof Date?{__type:`date`,value:e.toJSON()}:Array.isArray(e)?e.map(e=>_h(e)):typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_h(t)])):e}var vh=`queryCollection:gc:`,yh=class{constructor(e,t,n){this.state=e,this.refetchFn=t,this.refetch=t,this.writeInsert=n.writeInsert,this.writeUpdate=n.writeUpdate,this.writeDelete=n.writeDelete,this.writeUpsert=n.writeUpsert,this.writeBatch=n.writeBatch}async clearError(){this.state.lastError=void 0,this.state.errorCount=0,this.state.lastErrorUpdatedAt=0,await this.refetchFn({throwOnError:!0})}get lastError(){return this.state.lastError}get isError(){return!!this.state.lastError}get errorCount(){return this.state.errorCount}get isFetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isFetching)}get isRefetching(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isRefetching)}get isLoading(){return Array.from(this.state.observers.values()).some(e=>e.getCurrentResult().isLoading)}get dataUpdatedAt(){return Math.max(0,...Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().dataUpdatedAt))}get fetchStatus(){return Array.from(this.state.observers.values()).map(e=>e.getCurrentResult().fetchStatus)}};function bh(e){let{queryKey:t,queryFn:n,select:r,queryClient:i,enabled:a,refetchInterval:o,retry:s,retryDelay:c,staleTime:l,persistedGcTime:u,getKey:d,onInsert:f,onUpdate:p,onDelete:m,meta:h,...g}=e,_=g.syncMode??`eager`,v=typeof t==`function`?t({}):t,y=e=>{typeof t==`function`&&(e.length>=v.length&&v.every((t,n)=>os(t,e[n]))||console.warn(`[QueryCollection] queryKey function must return keys that extend the base key prefix. Base: ${JSON.stringify(v)}, Got: ${JSON.stringify(e)}. This can cause stale cache issues.`))};if(!t)throw new nh;if(!n)throw new rh;if(!i)throw new ih;if(!d)throw new ah;let b={lastError:void 0,errorCount:0,lastErrorUpdatedAt:0,observers:new Map},x=new Map,S=new Map,C=new Map,w=new Map,T=new Map,E=(e,t)=>{let n=C.get(e)||new Set;n.add(t),C.set(e,n);let r=S.get(t)||new Set;r.add(e),S.set(t,r)},D=(e,t)=>{let n=C.get(e)||new Set;n.delete(t),C.set(e,n);let r=S.get(t)||new Set;return r.delete(e),S.set(t,r),n.size===0},O=e=>{let{begin:f,write:p,commit:m,markReady:g,collection:v,metadata:O}=e,k=O,A=!1,j=!1,M=new Set,N=new Map,P=new Map,ee=Promise.resolve(),F=e=>O?.row.get(e)??v._state.syncedMetadata.get(e),te=e=>{let t=F(e)?.queryCollection;if(!t||typeof t!=`object`)return new Set;let n=t.owners;return!n||typeof n!=`object`?new Set:new Set(Object.keys(n))},ne=(e,t)=>{if(!O)return;let n={...F(e)??{}};if(t.size===0){delete n.queryCollection,Object.keys(n).length===0?O.row.delete(e):O.row.set(e,n);return}O.row.set(e,{...n,queryCollection:{owners:Object.fromEntries(Array.from(t.values()).map(e=>[e,!0]))}})},re=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.queryHash===t){if(n.mode===`until-revalidated`)return{queryHash:t,mode:`until-revalidated`};if(n.mode===`ttl`&&typeof n.expiresAt==`number`&&Number.isFinite(n.expiresAt))return{queryHash:t,mode:`ttl`,expiresAt:n.expiresAt}}},ie=e=>(ee=ee.then(e,e),ee),I=e=>{let t=P.get(e);t&&(clearTimeout(t),P.delete(e))},L=e=>{let t=S.get(e);if(t)return new Set(t);let n=new Set;for(let[t]of v._state.syncedData.entries()){let r=te(t);r.size!==0&&(C.set(t,new Set(r)),r.forEach(e=>{let n=S.get(e)||new Set;n.add(t),S.set(e,n)}),r.has(e)&&n.add(t))}return n},ae=async e=>{let t=S.get(e);if(t&&Array.from(t).every(e=>v.has(e))){let e=new Map;return t.forEach(t=>{let n=v.get(t),r=C.get(t);n&&r&&e.set(t,{value:n,owners:new Set(r)})}),e}let n=k?.row.scanPersisted;if(!n){let t=new Map;return L(e).forEach(e=>{let n=v.get(e),r=C.get(e);n&&r&&t.set(e,{value:n,owners:new Set(r)})}),t}let r=new Map;return(await n()).forEach(t=>{let n=t.metadata?.queryCollection;if(!n||typeof n!=`object`)return;let i=n.owners;if(!i||typeof i!=`object`)return;let a=new Set(Object.keys(i));a.size!==0&&(C.set(t.key,new Set(a)),a.forEach(e=>{let n=S.get(e)||new Set;n.add(t.key),S.set(e,n)}),a.has(e)&&r.set(t.key,{value:t.value,owners:a}))}),r},oe=async e=>{if(!O)return;let t=await ae(e),n=[];f(),t.forEach(({value:t,owners:r},i)=>{r.delete(e),ne(i,r),D(i,e)&&n.push(t)}),n.forEach(e=>{p({type:`delete`,value:e})}),O.collection.delete(`${vh}${e}`),m()},R=e=>{if(e.mode!==`ttl`)return;I(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{P.delete(e.queryHash),ie(async()=>{let t=O?.collection.get(`${vh}${e.queryHash}`),n=re(t,e.queryHash);!n||n.mode!==`ttl`||n.expiresAt>Date.now()||await oe(e.queryHash)})},t);P.set(e.queryHash,n)},se=async()=>{if(!O)return;let e=O.collection.list(vh),t=Date.now();for(let{key:n,value:r}of e){let e=re(r,n.slice(vh.length));e&&(e.mode===`ttl`&&e.expiresAt<=t?await oe(e.queryHash):e.mode===`ttl`&&R(e))}},z=e=>{if(typeof t==`function`)return t(e);if(_===`on-demand`){let n=hh(e);return n===void 0?t:[...t,n]}else return t},ce=O?.collection.list(vh),B=!ce||ce.length===0?(j=!0,Promise.resolve()):ie(async()=>{try{await se()}finally{j=!0}}),V=(e={},t=n)=>{if(!j)return B.then(()=>{let n=V(e,t);return n===!0?void 0:n});let r=z(e),d=um(r),f={...h,loadSubsetOptions:e},p=O?.collection.get(`${vh}${d}`);if(re(p,d)!==void 0&&M.add(d),I(d),y(r),b.observers.has(d)){T.set(d,(T.get(d)||0)+1);let e=b.observers.get(d),t=e.getCurrentResult();return t.isSuccess?!0:t.isError?Promise.reject(t.error):i.getQueryData(r)===void 0?new Promise((t,n)=>{let r=e.subscribe(e=>{queueMicrotask(()=>{e.isSuccess?(r(),t()):e.isError&&(r(),n(e.error))})})}):!0}let m=new Hm(i,{queryKey:r,queryFn:t,meta:f,structuralSharing:!0,notifyOnChangeProps:`all`,...a!==void 0&&{enabled:a},...o!==void 0&&{refetchInterval:o},...s!==void 0&&{retry:s},...c!==void 0&&{retryDelay:c},...l!==void 0&&{staleTime:l}}),g=i.getQueryCache().find({queryKey:r,exact:!0})?.gcTime,_=u??g;if(x.set(d,r),b.observers.set(d,m),_===void 0?N.delete(d):N.set(d,_),T.set(d,(T.get(d)||0)+1),i.getQueryData(r)!==void 0)return(A||v.subscriberCount>0)&&pe(m,d),!0;let S=new Promise((e,t)=>{let n=m.subscribe(r=>{queueMicrotask(()=>{r.isSuccess?(n(),e()):r.isError&&(n(),t(r.error))})})});return(A||v.subscriberCount>0)&&pe(m,d),S},le=(e,t,n)=>{let i=um(e);if(v.status===`cleaned-up`)return;b.lastError=void 0,b.errorCount=0;let a=t.data,o=r?r(a):a;if(!Array.isArray(o)||o.some(e=>typeof e!=`object`)){let t=r?`@tanstack/query-db-collection: select() must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`:`@tanstack/query-db-collection: queryFn must return an array of objects. Got: ${typeof o} for queryKey ${JSON.stringify(e)}`;console.error(t);return}let s=new Map(v._state.syncedData.entries()),c=n!==void 0,l=c?new Set(n.keys()):L(i),u=new Map;o.forEach(e=>{let t=d(e);u.set(t,e)}),f(),O&&O.collection.delete(`${vh}${i}`),l.forEach(e=>{let t=c?n.get(e)?.value:s.get(e);if(!t)return;let r=u.get(e);if(r)os(t,r)||p({type:`update`,value:r});else{let n=te(e);n.delete(i),ne(e,n),D(e,i)&&p({type:`delete`,value:t})}}),u.forEach((e,t)=>{let n=te(t);n.has(i)||(n.add(i),ne(t,n)),E(t,i),s.has(t)||p({type:`insert`,value:e})}),m(),M.delete(i),I(i),g()},ue=async(e,t)=>{let n=await ae(um(e));v.status!==`cleaned-up`&&le(e,t,n)},de=e=>{let t=um(e);return n=>{if(n.isSuccess){if(v.deferDataRefresh){v.deferDataRefresh.then(()=>{let e=b.observers.get(t);e&&e.refetch().catch(()=>{})});return}M.has(t)?ue(e,n).catch(t=>{console.error(`[QueryCollection] Error reconciling query ${String(e)}:`,t)}):le(e,n)}else n.isError&&((n.errorUpdatedAt!==b.lastErrorUpdatedAt||n.error!==b.lastError)&&(b.lastError=n.error,b.errorCount++,b.lastErrorUpdatedAt=n.errorUpdatedAt),console.error(`[QueryCollection] Error observing query ${String(e)}:`,n.error),g())}},fe=e=>w.has(e),pe=(e,t)=>{if(!fe(t)){let n=de(x.get(t)),r=e.subscribe(n);w.set(t,r);let i=e.getCurrentResult();(i.isSuccess||i.isError)&&n(i)}},me=()=>{b.observers.forEach(pe)},he=()=>{w.forEach(e=>{e()}),w.clear()};A=!0;let ge=v.on(`subscribers:change`,({subscriberCount:e})=>{e>0?me():e===0&&he()});if(_===`eager`){let e=V({});e instanceof Promise&&e.catch(()=>{})}else j?g():B.then(()=>{g()});me(),b.observers.forEach((e,t)=>{de(x.get(t))(e.getCurrentResult())});let _e=e=>{w.get(e)?.(),w.delete(e),I(e),M.delete(e);let t=S.get(e)??new Set,n=new Map,r=[];t.forEach(t=>{let i=C.get(t);if(!i)return;let a=new Set(i);a.delete(e),n.set(t,a),a.size===0&&v.has(t)&&r.push(v.get(t))});let i=O!==void 0&&n.size>0,a=i||r.length>0;a&&f(),n.forEach((e,t)=>{e.size===0?C.delete(t):C.set(t,e),i&&ne(t,e)}),r.length>0&&r.forEach(e=>{p({type:`delete`,value:e})}),a&&m(),b.observers.delete(e),S.delete(e),x.delete(e),T.delete(e),N.delete(e)},ve=e=>{let t=T.get(e)||0,n=b.observers.get(e),r=N.get(e);if(t<=0&&(w.get(e)?.(),w.delete(e)),n?.hasListeners()??!1){T.set(e,0);return}if(t>0&&console.warn(`[cleanupQueryIfIdle] Invariant violation: refcount=${t} but no listeners. Cleaning up to prevent leak.`,{hashedQueryKey:e}),r!==void 0&&O&&k?.row.scanPersisted){f(),O.collection.set(`${vh}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),m(),r!==1/0&&R({queryHash:e,mode:`ttl`,expiresAt:Date.now()+r}),w.get(e)?.(),w.delete(e),b.observers.delete(e),x.delete(e),T.set(e,0);return}_e(e)},ye=e=>{_e(e)},be=i.getQueryCache().subscribe(e=>{let t=e.query.queryHash;e.type===`removed`&&x.has(t)&&ve(t)});return{loadSubset:_===`eager`?void 0:V,unloadSubset:_===`eager`?void 0:e=>{let t=um(z(e)),n=(T.get(t)||0)-1;n<=0?(T.set(t,0),ve(t)):T.set(t,n)},cleanup:async()=>{ge(),he(),P.forEach(e=>{clearTimeout(e)}),P.clear();let e=[...x.values()],t=[...b.observers.keys()];for(let e of t)ye(e);be(),await Promise.all(e.map(async e=>{await i.cancelQueries({queryKey:e,exact:!0}),i.removeQueries({queryKey:e,exact:!0})}))}}},k=async e=>{let t=[...x.values()].map(t=>b.observers.get(um(t)).refetch({throwOnError:e?.throwOnError}));return Promise.all(t)},A=(e,t)=>{r?i.setQueryData(e,e=>{if(!e||typeof e!=`object`)return e;if(Array.isArray(e))return t;let n=r(e);if(Array.isArray(n)){for(let r of Object.keys(e))if(e[r]===n)return{...e,[r]:t}}if(Array.isArray(e.data))return{...e,data:t};if(Array.isArray(e.items))return{...e,items:t};if(Array.isArray(e.results))return{...e,results:t};for(let n of Object.keys(e))if(Array.isArray(e[n]))return{...e,[n]:t};return e}):i.setQueryData(e,t)},j=e=>{let t=i.getQueryCache().findAll({queryKey:v});if(t.length>0)for(let n of t)A(n.queryKey,e);else A(v,e)},M=null,N=e=>{let{begin:n,write:r,commit:a,collection:o}=e;return M={collection:o,queryClient:i,queryKey:typeof t==`function`?t({}):t,getKey:d,begin:n,write:r,commit:a,updateCacheData:j},O(e)},P=mh(()=>M),ee=f?async e=>{let t=await f(e)??{};return t.refetch!==!1&&await k(),t}:void 0,F=p?async e=>{let t=await p(e)??{};return t.refetch!==!1&&await k(),t}:void 0,te=m?async e=>{let t=await m(e)??{};return t.refetch!==!1&&await k(),t}:void 0,ne=new yh(b,k,P);return{...g,getKey:d,syncMode:_,sync:{sync:N},onInsert:ee,onUpdate:F,onDelete:te,utils:ne}}var xh=`/api`;async function Sh(e,t){let n=await fetch(`${xh}${e}`,t);if(!n.ok)throw Error(`${n.status} ${n.statusText}`);return n.json()}function Ch(e){let t=e.toString();return t?`?${t}`:``}function wh(e,t){return Sh(`/memories/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}function Th(e){return Sh(`/memories/${e}`,{method:`DELETE`})}function Eh(){return Sh(`/projects`)}function Dh(e,t){return Sh(`/projects/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:t})})}function Oh(e,t){return Sh(`/memories/${e}/projects`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({projectId:t})})}function kh(e,t){return Sh(`/memories/${e}/projects/${t}`,{method:`DELETE`})}function Ah(){return Sh(`/syntheses`)}function jh(e){return Sh(`/projects/${e}/synthesis`,{method:`POST`})}function Mh(e){return Sh(`/projects/${e}/synthesis/in-flight`,{method:`DELETE`})}function Nh(e){return Sh(`/projects/${e}/stats`)}function Ph(e,t){return Sh(`/projects/${e}/activity${t===void 0?``:`?days=${t}`}`)}function Fh(e){return Sh(`/activity${e===void 0?``:`?days=${e}`}`)}function Ih(e){let t=new URLSearchParams;return e.scope!==void 0&&t.set(`scope`,e.scope),e.type!==void 0&&t.set(`type`,e.type),e.since!==void 0&&t.set(`since`,e.since),e.limit!==void 0&&t.set(`limit`,String(e.limit)),Sh(`/activity/events${Ch(t)}`)}var Lh=new eh,Rh=Ud(bh({queryKey:[`memories`],queryFn:async()=>{let e=await fetch(`/api/memories`);if(!e.ok)throw Error(`${e.status}`);return e.json()},queryClient:Lh,getKey:e=>e.id,onUpdate:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>{let t=e.changes;return wh(e.original.id,{content:t.content,tags:t.tags,type:t.type,pinned:t.pinned})}))}catch{oa.error(`Failed to save — changes may not have been stored`)}},onDelete:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>Th(e.original.id)))}catch{oa.error(`Failed to delete — try again`)}}})),zh=Ud(bh({queryKey:[`syntheses`],queryFn:Ah,queryClient:Lh,getKey:e=>e.id})),Bh=Ud(bh({queryKey:[`projects`],queryFn:Eh,queryClient:Lh,getKey:e=>e.id,onUpdate:async({transaction:e})=>{await Promise.all(e.mutations.map(e=>{let t=e.changes;return t.name===void 0?Promise.resolve():Dh(e.original.id,t.name)}))}}));export{Ht as $,ae as $t,Vn as A,Ge as At,ln as B,ye as Bt,mr as C,gt as Ct,cr as D,Ze as Dt,fr as E,$e as Et,Dn as F,Re as Ft,sn as G,z as Gt,tn as H,ge as Ht,wn as I,Fe as It,on as J,te as Jt,Lt as K,L as Kt,Sn as L,Ne as Lt,Mn as M,ze as Mt,Tn as N,Ve as Nt,tr as O,Ye as Ot,En as P,je as Pt,Vt as Q,E as Qt,Cn as R,Pe as Rt,hr as S,vt as St,lr as T,ft as Tt,Qt as U,xe as Ut,cn as V,ve as Vt,zt as W,ce as Wt,Rt as X,F as Xt,rn as Y,oe as Yt,Zt as Z,R as Zt,oa as _,Et as _t,Oh as a,j as an,Kt as at,Bi as b,xt as bt,Ph as c,x as cn,Nt as ct,kh as d,f as dn,Dt as dt,ne as en,en as et,Mh as f,u as fn,jt as ft,xa as g,Tt as gt,Pu as h,Ot as ht,zh as i,A as in,Gt as it,Pn as j,Me as jt,Qn as k,Je as kt,Nh as l,g as ln,Mt as lt,Jp as m,c as mn,kt as mt,Bh as n,re as nn,Wt as nt,Ih as o,y as on,$t as ot,jh as p,o as pn,At as pt,nn as q,se as qt,Lh as r,w as rn,Ut as rt,Fh as s,b as sn,Ft as st,Rh as t,N as tn,Bt as tt,wh as u,m as un,Pt as ut,Gi as v,wt as vt,pr as w,pt as wt,Hi as x,yt as xt,Vi as y,Ct as yt,_n as z,_e as zt};