@membank/dashboard 0.9.0 → 0.10.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.
- package/dist/bin.mjs +37 -1
- package/dist/client/assets/WorkspaceMemoryDetail-B-SQPmf_.js +1 -0
- package/dist/client/assets/_projectId-ChOHT2g6.js +40 -0
- package/dist/client/assets/_projectId-DdCE-NRK.js +4 -0
- package/dist/client/assets/_projectId._memoryId-j78rWv7Z.js +1 -0
- package/dist/client/assets/collections-Ci78mgZL.js +19 -0
- package/dist/client/assets/index-DcreRb0E.js +10 -0
- package/dist/client/assets/index-RbnYc2mC.css +2 -0
- package/dist/client/assets/routes-CDZywPpw.js +1 -0
- package/dist/client/assets/typeColors-BREuYmod.js +3 -0
- package/dist/client/index.html +4 -4
- package/dist/index.cjs +36 -0
- package/dist/index.mjs +37 -1
- package/package.json +2 -2
- package/dist/client/assets/WorkspaceMemoryDetail-BFpMjQWu.js +0 -1
- package/dist/client/assets/_projectId-Cs170Emi.js +0 -40
- package/dist/client/assets/_projectId-p99W0TrB.js +0 -4
- package/dist/client/assets/_projectId._memoryId-B8g4zsrH.js +0 -1
- package/dist/client/assets/collections-Bj4kWtiN.js +0 -19
- package/dist/client/assets/index-DwfCB-hG.js +0 -10
- package/dist/client/assets/index-JriiD5q1.css +0 -2
- package/dist/client/assets/routes-uvB1fUgz.js +0 -1
- package/dist/client/assets/typeColors-C2x_OYRB.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 F(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 I=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)},ee={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=ee,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:F}},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,I)}catch(e){I(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()}))(),_=c(u(),1),v=_.use,y=typeof window<`u`?_.useLayoutEffect:_.useEffect;function b(e){let t=_.useRef({value:e,prev:null}),n=t.current.value;return e!==n&&(t.current={value:e,prev:n}),t.current.prev}function x(e,t,n={},r={}){_.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 S(e){let t=_.useRef(null);return _.useImperativeHandle(e,()=>t.current,[]),t}function C(e){return e[e.length-1]}function w(e){return typeof e==`function`}function T(e,t){return w(e)?e(t):e}var E=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,O=()=>Object.create(null),k=(e,t)=>A(e,t,O);function A(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=P(e)&&P(i);if(!a&&!(M(e)&&M(i)))return i;let o=a?e:j(e);if(!o)return i;let s=a?i:j(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:E.call(e,o))&&d++;continue}if(l===null||f===null||typeof l!=`object`||typeof f!=`object`){u[o]=f;continue}let p=A(l,f,n,r+1);u[o]=p,p===l&&d++}return c===l&&d===c?e:u}function j(e){let t=Object.getOwnPropertyNames(e);for(let n of t)if(!D.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(!D.call(e,t))return!1;r.push(t)}return r}function M(e){if(!N(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!N(n)||!n.hasOwnProperty(`isPrototypeOf`))}function N(e){return Object.prototype.toString.call(e)===`[object Object]`}function P(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(M(e)&&M(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 I(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 ee(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 te(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}function ne(e){return e.replace(/[\x00-\x1f\x7f]/g,``)}function re(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 ne(t)}var L=[`http:`,`https:`,`mailto:`,`tel:`];function R(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}function ie(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+=re(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=re(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function ae(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function z(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 oe(){throw Error(`Invariant failed`)}function B(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 se=4,ce=5;function V(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 le(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=V(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 ue(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=le(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=pe(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=pe(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=me(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=me(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=me(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=pe(n.fullPath??n.from);e.kind=ce,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=pe(n.fullPath??n.from);e.kind=se,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)ue(e,t,r,s,i,a,o)}function de(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 fe(e){if(e.pathless)for(let t of e.pathless)fe(t);if(e.static)for(let t of e.static.values())fe(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())fe(t);if(e.dynamic?.length){e.dynamic.sort(de);for(let t of e.dynamic)fe(t)}if(e.optional?.length){e.optional.sort(de);for(let t of e.optional)fe(t)}if(e.wildcard?.length){e.wildcard.sort(de);for(let t of e.wildcard)fe(t)}}function pe(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 me(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 he(e,t){let n=pe(`/`),r=new Uint16Array(6);for(let t of e)ue(!1,r,t,1,n,0);fe(n),t.masksTree=n,t.flatCache=B(1e3)}function ge(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=xe(e,t.masksTree);return t.flatCache.set(e,r),r}function _e(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=pe(`/`),ue(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),xe(r,o,n)}function ve(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=xe(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=Ce(a.route)),t.matchCache.set(r,a),a}function ye(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function be(e,t=!1,n){let r=pe(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return ue(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&oe(),a[e.id]=e,s!==0&&e.path){let t=ye(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),fe(r),{processedTree:{segmentTree:r,singleCache:B(1e3),matchCache:B(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function xe(e,t,n=!1){let r=e.split(`/`),i=Te(e,r,t,n);if(!i)return null;let[a]=Se(e,r,i);return{route:i.node.route,rawParams:a,parsedParams:i.parsedParams}}function Se(e,t,n){let r=we(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===se)break;if(u.kind===ce){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 Ce(e){let t=[e];for(;e.parentRoute;)e=e.parentRoute,t.push(e);return t.reverse(),t}function we(e){let t=Array(e.depth+1);do t[e.depth]=e,e=e.parent;while(e);return t}function Te(e,t,n,r){if(e===`/`&&n.index)return{node:n.index,skipped:0};let i=!C(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&&!ke(l,n))continue;if(i.skipOnParamError){if(!Oe(e,t,n))continue;_=n.rawParams,g=n.extract,v=n.parsedParams}r&&i.route&&i.kind!==se&&ke(c,n)&&(c=n);let y=u===o;if(y&&(i.route&&(!a||i.kind===se||i.kind===2)&&ke(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&&(Oe(e,t,n)||(r=!1)),r){if(!m&&!h&&!d&&De(p,o))return n;ke(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+Ee(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+Ee(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+Ee(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+Ee(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 Ee(e,t){return 2**(e-t-1)}function De(e,t){return e===2**(t-1)-1}function Oe(e,t,n){try{let[r,i]=Se(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 ke(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===se)>(e.node.kind===se)||t.node.kind===se==(e.node.kind===se)&&t.depth>e.depth))):!0}function Ae(e){return je(e.filter(e=>e!==void 0).join(`/`))}function je(e){return e.replace(/\/{2,}/g,`/`)}function Me(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function Ne(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function Pe(e){return Ne(Me(e))}function Fe(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function Ie(e,t,n){return Fe(e,n)===Fe(t,n)}function Le({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&&C(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&&(C(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=le(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=je(l);let u=l||`/`;return o&&r&&r.set(o,u),u}function Re(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 ze(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Ve(e,n)).join(`/`):Ve(r,n):r}function Be({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=le(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=ze(`_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=ze(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=ze(i,t,n)??``;l+=`/`+u+f+d;continue}}return e.endsWith(`/`)&&(l+=`/`),{usedParams:a,interpolatedPath:l||`/`,isMissingParams:i}}function Ve(e,t){let n=encodeURIComponent(e);return t?.(n)??n}var He=`Error preloading route! ☝️`,Ue=f();function We({children:e,fallback:t=null}){return Ge()?(0,Ue.jsx)(_.Fragment,{children:e}):(0,Ue.jsx)(_.Fragment,{children:t})}function Ge(){return _.useSyncExternalStore(Ke,()=>!0,()=>!1)}function Ke(){return()=>{}}var qe=_.createContext(null);function Je(e){return _.useContext(qe)}function Ye(e,t){return e===t}function Xe(e,t,n=Ye){let r=(0,_.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,_.useCallback)(()=>e?.get(),[e]);return(0,g.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Ze=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`})),Qe=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=Ze()})),$e=c(Qe(),1);function et(e,t){let n=Je(),r=S(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:v,disabled:y,style:b,className:C,onClick:w,onBlur:E,onFocus:D,onMouseEnter:O,onMouseLeave:k,onTouchStart:A,ignoreBlocker:j,params:M,search:N,hash:P,state:I,mask:ee,reloadDocument:te,unsafeRelative:ne,from:re,_fromLocation:L,...ie}=e,ae=Ge(),z=_.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),oe=Xe(n.stores.location,e=>e,(e,t)=>e.href===t.href),B=_.useMemo(()=>{let e={_fromLocation:oe,...z};return n.buildLocation(e)},[n,oe,z]),se=B.maskedLocation?B.maskedLocation.publicHref:B.publicHref,ce=B.maskedLocation?B.maskedLocation.external:B.external,V=_.useMemo(()=>lt(se,ce,n.history,y),[y,ce,se,n.history]),le=_.useMemo(()=>{if(V?.external)return R(V.href,n.protocolAllowlist)?void 0:V.href;if(!ut(s)&&!(typeof s!=`string`||s.indexOf(`:`)===-1))try{return new URL(s),R(s,n.protocolAllowlist)?void 0:s}catch{}},[s,V,n.protocolAllowlist]),ue=_.useMemo(()=>{if(le)return!1;if(o?.exact){if(!Ie(oe.pathname,B.pathname,n.basepath))return!1}else{let e=Fe(oe.pathname,n.basepath),t=Fe(B.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!F(oe.search,B.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:o?.includeHash?ae&&oe.hash===B.hash:!0},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,oe,le,ae,B.hash,B.pathname,B.search,n.basepath]),de=ue?T(i,{})??nt:tt,fe=ue?tt:T(a,{})??tt,pe=[C,de.className,fe.className].filter(Boolean).join(` `),me=(b||de.style||fe.style)&&{...b,...de.style,...fe.style},[he,ge]=_.useState(!1),_e=_.useRef(!1),ve=e.reloadDocument||le?!1:c??n.options.defaultPreload,ye=l??n.options.defaultPreloadDelay??0,be=_.useCallback(()=>{n.preloadRoute({...z,_builtLocation:B}).catch(e=>{console.warn(e),console.warn(He)})},[n,z,B]);x(r,_.useCallback(e=>{e?.isIntersecting&&be()},[be]),st,{disabled:!!y||ve!==`viewport`}),_.useEffect(()=>{_e.current||!y&&ve===`render`&&(be(),_e.current=!0)},[y,be,ve]);let xe=e=>{let t=e.currentTarget.getAttribute(`target`),r=v===void 0?t:v;if(!y&&!pt(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,$e.flushSync)(()=>{ge(!0)});let t=n.subscribe(`onResolved`,()=>{t(),ge(!1)});n.navigate({...z,replace:f,resetScroll:m,hashScrollIntoView:d,startTransition:p,viewTransition:h,ignoreBlocker:j})}};if(le)return{...ie,ref:r,href:le,...g&&{children:g},...v&&{target:v},...y&&{disabled:y},...b&&{style:b},...C&&{className:C},...w&&{onClick:w},...E&&{onBlur:E},...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(ot.has(t))return;let n=setTimeout(()=>{ot.delete(t),be()},ye);ot.set(t,n)},Ce=e=>{y||ve!==`intent`||be()},we=e=>{if(y||!ve||!ye)return;let t=e.currentTarget,n=ot.get(t);n&&(clearTimeout(n),ot.delete(t))};return{...ie,...de,...fe,href:V?.href,ref:r,onClick:ct([w,xe]),onBlur:ct([E,we]),onFocus:ct([D,Se]),onMouseEnter:ct([O,Se]),onMouseLeave:ct([k,we]),onTouchStart:ct([A,Ce]),disabled:!!y,target:v,...me&&{style:me},...pe&&{className:pe},...y&&rt,...ue&&it,...ae&&he&&at}}var tt={},nt={className:`active`},rt={role:`link`,"aria-disabled":!0},it={"data-status":`active`,"aria-current":`page`},at={"data-transitioning":`transitioning`},ot=new WeakMap,st={rootMargin:`100px`},ct=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function lt(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function ut(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}function dt(e){return _.forwardRef(function(t,n){return(0,Ue.jsx)(ft,{...t,_asChild:e,ref:n})})}var ft=_.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=et(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return _.createElement(`a`,t,o)}return _.createElement(n,a,o)});function pt(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var mt=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)}})),ht=o(((e,t)=>{t.exports=mt()})),gt={};function _t(e,t){let n=_.useRef(gt);return n.current===gt&&(n.current=e(t)),n}var vt=m(),yt=[],bt=void 0;function xt(){return bt}function St(e){yt.push(e)}function Ct(e){let t=(t,n)=>{let r=_t(Tt).current,i;try{bt=r;for(let e of yt)e.before(r);i=e(t,n);for(let e of yt)e.after(r);r.didInitialize=!0}finally{bt=void 0}return i};return t.displayName=e.displayName||e.name,t}function wt(e){return _.forwardRef(Ct(e))}function Tt(){return{didInitialize:!1}}function Et(e){let t=_.useRef(!0);t.current&&(t.current=!1,e())}var Dt=typeof document<`u`?_.useLayoutEffect:()=>{};function Ot(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 kt=Ot(`https://base-ui.com/production-error`,`Base UI`),At=[];function jt(e){_.useEffect(e,At)}var Mt=0,Nt=class e{static create(){return new e}currentId=Mt;start(e,t){this.clear(),this.currentId=setTimeout(()=>{this.currentId=Mt,t()},e)}isStarted(){return this.currentId!==Mt}clear=()=>{this.currentId!==Mt&&(clearTimeout(this.currentId),this.currentId=Mt)};disposeEffect=()=>this.clear};function Pt(){let e=_t(Nt.create).current;return jt(e.disposeEffect),e}var Ft=typeof navigator<`u`,It=Gt(),Lt=qt(),Rt=Kt(),zt=typeof CSS>`u`||!CSS.supports?!1:CSS.supports(`-webkit-backdrop-filter:none`),Bt=It.platform===`MacIntel`&&It.maxTouchPoints>1?!0:/iP(hone|ad|od)|iOS/.test(It.platform);Ft&&/firefox/i.test(Rt);var Vt=Ft&&/apple/i.test(navigator.vendor);Ft&&/Edg/i.test(Rt);var Ht=Ft&&/android/i.test(Lt)||/android/i.test(Rt),Ut=Ft&&Lt.toLowerCase().startsWith(`mac`)&&!navigator.maxTouchPoints,Wt=Rt.includes(`jsdom/`);function Gt(){if(!Ft)return{platform:``,maxTouchPoints:-1};let e=navigator.userAgentData;return e?.platform?{platform:e.platform,maxTouchPoints:navigator.maxTouchPoints}:{platform:navigator.platform??``,maxTouchPoints:navigator.maxTouchPoints??-1}}function Kt(){if(!Ft)return``;let e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(({brand:e,version:t})=>`${e}/${t}`).join(` `):navigator.userAgent}function qt(){if(!Ft)return``;let e=navigator.userAgentData;return e?.platform?e.platform:navigator.platform??``}function Jt(e){e.preventDefault(),e.stopPropagation()}function Yt(e){return`nativeEvent`in e}function Xt(e){return e.pointerType===``&&e.isTrusted?!0:Ht&&e.pointerType?e.type===`click`&&e.buttons===1:e.detail===0&&!e.pointerType}function Zt(e){return Wt?!1:!Ht&&e.width===0&&e.height===0||Ht&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType===`mouse`||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType===`touch`}function Qt(e,t){let n=[`mouse`,`pen`];return t||n.push(``,void 0),n.includes(e)}function $t(e){let t=e.type;return t===`click`||t===`mousedown`||t===`keydown`||t===`keyup`}function en(){}var tn=Object.freeze([]),nn=Object.freeze({}),rn=`none`,an=`trigger-press`,on=`trigger-hover`,sn=`trigger-focus`,cn=`outside-press`,ln=`close-press`,un=`focus-out`,dn=`escape-key`,fn=`disabled`,pn=`imperative-action`;function mn(e,t,n,r){let i=!1,a=!1,o=r??nn;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 hn(){return typeof window<`u`}function gn(e){return yn(e)?(e.nodeName||``).toLowerCase():`#document`}function _n(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function vn(e){return((yn(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function yn(e){return hn()?e instanceof Node||e instanceof _n(e).Node:!1}function bn(e){return hn()?e instanceof Element||e instanceof _n(e).Element:!1}function xn(e){return hn()?e instanceof HTMLElement||e instanceof _n(e).HTMLElement:!1}function Sn(e){return!hn()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof _n(e).ShadowRoot}function Cn(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=Pn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function wn(e){return/^(table|td|th)$/.test(gn(e))}function Tn(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var En=/transform|translate|scale|rotate|perspective|filter/,Dn=/paint|layout|strict|content/,On=e=>!!e&&e!==`none`,kn;function An(e){let t=bn(e)?Pn(e):e;return On(t.transform)||On(t.translate)||On(t.scale)||On(t.rotate)||On(t.perspective)||!Mn()&&(On(t.backdropFilter)||On(t.filter))||En.test(t.willChange||``)||Dn.test(t.contain||``)}function jn(e){let t=In(e);for(;xn(t)&&!Nn(t);){if(An(t))return t;if(Tn(t))return null;t=In(t)}return null}function Mn(){return kn??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),kn}function Nn(e){return/^(html|body|#document)$/.test(gn(e))}function Pn(e){return _n(e).getComputedStyle(e)}function Fn(e){return bn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function In(e){if(gn(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Sn(e)&&e.host||vn(e);return Sn(t)?t.host:t}function Ln(e){let t=In(e);return Nn(t)?e.ownerDocument?e.ownerDocument.body:e.body:xn(t)&&Cn(t)?t:Ln(t)}function Rn(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=Ln(e),i=r===e.ownerDocument?.body,a=_n(r);if(i){let e=zn(a);return t.concat(a,a.visualViewport||[],Cn(r)?r:[],e&&n?Rn(e):[])}else return t.concat(r,Rn(r,[],n))}function zn(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Bn(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function Vn(...e){return()=>{for(let t=0;t<e.length;t+=1){let n=e[t];n&&n()}}}function Hn(e,t,n,r){let i=_t(Wn).current;return Gn(i,e,t,n,r)&&qn(i,[e,t,n,r]),i.callback}function Un(e){let t=_t(Wn).current;return Kn(t,e)&&qn(t,e),t.callback}function Wn(){return{callback:null,cleanup:null,refs:[]}}function Gn(e,t,n,r,i){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==i}function Kn(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}function qn(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:}}}}}}function Jn(e){let t=_t(Yn,e).current;return t.next=e,Dt(t.effect),t}function Yn(e){let t={current:e,next:e,effect:()=>{t.current=t.next}};return t}var Xn=_[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0,-3)],Zn=Xn&&Xn!==_.useLayoutEffect?Xn:e=>e();function Qn(e){let t=_t($n).current;return t.next=e,Zn(t.effect),t.trampoline}function $n(){let e={next:void 0,callback:er,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function er(){}var tr=null;globalThis.requestAnimationFrame;var nr=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)}},rr=class e{static create(){return new e}static request(e){return nr.request(e)}static cancel(e){return nr.cancel(e)}currentId=tr;request(e){this.cancel(),this.currentId=nr.request(()=>{this.currentId=tr,e()})}cancel=()=>{this.currentId!==tr&&(nr.cancel(this.currentId),this.currentId=tr)};disposeEffect=()=>this.cancel};function ir(){let e=_t(rr.create).current;return jt(e.disposeEffect),e}function ar(e){return e?.ownerDocument||document}var or={clipPath:`inset(50%)`,overflow:`hidden`,whiteSpace:`nowrap`,border:0,padding:0,width:1,height:1,margin:-1},sr={...or,position:`fixed`,top:0,left:0};({...or});var cr=_.forwardRef(function(e,t){let[n,r]=_.useState();Dt(()=>{Vt&&r(`button`)},[]);let i={tabIndex:0,role:n};return(0,Ue.jsx)(`span`,{...e,ref:t,style:sr,"aria-hidden":n?void 0:!0,...i,"data-base-ui-focus-guard":``})}),lr=`data-base-ui-focusable`,ur=`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`;function dr(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function fr(e,t){if(!e||!t)return!1;let n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&Sn(n)){let n=t;for(;n;){if(e===n)return!0;n=n.parentNode||n.host}}return!1}function pr(e){return`composedPath`in e?e.composedPath()[0]:e.target}function mr(e,t){if(!bn(e))return!1;let n=e;if(t.hasElement(n))return!n.hasAttribute(`data-trigger-disabled`);for(let[,e]of t.entries())if(fr(e,n))return!e.hasAttribute(`data-trigger-disabled`);return!1}function hr(e,t){if(t==null)return!1;if(`composedPath`in e)return e.composedPath().includes(t);let n=e;return n.target!=null&&t.contains(n.target)}function gr(e){return e.matches(`html,body`)}function _r(e){return xn(e)&&e.matches(`input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])`)}function vr(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${ur}`)!=null}function yr(e){return e?e.getAttribute(`role`)===`combobox`&&_r(e):!1}function br(e){if(!e||Wt)return!0;try{return e.matches(`:focus-visible`)}catch{return!0}}function xr(e){return e?e.hasAttribute(`data-base-ui-focusable`)?e:e.querySelector(`[data-base-ui-focusable]`)||e:null}var Sr=[`top`,`right`,`bottom`,`left`],Cr=Math.min,wr=Math.max,Tr=Math.round,Er=Math.floor,Dr=e=>({x:e,y:e}),Or={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function kr(e,t,n){return wr(e,Cr(t,n))}function Ar(e,t){return typeof e==`function`?e(t):e}function jr(e){return e.split(`-`)[0]}function Mr(e){return e.split(`-`)[1]}function Nr(e){return e===`x`?`y`:`x`}function Pr(e){return e===`y`?`height`:`width`}function Fr(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function Ir(e){return Nr(Fr(e))}function Lr(e,t,n){n===void 0&&(n=!1);let r=Mr(e),i=Ir(e),a=Pr(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=Kr(o)),[o,Kr(o)]}function Rr(e){let t=Kr(e);return[zr(e),t,zr(t)]}function zr(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var Br=[`left`,`right`],Vr=[`right`,`left`],Hr=[`top`,`bottom`],Ur=[`bottom`,`top`];function Wr(e,t,n){switch(e){case`top`:case`bottom`:return n?t?Vr:Br:t?Br:Vr;case`left`:case`right`:return t?Hr:Ur;default:return[]}}function Gr(e,t,n,r){let i=Mr(e),a=Wr(jr(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(zr)))),a}function Kr(e){let t=jr(e);return Or[t]+e.slice(t.length)}function qr(e){return{top:0,right:0,bottom:0,left:0,...e}}function Jr(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:qr(e)}function Yr(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Xr(e,t,n){return Math.floor(e/t)!==n}function Zr(e,t){return t<0||t>=e.length}function Qr(e,t){return ei(e.current,{disabledIndices:t})}function $r(e,t){return ei(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function ei(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:i=1}={}){let a=t;do a+=n?-i:i;while(a>=0&&a<=e.length-1&&ai(e,a,r));return a}function ti(e,{event:t,orientation:n,loopFocus:r,onLoop:i,rtl:a,cols:o,disabledIndices:s,minIndex:c,maxIndex:l,prevIndex:u,stopEvent:d=!1}){let f=u,p;if(t.key===`ArrowUp`?p=`up`:t.key===`ArrowDown`&&(p=`down`),p){let n=[],a=[],m=!1,h=0;{let t=null,r=-1;e.forEach((e,i)=>{if(e==null)return;h+=1;let o=e.closest(`[role="row"]`);o&&(m=!0),(o!==t||r===-1)&&(t=o,r+=1,n[r]=[]),n[r].push(i),a[i]=r})}let g=!1,_=0;if(m)for(let e of n){let t=e.length;t>_&&(_=t),t!==o&&(g=!0)}let v=g&&h<e.length,y=_||o,b=o=>{if(!g||u===-1)return;let c=a[u];if(c==null)return;let l=n[c].indexOf(u),d=o===`up`?-1:1;for(let o=c+d,f=0;f<n.length;f+=1,o+=d){if(o<0||o>=n.length){if(!r||v)return;if(o=o<0?n.length-1:0,i){let e=Math.min(l,n[o].length-1);o=a[i(t,u,n[o][e]??n[o][0])]??o}}let c=n[o];for(let t=Math.min(l,c.length-1);t>=0;--t){let n=c[t];if(!ai(e,n,s))return n}}},x=t=>{if(!v||u===-1)return;let n=u%y,i=t===`up`?-y:y,a=l-l%y,o=Er(l/y)+1;for(let t=u-n+i,c=0;c<o;c+=1,t+=i){if(t<0||t>l){if(!r)return;t=t<0?a:0}let i=Math.min(t+y-1,l);for(let r=Math.min(t+n,i);r>=t;--r)if(!ai(e,r,s))return r}};d&&Jt(t);let S=b(p)??x(p);if(S!==void 0)f=S;else if(u===-1)f=p===`up`?l:c;else if(f=ei(e,{startingIndex:u,amount:y,decrement:p===`up`,disabledIndices:s}),r){if(p===`up`&&(u-y<c||f<0)){let e=u%y,n=l%y,r=l-(n-e);f=n===e?l:n>e?r:r-y,i&&(f=i(t,u,f))}p===`down`&&u+y>l&&(f=ei(e,{startingIndex:u%y-y,amount:y,disabledIndices:s}),i&&(f=i(t,u,f)))}Zr(e,f)&&(f=u)}if(n===`both`){let n=Er(u/o);t.key===(a?`ArrowLeft`:`ArrowRight`)&&(d&&Jt(t),u%o===o-1?r&&(f=ei(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):(f=ei(e,{startingIndex:u,disabledIndices:s}),r&&Xr(f,o,n)&&(f=ei(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f)))),Xr(f,o,n)&&(f=u)),t.key===(a?`ArrowRight`:`ArrowLeft`)&&(d&&Jt(t),u%o===0?r&&(f=ei(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f))):(f=ei(e,{startingIndex:u,decrement:!0,disabledIndices:s}),r&&Xr(f,o,n)&&(f=ei(e,{startingIndex:u+(o-u%o),decrement:!0,disabledIndices:s}),i&&(f=i(t,u,f)))),Xr(f,o,n)&&(f=u));let c=Er(l/o)===n;Zr(e,f)&&(r&&c?(f=t.key===(a?`ArrowRight`:`ArrowLeft`)?l:ei(e,{startingIndex:u-u%o-1,disabledIndices:s}),i&&(f=i(t,u,f))):f=u)}return f}function ni(e,t,n){let r=[],i=0;return e.forEach(({width:e,height:a},o)=>{let s=!1;for(n&&(i=0);!s;){let n=[];for(let r=0;r<e;r+=1)for(let e=0;e<a;e+=1)n.push(i+r+e*t);i%t+e<=t&&n.every(e=>r[e]==null)?(n.forEach(e=>{r[e]=o}),s=!0):i+=1}}),[...r]}function ri(e,t,n,r,i){if(e===-1)return-1;let a=n.indexOf(e),o=t[e];switch(i){case`tl`:return a;case`tr`:return o?a+o.width-1:a;case`bl`:return o?a+(o.height-1)*r:a;case`br`:return n.lastIndexOf(e);default:return-1}}function ii(e,t){return t.flatMap((t,n)=>e.includes(t)?[n]:[])}function ai(e,t,n){if(typeof n==`function`?n(t):n?.includes(t)??!1)return!0;let r=e[t];return r?si(r)?!n&&(r.hasAttribute(`disabled`)||r.getAttribute(`aria-disabled`)===`true`):!0:!1}function oi(e){return e.visibility===`hidden`||e.visibility===`collapse`}function si(e,t=e?Pn(e):null){return!e||!e.isConnected||!t||oi(t)?!1:typeof e.checkVisibility==`function`?e.checkVisibility():t.display!==`none`&&t.display!==`contents`}var ci=`a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]`;function li(e){let t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;let n=e.getRootNode();return Sn(n)?n.host:null}function ui(e){for(let t of Array.from(e.children))if(gn(t)===`summary`)return t;return null}function di(e,t){let n=ui(t);return!!n&&(e===n||fr(n,e))}function fi(e){let t=e?gn(e):``;return e!=null&&e.matches(ci)&&(t!==`summary`||e.parentElement!=null&&gn(e.parentElement)===`details`&&ui(e.parentElement)===e)&&(t!==`details`||ui(e)==null)&&(t!==`input`||e.type!==`hidden`)}function pi(e){if(!fi(e)||!e.isConnected||e.matches(`:disabled`))return!1;for(let t=e;t;t=li(t)){let n=t!==e,r=gn(t)===`slot`;if(t.hasAttribute(`inert`)||n&&gn(t)===`details`&&!t.open&&!di(e,t)||t.hasAttribute(`hidden`)||!r&&!mi(t,n))return!1}return!0}function mi(e,t){let n=Pn(e);return t?n.display!==`none`:si(e,n)}function hi(e){let t=e.tabIndex;if(t<0){let t=gn(e);if(t===`details`||t===`audio`||t===`video`||xn(e)&&e.isContentEditable)return 0}return t}function gi(e){if(gn(e)!==`input`)return null;let t=e;return t.type===`radio`&&t.name!==``?t:null}function _i(e,t){let n=gi(e);if(!n)return!0;let r=t.find(e=>{let t=gi(e);return t?.name===n.name&&t.form===n.form&&t.checked});return r?r===n:t.find(e=>{let t=gi(e);return t?.name===n.name&&t.form===n.form})===n}function vi(e){if(xn(e)&&gn(e)===`slot`){let t=e.assignedElements({flatten:!0});if(t.length>0)return t}return xn(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function yi(e,t){vi(e).forEach(e=>{fi(e)&&t.push(e),yi(e,t)})}function bi(e,t,n){vi(e).forEach(e=>{xn(e)&&e.matches(t)&&n.push(e),bi(e,t,n)})}function xi(e){return pi(e)&&hi(e)>=0}function Si(e){let t=[];return yi(e,t),t.filter(pi)}function Ci(e){let t=Si(e);return t.filter(e=>hi(e)>=0&&_i(e,t))}function wi(e,t){let n=Ci(e),r=n.length;if(r===0)return;let i=dr(ar(e)),a=n.indexOf(i);return n[a===-1?t===1?0:r-1:a+t]}function Ti(e){return wi(ar(e).body,1)||e}function Ei(e){return wi(ar(e).body,-1)||e}function Di(e,t){let n=t||e.currentTarget,r=e.relatedTarget;return!r||!fr(n,r)}function Oi(e){Ci(e).forEach(e=>{e.dataset.tabindex=e.getAttribute(`tabindex`)||``,e.setAttribute(`tabindex`,`-1`)})}function ki(e){let t=[];bi(e,`[data-tabindex]`,t),t.forEach(e=>{let t=e.dataset.tabindex;delete e.dataset.tabindex,t?e.setAttribute(`tabindex`,t):e.removeAttribute(`tabindex`)})}function Ai(e,t,n=!0){return e.filter(e=>e.parentId===t).flatMap(t=>[...!n||t.context?.open?[t]:[],...Ai(e,t.id,n)])}function ji(e,t){let n=[],r=e.find(e=>e.id===t)?.parentId;for(;r;){let t=e.find(e=>e.id===r);r=t?.parentId,t&&(n=n.concat(t))}return n}function Mi(e){return`data-base-ui-${e}`}var Ni={..._},Pi=0;function Fi(e,t=`mui`){let[n,r]=_.useState(e),i=e||n;return _.useEffect(()=>{n??(Pi+=1,r(`${t}-${Pi}`))},[n,t]),i}var Ii=Ni.useId;function Li(e,t){if(Ii!==void 0){let n=Ii();return e??(t?`${t}-${n}`:n)}return Fi(e,t)}var Ri=19;function zi(e){return Ri>=e}function Bi(e){if(!_.isValidElement(e))return null;let t=e,n=t.props;return(zi(19)?n?.ref:t.ref)??null}function Vi(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}function Hi(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 Ui(e,t){return typeof e==`function`?e(t):e}function Wi(e,t){return typeof e==`function`?e(t):e}var Gi={};function Ki(e,t,n,r,i){if(!n&&!r&&!i&&!e)return Ji(t);let a=Ji(e);return t&&(a=Yi(a,t)),n&&(a=Yi(a,n)),r&&(a=Yi(a,r)),i&&(a=Yi(a,i)),a}function qi(e){if(e.length===0)return Gi;if(e.length===1)return Ji(e[0]);let t=Ji(e[0]);for(let n=1;n<e.length;n+=1)t=Yi(t,e[n]);return t}function Ji(e){return $i(e)?{...ea(e,Gi)}:Xi(e)}function Yi(e,t){return $i(t)?ea(t,e):Zi(e,t)}function Xi(e){let t={...e};for(let e in t){let n=t[e];Qi(e,n)&&(t[e]=na(n))}return t}function Zi(e,t){if(!t)return e;for(let n in t){let r=t[n];switch(n){case`style`:e[n]=Vi(e.style,r);break;case`className`:e[n]=ia(e.className,r);break;default:Qi(n,r)?e[n]=ta(e[n],r):e[n]=r}}return e}function Qi(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 $i(e){return typeof e==`function`}function ea(e,t){return $i(e)?e(t):e??Gi}function ta(e,t){return t?e?(...n)=>{let r=n[0];if(aa(r)){let i=r;ra(i);let a=t(...n);return i.baseUIHandlerPrevented||e?.(...n),a}let i=t(...n);return e?.(...n),i}:na(t):e}function na(e){return e&&((...t)=>{let n=t[0];return aa(n)&&ra(n),e(...t)})}function ra(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function ia(e,t){return t?e?t+` `+e:t:e}function aa(e){return typeof e==`object`&&!!e&&`nativeEvent`in e}function oa(e,t,n={}){let r=t.render,i=sa(t,n);return n.enabled===!1?null:ua(e,r,i,n.state??nn)}function sa(e,t={}){let{className:n,style:r,render:i}=e,{state:a=nn,ref:o,props:s,stateAttributesMapping:c,enabled:l=!0}=t,u=l?Ui(n,a):void 0,d=l?Wi(r,a):void 0,f=l?Hi(a,c):nn,p=l&&s?ca(s):void 0,m=l?Vi(f,p)??{}:nn;return typeof document<`u`&&(l?Array.isArray(o)?m.ref=Un([m.ref,Bi(i),...o]):m.ref=Hn(m.ref,Bi(i),o):Hn(null,null)),l?(u!==void 0&&(m.className=ia(m.className,u)),d!==void 0&&(m.style=Vi(m.style,d)),m):nn}function ca(e){return Array.isArray(e)?qi(e):Ki(void 0,e)}var la=Symbol.for(`react.lazy`);function ua(e,t,n,r){if(t){if(typeof t==`function`)return t(n,r);let e=Ki(n,t.props);e.ref=n.ref;let i=t;return i?.$$typeof===la&&(i=_.Children.toArray(t)[0]),_.cloneElement(i,e)}if(e&&typeof e==`string`)return da(e,n);throw Error(kt(8))}function da(e,t){return e===`button`?(0,_.createElement)(`button`,{type:`button`,...t,key:t.key}):e===`img`?(0,_.createElement)(`img`,{alt:``,...t,key:t.key}):_.createElement(e,t)}var fa={style:{transition:`none`}},pa=`data-base-ui-click-trigger`,ma={fallbackAxisSide:`end`},ha={clipPath:`inset(50%)`,position:`fixed`,top:0,left:0},ga=_.createContext(null),_a=()=>_.useContext(ga),va=Mi(`portal`);function ya(e={}){let{ref:t,container:n,componentProps:r=nn,elementProps:i}=e,a=Li(),o=_a()?.portalNode,[s,c]=_.useState(null),[l,u]=_.useState(null),d=Qn(e=>{e!==null&&u(e)}),f=_.useRef(null);Dt(()=>{if(n===null){f.current&&(f.current=null,u(null),c(null));return}if(a==null)return;let e=(n&&(yn(n)?n:n.current))??o??document.body;if(e==null){f.current&&(f.current=null,u(null),c(null));return}f.current!==e&&(f.current=e,u(null),c(e))},[n,o,a]);let p=oa(`div`,r,{ref:[t,d],props:[{id:a,[va]:``},i]});return{portalNode:l,portalSubtree:s&&p?$e.createPortal(p,s):null}}var ba=_.forwardRef(function(e,t){let{children:n,container:r,className:i,render:a,renderGuards:o,style:s,...c}=e,{portalNode:l,portalSubtree:u}=ya({container:r,ref:t,componentProps:e,elementProps:c}),d=_.useRef(null),f=_.useRef(null),p=_.useRef(null),m=_.useRef(null),[h,g]=_.useState(null),v=_.useRef(!1),y=h?.modal,b=h?.open,x=typeof o==`boolean`?o:!!h&&!h.modal&&h.open&&!!l;_.useEffect(()=>{if(!l||y)return;function e(e){l&&e.relatedTarget&&Di(e)&&(e.type===`focusin`?v.current&&=(ki(l),!1):(Oi(l),v.current=!0))}return Vn(Bn(l,`focusin`,e,!0),Bn(l,`focusout`,e,!0))},[l,y]),_.useEffect(()=>{!l||b!==!1||(ki(l),v.current=!1)},[b,l]);let S=_.useMemo(()=>({beforeOutsideRef:d,afterOutsideRef:f,beforeInsideRef:p,afterInsideRef:m,portalNode:l,setFocusManagerState:g}),[l]);return(0,Ue.jsxs)(_.Fragment,{children:[u,(0,Ue.jsxs)(ga.Provider,{value:S,children:[x&&l&&(0,Ue.jsx)(cr,{"data-type":`outside`,ref:d,onFocus:e=>{Di(e,l)?p.current?.focus():Ei(h?h.domReference:null)?.focus()}}),x&&l&&(0,Ue.jsx)(`span`,{"aria-owns":l.id,style:ha}),l&&$e.createPortal(n,l),x&&l&&(0,Ue.jsx)(cr,{"data-type":`outside`,ref:f,onFocus:e=>{Di(e,l)?m.current?.focus():(Ti(h?h.domReference:null)?.focus(),h?.closeOnFocusOut&&h?.onOpenChange(!1,mn(`focus-out`,e.nativeEvent)))}})]})]})});function xa(){let e=new Map;return{emit(t,n){e.get(t)?.forEach(e=>e(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}var Sa=_.createContext(null),Ca=_.createContext(null),wa=()=>_.useContext(Sa)?.id||null,Ta=e=>{let t=_.useContext(Ca);return e??t};function Ea(e){return e==null?e:`current`in e?e.current:e}var Da={intentional:`onClick`,sloppy:`onPointerDown`};function Oa(){return!1}function ka(e){return{escapeKey:typeof e==`boolean`?e:e?.escapeKey??!1,outsidePress:typeof e==`boolean`?e:e?.outsidePress??!0}}function Aa(e,t={}){let n=`rootStore`in e?e.rootStore:e,r=n.useState(`open`),i=n.useState(`floatingElement`),{dataRef:a}=n.context,{enabled:o=!0,escapeKey:s=!0,outsidePress:c=!0,outsidePressEvent:l=`sloppy`,referencePress:u=Oa,referencePressEvent:d=`sloppy`,bubbles:f,externalTree:p}=t,m=Ta(p),h=Qn(typeof c==`function`?c:()=>!1),g=typeof c==`function`?h:c,v=g!==!1,y=Qn(()=>l),b=_.useRef(!1),x=_.useRef(!1),S=_.useRef(!1),{escapeKey:C,outsidePress:w}=ka(f),T=_.useRef(null),E=Pt(),D=Pt(),O=Qn(()=>{D.clear(),a.current.insideReactTree=!1}),k=_.useRef(!1),A=_.useRef(``),j=Qn(u),M=Qn(e=>{if(!r||!o||!s||e.key!==`Escape`||k.current)return;let t=a.current.floatingContext?.nodeId,i=m?Ai(m.nodesRef.current,t):[];if(!C&&i.length>0){let e=!0;if(i.forEach(t=>{t.context?.open&&!t.context.dataRef.current.__escapeKeyBubbles&&(e=!1)}),!e)return}let c=mn(dn,Yt(e)?e.nativeEvent:e);n.setOpen(!1,c),!C&&!c.isPropagationAllowed&&e.stopPropagation()}),N=Qn(()=>{a.current.insideReactTree=!0,D.start(0,O)});_.useEffect(()=>{if(!r||!o)return;a.current.__escapeKeyBubbles=C,a.current.__outsidePressBubbles=w;let e=new Nt,t=new Nt;function c(){e.clear(),k.current=!0}function l(){e.start(Mn()?5:0,()=>{k.current=!1})}function u(){S.current=!0,t.start(0,()=>{S.current=!1})}function d(){b.current=!1,x.current=!1}function f(){let e=A.current,t=e===`pen`||!e?`mouse`:e,n=y(),r=typeof n==`function`?n():n;return typeof r==`string`?r:r[t]}function p(e){let t=f();return t===`intentional`&&e.type!==`click`||t===`sloppy`&&e.type===`click`}function h(e){let t=a.current.floatingContext?.nodeId,r=m&&Ai(m.nodesRef.current,t).some(t=>hr(e,t.context?.elements.floating));return hr(e,n.select(`floatingElement`))||hr(e,n.select(`domReferenceElement`))||r}function _(e){if(p(e)){O();return}if(a.current.insideReactTree){O();return}let r=pr(e),i=`[${Mi(`inert`)}]`,o=bn(r)?r.getRootNode():null,s=Array.from((Sn(o)?o:ar(n.select(`floatingElement`))).querySelectorAll(i)),c=n.context.triggerElements;if(r&&(c.hasElement(r)||c.hasMatchingElement(e=>fr(e,r))))return;let l=bn(r)?r:null;for(;l&&!Nn(l);){let e=In(l);if(Nn(e)||!bn(e))break;l=e}if(s.length&&bn(r)&&!gr(r)&&!fr(r,n.select(`floatingElement`))&&s.every(e=>!fr(l,e)))return;if(xn(r)&&!(`touches`in e)){let t=Nn(r),n=Pn(r),i=/auto|scroll/,a=t||i.test(n.overflowX),o=t||i.test(n.overflowY),s=a&&r.clientWidth>0&&r.scrollWidth>r.clientWidth,c=o&&r.clientHeight>0&&r.scrollHeight>r.clientHeight,l=n.direction===`rtl`,u=c&&(l?e.offsetX<=r.offsetWidth-r.clientWidth:e.offsetX>r.clientWidth),d=s&&e.offsetY>r.clientHeight;if(u||d)return}if(h(e))return;if(f()===`intentional`&&S.current){t.clear(),S.current=!1;return}if(typeof g==`function`&&!g(e))return;let u=a.current.floatingContext?.nodeId,d=m?Ai(m.nodesRef.current,u):[];if(d.length>0){let e=!0;if(d.forEach(t=>{t.context?.open&&!t.context.dataRef.current.__outsidePressBubbles&&(e=!1)}),!e)return}n.setOpen(!1,mn(cn,e)),O()}function D(e){f()!==`sloppy`||e.pointerType===`touch`||!n.select(`open`)||!o||hr(e,n.select(`floatingElement`))||hr(e,n.select(`domReferenceElement`))||_(e)}function j(e){if(f()!==`sloppy`||!n.select(`open`)||!o||hr(e,n.select(`floatingElement`))||hr(e,n.select(`domReferenceElement`)))return;let t=e.touches[0];t&&(T.current={startTime:Date.now(),startX:t.clientX,startY:t.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},E.start(1e3,()=>{T.current&&(T.current.dismissOnTouchEnd=!1,T.current.dismissOnMouseDown=!1)}))}function N(e,t){let n=pr(e);if(!n)return;let r=Bn(n,e.type,()=>{t(e),r()})}function P(e){A.current=`touch`,N(e,j)}function F(e){E.clear(),e.type===`pointerdown`&&(A.current=e.pointerType),!(e.type===`mousedown`&&T.current&&!T.current.dismissOnMouseDown)&&N(e,e=>{e.type===`pointerdown`?D(e):_(e)})}function I(e){if(!b.current)return;let n=x.current;if(d(),f()===`intentional`){if(e.type===`pointercancel`){n&&u();return}if(!h(e)){if(n){u();return}typeof g==`function`&&!g(e)||(t.clear(),S.current=!0,O())}}}function ee(e){if(f()!==`sloppy`||!T.current||hr(e,n.select(`floatingElement`))||hr(e,n.select(`domReferenceElement`)))return;let t=e.touches[0];if(!t)return;let r=Math.abs(t.clientX-T.current.startX),i=Math.abs(t.clientY-T.current.startY),a=Math.sqrt(r*r+i*i);a>5&&(T.current.dismissOnTouchEnd=!0),a>10&&(_(e),E.clear(),T.current=null)}function te(e){N(e,ee)}function ne(e){f()!==`sloppy`||!T.current||hr(e,n.select(`floatingElement`))||hr(e,n.select(`domReferenceElement`))||(T.current.dismissOnTouchEnd&&_(e),E.clear(),T.current=null)}function re(e){N(e,ne)}let L=ar(i),R=Vn(s&&Vn(Bn(L,`keydown`,M),Bn(L,`compositionstart`,c),Bn(L,`compositionend`,l)),v&&Vn(Bn(L,`click`,F,!0),Bn(L,`pointerdown`,F,!0),Bn(L,`pointerup`,I,!0),Bn(L,`pointercancel`,I,!0),Bn(L,`mousedown`,F,!0),Bn(L,`mouseup`,I,!0),Bn(L,`touchstart`,P,!0),Bn(L,`touchmove`,te,!0),Bn(L,`touchend`,re,!0)));return()=>{R(),e.clear(),t.clear(),d(),S.current=!1}},[a,i,s,v,g,r,o,C,w,M,O,y,m,n,E]),_.useEffect(O,[g,O]);let P=_.useMemo(()=>({onKeyDown:M,[Da[d]]:e=>{j()&&n.setOpen(!1,mn(an,e.nativeEvent))},...d!==`intentional`&&{onClick(e){j()&&n.setOpen(!1,mn(`trigger-press`,e.nativeEvent))}}}),[M,n,d,j]),F=Qn(e=>{if(!r||!o||e.button!==0)return;let t=pr(e.nativeEvent);fr(n.select(`floatingElement`),t)&&(b.current||(b.current=!0,x.current=!1))}),I=Qn(e=>{!r||!o||(e.defaultPrevented||e.nativeEvent.defaultPrevented)&&b.current&&(x.current=!0)}),ee=_.useMemo(()=>({onKeyDown:M,onPointerDown:I,onMouseDown:I,onClickCapture:N,onMouseDownCapture(e){N(),F(e)},onPointerDownCapture(e){N(),F(e)},onMouseUpCapture:N,onTouchEndCapture:N,onTouchMoveCapture:N}),[M,N,F,I]);return _.useMemo(()=>o?{reference:P,floating:ee,trigger:P}:{},[o,P,ee])}var H=(e,t,n,r,i,a,...o)=>{if(o.length>0)throw Error(kt(1));let s;if(e&&t&&n&&r&&i&&a)s=(o,s,c,l)=>a(e(o,s,c,l),t(o,s,c,l),n(o,s,c,l),r(o,s,c,l),i(o,s,c,l),s,c,l);else if(e&&t&&n&&r&&i)s=(a,o,s,c)=>i(e(a,o,s,c),t(a,o,s,c),n(a,o,s,c),r(a,o,s,c),o,s,c);else if(e&&t&&n&&r)s=(i,a,o,s)=>r(e(i,a,o,s),t(i,a,o,s),n(i,a,o,s),a,o,s);else if(e&&t&&n)s=(r,i,a,o)=>n(e(r,i,a,o),t(r,i,a,o),i,a,o);else if(e&&t)s=(n,r,i,a)=>t(e(n,r,i,a),r,i,a);else if(e)s=e;else throw Error(`Missing arguments`);return s},ja=zi(19)?Pa:Fa;function Ma(e,t,n,r,i){return ja(e,t,n,r,i)}function Na(e,t,n,r,i){let a=_.useCallback(()=>t(e.getSnapshot(),n,r,i),[e,t,n,r,i]);return(0,vt.useSyncExternalStore)(e.subscribe,a,a)}St({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){let r=e.syncHooks[n],i=r.selector(r.store.state,r.a1,r.a2,r.a3);(r.didChange||!Object.is(r.value,i))&&(t=!0,r.value=i,r.didChange=!1)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{let n=new Set;for(let t of e.syncHooks)n.add(t.store);let r=[];for(let e of n)r.push(e.subscribe(t));return()=>{for(let e of r)e()}}),(0,vt.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot))}});function Pa(e,t,n,r,i){let a=xt();if(!a)return Na(e,t,n,r,i);let o=a.syncIndex;a.syncIndex+=1;let s;return a.didInitialize?(s=a.syncHooks[o],(s.store!==e||s.selector!==t||!Object.is(s.a1,n)||!Object.is(s.a2,r)||!Object.is(s.a3,i))&&(s.store!==e&&(a.didChangeStore=!0),s.store=e,s.selector=t,s.a1=n,s.a2=r,s.a3=i,s.didChange=!0)):(s={store:e,selector:t,a1:n,a2:r,a3:i,value:t(e.getSnapshot(),n,r,i),didChange:!1},a.syncHooks.push(s)),s.value}function Fa(e,t,n,r,i){return(0,g.useSyncExternalStoreWithSelector)(e.subscribe,e.getSnapshot,e.getSnapshot,e=>t(e,n,r,i))}var Ia=class{constructor(e){this.state=e,this.listeners=new Set,this.updateTick=0}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.state;setState(e){if(this.state===e)return;this.state=e,this.updateTick+=1;let t=this.updateTick;for(let n of this.listeners){if(t!==this.updateTick)return;n(e)}}update(e){for(let t in e)if(!Object.is(this.state[t],e[t])){this.setState({...this.state,...e});return}}set(e,t){Object.is(this.state[e],t)||this.setState({...this.state,[e]:t})}notifyAll(){let e={...this.state};this.setState(e)}use(e,t,n,r){return Ma(this,e,t,n,r)}},La=class extends Ia{constructor(e,t={},n){super(e),this.context=t,this.selectors=n}useSyncedValue(e,t){_.useDebugValue(e),Dt(()=>{this.state[e]!==t&&this.set(e,t)},[e,t])}useSyncedValueWithCleanup(e,t){let n=this;Dt(()=>(n.state[e]!==t&&n.set(e,t),()=>{n.set(e,void 0)}),[n,e,t])}useSyncedValues(e){let t=this;Dt(()=>{t.update(e)},[t,...Object.values(e)])}useControlledProp(e,t){_.useDebugValue(e);let n=t!==void 0;Dt(()=>{n&&!Object.is(this.state[e],t)&&super.setState({...this.state,[e]:t})},[e,t,n])}select(e,t,n,r){let i=this.selectors[e];return i(this.state,t,n,r)}useState(e,t,n,r){return _.useDebugValue(e),Ma(this,this.selectors[e],t,n,r)}useContextCallback(e,t){_.useDebugValue(e);let n=Qn(t??en);this.context[e]=n}useStateSetter(e){let t=_.useRef(void 0);return t.current===void 0&&(t.current=t=>{this.set(e,t)}),t.current}observe(e,t){let n;n=typeof e==`function`?e:this.selectors[e];let r=n(this.state);return t(r,r,this),this.subscribe(e=>{let i=n(e);if(!Object.is(r,i)){let e=r;r=i,t(i,e,this)}})}},Ra={open:H(e=>e.open),transitionStatus:H(e=>e.transitionStatus),domReferenceElement:H(e=>e.domReferenceElement),referenceElement:H(e=>e.positionReference??e.referenceElement),floatingElement:H(e=>e.floatingElement),floatingId:H(e=>e.floatingId)},za=class extends La{constructor(e){let{syncOnly:t,nested:n,onOpenChange:r,triggerElements:i,...a}=e;super({...a,positionReference:a.referenceElement,domReferenceElement:a.referenceElement},{onOpenChange:r,dataRef:{current:{}},events:xa(),nested:n,triggerElements:i},Ra),this.syncOnly=t}syncOpenEvent=(e,t)=>{(!e||!this.state.open||t!=null&&$t(t))&&(this.context.dataRef.current.openEvent=e?t:void 0)};dispatchOpenChange=(e,t)=>{this.syncOpenEvent(e,t.event);let n={open:e,reason:t.reason,nativeEvent:t.event,nested:this.context.nested,triggerElement:t.trigger};this.context.events.emit(`openchange`,n)};setOpen=(e,t)=>{if(this.syncOnly){this.context.onOpenChange?.(e,t);return}this.dispatchOpenChange(e,t),this.context.onOpenChange?.(e,t)}};function Ba(e,t=!1,n=!1){let[r,i]=_.useState(e&&t?`idle`:void 0),[a,o]=_.useState(e);return e&&!a&&(o(!0),i(`starting`)),!e&&a&&r!==`ending`&&!n&&i(`ending`),!e&&!a&&r===`ending`&&i(void 0),Dt(()=>{if(!e&&a&&r!==`ending`&&n){let e=rr.request(()=>{i(`ending`)});return()=>{rr.cancel(e)}}},[e,a,r,n]),Dt(()=>{if(!e||t)return;let n=rr.request(()=>{i(void 0)});return()=>{rr.cancel(n)}},[t,e]),Dt(()=>{if(!e||!t)return;e&&a&&r!==`idle`&&i(`starting`);let n=rr.request(()=>{i(`idle`)});return()=>{rr.cancel(n)}},[t,e,a,r]),{mounted:a,setMounted:o,transitionStatus:r}}var Va=function(e){return e.startingStyle=`data-starting-style`,e.endingStyle=`data-ending-style`,e}({}),Ha={[Va.startingStyle]:``},Ua={[Va.endingStyle]:``},Wa={transitionStatus(e){return e===`starting`?Ha:e===`ending`?Ua:null}};function Ga(e,t=!1,n=!0){let r=ir();return Qn((i,a=null)=>{r.cancel();let o=Ea(e);if(o==null)return;let s=o,c=()=>{$e.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=Va.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 Ka(e){let{enabled:t=!0,open:n,ref:r,onComplete:i}=e,a=Qn(i),o=Ga(r,n,!1);_.useEffect(()=>{if(!t)return;let e=new AbortController;return o(a,e.signal),()=>{e.abort()}},[t,n,a,o])}function qa(e,t){let n=_.useRef(null),r=_.useRef(null);return _.useCallback(i=>{if(e!==void 0){if(n.current!==null){let e=n.current,i=r.current,a=t.context.triggerElements.getById(e);i&&a===i&&t.context.triggerElements.delete(e),n.current=null,r.current=null}i!==null&&(n.current=e,r.current=i,t.context.triggerElements.add(e,i))}},[t,e])}function Ja(e,t,n,r){let i=n.useState(`isMountedByTrigger`,e),a=qa(e,n),o=Qn(t=>{if(a(t),!t||!n.select(`open`))return;let i=n.select(`activeTriggerId`);if(i===e){n.update({activeTriggerElement:t,...r});return}i??n.update({activeTriggerId:e,activeTriggerElement:t,...r})});return Dt(()=>{i&&n.update({activeTriggerElement:t.current,...r})},[i,n,t,...Object.values(r)]),{registerTrigger:o,isMountedByThisTrigger:i}}function Ya(e){let t=e.useState(`open`);Dt(()=>{if(t&&!e.select(`activeTriggerId`)&&e.context.triggerElements.size===1){let t=e.context.triggerElements.entries().next();if(!t.done){let[n,r]=t.value;e.update({activeTriggerId:n,activeTriggerElement:r})}}},[t,e])}function Xa(e,t,n){let{mounted:r,setMounted:i,transitionStatus:a}=Ba(e);t.useSyncedValues({mounted:r,transitionStatus:a});let o=Qn(()=>{i(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1}),n?.(),t.context.onOpenChangeComplete?.(!1)});return Ka({enabled:!t.useState(`preventUnmountingOnClose`),open:e,ref:t.context.popupRef,onComplete(){e||o()}}),{forceUnmount:o,transitionStatus:a}}var Za=class{constructor(){this.elementsSet=new Set,this.idMap=new Map}add(e,t){let n=this.idMap.get(e);n!==t&&(n!==void 0&&this.elementsSet.delete(n),this.elementsSet.add(t),this.idMap.set(e,t))}delete(e){let t=this.idMap.get(e);t&&(this.elementsSet.delete(t),this.idMap.delete(e))}hasElement(e){return this.elementsSet.has(e)}hasMatchingElement(e){for(let t of this.elementsSet)if(e(t))return!0;return!1}getById(e){return this.idMap.get(e)}entries(){return this.idMap.entries()}elements(){return this.elementsSet.values()}get size(){return this.idMap.size}};function Qa(){return new za({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new Za,floatingId:``,syncOnly:!1,nested:!1,onOpenChange:void 0})}function $a(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:Qa(),preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:nn,inactiveTriggerProps:nn,popupProps:nn}}var eo=H(e=>e.triggerIdProp??e.activeTriggerId),to={open:H(e=>e.openProp??e.open),mounted:H(e=>e.mounted),transitionStatus:H(e=>e.transitionStatus),floatingRootContext:H(e=>e.floatingRootContext),preventUnmountingOnClose:H(e=>e.preventUnmountingOnClose),payload:H(e=>e.payload),activeTriggerId:eo,activeTriggerElement:H(e=>e.mounted?e.activeTriggerElement:null),isTriggerActive:H((e,t)=>t!==void 0&&eo(e)===t),isOpenedByTrigger:H((e,t)=>t!==void 0&&eo(e)===t&&e.open),isMountedByTrigger:H((e,t)=>t!==void 0&&eo(e)===t&&e.mounted),triggerProps:H((e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps),popupProps:H(e=>e.popupProps),popupElement:H(e=>e.popupElement),positionerElement:H(e=>e.positionerElement)};function no(e){let{popupStore:t,treatPopupAsFloatingElement:n=!1,onOpenChange:r}=e,i=Li(),a=wa()!=null,o=t.useState(`open`),s=t.useState(`activeTriggerElement`),c=t.useState(n?`popupElement`:`positionerElement`),l=t.context.triggerElements,u=_t(()=>new za({open:o,transitionStatus:void 0,referenceElement:s,floatingElement:c,triggerElements:l,onOpenChange:r,floatingId:i,syncOnly:!0,nested:a})).current;return Dt(()=>{let e={open:o,floatingId:i,referenceElement:s,floatingElement:c};bn(s)&&(e.domReferenceElement=s),u.state.positionReference===u.state.referenceElement&&(e.positionReference=s),u.update(e)},[o,i,s,c,u]),u.context.onOpenChange=r,u.context.nested=a,u}function ro(e=[]){let t=e.map(e=>e?.reference),n=e.map(e=>e?.floating),r=e.map(e=>e?.item),i=e.map(e=>e?.trigger),a=_.useCallback(t=>io(t,e,`reference`),t),o=_.useCallback(t=>io(t,e,`floating`),n),s=_.useCallback(t=>io(t,e,`item`),r),c=_.useCallback(t=>io(t,e,`trigger`),i);return _.useMemo(()=>({getReferenceProps:a,getFloatingProps:o,getItemProps:s,getTriggerProps:c}),[a,o,s,c])}function io(e,t,n){let r=new Map,i=n===`item`,a={};n===`floating`&&(a.tabIndex=-1,a[lr]=``);for(let t in e)i&&e&&(t===`active`||t===`selected`)||(a[t]=e[t]);for(let o=0;o<t.length;o+=1){let s,c=t[o]?.[n];s=typeof c==`function`?e?c(e):null:c,s&&ao(a,s,i,r)}return ao(a,e,i,r),a}function ao(e,t,n,r){for(let i in t){let a=t[i];n&&(i===`active`||i===`selected`)||(i.startsWith(`on`)?(r.has(i)||r.set(i,[]),typeof a==`function`&&(r.get(i)?.push(a),e[i]=(...e)=>r.get(i)?.map(t=>t(...e)).find(e=>e!==void 0))):e[i]=a)}}var oo=function(e){return e.open=`data-open`,e.closed=`data-closed`,e[e.startingStyle=Va.startingStyle]=`startingStyle`,e[e.endingStyle=Va.endingStyle]=`endingStyle`,e.anchorHidden=`data-anchor-hidden`,e.side=`data-side`,e.align=`data-align`,e}({}),so=function(e){return e.popupOpen=`data-popup-open`,e.pressed=`data-pressed`,e}({}),co={[so.popupOpen]:``};so.popupOpen,so.pressed;var lo={[oo.open]:``},uo={[oo.closed]:``},fo={[oo.anchorHidden]:``},po={open(e){return e?co:null}},mo={open(e){return e?lo:uo},anchorHidden(e){return e?fo:null}};function ho(e){return Li(e,`base-ui`)}function go(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=go(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function _o(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=go(e))&&(r&&(r+=` `),r+=t);return r}var vo=(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},yo=(e,t)=>({classGroupId:e,validator:t}),bo=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),xo=`-`,So=[],Co=`arbitrary..`,wo=e=>{let t=Do(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return Eo(e);let n=e.split(xo);return To(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?vo(i,t):t:i||So}return n[e]||So}}},To=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=To(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(xo):e.slice(t).join(xo),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},Eo=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?Co+r:void 0})(),Do=e=>{let{theme:t,classGroups:n}=e;return Oo(n,t)},Oo=(e,t)=>{let n=bo();for(let r in e){let i=e[r];ko(i,n,r,t)}return n},ko=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];Ao(i,t,n,r)}},Ao=(e,t,n,r)=>{if(typeof e==`string`){jo(e,t,n);return}if(typeof e==`function`){Mo(e,t,n,r);return}No(e,t,n,r)},jo=(e,t,n)=>{let r=e===``?t:Po(t,e);r.classGroupId=n},Mo=(e,t,n,r)=>{if(Fo(e)){ko(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(yo(n,e))},No=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];ko(o,Po(t,a),n,r)}},Po=(e,t)=>{let n=e,r=t.split(xo),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=bo(),n.nextPart.set(t,i)),n=i}return n},Fo=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,Io=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)}}},Lo=`!`,Ro=`:`,zo=[],Bo=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Vo=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===Ro){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(Lo)?(c=s.slice(0,-1),l=!0):s.startsWith(Lo)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return Bo(t,l,c,u)};if(t){let e=t+Ro,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):Bo(zo,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Ho=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}},Uo=e=>({cache:Io(e.cacheSize),parseClassName:Vo(e),sortModifiers:Ho(e),...wo(e)}),Wo=/\s+/,Go=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a}=t,o=[],s=e.trim().split(Wo),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+Lo: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},Ko=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=qo(n))&&(i&&(i+=` `),i+=r);return i},qo=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=qo(e[r]))&&(n&&(n+=` `),n+=t);return n},Jo=(e,...t)=>{let n,r,i,a,o=o=>(n=Uo(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=Go(e,n);return i(e,a),a};return a=o,(...e)=>a(Ko(...e))},Yo=[],U=e=>{let t=t=>t[e]||Yo;return t.isThemeGetter=!0,t},Xo=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Zo=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Qo=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,$o=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,es=/\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$/,ts=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,ns=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,rs=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,is=e=>Qo.test(e),W=e=>!!e&&!Number.isNaN(Number(e)),as=e=>!!e&&Number.isInteger(Number(e)),os=e=>e.endsWith(`%`)&&W(e.slice(0,-1)),ss=e=>$o.test(e),cs=()=>!0,ls=e=>es.test(e)&&!ts.test(e),us=()=>!1,ds=e=>ns.test(e),fs=e=>rs.test(e),ps=e=>!G(e)&&!K(e),ms=e=>ks(e,Ns,us),G=e=>Xo.test(e),hs=e=>ks(e,Ps,ls),gs=e=>ks(e,Fs,W),_s=e=>ks(e,Ls,cs),vs=e=>ks(e,Is,us),ys=e=>ks(e,js,us),bs=e=>ks(e,Ms,fs),xs=e=>ks(e,Rs,ds),K=e=>Zo.test(e),Ss=e=>As(e,Ps),Cs=e=>As(e,Is),ws=e=>As(e,js),Ts=e=>As(e,Ns),Es=e=>As(e,Ms),Ds=e=>As(e,Rs,!0),Os=e=>As(e,Ls,!0),ks=(e,t,n)=>{let r=Xo.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},As=(e,t,n=!1)=>{let r=Zo.exec(e);return r?r[1]?t(r[1]):n:!1},js=e=>e===`position`||e===`percentage`,Ms=e=>e===`image`||e===`url`,Ns=e=>e===`length`||e===`size`||e===`bg-size`,Ps=e=>e===`length`,Fs=e=>e===`number`,Is=e=>e===`family-name`,Ls=e=>e===`number`||e===`weight`,Rs=e=>e===`shadow`,zs=Jo(()=>{let e=U(`color`),t=U(`font`),n=U(`text`),r=U(`font-weight`),i=U(`tracking`),a=U(`leading`),o=U(`breakpoint`),s=U(`container`),c=U(`spacing`),l=U(`radius`),u=U(`shadow`),d=U(`inset-shadow`),f=U(`text-shadow`),p=U(`drop-shadow`),m=U(`blur`),h=U(`perspective`),g=U(`aspect`),_=U(`ease`),v=U(`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(),K,G],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[K,G,c],T=()=>[is,`full`,`auto`,...w()],E=()=>[as,`none`,`subgrid`,K,G],D=()=>[`auto`,{span:[`full`,as,K,G]},as,K,G],O=()=>[as,`auto`,K,G],k=()=>[`auto`,`min`,`max`,`fr`,K,G],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=()=>[is,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],P=()=>[is,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],F=()=>[is,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],I=()=>[e,K,G],ee=()=>[...b(),ws,ys,{position:[K,G]}],te=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],ne=()=>[`auto`,`cover`,`contain`,Ts,ms,{size:[K,G]}],re=()=>[os,Ss,hs],L=()=>[``,`none`,`full`,l,K,G],R=()=>[``,W,Ss,hs],ie=()=>[`solid`,`dashed`,`dotted`,`double`],ae=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],z=()=>[W,os,ws,ys],oe=()=>[``,`none`,m,K,G],B=()=>[`none`,W,K,G],se=()=>[`none`,W,K,G],ce=()=>[W,K,G],V=()=>[is,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[ss],breakpoint:[ss],color:[cs],container:[ss],"drop-shadow":[ss],ease:[`in`,`out`,`in-out`],font:[ps],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[ss],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[ss],shadow:[ss],spacing:[`px`,W],text:[ss],"text-shadow":[ss],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,is,G,K,g]}],container:[`container`],columns:[{columns:[W,G,K,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:[as,`auto`,K,G]}],basis:[{basis:[is,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[W,is,`auto`,`initial`,`none`,G]}],grow:[{grow:[``,W,K,G]}],shrink:[{shrink:[``,W,K,G]}],order:[{order:[as,`first`,`last`,`none`,K,G]}],"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`,...F()]}],"min-block-size":[{"min-block":[`auto`,...F()]}],"max-block-size":[{"max-block":[`none`,...F()]}],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,Ss,hs]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,Os,_s]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,os,G]}],"font-family":[{font:[Cs,vs,t]}],"font-features":[{"font-features":[G]}],"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,K,G]}],"line-clamp":[{"line-clamp":[W,`none`,K,gs]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,K,G]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,K,G]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:I()}],"text-color":[{text:I()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...ie(),`wavy`]}],"text-decoration-thickness":[{decoration:[W,`from-font`,`auto`,K,hs]}],"text-decoration-color":[{decoration:I()}],"underline-offset":[{"underline-offset":[W,`auto`,K,G]}],"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`,K,G]}],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`,K,G]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:ee()}],"bg-repeat":[{bg:te()}],"bg-size":[{bg:ne()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},as,K,G],radial:[``,K,G],conic:[as,K,G]},Es,bs]}],"bg-color":[{bg:I()}],"gradient-from-pos":[{from:re()}],"gradient-via-pos":[{via:re()}],"gradient-to-pos":[{to:re()}],"gradient-from":[{from:I()}],"gradient-via":[{via:I()}],"gradient-to":[{to:I()}],rounded:[{rounded:L()}],"rounded-s":[{"rounded-s":L()}],"rounded-e":[{"rounded-e":L()}],"rounded-t":[{"rounded-t":L()}],"rounded-r":[{"rounded-r":L()}],"rounded-b":[{"rounded-b":L()}],"rounded-l":[{"rounded-l":L()}],"rounded-ss":[{"rounded-ss":L()}],"rounded-se":[{"rounded-se":L()}],"rounded-ee":[{"rounded-ee":L()}],"rounded-es":[{"rounded-es":L()}],"rounded-tl":[{"rounded-tl":L()}],"rounded-tr":[{"rounded-tr":L()}],"rounded-br":[{"rounded-br":L()}],"rounded-bl":[{"rounded-bl":L()}],"border-w":[{border:R()}],"border-w-x":[{"border-x":R()}],"border-w-y":[{"border-y":R()}],"border-w-s":[{"border-s":R()}],"border-w-e":[{"border-e":R()}],"border-w-bs":[{"border-bs":R()}],"border-w-be":[{"border-be":R()}],"border-w-t":[{"border-t":R()}],"border-w-r":[{"border-r":R()}],"border-w-b":[{"border-b":R()}],"border-w-l":[{"border-l":R()}],"divide-x":[{"divide-x":R()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":R()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ie(),`hidden`,`none`]}],"divide-style":[{divide:[...ie(),`hidden`,`none`]}],"border-color":[{border:I()}],"border-color-x":[{"border-x":I()}],"border-color-y":[{"border-y":I()}],"border-color-s":[{"border-s":I()}],"border-color-e":[{"border-e":I()}],"border-color-bs":[{"border-bs":I()}],"border-color-be":[{"border-be":I()}],"border-color-t":[{"border-t":I()}],"border-color-r":[{"border-r":I()}],"border-color-b":[{"border-b":I()}],"border-color-l":[{"border-l":I()}],"divide-color":[{divide:I()}],"outline-style":[{outline:[...ie(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[W,K,G]}],"outline-w":[{outline:[``,W,Ss,hs]}],"outline-color":[{outline:I()}],shadow:[{shadow:[``,`none`,u,Ds,xs]}],"shadow-color":[{shadow:I()}],"inset-shadow":[{"inset-shadow":[`none`,d,Ds,xs]}],"inset-shadow-color":[{"inset-shadow":I()}],"ring-w":[{ring:R()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:I()}],"ring-offset-w":[{"ring-offset":[W,hs]}],"ring-offset-color":[{"ring-offset":I()}],"inset-ring-w":[{"inset-ring":R()}],"inset-ring-color":[{"inset-ring":I()}],"text-shadow":[{"text-shadow":[`none`,f,Ds,xs]}],"text-shadow-color":[{"text-shadow":I()}],opacity:[{opacity:[W,K,G]}],"mix-blend":[{"mix-blend":[...ae(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":ae()}],"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":[W]}],"mask-image-linear-from-pos":[{"mask-linear-from":z()}],"mask-image-linear-to-pos":[{"mask-linear-to":z()}],"mask-image-linear-from-color":[{"mask-linear-from":I()}],"mask-image-linear-to-color":[{"mask-linear-to":I()}],"mask-image-t-from-pos":[{"mask-t-from":z()}],"mask-image-t-to-pos":[{"mask-t-to":z()}],"mask-image-t-from-color":[{"mask-t-from":I()}],"mask-image-t-to-color":[{"mask-t-to":I()}],"mask-image-r-from-pos":[{"mask-r-from":z()}],"mask-image-r-to-pos":[{"mask-r-to":z()}],"mask-image-r-from-color":[{"mask-r-from":I()}],"mask-image-r-to-color":[{"mask-r-to":I()}],"mask-image-b-from-pos":[{"mask-b-from":z()}],"mask-image-b-to-pos":[{"mask-b-to":z()}],"mask-image-b-from-color":[{"mask-b-from":I()}],"mask-image-b-to-color":[{"mask-b-to":I()}],"mask-image-l-from-pos":[{"mask-l-from":z()}],"mask-image-l-to-pos":[{"mask-l-to":z()}],"mask-image-l-from-color":[{"mask-l-from":I()}],"mask-image-l-to-color":[{"mask-l-to":I()}],"mask-image-x-from-pos":[{"mask-x-from":z()}],"mask-image-x-to-pos":[{"mask-x-to":z()}],"mask-image-x-from-color":[{"mask-x-from":I()}],"mask-image-x-to-color":[{"mask-x-to":I()}],"mask-image-y-from-pos":[{"mask-y-from":z()}],"mask-image-y-to-pos":[{"mask-y-to":z()}],"mask-image-y-from-color":[{"mask-y-from":I()}],"mask-image-y-to-color":[{"mask-y-to":I()}],"mask-image-radial":[{"mask-radial":[K,G]}],"mask-image-radial-from-pos":[{"mask-radial-from":z()}],"mask-image-radial-to-pos":[{"mask-radial-to":z()}],"mask-image-radial-from-color":[{"mask-radial-from":I()}],"mask-image-radial-to-color":[{"mask-radial-to":I()}],"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":[W]}],"mask-image-conic-from-pos":[{"mask-conic-from":z()}],"mask-image-conic-to-pos":[{"mask-conic-to":z()}],"mask-image-conic-from-color":[{"mask-conic-from":I()}],"mask-image-conic-to-color":[{"mask-conic-to":I()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:ee()}],"mask-repeat":[{mask:te()}],"mask-size":[{mask:ne()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,K,G]}],filter:[{filter:[``,`none`,K,G]}],blur:[{blur:oe()}],brightness:[{brightness:[W,K,G]}],contrast:[{contrast:[W,K,G]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Ds,xs]}],"drop-shadow-color":[{"drop-shadow":I()}],grayscale:[{grayscale:[``,W,K,G]}],"hue-rotate":[{"hue-rotate":[W,K,G]}],invert:[{invert:[``,W,K,G]}],saturate:[{saturate:[W,K,G]}],sepia:[{sepia:[``,W,K,G]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,K,G]}],"backdrop-blur":[{"backdrop-blur":oe()}],"backdrop-brightness":[{"backdrop-brightness":[W,K,G]}],"backdrop-contrast":[{"backdrop-contrast":[W,K,G]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,W,K,G]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[W,K,G]}],"backdrop-invert":[{"backdrop-invert":[``,W,K,G]}],"backdrop-opacity":[{"backdrop-opacity":[W,K,G]}],"backdrop-saturate":[{"backdrop-saturate":[W,K,G]}],"backdrop-sepia":[{"backdrop-sepia":[``,W,K,G]}],"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`,K,G]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[W,`initial`,K,G]}],ease:[{ease:[`linear`,`initial`,_,K,G]}],delay:[{delay:[W,K,G]}],animate:[{animate:[`none`,v,K,G]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,K,G]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:B()}],"rotate-x":[{"rotate-x":B()}],"rotate-y":[{"rotate-y":B()}],"rotate-z":[{"rotate-z":B()}],scale:[{scale:se()}],"scale-x":[{"scale-x":se()}],"scale-y":[{"scale-y":se()}],"scale-z":[{"scale-z":se()}],"scale-3d":[`scale-3d`],skew:[{skew:ce()}],"skew-x":[{"skew-x":ce()}],"skew-y":[{"skew-y":ce()}],transform:[{transform:[K,G,``,`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:I()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:I()}],"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`,K,G]}],"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`,K,G]}],fill:[{fill:[`none`,...I()]}],"stroke-w":[{stroke:[W,Ss,hs,gs]}],stroke:[{stroke:[`none`,...I()]}],"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 Bs(...e){return zs(_o(e))}function Vs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Hs(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 Us=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Ws=_o,Gs=(e,t)=>n=>{if(t?.variants==null)return Ws(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=Us(t)||Us(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 Ws(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 Ks(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 qs=e=>{switch(e){case`success`:return Xs;case`info`:return Qs;case`warning`:return Zs;case`error`:return $s;default:return null}},Js=Array(12).fill(0),Ys=({visible:e,className:t})=>_.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},_.createElement(`div`,{className:`sonner-spinner`},Js.map((e,t)=>_.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Xs=_.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},_.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`})),Zs=_.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},_.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`})),Qs=_.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},_.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`})),$s=_.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},_.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`})),ec=_.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`},_.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),_.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),tc=()=>{let[e,t]=_.useState(document.hidden);return _.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},nc=1,rc=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:nc++,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],_.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(ac(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`&&!_.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`&&!_.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`&&!_.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`&&!_.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||nc++;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}},ic=(e,t)=>{let n=t?.id||nc++;return rc.addToast({title:e,...t,id:n}),n},ac=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,oc=Object.assign(ic,{success:rc.success,info:rc.info,warning:rc.warning,error:rc.error,custom:rc.custom,message:rc.message,promise:rc.promise,dismiss:rc.dismiss,loading:rc.loading},{getHistory:()=>rc.toasts,getToasts:()=>rc.getActiveToasts()});Ks(`[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 sc(e){return e.label!==void 0}var cc=3,lc=`24px`,uc=`16px`,dc=4e3,fc=356,pc=14,mc=45,hc=200;function gc(...e){return e.filter(Boolean).join(` `)}function _c(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var vc=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:v=``,descriptionClassName:y=``,duration:b,position:x,gap:S,expandByDefault:C,classNames:w,icons:T,closeButtonAriaLabel:E=`Close toast`}=e,[D,O]=_.useState(null),[k,A]=_.useState(null),[j,M]=_.useState(!1),[N,P]=_.useState(!1),[F,I]=_.useState(!1),[ee,te]=_.useState(!1),[ne,re]=_.useState(!1),[L,R]=_.useState(0),[ie,ae]=_.useState(0),z=_.useRef(n.duration||b||dc),oe=_.useRef(null),B=_.useRef(null),se=c===0,ce=c+1<=o,V=n.type,le=n.dismissible!==!1,ue=n.className||``,de=n.descriptionClassName||``,fe=_.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),pe=_.useMemo(()=>n.closeButton??p,[n.closeButton,p]),me=_.useMemo(()=>n.duration||b||dc,[n.duration,b]),he=_.useRef(0),ge=_.useRef(0),_e=_.useRef(0),ve=_.useRef(null),[ye,be]=x.split(`-`),xe=_.useMemo(()=>s.reduce((e,t,n)=>n>=fe?e:e+t.height,0),[s,fe]),Se=tc(),Ce=n.invert||t,we=V===`loading`;ge.current=_.useMemo(()=>fe*S+xe,[fe,xe]),_.useEffect(()=>{z.current=me},[me]),_.useEffect(()=>{M(!0)},[]),_.useEffect(()=>{let e=B.current;if(e){let t=e.getBoundingClientRect().height;return ae(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),_.useLayoutEffect(()=>{if(!j)return;let e=B.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,ae(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=_.useCallback(()=>{P(!0),R(ge.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},hc)},[n,d,a,ge]);_.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;z.current-=e}_e.current=new Date().getTime()})():z.current!==1/0&&(he.current=new Date().getTime(),e=setTimeout(()=>{n.onAutoClose==null||n.onAutoClose.call(n,n),Te()},z.current)),()=>clearTimeout(e)},[u,i,n,V,Se,Te]),_.useEffect(()=>{n.delete&&(Te(),n.onDismiss==null||n.onDismiss.call(n,n))},[Te,n.delete]);function Ee(){return T?.loading?_.createElement(`div`,{className:gc(w?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":V===`loading`},T.loading):_.createElement(Ys,{className:gc(w?.loader,n?.classNames?.loader),visible:V===`loading`})}let De=n.icon||T?.[V]||qs(V);return _.createElement(`li`,{tabIndex:0,ref:B,className:gc(v,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":ne,"data-removed":N,"data-visible":ce,"data-y-position":ye,"data-x-position":be,"data-index":c,"data-front":se,"data-swiping":F,"data-dismissible":le,"data-type":V,"data-invert":Ce,"data-swipe-out":ee,"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?L:ge.current}px`,"--initial-height":C?`auto`:`${ie}px`,...m,...n.style},onDragEnd:()=>{I(!1),O(null),ve.current=null},onPointerDown:e=>{e.button!==2&&(we||!le||(oe.current=new Date,R(ge.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(I(!0),ve.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(ee||!le)return;ve.current=null;let e=Number(B.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(B.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-oe.current?.getTime(),i=D===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=mc||a>.11){R(ge.current),n.onDismiss==null||n.onDismiss.call(n,n),A(D===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Te(),te(!0);return}else{var o,s;(o=B.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=B.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}re(!1),I(!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??_c(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)&&re(!0),(n=B.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=B.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},pe&&!n.jsx&&V!==`loading`?_.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:gc(w?.closeButton,n?.classNames?.closeButton)},T?.close??ec):null,(V||n.icon||n.promise)&&n.icon!==null&&(T?.[V]!==null||n.icon)?_.createElement(`div`,{"data-icon":``,className:gc(w?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Ee():null,n.type===`loading`?null:De):null,_.createElement(`div`,{"data-content":``,className:gc(w?.content,n?.classNames?.content)},_.createElement(`div`,{"data-title":``,className:gc(w?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?_.createElement(`div`,{"data-description":``,className:gc(y,de,w?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),_.isValidElement(n.cancel)?n.cancel:n.cancel&&sc(n.cancel)?_.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{sc(n.cancel)&&le&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Te())},className:gc(w?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,_.isValidElement(n.action)?n.action:n.action&&sc(n.action)?_.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{sc(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Te())},className:gc(w?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function yc(){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 bc(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?uc:lc;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 xc=_.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=cc,toastOptions:g,dir:v=yc(),gap:y=pc,icons:b,containerAriaLabel:x=`Notifications`}=e,[S,C]=_.useState([]),w=_.useMemo(()=>n?S.filter(e=>e.toasterId===n):S.filter(e=>!e.toasterId),[S,n]),T=_.useMemo(()=>Array.from(new Set([i].concat(w.filter(e=>e.position).map(e=>e.position)))),[w,i]),[E,D]=_.useState([]),[O,k]=_.useState(!1),[A,j]=_.useState(!1),[M,N]=_.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),P=_.useRef(null),F=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),I=_.useRef(null),ee=_.useRef(!1),te=_.useCallback(e=>{C(t=>(t.find(t=>t.id===e.id)?.delete||rc.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return _.useEffect(()=>rc.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{C(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{$e.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]),_.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]),_.useEffect(()=>{S.length<=1&&k(!1)},[S]),_.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]),_.useEffect(()=>{if(P.current)return()=>{I.current&&(I.current.focus({preventScroll:!0}),I.current=null,ee.current=!1)}},[P.current]),_.createElement(`section`,{ref:t,"aria-label":`${x} ${F}`,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?_.createElement(`ol`,{key:t,dir:v===`auto`?yc():v,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":`${fc}px`,"--gap":`${y}px`,...m,...bc(l,u)},onBlur:e=>{ee.current&&!e.currentTarget.contains(e.relatedTarget)&&(ee.current=!1,I.current&&=(I.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||ee.current||(ee.current=!0,I.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)=>_.createElement(vc,{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:te,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}))}),Sc=`__includes_scalar__`,Cc=class{},wc=class extends Cc{constructor(e,t){super(),this.collection=e,this.alias=t,this.type=`collectionRef`}},Tc=class extends Cc{constructor(e,t){super(),this.query=e,this.alias=t,this.type=`queryRef`}},q=class extends Cc{constructor(e){super(),this.path=e,this.type=`ref`}},Ec=class extends Cc{constructor(e){super(),this.value=e,this.type=`val`}},Dc=class extends Cc{constructor(e,t){super(),this.name=e,this.args=t,this.type=`func`}},Oc=class extends Cc{constructor(e,t){super(),this.name=e,this.args=t,this.type=`agg`}},kc=class extends Cc{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 Ac(e){return e instanceof Oc||e instanceof Dc||e instanceof q||e instanceof Ec||e instanceof kc}function jc(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Mc(e){return typeof e==`object`&&`expression`in e?e.expression:e}function Nc(e){return typeof e==`object`&&`expression`in e&&e.residual===!0}function Pc(e){return{expression:e,residual:!0}}function Fc(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 Ic(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 Ic(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Fc(e,r);return a?a.type===`queryRef`?Ic(a.query,new q(i),n):{collection:a.collection,path:i}:void 0}}}var Lc=class extends Error{constructor(e){super(e),this.name=`TanStackDBError`}},Rc=class extends Lc{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}},zc=class extends Lc{constructor(e){super(e),this.name=`CollectionConfigurationError`}},Bc=class extends zc{constructor(){super(`Collection requires a config`)}},Vc=class extends zc{constructor(){super(`Collection requires a sync config`)}},Hc=class extends zc{constructor(){super(`Schema must implement the standard-schema interface`)}},Uc=class extends zc{constructor(){super(`Schema validation must be synchronous`)}},Wc=class extends Lc{constructor(e){super(e),this.name=`CollectionStateError`}},Gc=class extends Wc{constructor(e,t){super(`Cannot perform ${e} on collection "${t}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}},Kc=class extends Wc{constructor(e,t,n){super(`Invalid collection status transition from "${e}" to "${t}" for collection "${n}"`)}},qc=class extends Wc{constructor(){super(`Collection is in error state`)}},Jc=class extends Wc{constructor(){super(`Active subscribers count is negative - this should never happen`)}},Yc=class extends Lc{constructor(e){super(e),this.name=`CollectionOperationError`}},Xc=class extends Yc{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}},Zc=class extends Yc{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)}`)}},Qc=class extends Yc{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}},$c=class extends Yc{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)}},el=class extends Yc{constructor(){super(`The first argument to update is missing`)}},tl=class extends Yc{constructor(){super(`No keys were passed to update`)}},nl=class extends Yc{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}},rl=class extends Yc{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.`)}},il=class extends Yc{constructor(){super(`No keys were passed to delete`)}},al=class extends Yc{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}},ol=class extends Lc{constructor(e){super(e),this.name=`MissingHandlerError`}},sl=class extends ol{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}},cl=class extends ol{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}},ll=class extends ol{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}},ul=class extends Lc{constructor(e){super(e),this.name=`TransactionError`}},dl=class extends ul{constructor(){super(`mutationFn is required when creating a transaction`)}},fl=class extends ul{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}},pl=class extends ul{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}},ml=class extends ul{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}},hl=class extends ul{constructor(){super(`No pending sync transaction to write to`)}},gl=class extends ul{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}},_l=class extends ul{constructor(){super(`No pending sync transaction to commit`)}},vl=class extends ul{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}},yl=class extends Lc{constructor(e){super(e),this.name=`QueryBuilderError`}},bl=class extends yl{constructor(e){super(`Only one source is allowed in the ${e}`)}},xl=class extends yl{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}},Sl=class extends yl{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.`)}},Cl=class extends yl{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}`)}},wl=class extends yl{constructor(){super(`Join condition must be an equality expression`)}},Tl=class extends yl{constructor(){super(`Query must have a from clause`)}},El=class extends yl{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`)}},Dl=class extends Lc{constructor(e){super(e),this.name=`QueryCompilationError`}},Ol=class extends Dl{constructor(){super(`DISTINCT requires a SELECT clause.`)}},kl=class extends Dl{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().`)}},Al=class extends Dl{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(...)).`)}},jl=class extends Dl{constructor(){super(`HAVING clause requires GROUP BY clause`)}},Ml=class extends Dl{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}},Nl=class extends Dl{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}`)}},Pl=class extends Dl{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.`)}},Fl=class extends Dl{constructor(e){super(`Unsupported FROM type: ${e}`)}},Il=class extends Dl{constructor(e){super(`Unknown expression type: ${e}`)}},Ll=class extends Dl{constructor(){super(`Reference path cannot be empty`)}},Rl=class extends Dl{constructor(e){super(`Unknown function: ${e}`)}},zl=class extends Dl{constructor(e){super(`Collection "${e}" not found during compilation of join`)}},Bl=class extends Lc{constructor(e){super(e),this.name=`JoinError`}},Vl=class extends Bl{constructor(e){super(`Unsupported join type: ${e}`)}},Hl=class extends Bl{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}},Ul=class extends Bl{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}},Wl=class extends Bl{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}},Gl=class extends Bl{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}},Kl=class extends Bl{constructor(){super(`Invalid join condition`)}},ql=class extends Bl{constructor(e){super(`Unsupported join source type: ${e}`)}},Jl=class extends Lc{constructor(e){super(e),this.name=`GroupByError`}},Yl=class extends Jl{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}},Xl=class extends Jl{constructor(e){super(`Unsupported aggregate function: ${e}`)}},Zl=class extends Jl{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}},Ql=class extends Jl{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}},$l=class extends Lc{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`}},eu=class extends Lc{constructor(e){super(e),this.name=`QueryOptimizerError`}},tu=class extends eu{constructor(){super(`Cannot combine empty expression list`)}},nu=class extends Dl{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.`)}},ru=class extends Dl{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}},iu=class extends Dl{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}};function au(e,t){return ou(e,t,new Map)}function ou(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)&&ou(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(cu(e)&&cu(t))return e[Symbol.toStringTag]===t[Symbol.toStringTag]?typeof e.equals==`function`?e.equals(t):e.toString()===t.toString():!1;if(cu(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)=>ou(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&&ou(e[r],t[r],n));return n.delete(e),a}return!1}var su=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function cu(e){if(typeof e!=`object`||!e)return!1;let t=e[Symbol.toStringTag];return typeof t==`string`&&su.has(t)}var lu={direction:`asc`,nulls:`first`,stringSort:`locale`},uu=new WeakMap,du=1;function fu(e){if(uu.has(e))return uu.get(e);let t=du++;return uu.set(e,t),t}var pu=(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=pu(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(cu(e)&&cu(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 fu(e)-fu(t);if(i)return 1;if(a)return-1}return e<t?-1:+(e>t)},mu=(e,t,n)=>pu(t,e,{...n,nulls:n.nulls===`first`?`last`:`first`});function hu(e){return(t,n)=>e.direction===`asc`?pu(t,n,e):mu(t,n,e)}var gu=hu({direction:`asc`,nulls:`first`,stringSort:`locale`});function _u(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 vu=128;function yu(e){return e instanceof Date?e.getTime():cu(e)?`__temporal__${e[Symbol.toStringTag]}__${e.toString()}`:(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)&&e.byteLength<=vu?`__u8__${Array.from(e).join(`,`)}`:e}function bu(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?_u(e,t):!1}function J(e){return e==null}function xu(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 Su(e,t){return e===`%Y-%m-%d`?t.toISOString().slice(0,10):t.toISOString()}function Cu(e){return e===!0}function Y(e,t=!1){return Tu(e,t)}function wu(e){return Tu(e,!0)}function Tu(e,t){switch(e.type){case`val`:{let t=e.value;return()=>t}case`ref`:return t?Du(e):Eu(e);case`func`:return Ou(e,t);default:throw new Il(e.type)}}function Eu(e){let[t,...n]=e.path;if(!t)throw new Ll;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 Du(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 Ou(e,t){let n=e.args.map(e=>Tu(e,t));switch(e.name){case`eq`:{let e=n[0],t=n[1];return n=>{let r=yu(e(n)),i=yu(t(n));return J(r)||J(i)?null:bu(r,i)}}case`gt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(i)?null:r>i}}case`gte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(i)?null:r>=i}}case`lt`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(i)?null:r<i}}case`lte`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(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;J(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;J(n)&&(t=!0)}return t?null:!1};case`not`:{let e=n[0];return t=>{let n=e(t);return J(n)?null:!n}}case`in`:{let e=n[0],t=n[1];return n=>{let r=yu(e(n)),i=t(n);return J(r)?null:Array.isArray(i)?i.some(e=>yu(e)===r):!1}}case`like`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(i)?null:ku(r,i,!1)}}case`ilike`:{let e=n[0],t=n[1];return n=>{let r=e(n),i=t(n);return J(r)||J(i)?null:ku(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=xu(e(t));return n?n.toISOString().slice(0,10):null}}case`datetime`:{let e=n[0];return t=>{let n=xu(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=xu(t(n));return i?Su(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 Rl(e.name)}}function ku(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 Au=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 ju(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 Mu=[`$synced`,`$origin`,`$key`,`$collectionId`];function Nu(e){return Mu.includes(e)}function Pu(e){return e.some(e=>Nu(e))}function Fu(e,t,n){if(Pu(t))return;let r=n??{...lu,...e.compareOptions};for(let n of e.indexes.values())if(n.matchesField(t)&&n.matchesCompareOptions(r))return n.matchesDirection(r.direction)?n:new Au(n)}function Iu(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 Lu(e){let t=new Set;for(let n of e)for(let e of n)t.add(e);return t}function Ru(e,t){return zu(e,t)}function zu(e,t){if(e.type===`func`)switch(e.name){case`eq`:case`gt`:case`gte`:case`lt`:case`lte`:return Vu(e,t);case`and`:return Hu(e,t);case`or`:return Uu(e,t);case`in`:return Wu(e,t)}return{canOptimize:!1,matchingKeys:new Set}}function Bu(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=Fu(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 Vu(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=Fu(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 Hu(e,t){if(e.type!==`func`||e.args.length<2)return{canOptimize:!1,matchingKeys:new Set};let n=Bu(e,t);if(n.canOptimize)return n;let r=[];for(let n of e.args){let e=zu(n,t);e.canOptimize&&r.push(e)}return r.length>0?{canOptimize:!0,matchingKeys:Iu(r.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function Uu(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=zu(r,t);e.canOptimize&&n.push(e)}return n.length>0?{canOptimize:!0,matchingKeys:Lu(n.map(e=>e.matchingKeys))}:{canOptimize:!1,matchingKeys:new Set}}function Wu(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=Fu(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 Gu={enabled:!0,collectionSizeThreshold:1e3,slowQueryThresholdMs:10,onSuggestion:null};function Ku(){return Gu.enabled&&!1}function qu(e){if(Ku())if(Gu.onSuggestion)try{Gu.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 Ju(e,t,n){Ku()&&t>Gu.collectionSizeThreshold&&qu({type:`collection-size`,collectionId:e,fieldPath:n,message:`Collection has ${t} items. Queries on "${n.join(`.`)}" may benefit from an index.`,collectionSize:t})}function Yu(e){return e.config.autoIndex===`eager`}function Xu(e,t,n,r,i){if(Pu(t)||!Yu(n))return;let a=r??{...lu,...n.compareOptions};if(!Array.from(n.indexes.values()).find(e=>e.matchesField(t)&&e.matchesCompareOptions(a))){Ku()&&Ju(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 Zu(e,t){if(!Yu(t))return;let n=Qu(e);for(let{fieldName:e,fieldPath:r}of n)Xu(e,r,t)}function Qu(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 $u=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}},ed=3e4;function td(e,t){if(t.length<=ed)e.push(...t);else for(let n=0;n<t.length;n+=ed){let r=t.slice(n,n+ed);e.push(...r)}}function nd(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 rd=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 id(e,t){let[n,r]=e,[i,a]=t;return{onlyInA:[...ad(n,Math.min(r,i)),...ad(Math.max(n,a),r)],onlyInB:[...ad(i,Math.min(a,n)),...ad(Math.max(i,r),a)]}}function ad(e,t){let n=[];for(let r=e;r<t;r++)n.push(r);return n}function od(e,t){return typeof e==typeof t?e<t?-1:+(e>t):typeof e==`string`?-1:1}function sd(e){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t instanceof Date?t.toISOString():t)}var cd=X(),ld=X(),ud=X(),dd=X(),fd=X();function X(){return Math.random()*(2**31-1)>>>0}var pd=new ArrayBuffer(8),md=new DataView(pd),hd=new Uint8Array(pd),gd=class{constructor(){this.hash=cd,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(fd);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(ld);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`:md.setFloat64(0,e,!0),this.writeByte(hd[0]),this.writeByte(hd[1]),this.writeByte(hd[2]),this.writeByte(hd[3]),this.writeByte(hd[4]),this.writeByte(hd[5]),this.writeByte(hd[6]),this.writeByte(hd[7]);return;case`bigint`:{let t=e;for(t<0n?(t=-t,this.update(dd)):this.update(ud);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}},_d=X(),vd=X(),yd=X(),bd=X(),xd=X(),Sd=X(),Cd=X(),wd=X(),Td=X(),Ed=X(),Dd=X(),Od=X(),kd=X(),Ad=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function jd(e){let t=e[Symbol.toStringTag];return typeof t==`string`&&Ad.has(t)}var Md=128,Nd=new WeakMap;function Pd(e){let t=new gd;return Bd(t,e),t.digest()}function Fd(e){let t=Nd.get(e);if(t!==void 0)return t;let n;if(e instanceof Date)n=Id(e);else if(typeof Buffer<`u`&&e instanceof Buffer||e instanceof Uint8Array)if(e.byteLength<=Md)n=Ld(e);else return Ud(e);else if(e instanceof File)return Ud(e);else if(jd(e))n=Rd(e);else{let t=e,r=wd;e instanceof Array&&(r=Td),e instanceof Map&&(r=Ed,t=[...e.entries()]),e instanceof Set&&(r=Dd,t=[...e.entries()]),n=zd(t,r)}return Nd.set(e,n),n}function Id(e){let t=new gd;return t.update(Cd),t.update(e.getTime()),t.digest()}function Ld(e){let t=new gd;t.update(Od),t.update(e.byteLength);for(let n=0;n<e.byteLength;n++)t.writeByte(e[n]);return t.digest()}function Rd(e){let t=new gd;return t.update(kd),t.update(e[Symbol.toStringTag]),t.update(e.toString()),t.digest()}function zd(e,t){let n=new gd;n.update(t);let r=Object.keys(e);r.sort(Wd);for(let t of r)n.update(xd),n.update(t),Bd(n,e[t]);return n.digest()}function Bd(e,t){if(t===null){e.update(yd);return}switch(typeof t){case`undefined`:e.update(bd);return;case`boolean`:e.update(t?_d:vd);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(Vd(t));return;case`function`:e.update(Ud(t));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof t} which is not supported`)}}function Vd(e){let t=Nd.get(e);return t===void 0&&(t=Fd(e)),t}var Hd=1;function Ud(e){let t=Nd.get(e);return t===void 0&&(t=Hd^Sd,Hd++,Nd.set(e,t)),t}function Wd(e,t){return e.localeCompare(t)}var Gd=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 td(n,this.#e),td(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`${rd.getStringId(t)}|${rd.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):rd.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 $u(()=>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?Pd(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;td(this.#e,n)}add(e,t){t!==0&&this.#e.push([e,t])}getInner(){return this.#e}},Kd=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}},qd=class{#e=[];sendData(e){e instanceof Gd||(e=new Gd(e));for(let t of this.#e)t.unshift(e)}newReader(){let e=[];return this.#e.push(e),new Kd(e)}},Jd=class{constructor(e,t,n){this.id=e,this.inputs=t,this.output=n}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}},Yd=class extends Jd{constructor(e,t,n){super(e,[t],n),this.id=e}inputMessages(){return this.inputs[0].drain()}},Xd=class extends Jd{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()}},Zd=class extends Yd{run(){for(let e of this.inputMessages())this.output.sendData(this.inner(e))}},Qd=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 qd;return new ef(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()}},$d=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)}},ef=class extends $d{sendData(e){this.writer.sendData(e)}},tf=class extends Yd{run(){let e=this.inputMessages();if(e.length===0)return;let t=new Gd;for(let n of e)t.extend(n);let n=t.consolidate();n.getInner().length>0&&this.output.sendData(n)}};function nf(){return e=>{let t=new $d(e.graph,new qd),n=new tf(e.graph.getNextOperatorId(),e.connectReader(),t.writer);return e.graph.addOperator(n),t}}var rf=Symbol(`NO_PREFIX`),af=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=cf(e),r=this.get(n);if(lf(r)){let[i,a]=r;if(cf(i)!==n)throw Error(`Mismatching prefixes, this should never happen`);if(i===e||Pd(i)===Pd(e)){let r=a+t;r===0?this.delete(n):this.set(n,[e,r])}else{let a=new of;a.set(Pd(i),r),a.set(Pd(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}},of=class extends Map{addValue(e,t){if(t===0)return this.size===0;let n=Pd(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}},sf=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(lf(t))yield t;else if(t===void 0)return;else if(t instanceof of)for(let e of t.values())yield e;else for(let e of t.values())if(lf(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(lf(a)){this.#n(e,a,n,r);return}if(a instanceof of){let i=cf(n);if(i!==rf){let n=new af;n.set(rf,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=cf(n),s=cf(i);if(s===o&&(i===n||Pd(i)===Pd(n))){let t=a+r;t===0?this.#e.delete(e):this.#e.set(e,[n,t]);return}if(s===rf&&o===rf){let a=new of;a.set(Pd(i),t),a.set(Pd(n),[n,r]),this.#e.set(e,a)}else{let a=new af;if(s===o){let e=new of;e.set(Pd(i),t),e.set(Pd(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 Gd(t)}};function cf(e){return Array.isArray(e)&&(typeof e[0]==`string`||typeof e[0]==`number`||typeof e[0]==`bigint`)?e[0]:rf}function lf(e){return Array.isArray(e)}var uf=class extends Yd{#e=new sf;#t=new sf;#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 Gd(t))}};function df(e){return t=>{let n=new $d(t.graph,new qd),r=new uf(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var ff=class extends Yd{#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=Pd(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([[Pd(this.#e(i)),i[1]],1]):e>0&&r<=0&&t.push([[Pd(this.#e(i)),i[1]],-1])}t.length>0&&this.output.sendData(new Gd(t))}};function pf(e=e=>e){return t=>{let n=new $d(t.graph,new qd),r=new ff(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var mf=class extends Zd{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.filter(this.#e)}};function hf(e){return t=>{let n=new $d(t.graph,new qd),r=new mf(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var gf=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function _f(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)+_f(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]+_f(e.slice(1),null,n)}function vf(e){if(e.length!==yf(e[0]))throw Error(`invalid integer part of order key: `+e)}function yf(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 bf(e){let t=yf(e[0]);if(t>e.length)throw Error(`invalid order key: `+e);return e.slice(0,t)}function xf(e,t){if(e===`A`+t[0].repeat(26))throw Error(`invalid order key: `+e);let n=bf(e);if(e.slice(n.length).slice(-1)===t[0])throw Error(`invalid order key: `+e)}function Sf(e,t){vf(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 Cf(e,t){vf(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 wf(e,t,n=gf){if(e!=null&&xf(e,n),t!=null&&xf(t,n),e!=null&&t!=null&&e>=t)throw Error(e+` >= `+t);if(e==null){if(t==null)return`a`+n[0];let e=bf(t),r=t.slice(e.length);if(e===`A`+n[0].repeat(26))return e+_f(``,r,n);if(e<t)return e;let i=Cf(e,n);if(i==null)throw Error(`cannot decrement any more`);return i}if(t==null){let t=bf(e),r=e.slice(t.length);return Sf(t,n)??t+_f(r,null,n)}let r=bf(e),i=e.slice(r.length),a=bf(t),o=t.slice(a.length);if(r===a)return r+_f(i,o,n);let s=Sf(r,n);if(s==null)throw Error(`cannot increment any more`);return s<t?s:r+_f(i,null,n)}function Tf(e,t){return[e,t]}function Ef(e){return e[0]}function Df(e){return e[1]}function Of(e){return([t,n],[r,i])=>{let a=e(n,i);return a===0?od(t,r):a}}var kf=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}=id(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=Tf(e,wf(n===0?null:Df(this.#e[n-1]),n===this.#e.length?null:Df(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 nd(this.#e,Tf(e,``),(e,t)=>this.#t(Ef(e),Ef(t)))}},Af=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 kf))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 jf(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],1])}}function Mf(e,t){if(e){let[[n,r],i]=e;t.push([[n,[r,i]],-1])}}var Nf=class extends Yd{#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=Of(r),i.setSizeCallback?.(()=>this.#a()),i.setWindowFn?.(this.#c.bind(this))}createTopK(e,t,n){return new kf(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 Af(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=>jf(e,n)),t.moveOuts.forEach(e=>Mf(e,n)),t.changes&&(r=!0)}r&&this.output.sendData(new Gd(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 Gd(e))}#l(e,t,n,r){let i=this.#t(e,t),a=this.#o(i),o=a.processElement(e,t,n);jf(o.moveIn,r),Mf(o.moveOut,r),this.#s(i,a)}};function Pf(e,t){return n=>{let r=new $d(n.graph,new qd),i=new Nf(n.graph.getNextOperatorId(),n.connectReader(),r.writer,e,t);return n.graph.addOperator(i),r}}var Ff=class extends Xd{#e=new sf;#t=new sf;#n;constructor(e,t,n,r,i=`inner`){super(e,t,n,r),this.#n=i}run(){let e=sf.fromMultiSets(this.inputAMessages()),t=sf.fromMultiSets(this.inputBMessages());if(e.size===0&&t.size===0)return;let n=new Gd;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 If(e,t=`inner`){return n=>{if(n.graph!==e.graph)throw Error(`Cannot join streams from different graphs`);let r=new $d(n.graph,new qd),i=new Ff(n.graph.getNextOperatorId(),n.connectReader(),e.connectReader(),r.writer,t);return n.graph.addOperator(i),r}}var Lf=class extends Zd{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return e.map(this.#e)}};function Z(e){return t=>{let n=new $d(t.graph,new qd),r=new Lf(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Rf=class extends Yd{#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 zf(e){return t=>{let n=new $d(t.graph,new qd),r=new Rf(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Bf=class extends Zd{#e;constructor(e,t,n,r){super(e,t,n),this.#e=r}inner(e){return this.#e(e),e}};function Vf(e){return t=>{let n=new $d(t.graph,new qd),r=new Bf(t.graph.getNextOperatorId(),t.connectReader(),n.writer,e);return t.graph.addOperator(r),n}}var Hf=class extends Yd{#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,Of(r));this.#e=new Af(s),i.setSizeCallback?.(()=>this.#e.size),i.setWindowFn?.(this.moveTopK.bind(this))}createTopK(e,t,n){return new kf(e,t,n)}moveTopK({offset:e,limit:t}){let n=[],r=this.#e.move({offset:e,limit:t});r.moveIns.forEach(e=>jf(e,n)),r.moveOuts.forEach(e=>Mf(e,n)),r.changes&&this.output.sendData(new Gd(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 Gd(e))}processElement(e,t,n,r){let i=this.#e.processElement(e,t,n);jf(i.moveIn,r),Mf(i.moveOut,r)}};function Uf(e,t){let n=t||{};return t=>{let r=new $d(t.graph,new qd),i=new Hf(t.graph.getNextOperatorId(),t.connectReader(),r.writer,e,n);return t.graph.addOperator(i),r}}function Wf(e){return`pipe`in e}function Gf(e,t={}){let n=Object.fromEntries(Object.entries(t).filter(([e,t])=>!Wf(t)));return Object.fromEntries(Object.entries(t).filter(([e,t])=>Wf(t))),t=>{let r=`__original_key__`;return t.pipe(Z(t=>{let i=e(t),a=sd(i),o={};o[r]=i;for(let[e,r]of Object.entries(n))o[e]=r.preMap(t);return[a,o]})).pipe(df(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(Z(([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 Kf(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 qf(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 Jf(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 Yf(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 Xf(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 Zf(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 Qf(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 $f={sum:Kf,count:qf,avg:Jf,min:Yf,max:Xf,median:Zf,mode:Qf};function ep(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(Pf((t,n)=>s(e(t),e(n)),{limit:n,offset:r,setSizeCallback:i,setWindowFn:a,groupKeyFn:o}),nf())}function tp(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}),nf())}function np(e,t){return tp(Uf,e,t)}var rp=`__virtual_synced__`,ip=`__virtual_has_local__`;function ap(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:op,count:sp,avg:cp,min:lp,max:up}=$f;function dp(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`||_p(i))continue;let t=r.findIndex(e=>pp(i,e));if(t===-1)throw new Yl(e);n.set(e,t)}return{selectToGroupByIndex:n,groupByExpressions:r}}function fp(e,t,n,r,i,a,o){let s={[rp]:{preMap:([,e])=>ap(e).synced,reduce:e=>{for(let[t,n]of e)if(!t&&n>0)return!1;return!0}},[ip]:{preMap:([,e])=>ap(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]=mp(n);else if(_p(n)){let{transformed:r,extracted:i}=vp(n,l);for(let[e,n]of Object.entries(i))t[e]=mp(n);c[e]=Y(r)}}let u=o?([,e])=>({__singleGroup:!0,__correlationKey:e?.[o]?.__correlationKey}):()=>({__singleGroup:!0});if(e=e.pipe(Gf(u,t)),e=e.pipe(Z(([,e])=>{let t={...e.$selected||{}};if(r){for(let[n,i]of Object.entries(r))i.type===`agg`&&(t[n]=e[n]);gp(t,e,c)}let n=o?e.__correlationKey:void 0,i=n===void 0?`single_group`:`single_group_${sd(n)}`,s={...e,$selected:t},l=e[rp],u=e[ip];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=Y(hp(Mc(t),r||{},`$selected`));e=e.pipe(hf(([,e])=>Cu(n({$selected:e.$selected}))))}if(i&&i.length>0)for(let t of i)e=e.pipe(hf(([,e])=>Cu(t({$selected:e.$selected}))));return e}let c=dp(t,r),l=t.map(e=>Y(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]=mp(t);else if(_p(t)){let{transformed:n,extracted:r}=vp(t,p);for(let[e,t]of Object.entries(r))d[e]=mp(t);f[e]=Y(n)}}if(e=e.pipe(Gf(u,d)),e=e.pipe(Z(([,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}`]}gp(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]:sd(l),d={...e,$selected:i},p=e[rp],m=e[ip];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=Y(hp(Mc(t),r||{}));e=e.pipe(hf(([,e])=>n({$selected:e.$selected})))}if(i&&i.length>0)for(let t of i)e=e.pipe(hf(([,e])=>Cu(t({$selected:e.$selected}))));return e}function pp(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)=>pp(e,t.args[n]));case`agg`:return e.name===t.name&&e.args?.length===t.args?.length&&(e.args||[]).every((e,n)=>pp(e,t.args[n]));default:return!1}}function mp(e){let t=Y(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 op(n);case`count`:return sp(i);case`avg`:return cp(n);case`min`:return lp(r);case`max`:return up(r);default:throw new Xl(e.name)}}function hp(e,t,n=`$selected`){switch(e.type){case`agg`:{let r=e;for(let[e,i]of Object.entries(t))if(i.type===`agg`&&yp(r,i))return new q([n,e]);throw new Zl(r.name)}case`func`:{let n=e,r=n.args.map(e=>hp(e,t));return new Dc(n.name,r)}case`ref`:return e;case`val`:return e;default:throw new Ql(e.type)}}function gp(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 _p(e){return Ac(e)?e.type===`agg`?!0:e.type===`func`&&`args`in e?e.args.some(e=>_p(e)):!1:!1}function vp(e,t){if(e.type===`agg`){let n=`__agg_${t.value++}`;return{transformed:new q([`$selected`,n]),extracted:{[n]:e}}}if(e.type===`func`){let n={},r=e.args.map(e=>{let r=vp(e,t);return Object.assign(n,r.extracted),r.transformed});return{transformed:new Dc(e.name,r),extracted:n}}return{transformed:e,extracted:{}}}function yp(e,t){return e.name===t.name&&e.args.length===t.args.length&&e.args.every((e,n)=>pp(e,t.args[n]))}function bp(e,t,n,r,i,a,o,s,c,l){let u=n.map(e=>({compiledExpression:Y(hp(e.expression,r,`$selected`)),compareOptions:xp(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=hu(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 hu(n.compareOptions)(e,t)}return gu(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=Ic(e,d,i);if(n){r=n.collection;let i=n.path[0],a=xp(u,r);if(i){let e=hu(a);Xu(i,n.path,r,a,e)}if(o=Y(new q(n.path),!0),t=Fu(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=Ic(e,n,i);return Y(r?new q(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(ep(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(np(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 xp(e,t){return e.compareOptions.stringSort===void 0?{...t.compareOptions,direction:e.compareOptions.direction,nulls:e.compareOptions.nulls}:e.compareOptions}function Sp(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?Cp(t.where):void 0,r=Tp(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=Ru(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(Cp(r))}catch(r){console.warn(`${e.id?`[${e.id}] `:``}Error processing where clause, falling back to full scan:`,r);let i=Cp(t.where);return t.optimizedOnly?void 0:n(i)}}function Cp(e){let t=wu(e);return e=>{try{return Cu(t(e))}catch{return!1}}}function wp(e,t){let n=Cp(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 Tp(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=xp(i,e);Xu(t[0],t,e,o);let s=Fu(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=hu(r.compareOptions)(Ep(e.value,r.expression),Ep(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 Ep(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 wu(t)(e)}var Dp=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=od(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=od(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)}},Op=`__tanstack_db_direct`,kp=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:ju(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&&au(f.value,n)||r!==void 0&&au(f.value,r))&&(m=!0);let h=c&&n!==void 0&&r!==void 0&&au(n,r);if(!(m&&!h))if(n===void 0&&r!==void 0){let e=p.get(t);if(e){let n=e.value,i=ju(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&&(!au(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 Dp((e,t)=>e.compareCreatedAt(t)),this.syncedData=new Dp(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[Op]===!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 Ap(){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 jp(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 Mp(e){let t=jp(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 Q(e){if(Np(e))return new q(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 Ec(e)}function Np(e){return e&&typeof e==`object`&&e.__refProxy===!0}function Pp(e,t){return new Dc(`eq`,[Q(e),Q(t)])}function Fp(e,t){return new Dc(`gt`,[Q(e),Q(t)])}function Ip(e,t){return new Dc(`gte`,[Q(e),Q(t)])}function Lp(e,t){return new Dc(`lt`,[Q(e),Q(t)])}function Rp(e,t,...n){return new Dc(`and`,[e,t,...n].map(e=>Q(e)))}function zp(e,t,...n){return new Dc(`or`,[e,t,...n].map(e=>Q(e)))}function Bp(e,t){return new Dc(`in`,[Q(e),Q(t)])}var Vp=class{constructor(e){this.query=e,this.__brand=`ToArrayWrapper`}},Hp=class{constructor(e){this.query=e,this.__brand=`ConcatToArrayWrapper`}},Up=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 Wp(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`?Fp:Lp)(n,new Ec(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(Pp(r.expression,new Ec(i)))}let s=(i.compareOptions.direction===`asc`?Fp:Lp)(i.expression,new Ec(a));if(o.length===0)n.push(s);else{let e=[...o,s];n.push(e.reduce((e,t)=>Rp(e,t)))}}return n.length===1?n[0]:n.reduce((e,t)=>zp(e,t))}var Gp=class extends Up{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&&Zu(n.whereExpression,this.collection);let r=e=>{t(e),this.trackSentKeys(e)};this.callback=r,this.filteredCallback=n.whereExpression?wp(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=Rp(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?Cp(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:Pp(n,new Ec(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`?Y(new q(_.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=Wp(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=Rp(Ip(r,new Ec(i)),Lp(r,new Ec(e)))}else a=Pp(r,new Ec(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()}},Kp=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=Q(n(Ap())));let a=new Gp(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 Jc;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}},qp=e=>setTimeout(()=>{e({didTimeout:!0,timeRemaining:()=>50})},0),Jp=e=>{clearTimeout(e)},Yp=typeof window<`u`&&`requestIdleCallback`in window?(e,t)=>window.requestIdleCallback(e,t):(e,t)=>qp(e),Xp=typeof window<`u`&&`cancelIdleCallback`in window?e=>window.cancelIdleCallback(e):Jp,Zp=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)}};Zp.instance=null;var Qp=Zp,$p=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 Kc(e,t,this.id)}setStatus(e,t=!1){if(e===`ready`&&!t)throw new Wc(`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 Gc(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)||Qp.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Qp.getInstance().cancel(this),this.idleCallbackId!==null&&(Xp(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Xp(this.idleCallbackId),this.idleCallbackId=Yp(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(),Qp.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&&(Xp(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}},em=Symbol(`liveQueryInternal`),tm=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=nm(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 hl;if(t.committed)throw new gl;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&&au(t,e.value))r=`update`;else{let e=this.config.utils[em];throw new $c(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 _l;if(e.committed)throw new vl;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 hl;if(e.committed)throw new gl;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 zc(`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 hl;if(e.committed)throw new gl;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 qc);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 $l(this.id,e);throw t.cause=e,t.stack=e.stack,t}else throw new $l(this.id,e)})}this.preloadPromise=null}};function nm(e){if(typeof e==`function`)return{cleanup:e};if(typeof e==`object`)return e}var rm=1;function im(e,t){return e===t?0:e<t?-1:1}function am(e){return{kind:`constructor`,...e.name?{name:e.name}:{}}}function om(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=>om(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=>om(e)??null).sort((e,t)=>im(sm(e),sm(t)))};if(e instanceof Map)return{__type:`map`,entries:Array.from(e.entries()).map(([e,t])=>({key:om(e)??null,value:om(t)??null})).sort((e,t)=>im(sm(e.key),sm(t.key)))};if(e instanceof RegExp)return{__type:`regexp`,value:e.toString()};let t={},n=Object.entries(e).sort(([e],[t])=>im(e,t));for(let[e,r]of n){let n=om(r);n!==void 0&&(t[e]=n)}return t}function sm(e){return e===null?`null`:Array.isArray(e)?`[${e.map(sm).join(`,`)}]`:typeof e==`object`?`{${Object.keys(e).sort((e,t)=>im(e,t)).map(t=>`${JSON.stringify(t)}:${sm(e[t])}`).join(`,`)}}`:JSON.stringify(e)}function cm(e,t,n,r,i){let a=am(r),o=om(t)??null,s=om(i);return{signatureVersion:rm,signature:sm(om({signatureVersion:rm,expression:o,options:s??null})??null),indexId:e,name:n,expression:t,resolver:a,...s===void 0?{}:{options:s}}}function lm(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>lm(e));let t={};for(let[n,r]of Object.entries(e))t[n]=lm(r);return t}function um(e){return JSON.parse(JSON.stringify(e))}var dm=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=Q(e(Ap())),i=t.indexType??this.defaultIndexType;if(!i)throw new zc(`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=cm(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:um(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:lm(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()}},fm=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),pm=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),mm=new Set([`set`,`delete`,`clear`,`add`]),hm=new Set([`entries`,`keys`,`values`,`forEach`]);function gm(e){return typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof RegExp)&&!cu(e)}function _m(e,t,n,r){if(fm.has(e))return function(...i){let a=i[0];if(typeof a!=`function`)return t.apply(n.copy_,i);let o=(e,t)=>{if(gm(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 vm(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(gm(i)){let{proxy:n}=t(i,{tracker:e,prop:String(r)});a=n}return r++,{done:!1,value:a}},[Symbol.iterator](){return this}}}}function ym(e,t,n){return function(...r){let i=e.apply(t.copy_,r);return n(t),i}}function bm(e,t,n,r,i,a,o){if(hm.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 $(...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 xm(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]=xm(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,xm(e,t))}),n}if(e instanceof Set){let n=new Set;return t.set(e,n),e.forEach(e=>{n.add(xm(e,t))}),n}if(cu(e))return e;let n={};t.set(e,n);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=xm(e[r],t));let r=Object.getOwnPropertySymbols(e);for(let i of r)n[i]=xm(e[i],t);return n}var Sm=0;function Cm(){return Sm+=1,Sm}function wm(e,t){let n=new Map;function r(e,t){if($(`Object ID:`,e.constructor.name),n.has(e))return n.get(e);{let r=wm(e,t);return n.set(e,r),r}}let i=new Map,a={copy_:xm(e),originalObject:xm(e),proxyCount:Cm(),modified:!1,assigned_:{},parent:t,target:e};$(`createChangeProxy called for target`,e,a.proxyCount);function o(e){e.modified||=!0,e.parent&&($(`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($(`checkIfReverted called with assigned keys:`,Object.keys(e.assigned_)),Object.keys(e.assigned_).length===0&&Object.getOwnPropertySymbols(e.assigned_).length===0)return $(`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($(`Checking property ${String(t)}, current:`,n,`original:`,r),!au(n,r))return $(`Property ${String(t)} is different, returning false`),!1}else if(e.assigned_[t]===!1)return $(`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(!au(t,r))return $(`Symbol property is different, returning false`),!1}else if(e.assigned_[n]===!1)return $(`Symbol property was deleted, returning false`),!1;return $(`All properties match original values, returning true`),!0}function c(e,t){$(`checkParentStatus called for child prop:`,t);let n=s(e);$(`Parent checkIfReverted returned:`,n),n&&($(`Parent is fully reverted, clearing tracking`),e.modified=!1,e.assigned_={},e.parent&&($(`Continuing up the parent chain`),c(e.parent.tracker,e.parent.prop)))}function l(e){if($(`createObjectProxy`,e),i.has(e))return $(`proxyCache found match`),i.get(e);let n=new Proxy(e,{get(e,t){$(`get`,e,t);let n=a.copy_[t]??a.originalObject[t],s=a.originalObject[t];if($(`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(pm.has(e))return ym(n,a,o);let i=_m(e,n,a,r);if(i)return i;if(t===Symbol.iterator)return vm(a,r)}if(e instanceof Map||e instanceof Set){let i=t.toString();if(mm.has(i))return ym(n,a,o);let s=bm(i,t,n,e,a,r,o);if(s)return s}return n.bind(e)}if(gm(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($(`set called for property ${String(n)}, current:`,i,`new:`,r),au(i,r))$(`Value unchanged, not tracking`);else{let e=a.originalObject[n],i=au(r,e);if($(`value:`,r,`original:`,e,`isRevertToOriginal:`,i),i){$(`Reverting property ${String(n)} to original value`),delete a.assigned_[n.toString()],$(`Updating copy with original value for ${String(n)}`),a.copy_[n]=xm(e),$(`Checking if all properties reverted`);let r=s(a);$(`All reverted:`,r),r?($(`All properties reverted, clearing tracking`),a.modified=!1,a.assigned_={},t&&($(`Updating parent for property:`,t.prop),c(t.tracker,t.prop))):($(`Some properties still changed, keeping modified flag`),a.modified=!0)}else $(`Setting new value for property ${String(n)}`),a.copy_[n]=r,a.assigned_[n.toString()]=!0,$(`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]=xm(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){$(`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($(`getChanges called, modified:`,a.modified),$(a),!a.modified)return $(`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 $(`Returning copy:`,e),e}}}function Tm(e){let t=e.map(e=>wm(e));return{proxies:t.map(e=>e.proxy),getChanges:()=>t.map(e=>e.getChanges())}}function Em(e,t){let{proxy:n,getChanges:r}=wm(e);return t(n),r()}function Dm(e,t){let{proxies:n,getChanges:r}=Tm(e);return t(n),r()}function Om(){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 km(e){return typeof e==`object`&&!!e&&typeof e.hasPendingGraphRun==`function`}var Am=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=km(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))}},jm=[],Mm=[],Nm=0;function Pm(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 Fm(e){let t=new Bm(e);return jm.push(t),t}function Im(){if(Mm.length>0)return Mm.slice(-1)[0]}function Lm(e){Am.clear(e.id),Mm.push(e)}function Rm(e){try{Am.flush(e.id)}finally{Mm=Mm.filter(t=>t.id!==e.id)}}function zm(e){let t=jm.findIndex(t=>t.id===e.id);t!==-1&&jm.splice(t,1)}var Bm=class{constructor(e){if(e.mutationFn===void 0)throw new dl;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=Om(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Nm++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e===`completed`||e===`failed`)&&zm(this)}mutate(e){if(this.state!==`pending`)throw new fl;Lm(this);try{e()}finally{Rm(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=Pm(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 pl;if(this.setState(`failed`),!t){let e=new Set;this.mutations.forEach(t=>e.add(t.globalKey));for(let t of jm)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 ml;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}},Vm=class{constructor(e,t){this.insert=(e,t)=>{this.lifecycle.validateCollectionUsable(`insert`);let n=this.state,r=Im();if(!r&&!this.config.onInsert)throw new sl;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 Qc(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=Fm({metadata:{[Op]:!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=Im();if(!r&&!this.config.onDelete)throw new ll;if(Array.isArray(e)&&e.length===0)throw new il;let i=Array.isArray(e)?e:[e],a=[];for(let e of i){if(!this.state.has(e))throw new al(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=Fm({autoCommit:!0,metadata:{[Op]:!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 Hc}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 Uc;if(`issues`in a&&a.issues)throw new Rc(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 Uc;if(`issues`in i&&i.issues)throw new Rc(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 Xc(t):new Zc(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 el;let r=this.state;this.lifecycle.validateCollectionUsable(`update`);let i=Im();if(!i&&!this.config.onUpdate)throw new cl;let a=Array.isArray(e),o=a?e:[e];if(a&&o.length===0)throw new tl;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 nl(e);return t}),u;u=a?Dm(l,s):[Em(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 rl(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=Fm({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=Fm({metadata:{[Op]:!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}},Hm=class extends Up{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 Um(e){let t=new Wm(e);return e.utils?t.utils=e.utils:t.utils={},t}var Wm=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 Bc;if(!e.sync)throw new Vc;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 zc(`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 Kp,this._events=new Hm,this._indexes=new dm,this._lifecycle=new $p(e,this.id),this._mutations=new Vm(e,this.id),this._state=new kp(e),this._sync=new tm(e,this.id),this.comparisonOpts=Gm(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 Sp(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 Gm(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 Km(e){let t=qm(e),n=e,r,i=0;for(;i<10&&!au(n,r);)r=n,n=Xm(n),i++;return{optimizedQuery:Qm(n),sourceWhereClauses:t}}function qm(e){let t=new Map;if(!e.where||e.where.length===0)return t;let n=ih(th(e.where).map(e=>rh(e))),r=Ym(e);for(let[i,a]of n.singleSource)Jm(e,i)&&!r.has(i)&&t.set(i,a);return t}function Jm(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 Ym(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 Xm(e){return Zm({...e,from:e.from.type===`queryRef`?new Tc(Xm(e.from.query),e.from.alias):e.from,join:e.join?.map(e=>({...e,from:e.from.type===`queryRef`?new Tc(Xm(e.from.query),e.from.alias):e.from}))})}function Zm(e){if(!e.where||e.where.length===0)return e;if(!e.join||e.join.length===0){if(e.where.length>1){let t=vh(th(e.where));return{...e,where:[t]}}return e}let t=ah(e,ih(th(e.where.filter(e=>!Nc(e))).map(e=>rh(e)))),n=e.where.filter(e=>Nc(e));return n.length>0&&(t.where=[...t.where||[],...n]),t}function Qm(e){return{...e,from:$m(e.from),join:e.join?.map(e=>({...e,from:$m(e.from)}))}}function $m(e){if(e.type===`collectionRef`)return e;let t=Qm(e.query);if(eh(t)){let n=$m(t.from);return n.type===`collectionRef`?new wc(n.collection,e.alias):new Tc(n.query,e.alias)}return new Tc(t,e.alias)}function eh(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 th(e){let t=[];for(let n of e){let e=jc(n);t.push(...nh(e))}return t}function nh(e){if(e.type===`func`&&e.name===`and`){let t=[];for(let n of e.args)t.push(...nh(n));return t}else return[e]}function rh(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 ih(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,vh(n));return{singleSource:r,multiSource:n.length>0?vh(n):void 0}}function ah(e,t){let n=new Set,r=Ym(e),i=new Map;for(let[e,n]of t.singleSource)r.has(e)||i.set(e,n);let a=sh(e.from,i,n),o=e.join?e.join.map(e=>({...e,from:sh(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(Pc(r)):s.push(r);let l=s.length>1?[vh(s.flatMap(e=>nh(jc(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 oh(e){return{from:e.from.type===`collectionRef`?new wc(e.from.collection,e.from.alias):new Tc(oh(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 wc(e.from.collection,e.from.alias):new Tc(oh(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 sh(e,t,n){let r=t.get(e.alias);if(!r)return e.type===`collectionRef`?new wc(e.collection,e.alias):new Tc(oh(e.query),e.alias);if(e.type===`collectionRef`){let t={from:new wc(e.collection,e.alias),where:[r]};return n.add(e.alias),new Tc(t,e.alias)}if(!ph(e.query,r,e.alias)||_h(e.query,r,e.alias))return new Tc(oh(e.query),e.alias);let i=e.query.where||[],a={...oh(e.query),where:[...i,r]};return n.add(e.alias),new Tc(a,e.alias)}function ch(e,t,n){return e.select?mh(e.select)||gh(e.select,t,n):!1}function lh(e){return e.groupBy&&e.groupBy.length>0}function uh(e){return e.having&&e.having.length>0}function dh(e){return e.orderBy&&e.orderBy.length>0&&(e.limit!==void 0||e.offset!==void 0)}function fh(e){return e.fnSelect||e.fnWhere&&e.fnWhere.length>0||e.fnHaving&&e.fnHaving.length>0}function ph(e,t,n){return!(ch(e,t,n)||lh(e)||uh(e)||dh(e)||fh(e))}function mh(e){for(let t of Object.values(e))if(typeof t==`object`){let e=t;if(e.type===`agg`||!(`type`in e)&&mh(e))return!0}return!1}function hh(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(...hh(n));break}return t}function gh(e,t,n){let r=new Set;for(let[t,n]of Object.entries(e))t.startsWith(`__SPREAD_SENTINEL__`)||n instanceof q||r.add(t);let i=hh(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 _h(e,t,n){let r=hh(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 q)||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 vh(e){if(e.length===0)throw new tu;return e.length===1?e[0]:new Dc(`and`,e)}function yh(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=bh(y,e,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v);return y}function bh(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}=Ch(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 zl(r);if(!w)throw new zl(S);let{activeSource:T,lazySource:E}=Th(t.type,C,w),D=Object.keys(n),{mainExpr:O,joinedExpr:k}=xh(t.left,t.right,D,b),A=Y(O),j=Y(k),M=e.pipe(Z(([e,t])=>[yu(A(t)),[e,t]])),N=x.pipe(Z(([e,t])=>{let n={[b]:t};return[yu(j(n)),[e,n]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new Vl(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=Ic(m,T===`main`?k:O,E),r=n.collection,a=n.path[0];a&&Xu(a,n.path,r);let o=t.pipe(Vf(t=>{let i=_[e]||e,a=l[i];if(!a)throw new nu(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 q(n.path);if(!a.requestSnapshot({where:Bp(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(If(N,t.type),wh(t.type))}function xh(e,t,n,r){let i=n.filter(e=>e!==r),a=Sh(e),o=Sh(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 Ul:a===o?new Hl(a):i.includes(a)?o===r?new Kl:new Gl(r):new Wl(a)}function Sh(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=Sh(n);e&&t.add(e)}return t.size===1?Array.from(t)[0]:null}default:return null}}function Ch(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 Nl(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(Z(e=>{let[t,[n,r]]=e;return[t,n]}));return{alias:e.alias,input:v,collectionId:m.collectionId}}default:throw new ql(e.type)}}function wh(e){return function(t){return t.pipe(hf(t=>{let[n,[r,i]]=t,a=r?.[1],o=i?.[1];return e===`inner`?!!(a&&o):e===`left`?!!a:e===`right`?!!o:!0}),Z(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 Th(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 Eh(e){return e instanceof Ec?e.value:e}function Dh(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]=Eh(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]=Eh(n)}else{let e=t[n];(typeof e!=`object`||!e)&&(t[n]={}),t=t[n]}}}}function Oh(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]]=Eh(e.compiled(t))}}function kh([e,t],n){let r={};for(let e of n)e.kind===`merge`?Dh(e,t,r):Oh(e,t,r);return[e,{...t,$selected:r}]}function Ah(e,t,n){let r=[];return Nh([],t,r),e.pipe(Z(e=>kh(e,r)))}function jh(e){return e.type===`agg`}function Mh(e){return e&&typeof e==`object`&&!Ac(e)}function Nh(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=Y(s?i:new q(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(Mh(t)){Nh([...e,r],t,n);continue}if(jh(t)||_p(t))n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>null});else{if(t===void 0||!Ac(t)){n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>t});continue}if(t instanceof Ec){let i=t.value;n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:()=>i})}else n.push({kind:`field`,alias:[...e,r].join(`.`),compiled:Y(t)})}}}var Ph=Symbol(`includesRouting`);function Fh(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;Lh(e);let{optimizedQuery:p,sourceWhereClauses:m}=Km(e),h=p;l.set(h,e),Hh(h,e,l);let g={...t},_={},v={},y={},{alias:b,input:x,collectionId:S}=Rh(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(Z(([t,n])=>[Yh(n,e),[t,n]])).pipe(If(u,`inner`)).pipe(hf(([e,[t]])=>t!=null),Z(([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(Z(([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=yh(w,h.join,y,S,b,g,c,l,n,r,i,a,o,s,e,Fh,_,v,m)),h.where&&h.where.length>0)for(let e of h.where){let t=Y(jc(e));w=w.pipe(hf(([e,n])=>Cu(t(n))))}if(h.fnWhere&&h.fnWhere.length>0)for(let e of h.fnWhere)w=w.pipe(hf(([t,n])=>Cu(e(n))));let T=[],E=[];if(h.select){let e=Gh(h.select);e.length>0&&(h={...h,select:{...h.select}});for(let{key:t,subquery:u}of e){let e=Y(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:Y(e)}));d=w.pipe(Z(([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(Z(([t,n])=>[e(n),null]));d=d.pipe(df(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=Wh(u.query,u.childCorrelationField,p);if(y){let e=y.collection,t=y.path,n=t[0];a.add(f),n&&Xu(n,t,e),d=d.pipe(Vf(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 q(t);n.requestSnapshot({where:Bp(a,i)})}))}let b=Fh(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:Y(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})});Jh(h.select,t)}}if(h.distinct&&!h.fnSelect&&!h.select)throw new Ol;if(h.fnSelect&&h.groupBy&&h.groupBy.length>0)throw new kl;w=h.fnSelect?w.pipe(Z(([e,t])=>{let n=h.fnSelect(t);return[e,{...t,$selected:n}]})):h.select?Ah(w,h.select):w.pipe(Z(([e,t])=>{let n=!h.join&&!h.groupBy?t[b]:t;return[e,{...t,$selected:n}]})),E.length>0&&(w=w.pipe(Z(([e,t])=>{let n={};for(let{fieldName:e,getRouting:r}of E)n[e]=r(t);return t.$selected[Ph]=n,[e,t]})));let D=u?b:void 0;if(h.groupBy&&h.groupBy.length>0?w=fp(w,h.groupBy,h.having,h.select,h.fnHaving,S,D):h.select&&Object.values(h.select).some(e=>e.type===`agg`||_p(e))&&(w=fp(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 jl;if(h.fnHaving&&h.fnHaving.length>0&&(!h.groupBy||h.groupBy.length===0))for(let e of h.fnHaving)w=w.pipe(hf(([t,n])=>e(n)));if(h.distinct&&(w=w.pipe(pf(([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:bp(e,w,h.orderBy,h.select||{},n[S],o,s,h.limit,h.offset,t).pipe(Z(([e,[t,n]])=>{let r=t.$selected,i=Vh(Bh(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 Ml;let O={collectionId:S,pipeline:w.pipe(Z(([e,t])=>{let n=t.$selected,r=Vh(Bh(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 Ih(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 Lh(e,t=new Set){let n=Ih(e);for(let e of n)if(t.has(e))throw new Pl(e,Array.from(t));let r=new Set([...t,...n]);if(e.from.type===`queryRef`&&Lh(e.from.query,r),e.join)for(let t of e.join)t.from.type===`queryRef`&&Lh(t.from.query,r)}function Rh(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 Nl(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=Fh(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(Z(e=>{let[t,[n,r]]=e;return[t,Bh(n)]}));return{alias:e.alias,input:_,collectionId:p.collectionId}}default:throw new Fl(e.type)}}function zh(e){return e instanceof Ec||e&&typeof e==`object`&&`type`in e&&e.type===`val`}function Bh(e){return zh(e)?e.value:e}function Vh(e,t){if(!e||typeof e!=`object`)return e;let n=!1;for(let r of Mu)if(e[r]==null&&r in t){n=!0;break}if(!n)return e;for(let n of Mu)e[n]==null&&n in t&&(e[n]=t[n]);return e}function Hh(e,t,n){if(e.from.type===`queryRef`&&t.from.type===`queryRef`&&(n.set(e.from.query,t.from.query),Hh(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),Hh(i.from.query,a.from.query,n))}}function Uh(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 Wh(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 Wh(e,t,n)}return{collection:n,path:[r]}}if(t.path.length>1){let[r,...i]=t.path,a=Uh(e,r);return a?a.type===`queryRef`?Wh(a.query,new q(i),n):{collection:a.collection,path:i}:void 0}}}function Gh(e){let t=[];for(let[n,r]of Object.entries(e))n.startsWith(`__SPREAD_SENTINEL__`)||(r instanceof kc?t.push({key:n,subquery:r}):Kh(r)&&qh(r,n));return t}function Kh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type!=`string`}function qh(e,t){for(let[n,r]of Object.entries(e))if(!n.startsWith(`__SPREAD_SENTINEL__`)){if(r instanceof kc)throw Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${t}.${n}".`);Kh(r)&&qh(r,`${t}.${n}`)}}function Jh(e,t){e[t]=new Ec(null)}function Yh(e,t){let n=e;for(let e of t){if(n==null)return n;n=n[e]}return n}function Xh(e,t){let n=e.type;if(n===`val`)return new Ec(e.value);if(n===`ref`){let n=e.path;if(Array.isArray(n)){if(n[0]===t&&n.length>1)return new q(n.slice(1));if(n.length===1&&n[0]!==void 0)return new q([n[0]])}return new q(Array.isArray(n)?n:[String(n)])}else{let n=[];for(let r of e.args){let e=Xh(r,t);n.push(e)}return new Dc(e.name,n)}}function Zh(e,t){return e.map(e=>{let n=Xh(e.expression,t);return{...e,expression:n}})}var Qh=new WeakMap;function $h(e){return e.utils?.[em]?.getBuilder?.()}function eg(e,t){Qh.set(e,t)}function tg(e){return Qh.get(e)}var ng=class e{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(t,n){let r;try{r=Object.keys(t)}catch{throw new Cl(n,t===null?`null`:`undefined`)}if(Array.isArray(t))throw new Cl(n,`array`);if(r.length!==1)throw r.length===0?new Cl(n,`empty object`):r.every(e=>!isNaN(Number(e)))?new Cl(n,`string`):new bl(n);let i=r[0],a=t[i],o;if(a instanceof Wm)o=new wc(a,i);else if(a instanceof e){let e=a._getQuery();if(!e.from)throw new xl(n);o=new Tc(e,i)}else throw new Sl(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(jp([...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 wl;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(jp(this._getCurrentAliases())),r=Np(n)?Q(n):n;if(!Ac(r))throw new El(rg(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?Mp(n):jp(n)),i=Np(r)?Q(r):r;if(!Ac(i))throw new El(rg(i));let a=this.query.having||[];return new e({...this.query,having:[...a,i]})}select(t){let n=this._getCurrentAliases(),r=t(jp(n));Np(r)&&r.__path.length===1&&(r={[`__SPREAD_SENTINEL__${r.__path[0]}__0`]:!0});let i=og(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?Mp(r):jp(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:Q(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(jp(this._getCurrentAliases())),r=Array.isArray(n)?n.map(e=>Q(e)):[Q(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 Tl;return this.query}};function rg(e){return e===null?`null`:e===void 0?`undefined`:typeof e==`object`?`object`:typeof e}function ig(e){return e===void 0?Q(null):e instanceof Oc||e instanceof Dc||e instanceof q||e instanceof Ec?e:Q(e)}function ag(e){return typeof e==`object`&&!!e&&!Ac(e)&&!e.__refProxy}function og(e,t=[]){if(!ag(e))return ig(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 ng){n[r]=lg(i,r,t,`collection`);continue}if(i instanceof Vp){if(!(i.query instanceof ng))throw Error(`toArray() must wrap a subquery builder`);n[r]=lg(i.query,r,t,`array`);continue}if(i instanceof Hp){if(!(i.query instanceof ng))throw Error(`concat(toArray(...)) must wrap a subquery builder`);n[r]=lg(i.query,r,t,`concat`);continue}n[r]=og(i,t)}return n}function sg(e){let t=[];switch(e.type){case`ref`:t.push(e);break;case`func`:for(let n of e.args??[])t.push(...sg(n));break}return t}function cg(e,t){return sg(typeof e==`object`&&`expression`in e?e.expression:e).some(e=>e.path[0]!=null&&t.includes(e.path[0]))}function lg(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=ug(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=ug(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 Dc(`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)cg(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 sg(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||ag(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=Sc,_={...m,select:{[v]:h}}}return new kc(_,o,s,t,f.length>0?f:void 0,p,r,v)}function ug(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 dg(e){return fg(e(new ng))}function fg(e){return e._getQuery()}function pg(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 kc?r(n.query):gg(n)&&i(n))}return r(e),t}function mg(e){let t=e.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return mg(t.query);throw Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(e)}`)}function hg(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 kc?i(n.query):gg(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 gg(e){return!(typeof e!=`object`||!e||e instanceof kc||`type`in e&&typeof e.type==`string`||e.__refProxy)}function _g(e){let t=typeof e.query==`function`?dg(e.query):fg(e.query);if(e.requireObjectResult&&t.select&&!gg(t.select))throw new Al;return t}function vg(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 Gd(r)),r.length}function*yg(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 bg(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 xg(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 Sg(e,t){let{orderBy:n,limit:r,offset:i}=e,a=r!==void 0&&i!==void 0?r+i:r,o=n?Zh(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 Cg(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=sd({minValues:l??null,offset:s,limit:i});if(n===u)return;let d=Zh(a,r);return{minValues:l,normalizedOrderBy:d,loadRequestKey:u}}var wg=Symbol.for(`@tanstack/db.collection-config-builder`),Tg=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=Xh(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=bg(Array.isArray(e)?e:[...e],this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],i=vg(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=Sg(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=yg(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=Zh(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[wg]??=this.loadMoreIfNeeded.bind(this,t),this.sendChangesToPipeline(e,n[wg])}loadNextItems(e,t){let n=this.getOrderByInfo();if(!n)return;let r=Cg(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=xg(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)}},Eg=0,Dg=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-${++Eg}`,this.query=_g({query:e.query,requireObjectResult:!0}),this.collections=pg(this.query);let t=hg(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=Og(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??mg(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),[em]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){if(!this.windowFn)throw new iu;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??Im()?.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;Am.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=Am.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 Qd,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(e=>[e,this.graphCache.newInput()]));let e=Fh(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 ru(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(zf(e=>{let n=e.getInner();t.messagesCount+=n.length,n.reduce(Hg,s)}));let c=this.setupIncludesOutput(this.includesCache,t);return t.flushPendingChanges=()=>{let t=s.size>0,i=Bg(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,zg(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(zf(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Lg(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=jg(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=tg(i);a&&a!==this?(this.aliasDependencies[n]=[a],this.builderDependencies.add(a)):this.aliasDependencies[n]=[];let o=new Tg(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 Og(e){return(t,n)=>{let r=e.get(t),i=e.get(n);return r&&i?r<i?-1:+(r>i):0}}function kg(e){return e.materialization!==`collection`}function Ag(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 jg(e,t){return e.map(e=>{let n=new Map;e.pipeline.pipe(zf(e=>{let r=e.getInner();t.messagesCount+=r.length;for(let[[e,t],i]of r){let[r,a,o,s]=t,c=Lg(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=jg(e.childCompilationResult.includes,t)),r})}function Mg(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 Ng(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 Pg(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[Ph]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Lg(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[Ph]?.[r.compilationResult.fieldName],a=n?.correlationKey,o=Lg(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 Fg(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 Ig(e){for(let t of e)if(t.buffer.size>0||t.nestedSetups&&Ig(t.nestedSetups))return!0;return!1}function Lg(e,t){return t==null?e:JSON.stringify([e,t])}function Rg(e,t,n,r,i){let a=new WeakMap,o=r?new WeakMap:null,s=null,c=o?Og(o):void 0,l={collection:Um({id:`__child-collection:${e}-${t}-${sd(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=Mg(i)),l}function zg(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[Ph]?.[a.fieldName],s=o?.correlationKey,c=Lg(s,o?.parentContext??null);if(s!=null){if(!a.childRegistry.has(c)){let e=Rg(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=Ag(a,a.childRegistry.get(c));r[a.fieldName]=o;let s=t.get(e);s&&s!==r&&(s[a.fieldName]=o)}}}let e=kg(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=Rg(n,a.fieldName,e,a.hasOrderBy,a.nestedSetups),a.childRegistry.set(e,i)),a.materialization===`collection`&&Vg(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()}Pg(a,e,r),o.set(e,{entry:i,childChanges:r})}a.pendingChildChanges.clear()}let s=Ng(a);for(let[,{entry:e,childChanges:t}]of o)e.includesStates&&zg(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&&zg(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&&Bg(t.includesStates)&&(zg(t.includesStates,t.collection,t.collection.id,null,t.syncMethods),c.add(e));let l=kg(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]=Ag(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[Ph]?.[a.fieldName],r=n?.correlationKey,i=Lg(r,n?.parentContext??null);if(r!=null){let t=a.correlationToParentKeys.get(i);t&&(t.delete(e),t.size===0&&(Fg(a,i),a.childRegistry.delete(i),a.correlationToParentKeys.delete(i)))}}}}if(r)for(let[,e]of r)delete e.value[Ph]}function Bg(e){for(let t of e)if(t.pendingChildChanges.size>0||t.nestedSetups&&Ig(t.nestedSetups))return!0;return!1}function Vg(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 Hg(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 Ug(e){return new Dg(e).getConfig()}function Wg(e){if(typeof e==`function`)return Gg(Ug({query:e}));{let t=e,n=Ug(t);return t.utils&&(n.utils={...n.utils,...t.utils}),Gg(n)}}function Gg(e){let t=Um(e),n=$h(e);return n&&eg(t,n),t}var Kg=1;function qg(e,t=[]){let n=e&&typeof e==`object`&&typeof e.subscribeChanges==`function`&&typeof e.startSyncImmediate==`function`&&typeof e.id==`string`,r=(0,_.useRef)(null),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=(0,_.useRef)(0),s=(0,_.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 ng);if(n==null)r.current=null;else if(n instanceof Wm)n.startSyncImmediate(),r.current=n;else if(n instanceof ng)r.current=Wg({query:e,startSync:!0,gcTime:Kg});else if(n&&typeof n==`object`)r.current=Wg({startSync:!0,gcTime:Kg,...n});else throw Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof n}`);i.current=[...t]}else r.current=Wg({startSync:!0,gcTime:Kg,...e}),i.current=[...t];c&&(o.current=0,s.current=null);let l=(0,_.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,_.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,_.useSyncExternalStore)(l.current,u.current),f=(0,_.useRef)(null),p=(0,_.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 Jg=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(){}},Yg=new class extends Jg{#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`}},Xg={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Zg=new class{#e=Xg;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 Qg(e){setTimeout(e,0)}var $g=typeof window>`u`||`Deno`in globalThis;function e_(){}function t_(e,t){return typeof e==`function`?e(t):e}function n_(e){return typeof e==`number`&&e>=0&&e!==1/0}function r_(e,t){return Math.max(e+(t||0)-Date.now(),0)}function i_(e,t){return typeof e==`function`?e(t):e}function a_(e,t){return typeof e==`function`?e(t):e}function o_(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==c_(o,t.options))return!1}else if(!u_(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 s_(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(l_(t.options.mutationKey)!==l_(a))return!1}else if(!u_(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function c_(e,t){return(t?.queryKeyHashFn||l_)(e)}function l_(e){return JSON.stringify(e,(e,t)=>h_(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function u_(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>u_(e[n],t[n])):!1}var d_=Object.prototype.hasOwnProperty;function f_(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=m_(e)&&m_(t);if(!r&&!(h_(e)&&h_(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:d_.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=f_(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function p_(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 m_(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function h_(e){if(!g_(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!g_(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function g_(e){return Object.prototype.toString.call(e)===`[object Object]`}function __(e){return new Promise(t=>{Zg.setTimeout(t,e)})}function v_(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:f_(e,t)}function y_(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function b_(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var x_=Symbol();function S_(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===x_?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function C_(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 w_=(()=>{let e=()=>$g;return{isServer(){return e()},setIsServer(t){e=t}}})();function T_(){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 E_=Qg;function D_(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=E_,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 O_=D_(),k_=new class extends Jg{#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 A_(e){return Math.min(1e3*2**e,3e4)}function j_(e){return(e??`online`)===`online`?k_.isOnline():!0}var M_=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function N_(e){let t=!1,n=0,r,i=T_(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new M_(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>Yg.isFocused()&&(e.networkMode===`always`||k_.isOnline())&&e.canRun(),u=()=>j_(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??(w_.isServer()?0:3),o=e.retryDelay??A_,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),__(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 P_=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),n_(this.gcTime)&&(this.#e=Zg.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(w_.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Zg.clearTimeout(this.#e),this.#e=void 0)}};function F_(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=>{C_(e,()=>t.signal,()=>n=!0)},u=S_(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?b_:y_;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?L_:I_,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:I_(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 I_(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 L_(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var R_=class extends P_{#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=V_(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=V_(this.options);e.data!==void 0&&(this.setState(B_(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=v_(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(e_).catch(e_):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=>a_(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===x_||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>i_(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:!r_(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=S_(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`?F_(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=N_({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof M_&&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 M_){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,...z_(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...B_(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),O_.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function z_(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:j_(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function B_(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function V_(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 H_=class extends Jg{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=T_(),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),W_(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return G_(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return G_(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 a_(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&&!p_(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&K_(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||a_(this.options.enabled,this.#t)!==a_(t.enabled,this.#t)||i_(this.options.staleTime,this.#t)!==i_(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||a_(this.options.enabled,this.#t)!==a_(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 J_(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(e_)),t}#g(){this.#b();let e=i_(this.options.staleTime,this.#t);if(w_.isServer()||this.#r.isStale||!n_(e))return;let t=r_(this.#r.dataUpdatedAt,e)+1;this.#d=Zg.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,!(w_.isServer()||a_(this.options.enabled,this.#t)===!1||!n_(this.#p)||this.#p===0)&&(this.#f=Zg.setInterval(()=>{(this.options.refetchIntervalInBackground||Yg.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(Zg.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(Zg.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&&W_(e,t),o=i&&K_(e,n,t,r);(a||o)&&(l={...l,...z_(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=v_(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=v_(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:q_(e,t),refetch:this.refetch,promise:this.#o,isEnabled:a_(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=T_())},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),!p_(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){O_.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function U_(e,t){return a_(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&a_(t.retryOnMount,e)===!1)}function W_(e,t){return U_(e,t)||e.state.data!==void 0&&G_(e,t,t.refetchOnMount)}function G_(e,t,n){if(a_(t.enabled,e)!==!1&&i_(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&q_(e,t)}return!1}function K_(e,t,n,r){return(e!==t||a_(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&q_(e,n)}function q_(e,t){return a_(t.enabled,e)!==!1&&e.isStaleByTime(i_(t.staleTime,e))}function J_(e,t){return!p_(e.getCurrentResult(),t)}var Y_=class extends P_{#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||X_(),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=N_({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),O_.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function X_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Z_=class extends Jg{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 Y_({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=Q_(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=Q_(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=Q_(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=Q_(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){O_.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=>s_(t,e))}findAll(e={}){return this.getAll().filter(t=>s_(e,t))}notify(e){O_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return O_.batch(()=>Promise.all(e.map(e=>e.continue().catch(e_))))}};function Q_(e){return e.options.scope?.id}var $_=class extends Jg{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??c_(r,t),a=this.get(i);return a||(a=new R_({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(){O_.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=>o_(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>o_(e,t)):t}notify(e){O_.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){O_.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){O_.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ev=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new $_,this.#t=e.mutationCache||new Z_,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Yg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=k_.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(i_(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=t_(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return O_.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;O_.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return O_.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=O_.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(e_).catch(e_)}invalidateQueries(e,t={}){return O_.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=O_.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(e_)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(e_)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(i_(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(e_).catch(e_)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(e_).catch(e_)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return k_.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(l_(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{u_(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(l_(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{u_(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||=c_(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===x_&&(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()}},tv=class extends Lc{constructor(e){super(e),this.name=`QueryCollectionError`}},nv=class extends tv{constructor(){super(`[QueryCollection] queryKey must be provided.`),this.name=`QueryKeyRequiredError`}},rv=class extends tv{constructor(){super(`[QueryCollection] queryFn must be provided.`),this.name=`QueryFnRequiredError`}},iv=class extends tv{constructor(){super(`[QueryCollection] queryClient must be provided.`),this.name=`QueryClientRequiredError`}},av=class extends tv{constructor(){super(`[QueryCollection] getKey must be provided.`),this.name=`GetKeyRequiredError`}},ov=class extends tv{constructor(){super(`Collection must be in 'ready' state for manual sync operations. Sync not initialized yet.`),this.name=`SyncNotInitializedError`}},sv=class extends tv{constructor(e){super(`Duplicate key '${e}' found within batch operations`),this.name=`DuplicateKeyInBatchError`}},cv=class extends tv{constructor(e){super(`Update operation: Item with key '${e}' does not exist`),this.name=`UpdateOperationItemNotFoundError`}},lv=class extends tv{constructor(e){super(`Delete operation: Item with key '${e}' does not exist`),this.name=`DeleteOperationItemNotFoundError`}},uv=new WeakMap;function dv(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 fv(e,t){let n=new Set;for(let r of e){if(n.has(r.key))throw new sv(r.key);if(n.add(r.key),r.type===`update`){if(!t.collection._state.syncedData.has(r.key))throw new cv(r.key)}else if(r.type===`delete`&&!t.collection._state.syncedData.has(r.key))throw new lv(r.key)}}function pv(e,t){let n=dv(e,t);fv(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 mv(e){function t(){let t=e();if(!t)throw new ov;return t}return{writeInsert(e){let n={type:`insert`,data:e},r=t(),i=uv.get(r);if(i?.isActive){i.operations.push(n);return}pv(n,r)},writeUpdate(e){let n={type:`update`,data:e},r=t(),i=uv.get(r);if(i?.isActive){i.operations.push(n);return}pv(n,r)},writeDelete(e){let n={type:`delete`,key:e},r=t(),i=uv.get(r);if(i?.isActive){i.operations.push(n);return}pv(n,r)},writeUpsert(e){let n={type:`upsert`,data:e},r=t(),i=uv.get(r);if(i?.isActive){i.operations.push(n);return}pv(n,r)},writeBatch(e){let n=t();if(uv.get(n)?.isActive)throw Error(`Cannot nest writeBatch calls. Complete the current batch before starting a new one.`);let r={operations:[],isActive:!0};uv.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&&pv(r.operations,n)}finally{r.isActive=!1,uv.delete(n)}}}}function hv(e){if(!e)return;let t={};return e.where&&(t.where=gv(e.where)),e.orderBy?.length&&(t.orderBy=e.orderBy.map(e=>{let t={expression:gv(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 gv(e){if(!e)return null;switch(e.type){case`val`:return{type:`val`,value:_v(e.value)};case`ref`:return{type:`ref`,path:[...e.path]};case`func`:return{type:`func`,name:e.name,args:e.args.map(e=>gv(e))};default:return null}}function _v(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=>_v(e)):typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_v(t)])):e}var vv=`queryCollection:gc:`,yv=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 bv(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)=>au(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 nv;if(!n)throw new rv;if(!i)throw new iv;if(!d)throw new av;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,F=Promise.resolve(),I=e=>O?.row.get(e)??v._state.syncedMetadata.get(e),ee=e=>{let t=I(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))},te=(e,t)=>{if(!O)return;let n={...I(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]))}})},ne=(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}}},re=e=>(F=F.then(e,e),F),L=e=>{let t=P.get(e);t&&(clearTimeout(t),P.delete(e))},R=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=ee(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},ie=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 R(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},ae=async e=>{if(!O)return;let t=await ie(e),n=[];f(),t.forEach(({value:t,owners:r},i)=>{r.delete(e),te(i,r),D(i,e)&&n.push(t)}),n.forEach(e=>{p({type:`delete`,value:e})}),O.collection.delete(`${vv}${e}`),m()},z=e=>{if(e.mode!==`ttl`)return;L(e.queryHash);let t=Math.max(0,e.expiresAt-Date.now()),n=setTimeout(()=>{P.delete(e.queryHash),re(async()=>{let t=O?.collection.get(`${vv}${e.queryHash}`),n=ne(t,e.queryHash);!n||n.mode!==`ttl`||n.expiresAt>Date.now()||await ae(e.queryHash)})},t);P.set(e.queryHash,n)},oe=async()=>{if(!O)return;let e=O.collection.list(vv),t=Date.now();for(let{key:n,value:r}of e){let e=ne(r,n.slice(vv.length));e&&(e.mode===`ttl`&&e.expiresAt<=t?await ae(e.queryHash):e.mode===`ttl`&&z(e))}},B=e=>{if(typeof t==`function`)return t(e);if(_===`on-demand`){let n=hv(e);return n===void 0?t:[...t,n]}else return t},se=O?.collection.list(vv),ce=!se||se.length===0?(j=!0,Promise.resolve()):re(async()=>{try{await oe()}finally{j=!0}}),V=(e={},t=n)=>{if(!j)return ce.then(()=>{let n=V(e,t);return n===!0?void 0:n});let r=B(e),d=l_(r),f={...h,loadSubsetOptions:e},p=O?.collection.get(`${vv}${d}`);if(ne(p,d)!==void 0&&M.add(d),L(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 H_(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=l_(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()):R(i),u=new Map;o.forEach(e=>{let t=d(e);u.set(t,e)}),f(),O&&O.collection.delete(`${vv}${i}`),l.forEach(e=>{let t=c?n.get(e)?.value:s.get(e);if(!t)return;let r=u.get(e);if(r)au(t,r)||p({type:`update`,value:r});else{let n=ee(e);n.delete(i),te(e,n),D(e,i)&&p({type:`delete`,value:t})}}),u.forEach((e,t)=>{let n=ee(t);n.has(i)||(n.add(i),te(t,n)),E(t,i),s.has(t)||p({type:`insert`,value:e})}),m(),M.delete(i),L(i),g()},ue=async(e,t)=>{let n=await ie(l_(e));v.status!==`cleaned-up`&&le(e,t,n)},de=e=>{let t=l_(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():ce.then(()=>{g()});me(),b.observers.forEach((e,t)=>{de(x.get(t))(e.getCurrentResult())});let _e=e=>{w.get(e)?.(),w.delete(e),L(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&&te(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(`${vv}${e}`,{queryHash:e,mode:r===1/0?`until-revalidated`:`ttl`,...r===1/0?{}:{expiresAt:Date.now()+r}}),m(),r!==1/0&&z({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=l_(B(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(l_(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=mv(()=>M),F=f?async e=>{let t=await f(e)??{};return t.refetch!==!1&&await k(),t}:void 0,I=p?async e=>{let t=await p(e)??{};return t.refetch!==!1&&await k(),t}:void 0,ee=m?async e=>{let t=await m(e)??{};return t.refetch!==!1&&await k(),t}:void 0,te=new yv(b,k,P);return{...g,getKey:d,syncMode:_,sync:{sync:N},onInsert:F,onUpdate:I,onDelete:ee,utils:te}}var xv=`/api`;async function Sv(e,t){let n=await fetch(`${xv}${e}`,t);if(!n.ok)throw Error(`${n.status} ${n.statusText}`);return n.json()}function Cv(e){let t=e.toString();return t?`?${t}`:``}function wv(e,t){return Sv(`/memories/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}function Tv(e){return Sv(`/memories/${e}`,{method:`DELETE`})}function Ev(){return Sv(`/projects`)}function Dv(e,t){return Sv(`/projects/${e}`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:t})})}function Ov(e,t){return Sv(`/memories/${e}/projects`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({projectId:t})})}function kv(e,t){return Sv(`/memories/${e}/projects/${t}`,{method:`DELETE`})}function Av(){return Sv(`/syntheses`)}function jv(e){return Sv(`/projects/${e}/synthesis`,{method:`POST`})}function Mv(e){return Sv(`/projects/${e}/synthesis/in-flight`,{method:`DELETE`})}function Nv(e){return Sv(`/projects/${e}/stats`)}function Pv(e,t){return Sv(`/projects/${e}/activity${t===void 0?``:`?days=${t}`}`)}function Fv(e){return Sv(`/activity${e===void 0?``:`?days=${e}`}`)}function Iv(e){return Sv(`/memories/${e}/history`)}function Lv(e,t){return Sv(`/memories/${e}/revert`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({version:t})})}function Rv(e){return Sv(`/projects/${e}/synthesis/history`)}function zv(e,t){return Sv(`/projects/${e}/synthesis/revert`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({version:t})})}function Bv(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)),Sv(`/activity/events${Cv(t)}`)}var Vv=new ev,Hv=Um(bv({queryKey:[`memories`],queryFn:async()=>{let e=await fetch(`/api/memories`);if(!e.ok)throw Error(`${e.status}`);return e.json()},queryClient:Vv,getKey:e=>e.id,onUpdate:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>{let t=e.changes;return wv(e.original.id,{content:t.content,tags:t.tags,type:t.type,pinned:t.pinned})}))}catch{oc.error(`Failed to save — changes may not have been stored`)}},onDelete:async({transaction:e})=>{try{await Promise.all(e.mutations.map(e=>Tv(e.original.id)))}catch{oc.error(`Failed to delete — try again`)}}})),Uv=Um(bv({queryKey:[`syntheses`],queryFn:Av,queryClient:Vv,getKey:e=>e.id})),Wv=Um(bv({queryKey:[`projects`],queryFn:Ev,queryClient:Vv,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():Dv(e.original.id,t.name)}))}}));export{_a as $,jt as $n,dr as $t,po as A,ln as An,z as Ar,Er as At,Ga as B,tn as Bn,C as Br,jr as Bt,Vs as C,Nn as Cn,ve as Cr,Qr as Ct,oo as D,Tn as Dn,B as Dr,kr as Dt,ho as E,wn as En,be as Er,ai as Et,Za as F,rn as Fn,T as Fr,Rr as Ft,La as G,Zt as Gn,b as Gr,Tr as Gt,Wa as H,en as Hn,A as Hr,wr as Ht,Ya as I,cn as In,R as Ir,Nr as It,Ea as J,Ut as Jn,o as Jr,vr as Jt,H as K,Jt as Kn,f as Kr,Sr as Kt,Xa as L,sn as Ln,ee as Lr,Gr as Lt,no as M,dn as Mn,ie as Mr,Ir as Mt,$a as N,un as Nn,F as Nr,Lr as Nt,so as O,Mn as On,oe as Or,Dr as Ot,to as P,pn as Pn,ae as Pr,Pr as Pt,ya as Q,Pt as Qn,br as Qt,Ja as R,on as Rn,M as Rr,Kr as Rt,Gs as S,xn as Sn,ge as Sr,$r as St,Hs as T,Sn as Tn,he as Tr,Zr as Tt,Ba as U,Qt as Un,v as Ur,Cr as Ut,Va as V,nn as Vn,k as Vr,Fr as Vt,za as W,Xt as Wn,y as Wr,Yr as Wt,Ta as X,zt as Xn,yr as Xt,wa as Y,Vt as Yn,c as Yr,mr as Yt,ba as Z,Nt as Zn,_r as Zt,jv as _,Rn as _n,Ae as _r,ni as _t,Ov as a,ir as an,_t as ar,Ki as at,xc as b,An as bn,Me as br,ii as bt,Iv as c,Hn as cn,dt as cr,Mi as ct,Rv as d,Pn as dn,Je as dr,Si as dt,fr as en,kt as er,pa as et,wv as f,jn as fn,qe as fr,Ti as ft,zv as g,Fn as gn,Be as gr,Ci as gt,Lv as h,gn as hn,Re as hr,xi as ht,Uv as i,rr as in,wt as ir,ra as it,ro as j,fn as jn,I as jr,Mr as jt,mo as k,mn as kn,L as kr,Ar as kt,Pv as l,Vn as ln,Qe as lr,ji as lt,Mv as m,zn as mn,je as mr,Di as mt,Wv as n,cr as nn,Et as nr,ma as nt,Bv as o,Qn as on,ht as or,zi as ot,kv as p,vn as pn,We as pr,Ei as pt,Aa as q,Bt as qn,u as qr,xr as qt,Vv as r,ar as rn,Ct as rr,oa as rt,Fv as s,Jn as sn,ft as sr,Li as st,Hv as t,pr as tn,Dt as tr,fa as tt,Nv as u,Bn as un,Xe as ur,Ai as ut,qg as v,In as vn,Le as vr,ei as vt,Bs as w,Cn as wn,_e as wr,si as wt,oc as x,bn as xn,Ne as xr,ti as xt,Pp as y,_n as yn,Pe as yr,ri as yt,Ka as z,an as zn,te as zr,Jr as zt};
|