@scenetest/vite-plugin 0.13.0 → 0.15.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/analyze-app.d.ts +2 -4
- package/dist/analyze-app.d.ts.map +1 -1
- package/dist/analyze-app.js +6 -83
- package/dist/analyze-app.js.map +1 -1
- package/dist/dashboard.d.ts +2 -8
- package/dist/dashboard.d.ts.map +1 -1
- package/dist/dashboard.js +1135 -25
- package/dist/dashboard.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +54 -219
- package/dist/middleware.js.map +1 -1
- package/dist/strip.js +1 -1
- package/dist/strip.js.map +1 -1
- package/dist-app/assets/index-C_QY29vh.css +1 -0
- package/dist-app/assets/index-Dc2U6bWz.js +17 -0
- package/dist-app/index.html +22 -0
- package/package.json +15 -15
- package/dist/panels/observer/audio.d.ts +0 -81
- package/dist/panels/observer/audio.d.ts.map +0 -1
- package/dist/panels/observer/audio.js +0 -296
- package/dist/panels/observer/audio.js.map +0 -1
- package/dist/panels/observer/auto.d.ts +0 -10
- package/dist/panels/observer/auto.d.ts.map +0 -1
- package/dist/panels/observer/auto.js +0 -11
- package/dist/panels/observer/auto.js.map +0 -1
- package/dist/panels/observer/fs-viewer.d.ts +0 -20
- package/dist/panels/observer/fs-viewer.d.ts.map +0 -1
- package/dist/panels/observer/fs-viewer.js +0 -536
- package/dist/panels/observer/fs-viewer.js.map +0 -1
- package/dist/panels/observer/fullscreen.d.ts +0 -24
- package/dist/panels/observer/fullscreen.d.ts.map +0 -1
- package/dist/panels/observer/fullscreen.js +0 -701
- package/dist/panels/observer/fullscreen.js.map +0 -1
- package/dist/panels/observer/history.d.ts +0 -41
- package/dist/panels/observer/history.d.ts.map +0 -1
- package/dist/panels/observer/history.js +0 -307
- package/dist/panels/observer/history.js.map +0 -1
- package/dist/panels/observer/index.d.ts +0 -33
- package/dist/panels/observer/index.d.ts.map +0 -1
- package/dist/panels/observer/index.js +0 -128
- package/dist/panels/observer/index.js.map +0 -1
- package/dist/panels/observer/panel.d.ts +0 -12
- package/dist/panels/observer/panel.d.ts.map +0 -1
- package/dist/panels/observer/panel.js +0 -461
- package/dist/panels/observer/panel.js.map +0 -1
- package/dist/panels/observer/render.d.ts +0 -109
- package/dist/panels/observer/render.d.ts.map +0 -1
- package/dist/panels/observer/render.js +0 -760
- package/dist/panels/observer/render.js.map +0 -1
- package/dist/panels/observer/state.d.ts +0 -57
- package/dist/panels/observer/state.d.ts.map +0 -1
- package/dist/panels/observer/state.js +0 -187
- package/dist/panels/observer/state.js.map +0 -1
- package/dist/panels/observer/styles.d.ts +0 -6
- package/dist/panels/observer/styles.d.ts.map +0 -1
- package/dist/panels/observer/styles.js +0 -1706
- package/dist/panels/observer/styles.js.map +0 -1
- package/dist/panels/observer/types.d.ts +0 -102
- package/dist/panels/observer/types.d.ts.map +0 -1
- package/dist/panels/observer/types.js +0 -5
- package/dist/panels/observer/types.js.map +0 -1
- package/dist/panels/observer/utils.d.ts +0 -45
- package/dist/panels/observer/utils.d.ts.map +0 -1
- package/dist/panels/observer/utils.js +0 -101
- package/dist/panels/observer/utils.js.map +0 -1
- package/dist/panels/recorder/auto.d.ts +0 -10
- package/dist/panels/recorder/auto.d.ts.map +0 -1
- package/dist/panels/recorder/auto.js +0 -11
- package/dist/panels/recorder/auto.js.map +0 -1
- package/dist/panels/recorder/capture.d.ts +0 -18
- package/dist/panels/recorder/capture.d.ts.map +0 -1
- package/dist/panels/recorder/capture.js +0 -218
- package/dist/panels/recorder/capture.js.map +0 -1
- package/dist/panels/recorder/index.d.ts +0 -41
- package/dist/panels/recorder/index.d.ts.map +0 -1
- package/dist/panels/recorder/index.js +0 -208
- package/dist/panels/recorder/index.js.map +0 -1
- package/dist/panels/recorder/panel.d.ts +0 -55
- package/dist/panels/recorder/panel.d.ts.map +0 -1
- package/dist/panels/recorder/panel.js +0 -284
- package/dist/panels/recorder/panel.js.map +0 -1
- package/dist/panels/recorder/reverse-selector.d.ts +0 -31
- package/dist/panels/recorder/reverse-selector.d.ts.map +0 -1
- package/dist/panels/recorder/reverse-selector.js +0 -116
- package/dist/panels/recorder/reverse-selector.js.map +0 -1
- package/dist/panels/recorder/styles.d.ts +0 -5
- package/dist/panels/recorder/styles.d.ts.map +0 -1
- package/dist/panels/recorder/styles.js +0 -300
- package/dist/panels/recorder/styles.js.map +0 -1
- package/dist/panels/recorder/types.d.ts +0 -51
- package/dist/panels/recorder/types.d.ts.map +0 -1
- package/dist/panels/recorder/types.js +0 -15
- package/dist/panels/recorder/types.js.map +0 -1
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
var qi=t=>{throw TypeError(t)};var Es=(t,e,n)=>e.has(t)||qi("Cannot "+n);var S=(t,e,n)=>(Es(t,e,"read from private field"),n?n.call(t):e.get(t)),P=(t,e,n)=>e.has(t)?qi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),K=(t,e,n,s)=>(Es(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),ie=(t,e,n)=>(Es(t,e,"access private method"),n);var Hi=(t,e,n,s)=>({set _(i){K(t,e,i,n)},get _(){return S(t,e,s)}});(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const r of i)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(i){if(i.ep)return;i.ep=!0;const r=n(i);fetch(i.href,r)}})();var Ss,z,no,Ge,Gi,so,io,Rs,Kn,Ht,ro,gi,Us,qs,es={},ts=[],Mc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,bs=Array.isArray;function ze(t,e){for(var n in e)t[n]=e[n];return t}function mi(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function $c(t,e,n){var s,i,r,o={};for(r in e)r=="key"?s=e[r]:r=="ref"?i=e[r]:o[r]=e[r];if(arguments.length>2&&(o.children=arguments.length>3?Ss.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)o[r]===void 0&&(o[r]=t.defaultProps[r]);return Fn(t,o,s,i,null)}function Fn(t,e,n,s,i){var r={type:t,props:e,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++no,__i:-1,__u:0};return i==null&&z.vnode!=null&&z.vnode(r),r}function vs(t){return t.children}function Bn(t,e){this.props=t,this.context=e}function jt(t,e){if(e==null)return t.__?jt(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?jt(t):null}function Dc(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,s=[],i=[],r=ze({},e);r.__v=e.__v+1,z.vnode&&z.vnode(r),_i(t.__P,r,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,s,n??jt(e),!!(32&e.__u),i),r.__v=e.__v,r.__.__k[r.__i]=r,lo(s,r,i),e.__e=e.__=null,r.__e!=n&&oo(r)}}function oo(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),oo(t)}function Ji(t){(!t.__d&&(t.__d=!0)&&Ge.push(t)&&!ns.__r++||Gi!=z.debounceRendering)&&((Gi=z.debounceRendering)||so)(ns)}function ns(){try{for(var t,e=1;Ge.length;)Ge.length>e&&Ge.sort(io),t=Ge.shift(),e=Ge.length,Dc(t)}finally{Ge.length=ns.__r=0}}function co(t,e,n,s,i,r,o,c,a,l,f){var u,y,p,h,d,g,w,C=s&&s.__k||ts,m=e.length;for(a=jc(n,e,C,a,m),u=0;u<m;u++)(p=n.__k[u])!=null&&(y=p.__i!=-1&&C[p.__i]||es,p.__i=u,g=_i(t,p,y,i,r,o,c,a,l,f),h=p.__e,p.ref&&y.ref!=p.ref&&(y.ref&&wi(y.ref,null,p),f.push(p.ref,p.__c||h,p)),d==null&&h!=null&&(d=h),(w=!!(4&p.__u))||y.__k===p.__k?(a=ao(p,a,t,w),w&&y.__e&&(y.__e=null)):typeof p.type=="function"&&g!==void 0?a=g:h&&(a=h.nextSibling),p.__u&=-7);return n.__e=d,a}function jc(t,e,n,s,i){var r,o,c,a,l,f=n.length,u=f,y=0;for(t.__k=new Array(i),r=0;r<i;r++)(o=e[r])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=t.__k[r]=Fn(null,o,null,null,null):bs(o)?o=t.__k[r]=Fn(vs,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[r]=Fn(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[r]=o,a=r+y,o.__=t,o.__b=t.__b+1,c=null,(l=o.__i=Kc(o,n,a,u))!=-1&&(u--,(c=n[l])&&(c.__u|=2)),c==null||c.__v==null?(l==-1&&(i>f?y--:i<f&&y++),typeof o.type!="function"&&(o.__u|=4)):l!=a&&(l==a-1?y--:l==a+1?y++:(l>a?y--:y++,o.__u|=4))):t.__k[r]=null;if(u)for(r=0;r<f;r++)(c=n[r])!=null&&(2&c.__u)==0&&(c.__e==s&&(s=jt(c)),fo(c,c));return s}function ao(t,e,n,s){var i,r;if(typeof t.type=="function"){for(i=t.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=t,e=ao(i[r],e,n,s));return e}t.__e!=e&&(s&&(e&&t.type&&!e.parentNode&&(e=jt(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Kc(t,e,n,s){var i,r,o,c=t.key,a=t.type,l=e[n],f=l!=null&&(2&l.__u)==0;if(l===null&&c==null||f&&c==l.key&&a==l.type)return n;if(s>(f?1:0)){for(i=n-1,r=n+1;i>=0||r<e.length;)if((l=e[o=i>=0?i--:r++])!=null&&(2&l.__u)==0&&c==l.key&&a==l.type)return o}return-1}function Qi(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Mc.test(e)?n:n+"px"}function Rn(t,e,n,s,i){var r,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof s=="string"&&(t.style.cssText=s=""),s)for(e in s)n&&e in n||Qi(t.style,e,"");if(n)for(e in n)s&&n[e]==s[e]||Qi(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(ro,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?s?n[Ht]=s[Ht]:(n[Ht]=gi,t.addEventListener(e,r?qs:Us,r)):t.removeEventListener(e,r?qs:Us,r);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Yi(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[Kn]==null)e[Kn]=gi++;else if(e[Kn]<n[Ht])return;return n(z.event?z.event(e):e)}}}function _i(t,e,n,s,i,r,o,c,a,l){var f,u,y,p,h,d,g,w,C,m,b,v,x,I,M,O=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(a=!!(32&n.__u),r=[c=e.__e=n.__e]),(f=z.__b)&&f(e);e:if(typeof O=="function")try{if(w=e.props,C=O.prototype&&O.prototype.render,m=(f=O.contextType)&&s[f.__c],b=f?m?m.props.value:f.__:s,n.__c?g=(u=e.__c=n.__c).__=u.__E:(C?e.__c=u=new O(w,b):(e.__c=u=new Bn(w,b),u.constructor=O,u.render=Bc),m&&m.sub(u),u.state||(u.state={}),u.__n=s,y=u.__d=!0,u.__h=[],u._sb=[]),C&&u.__s==null&&(u.__s=u.state),C&&O.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=ze({},u.__s)),ze(u.__s,O.getDerivedStateFromProps(w,u.__s))),p=u.props,h=u.state,u.__v=e,y)C&&O.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),C&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(C&&O.getDerivedStateFromProps==null&&w!==p&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(w,b),e.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(w,u.__s,b)===!1){e.__v!=n.__v&&(u.props=w,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(E){E&&(E.__=e)}),ts.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&o.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(w,u.__s,b),C&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(p,h,d)})}if(u.context=b,u.props=w,u.__P=t,u.__e=!1,v=z.__r,x=0,C)u.state=u.__s,u.__d=!1,v&&v(e),f=u.render(u.props,u.state,u.context),ts.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,v&&v(e),f=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++x<25);u.state=u.__s,u.getChildContext!=null&&(s=ze(ze({},s),u.getChildContext())),C&&!y&&u.getSnapshotBeforeUpdate!=null&&(d=u.getSnapshotBeforeUpdate(p,h)),I=f!=null&&f.type===vs&&f.key==null?uo(f.props.children):f,c=co(t,bs(I)?I:[I],e,n,s,i,r,o,c,a,l),u.base=e.__e,e.__u&=-161,u.__h.length&&o.push(u),g&&(u.__E=u.__=null)}catch(E){if(e.__v=null,a||r!=null)if(E.then){for(e.__u|=a?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;r[r.indexOf(c)]=null,e.__e=c}else{for(M=r.length;M--;)mi(r[M]);Hs(e)}else e.__e=n.__e,e.__k=n.__k,E.then||Hs(e);z.__e(E,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):c=e.__e=Fc(n.__e,e,n,s,i,r,o,a,l);return(f=z.diffed)&&f(e),128&e.__u?void 0:c}function Hs(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Hs))}function lo(t,e,n){for(var s=0;s<n.length;s++)wi(n[s],n[++s],n[++s]);z.__c&&z.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(r){r.call(i)})}catch(r){z.__e(r,i.__v)}})}function uo(t){return typeof t!="object"||t==null||t.__b>0?t:bs(t)?t.map(uo):ze({},t)}function Fc(t,e,n,s,i,r,o,c,a){var l,f,u,y,p,h,d,g=n.props||es,w=e.props,C=e.type;if(C=="svg"?i="http://www.w3.org/2000/svg":C=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),r!=null){for(l=0;l<r.length;l++)if((p=r[l])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,r[l]=null;break}}if(t==null){if(C==null)return document.createTextNode(w);t=document.createElementNS(i,C,w.is&&w),c&&(z.__m&&z.__m(e,r),c=!1),r=null}if(C==null)g===w||c&&t.data==w||(t.data=w);else{if(r=r&&Ss.call(t.childNodes),!c&&r!=null)for(g={},l=0;l<t.attributes.length;l++)g[(p=t.attributes[l]).name]=p.value;for(l in g)p=g[l],l=="dangerouslySetInnerHTML"?u=p:l=="children"||l in w||l=="value"&&"defaultValue"in w||l=="checked"&&"defaultChecked"in w||Rn(t,l,null,p,i);for(l in w)p=w[l],l=="children"?y=p:l=="dangerouslySetInnerHTML"?f=p:l=="value"?h=p:l=="checked"?d=p:c&&typeof p!="function"||g[l]===p||Rn(t,l,p,g[l],i);if(f)c||u&&(f.__html==u.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(u&&(t.innerHTML=""),co(e.type=="template"?t.content:t,bs(y)?y:[y],e,n,s,C=="foreignObject"?"http://www.w3.org/1999/xhtml":i,r,o,r?r[0]:n.__k&&jt(n,0),c,a),r!=null)for(l=r.length;l--;)mi(r[l]);c||(l="value",C=="progress"&&h==null?t.removeAttribute("value"):h!=null&&(h!==t[l]||C=="progress"&&!h||C=="option"&&h!=g[l])&&Rn(t,l,h,g[l],i),l="checked",d!=null&&d!=t[l]&&Rn(t,l,d,g[l],i))}return t}function wi(t,e,n){try{if(typeof t=="function"){var s=typeof t.__u=="function";s&&t.__u(),s&&e==null||(t.__u=t(e))}else t.current=e}catch(i){z.__e(i,n)}}function fo(t,e,n){var s,i;if(z.unmount&&z.unmount(t),(s=t.ref)&&(s.current&&s.current!=t.__e||wi(s,null,e)),(s=t.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(r){z.__e(r,e)}s.base=s.__P=null}if(s=t.__k)for(i=0;i<s.length;i++)s[i]&&fo(s[i],e,n||typeof t.type!="function");n||mi(t.__e),t.__c=t.__=t.__e=void 0}function Bc(t,e,n){return this.constructor(t,n)}function Lc(t,e,n){var s,i,r,o;e==document&&(e=document.documentElement),z.__&&z.__(t,e),i=(s=!1)?null:e.__k,r=[],o=[],_i(e,t=e.__k=$c(vs,null,[t]),i||es,es,e.namespaceURI,i?null:e.firstChild?Ss.call(e.childNodes):null,r,i?i.__e:e.firstChild,s,o),lo(r,t,o)}Ss=ts.slice,z={__e:function(t,e,n,s){for(var i,r,o;e=e.__;)if((i=e.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(t)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,s||{}),o=i.__d),o)return i.__E=i}catch(c){t=c}throw t}},no=0,Bn.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ze({},this.state),typeof t=="function"&&(t=t(ze({},n),this.props)),t&&ze(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ji(this))},Bn.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ji(this))},Bn.prototype.render=vs,Ge=[],so=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,io=function(t,e){return t.__v.__b-e.__v.__b},ns.__r=0,Rs=Math.random().toString(8),Kn="__d"+Rs,Ht="__a"+Rs,ro=/(PointerCapture)$|Capture$/i,gi=0,Us=Yi(!1),qs=Yi(!0);var Vc=0;function _(t,e,n,s,i,r){e||(e={});var o,c,a=e;if("ref"in a)for(c in a={},e)c=="ref"?o=e[c]:a[c]=e[c];var l={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Vc,__i:-1,__u:0,__source:i,__self:r};if(typeof t=="function"&&(o=t.defaultProps))for(c in o)a[c]===void 0&&(a[c]=o[c]);return z.vnode&&z.vnode(l),l}var Zt,Y,As,Zi,Xt=0,ho=[],ne=z,Xi=ne.__b,er=ne.__r,tr=ne.diffed,nr=ne.__c,sr=ne.unmount,ir=ne.__;function Si(t,e){ne.__h&&ne.__h(Y,t,Xt||e),Xt=0;var n=Y.__H||(Y.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function be(t){return Xt=1,Nc(yo,t)}function Nc(t,e,n){var s=Si(Zt++,2);if(s.t=t,!s.__c&&(s.__=[yo(void 0,e),function(c){var a=s.__N?s.__N[0]:s.__[0],l=s.t(a,c);a!==l&&(s.__N=[l,s.__[1]],s.__c.setState({}))}],s.__c=Y,!Y.__f)){var i=function(c,a,l){if(!s.__c.__H)return!0;var f=s.__c.__H.__.filter(function(y){return y.__c});if(f.every(function(y){return!y.__N}))return!r||r.call(this,c,a,l);var u=s.__c.props!==c;return f.some(function(y){if(y.__N){var p=y.__[0];y.__=y.__N,y.__N=void 0,p!==y.__[0]&&(u=!0)}}),r&&r.call(this,c,a,l)||u};Y.__f=!0;var r=Y.shouldComponentUpdate,o=Y.componentWillUpdate;Y.componentWillUpdate=function(c,a,l){if(this.__e){var f=r;r=void 0,i(c,a,l),r=f}o&&o.call(this,c,a,l)},Y.shouldComponentUpdate=i}return s.__N||s.__}function We(t,e){var n=Si(Zt++,3);!ne.__s&&po(n.__H,e)&&(n.__=t,n.u=e,Y.__H.__h.push(n))}function zc(t){return Xt=5,Ue(function(){return{current:t}},[])}function Ue(t,e){var n=Si(Zt++,7);return po(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Wc(t,e){return Xt=8,Ue(function(){return t},e)}function Uc(){for(var t;t=ho.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Ln),e.__h.some(Gs),e.__h=[]}catch(n){e.__h=[],ne.__e(n,t.__v)}}}ne.__b=function(t){Y=null,Xi&&Xi(t)},ne.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ir&&ir(t,e)},ne.__r=function(t){er&&er(t),Zt=0;var e=(Y=t.__c).__H;e&&(As===Y?(e.__h=[],Y.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(Ln),e.__h.some(Gs),e.__h=[],Zt=0)),As=Y},ne.diffed=function(t){tr&&tr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ho.push(e)!==1&&Zi===ne.requestAnimationFrame||((Zi=ne.requestAnimationFrame)||qc)(Uc)),e.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),As=Y=null},ne.__c=function(t,e){e.some(function(n){try{n.__h.some(Ln),n.__h=n.__h.filter(function(s){return!s.__||Gs(s)})}catch(s){e.some(function(i){i.__h&&(i.__h=[])}),e=[],ne.__e(s,n.__v)}}),nr&&nr(t,e)},ne.unmount=function(t){sr&&sr(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(s){try{Ln(s)}catch(i){e=i}}),n.__H=void 0,e&&ne.__e(e,n.__v))};var rr=typeof requestAnimationFrame=="function";function qc(t){var e,n=function(){clearTimeout(s),rr&&cancelAnimationFrame(e),setTimeout(t)},s=setTimeout(n,35);rr&&(e=requestAnimationFrame(n))}function Ln(t){var e=Y,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),Y=e}function Gs(t){var e=Y;t.__c=t.__(),Y=e}function po(t,e){return!t||t.length!==e.length||e.some(function(n,s){return n!==t[s]})}function yo(t,e){return typeof e=="function"?e(t):e}const Hc="__includes_scalar__";class Fe{}class en extends Fe{constructor(e,n){super(),this.collection=e,this.alias=n,this.type="collectionRef"}}class Te extends Fe{constructor(e,n){super(),this.query=e,this.alias=n,this.type="queryRef"}}class vn extends Fe{constructor(e){super(),this.sources=e,this.type="unionFrom"}get alias(){var e;return((e=this.sources[0])==null?void 0:e.alias)??""}}class Bt extends Fe{constructor(e){super(),this.queries=e,this.type="unionAll"}get alias(){return""}}class G extends Fe{constructor(e){super(),this.path=e,this.type="ref"}}class de extends Fe{constructor(e){super(),this.value=e,this.type="val"}}class ye extends Fe{constructor(e,n){super(),this.name=e,this.args=n,this.type="func"}}class go extends Fe{constructor(e,n){super(),this.name=e,this.args=n,this.type="agg"}}class Pe extends Fe{constructor(e,n,s,i,r,o,c="collection",a){super(),this.query=e,this.correlationField=n,this.childCorrelationField=s,this.fieldName=i,this.parentFilters=r,this.parentProjection=o,this.materialization=c,this.scalarField=a,this.type="includesSubquery"}}class he extends Fe{constructor(e,n){super(),this.branches=e,this.defaultValue=n,this.type="conditionalSelect"}}function Ie(t){return t instanceof go||t instanceof he||t instanceof ye||t instanceof G||t instanceof de||t instanceof Pe?!0:!t||typeof t!="object"?!1:t.type==="conditionalSelect"?Array.isArray(t.branches):t.type==="agg"||t.type==="func"?typeof t.name=="string"&&Array.isArray(t.args):t.type==="ref"?Array.isArray(t.path):t.type==="val"?"value"in t:t.type==="includesSubquery"?"query"in t&&"fieldName"in t:!1}function bi(t){return typeof t=="object"&&"expression"in t?t.expression:t}function or(t){return typeof t=="object"&&"expression"in t?t.expression:t}function cr(t){return typeof t=="object"&&"expression"in t&&t.residual===!0}function Gc(t){return{expression:t,residual:!0}}function Jc(t,e){if(t.from.type==="unionFrom"){for(const n of t.from.sources)if(n.alias===e)return n}else if(t.from.type!=="unionAll"&&t.from.alias===e)return t.from;for(const n of t.join||[])if(n.from.alias===e)return n.from}function tn(t,e,n){if(e.path.length!==0){if(e.path.length===1){const s=e.path[0];if(t.select){const i=t.select[s];if(i&&i.type==="ref")return tn(t,i,n)}return{collection:n,path:[s]}}if(e.path.length>1){const[s,...i]=e.path,r=Jc(t,s);return r?r.type==="queryRef"?tn(r.query,new G(i),n):{collection:r.collection,path:i}:void 0}}}class ke extends Error{constructor(e){super(e),this.name="TanStackDBError"}}class ar extends ke{constructor(e,n,s){const i=`${e==="insert"?"Insert":"Update"} validation failed: ${n.map(r=>`
|
|
2
|
+
- ${r.message} - path: ${r.path}`).join("")}`;super(s||i),this.name="SchemaValidationError",this.type=e,this.issues=n}}class bt extends ke{constructor(e){super(e),this.name="CollectionConfigurationError"}}class Qc extends bt{constructor(){super("Collection requires a config")}}class Yc extends bt{constructor(){super("Collection requires a sync config")}}class Zc extends bt{constructor(){super("Schema must implement the standard-schema interface")}}class lr extends bt{constructor(){super("Schema validation must be synchronous")}}class Cn extends ke{constructor(e){super(e),this.name="CollectionStateError"}}class Xc extends Cn{constructor(e,n){super(`Cannot perform ${e} on collection "${n}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class ea extends Cn{constructor(e,n,s){super(`Invalid collection status transition from "${e}" to "${n}" for collection "${s}"`)}}class ta extends Cn{constructor(){super("Collection is in error state")}}class na extends Cn{constructor(){super("Active subscribers count is negative - this should never happen")}}class Be extends ke{constructor(e){super(e),this.name="CollectionOperationError"}}class sa extends Be{constructor(e){super(`An object was created without a defined key: ${JSON.stringify(e)}`)}}class ia extends Be{constructor(e,n){const s=e===null?"null":typeof e;super(`getKey returned an invalid key type. Expected string or number, but got ${s}: ${JSON.stringify(e)}. Item: ${JSON.stringify(n)}`)}}class ra extends Be{constructor(e){super(`Cannot insert document with ID "${e}" because it already exists in the collection`)}}class oa extends Be{constructor(e,n,s){const i=`Cannot insert document with key "${e}" from sync because it already exists in the collection "${n}"`;s!=null&&s.hasCustomGetKey&&s.hasDistinct?super(`${i}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):s!=null&&s.hasCustomGetKey&&s.hasJoins?super(`${i}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(i)}}class ca extends Be{constructor(){super("The first argument to update is missing")}}class aa extends Be{constructor(){super("No keys were passed to update")}}class la extends Be{constructor(e){super(`The key "${e}" was passed to update but an object for this key was not found in the collection`)}}class ua extends Be{constructor(e,n){super(`Updating the key of an item is not allowed. Original key: "${e}", Attempted new key: "${n}". Please delete the old item and create a new one if a key change is necessary.`)}}class fa extends Be{constructor(){super("No keys were passed to delete")}}class da extends Be{constructor(e){super(`Collection.delete was called with key '${e}' but there is no item in the collection with this key`)}}class vi extends ke{constructor(e){super(e),this.name="MissingHandlerError"}}class ha extends vi{constructor(){super("Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.")}}class pa extends vi{constructor(){super("Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.")}}class ya extends vi{constructor(){super("Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.")}}class it extends ke{constructor(e){super(e),this.name="TransactionError"}}class ga extends it{constructor(){super("mutationFn is required when creating a transaction")}}class ma extends it{constructor(){super("You can no longer call .mutate() as the transaction is no longer pending")}}class _a extends it{constructor(){super("You can no longer call .rollback() as the transaction is already completed")}}class wa extends it{constructor(){super("You can no longer call .commit() as the transaction is no longer pending")}}class Ts extends it{constructor(){super("No pending sync transaction to write to")}}class Ps extends it{constructor(){super("The pending sync transaction is already committed, you can't still write to it.")}}class Sa extends it{constructor(){super("No pending sync transaction to commit")}}class ba extends it{constructor(){super("The pending sync transaction is already committed, you can't commit it again.")}}class vt extends ke{constructor(e){super(e),this.name="QueryBuilderError"}}class ur extends vt{constructor(e){super(`Only one source is allowed in the ${e}`)}}class va extends vt{constructor(e){super(`A sub query passed to a ${e} must have a from clause itself`)}}class Ca extends vt{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.`)}}class An extends vt{constructor(e,n){const s=e==="unionAll clause"?"an object with one or more key-value pairs like { alias: collection }":"an object with a single key-value pair like { alias: collection }",i=e==="unionAll clause"?".unionAll({ todos: todosCollection, events: eventsCollection })":e==="join clause"?".join({ todos: todosCollection }, ({ todo, todos }) => eq(todo.id, todos.id))":".from({ todos: todosCollection })";super(`Invalid source for ${e}: Expected ${s}. For example: ${i}. Got: ${n}`)}}class xa extends vt{constructor(){super("Join condition must be an equality expression")}}class Ia extends vt{constructor(){super("Query must have a from clause")}}class fr extends vt{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`)}}class ge extends ke{constructor(e){super(e),this.name="QueryCompilationError"}}class Oa extends ge{constructor(){super("DISTINCT requires a SELECT clause.")}}class ka extends ge{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().")}}class Ea extends ge{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(...)).")}}class Ra extends ge{constructor(){super("HAVING clause requires GROUP BY clause")}}class Aa extends ge{constructor(){super("LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results")}}class mo extends ge{constructor(e,n,s){const i=n?`alias "${e}" (collection "${n}")`:`collection "${e}"`,r=s!=null&&s.length?`. Available keys: ${s.join(", ")}`:"";super(`Input for ${i} not found in inputs map${r}`)}}class Ta extends ge{constructor(e,n){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: ${n.join(", ")}. Please rename "${e}" in either the parent query or subquery to avoid conflicts.`)}}class Ci extends ge{constructor(e){super(`Unsupported FROM type: ${e}`)}}class Pa extends ge{constructor(e){super(`Unknown expression type: ${e}`)}}class Ma extends ge{constructor(){super("Reference path cannot be empty")}}class $a extends ge{constructor(e){super(`Unknown function: ${e}`)}}class dr extends ge{constructor(e){super(`Collection "${e}" not found during compilation of join`)}}class Ct extends ke{constructor(e){super(e),this.name="JoinError"}}class Da extends Ct{constructor(e){super(`Unsupported join type: ${e}`)}}class ja extends Ct{constructor(e){super(`Invalid join condition: both expressions refer to the same source "${e}"`)}}class Ka extends Ct{constructor(){super("Invalid join condition: expressions must reference source aliases")}}class Fa extends Ct{constructor(e){super(`Invalid join condition: left expression refers to an unavailable source "${e}"`)}}class Ba extends Ct{constructor(e){super(`Invalid join condition: right expression does not refer to the joined source "${e}"`)}}class La extends Ct{constructor(){super("Invalid join condition")}}class Va extends Ct{constructor(e){super(`Unsupported join source type: ${e}`)}}class Cs extends ke{constructor(e){super(e),this.name="GroupByError"}}class Na extends Cs{constructor(e){super(`Non-aggregate expression '${e}' in SELECT must also appear in GROUP BY clause`)}}class za extends Cs{constructor(e){super(`Unsupported aggregate function: ${e}`)}}class Wa extends Cs{constructor(e){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${e}`)}}class Ua extends Cs{constructor(e){super(`Unknown expression type in HAVING clause: ${e}`)}}class hr extends ke{constructor(e,n){const s=n instanceof Error?n.message:String(n);super(`Collection "${e}" sync cleanup function threw an error: ${s}`),this.name="SyncCleanupError"}}class qa extends ke{constructor(e){super(e),this.name="QueryOptimizerError"}}class Ha extends qa{constructor(){super("Cannot combine empty expression list")}}class Ga extends ge{constructor(e,n,s,i){super(`Internal error: subscription for alias '${e}' (remapped from '${n}', collection '${s}') is missing in join pipeline. Available aliases: ${i.join(", ")}. This indicates a bug in alias tracking.`)}}class Ja extends ge{constructor(e){super(`Internal error: compiler returned aliases without inputs: ${e.join(", ")}. This indicates a bug in query compilation. Please report this issue.`)}}class Qa extends ge{constructor(){super("setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.")}}function Ke(t,e){return Vn(t,e,new Map)}function Vn(t,e,n){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date)return e instanceof Date?t.getTime()===e.getTime():!1;if(e instanceof Date)return!1;if(t instanceof RegExp)return e instanceof RegExp?t.source===e.source&&t.flags===e.flags:!1;if(e instanceof RegExp)return!1;if(t instanceof Map){if(!(e instanceof Map)||t.size!==e.size)return!1;if(n.has(t))return n.get(t)===e;n.set(t,e);const i=Array.from(t.entries()).every(([r,o])=>e.has(r)&&Vn(o,e.get(r),n));return n.delete(t),i}if(e instanceof Map)return!1;if(t instanceof Set){if(!(e instanceof Set)||t.size!==e.size)return!1;if(n.has(t))return n.get(t)===e;n.set(t,e);const s=Array.from(t),i=Array.from(e);if(s.every(o=>typeof o!="object"))return n.delete(t),s.every(o=>e.has(o));const r=s.length===i.length;return n.delete(t),r}if(e instanceof Set)return!1;if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)&&!(t instanceof DataView)&&!(e instanceof DataView)){const s=t,i=e;if(s.length!==i.length)return!1;for(let r=0;r<s.length;r++)if(s[r]!==i[r])return!1;return!0}if(ArrayBuffer.isView(e)&&!(e instanceof DataView)&&!ArrayBuffer.isView(t))return!1;if(nt(t)&&nt(e)){const s=t[Symbol.toStringTag],i=e[Symbol.toStringTag];return s!==i?!1:typeof t.equals=="function"?t.equals(e):t.toString()===e.toString()}if(nt(e))return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;if(n.has(t))return n.get(t)===e;n.set(t,e);const s=t.every((i,r)=>Vn(i,e[r],n));return n.delete(t),s}if(Array.isArray(e))return!1;if(typeof t=="object"){if(n.has(t))return n.get(t)===e;n.set(t,e);const s=Object.keys(t),i=Object.keys(e);if(s.length!==i.length)return n.delete(t),!1;const r=s.every(o=>o in e&&Vn(t[o],e[o],n));return n.delete(t),r}return!1}const Ya=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function nt(t){if(t==null||typeof t!="object")return!1;const e=t[Symbol.toStringTag];return typeof e=="string"&&Ya.has(e)}const _o={direction:"asc",nulls:"first",stringSort:"locale"},Ms=new WeakMap;let Za=1;function pr(t){if(Ms.has(t))return Ms.get(t);const e=Za++;return Ms.set(t,e),e}const xi=(t,e,n)=>{const{nulls:s}=n;if(t==null&&e==null)return 0;if(t==null)return s==="first"?-1:1;if(e==null)return s==="first"?1:-1;if(typeof t=="string"&&typeof e=="string"&&n.stringSort==="locale")return t.localeCompare(e,n.locale,n.localeOptions);if(Array.isArray(t)&&Array.isArray(e)){for(let o=0;o<Math.min(t.length,e.length);o++){const c=xi(t[o],e[o],n);if(c!==0)return c}return t.length-e.length}if(t instanceof Date&&e instanceof Date)return t.getTime()-e.getTime();if(nt(t)&&nt(e)){const o=t.toString(),c=e.toString();return o<c?-1:o>c?1:0}const i=typeof t=="object",r=typeof e=="object";if(i||r){if(i&&r){const o=pr(t),c=pr(e);return o-c}if(i)return 1;if(r)return-1}return t<e?-1:t>e?1:0},Xa=(t,e,n)=>xi(e,t,{...n,nulls:n.nulls==="first"?"last":"first"});function Gt(t){return(e,n)=>t.direction==="asc"?xi(e,n,t):Xa(e,n,t)}const el=Gt({direction:"asc",nulls:"first",stringSort:"locale"});function tl(t,e){if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}const nl=128;function Et(t){return t instanceof Date?t.getTime():nt(t)?`__temporal__${t[Symbol.toStringTag]}__${t.toString()}`:(typeof Buffer<"u"&&t instanceof Buffer||t instanceof Uint8Array)&&t.byteLength<=nl?`__u8__${Array.from(t).join(",")}`:t}function sl(t,e){if(t===e)return!0;const n=typeof Buffer<"u"&&t instanceof Buffer||t instanceof Uint8Array,s=typeof Buffer<"u"&&e instanceof Buffer||e instanceof Uint8Array;return n&&s?tl(t,e):!1}function re(t){return t==null}function $s(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="string"||typeof t=="number"){const e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null}function il(t,e){return t==="%Y-%m-%d"?e.toISOString().slice(0,10):e.toISOString()}function Tt(t){return t===!0}function q(t,e=!1){return Ii(t,e)}function wo(t){return Ii(t,!0)}function Ii(t,e){switch(t.type){case"val":{const n=t.value;return()=>n}case"ref":return e?ol(t):rl(t);case"func":return cl(t,e);default:throw new Pa(t.type)}}function rl(t){const[e,...n]=t.path;if(!e)throw new Ma;if(e==="$selected"){if(n.length===0)return i=>i.$selected;if(n.length===1){const i=n[0];return r=>{const o=r.$selected;return o==null?void 0:o[i]}}else return i=>{const r=i.$selected;if(r===void 0)return;let o=r;for(const c of n){if(o==null)return o;o=o[c]}return o}}const s=e;if(n.length===0)return i=>i[s];if(n.length===1){const i=n[0];return r=>{const o=r[s];return o==null?void 0:o[i]}}else return i=>{const r=i[s];if(r===void 0)return;let o=r;for(const c of n){if(o==null)return o;o=o[c]}return o}}function ol(t){const e=t.path;return n=>{let s=n;for(const i of e){if(s==null)return s;s=s[i]}return s}}function cl(t,e){const n=t.args.map(s=>Ii(s,e));switch(t.name){case"eq":{const s=n[0],i=n[1];return r=>{const o=Et(s(r)),c=Et(i(r));return re(o)||re(c)?null:sl(o,c)}}case"gt":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:o>c}}case"gte":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:o>=c}}case"lt":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:o<c}}case"lte":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:o<=c}}case"and":return s=>{let i=!1;for(const r of n){const o=r(s);if(o===!1)return!1;re(o)&&(i=!0)}return i?null:!0};case"or":return s=>{let i=!1;for(const r of n){const o=r(s);if(o===!0)return!0;re(o)&&(i=!0)}return i?null:!1};case"not":{const s=n[0];return i=>{const r=s(i);return re(r)?null:!r}}case"in":{const s=n[0],i=n[1];return r=>{const o=Et(s(r)),c=i(r);return re(o)?null:Array.isArray(c)?c.some(a=>Et(a)===o):!1}}case"like":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:yr(o,c,!1)}}case"ilike":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return re(o)||re(c)?null:yr(o,c,!0)}}case"upper":{const s=n[0];return i=>{const r=s(i);return typeof r=="string"?r.toUpperCase():r}}case"lower":{const s=n[0];return i=>{const r=s(i);return typeof r=="string"?r.toLowerCase():r}}case"length":{const s=n[0];return i=>{const r=s(i);return typeof r=="string"||Array.isArray(r)?r.length:0}}case"concat":return s=>n.map(i=>{const r=i(s);try{return String(r??"")}catch{try{return JSON.stringify(r)||""}catch{return"[object]"}}}).join("");case"coalesce":return s=>{for(const i of n){const r=i(s);if(r!=null)return r}return null};case"caseWhen":{const s=n.length%2===1,i=Math.floor(n.length/2);if(n.length<2)throw new Error("caseWhen() requires at least two arguments");return r=>{for(let o=0;o<i;o++){const c=n[o*2];if(xs(c(r))){const a=n[o*2+1];return a(r)}}return s?n[n.length-1](r):null}}case"add":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return(o??0)+(c??0)}}case"subtract":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return(o??0)-(c??0)}}case"multiply":{const s=n[0],i=n[1];return r=>{const o=s(r),c=i(r);return(o??0)*(c??0)}}case"divide":{const s=n[0],i=n[1];return r=>{const o=s(r),a=i(r)??0;return a!==0?(o??0)/a:null}}case"date":{const s=n[0];return i=>{const r=s(i),o=$s(r);return o?o.toISOString().slice(0,10):null}}case"datetime":{const s=n[0];return i=>{const r=s(i),o=$s(r);return o?o.toISOString():null}}case"strftime":{const s=n[0],i=n[1];return r=>{const o=s(r);if(typeof o!="string")return null;const c=i(r),a=$s(c);return a?il(o,a):null}}case"isUndefined":{const s=n[0];return i=>s(i)===void 0}case"isNull":{const s=n[0];return i=>s(i)===null}default:throw new $a(t.name)}}function xs(t){return t==null||t===!1?!1:t===!0?!0:typeof t=="number"?t!==0&&!Number.isNaN(t):typeof t=="bigint"?t!==0n:!!t}function yr(t,e,n){if(typeof t!="string"||typeof e!="string")return!1;const s=n?t.toLowerCase():t;let r=(n?e.toLowerCase():e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return r=r.replace(/%/g,".*"),r=r.replace(/_/g,"."),new RegExp(`^${r}$`,"s").test(s)}class al{constructor(e){this.originalIndex=e}lookup(e,n){const s=e==="gt"?"lt":e==="gte"?"lte":e==="lt"?"gt":e==="lte"?"gte":e;return this.originalIndex.lookup(s,n)}rangeQuery(e={}){return this.originalIndex.rangeQueryReversed(e)}rangeQueryReversed(e={}){return this.originalIndex.rangeQuery(e)}take(e,n,s){return this.originalIndex.takeReversed(e,n,s)}takeFromStart(e,n){return this.originalIndex.takeReversedFromEnd(e,n)}takeReversed(e,n,s){return this.originalIndex.take(e,n,s)}takeReversedFromEnd(e,n){return this.originalIndex.takeFromStart(e,n)}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,n){this.originalIndex.add(e,n)}remove(e,n){this.originalIndex.remove(e,n)}update(e,n,s){this.originalIndex.update(e,n,s)}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 gr(t,e,n,s,i){const r=t;return{...t,$synced:r.$synced??s(),$origin:r.$origin??i(),$key:r.$key??e,$collectionId:r.$collectionId??n}}const Js=["$synced","$origin","$key","$collectionId"];function ll(t){return Js.includes(t)}function So(t){return t.some(e=>ll(e))}function xn(t,e,n){if(So(e))return;const s=n??{..._o,...t.compareOptions};for(const i of t.indexes.values())if(i.matchesField(e)&&i.matchesCompareOptions(s))return i.matchesDirection(s.direction)?i:new al(i)}function ul(t){if(t.length===0)return new Set;if(t.length===1)return new Set(t[0]);let e=new Set(t[0]);for(let n=1;n<t.length;n++){const s=new Set;for(const i of e)t[n].has(i)&&s.add(i);e=s}return e}function fl(t){const e=new Set;for(const n of t)for(const s of n)e.add(s);return e}function dl(t,e){return Oi(t,e)}function Oi(t,e){if(t.type==="func")switch(t.name){case"eq":case"gt":case"gte":case"lt":case"lte":return pl(t,e);case"and":return yl(t,e);case"or":return gl(t,e);case"in":return ml(t,e)}return{canOptimize:!1,matchingKeys:new Set}}function hl(t,e){if(t.type!=="func"||t.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const n=new Map;for(const s of t.args)if(s.type==="func"&&["gt","gte","lt","lte"].includes(s.name)){const i=s;if(i.args.length===2){const r=i.args[0],o=i.args[1];let c=null,a=null,l=i.name;if(r.type==="ref"&&o.type==="val")c=r,a=o;else if(r.type==="val"&&o.type==="ref")switch(c=o,a=r,l){case"gt":l="lt";break;case"gte":l="lte";break;case"lt":l="gt";break;case"lte":l="gte";break}if(c&&a){const u=c.path.join("."),y=a.value;n.has(u)||n.set(u,[]),n.get(u).push({operation:l,value:y})}}}for(const[s,i]of n)if(i.length>=2){const r=s.split("."),o=xn(e,r);if(o&&o.supports("gt")&&o.supports("lt")){let c,a,l=!0,f=!0;for(const{operation:y,value:p}of i)switch(y){case"gt":(c===void 0||p>c)&&(c=p,l=!1);break;case"gte":(c===void 0||p>c)&&(c=p,l=!0);break;case"lt":(a===void 0||p<a)&&(a=p,f=!1);break;case"lte":(a===void 0||p<a)&&(a=p,f=!0);break}return{canOptimize:!0,matchingKeys:o.rangeQuery({from:c,to:a,fromInclusive:l,toInclusive:f})}}}return{canOptimize:!1,matchingKeys:new Set}}function pl(t,e){if(t.type!=="func"||t.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const n=t.args[0],s=t.args[1];let i=null,r=null,o=t.name;if(n.type==="ref"&&s.type==="val")i=n,r=s;else if(n.type==="val"&&s.type==="ref")switch(i=s,r=n,o){case"gt":o="lt";break;case"gte":o="lte";break;case"lt":o="gt";break;case"lte":o="gte";break}if(i&&r){const c=i.path,a=xn(e,c);if(a){const l=r.value,f=o;return a.supports(f)?{canOptimize:!0,matchingKeys:a.lookup(f,l)}:{canOptimize:!1,matchingKeys:new Set}}}return{canOptimize:!1,matchingKeys:new Set}}function yl(t,e){if(t.type!=="func"||t.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const n=hl(t,e);if(n.canOptimize)return n;const s=[];for(const i of t.args){const r=Oi(i,e);r.canOptimize&&s.push(r)}if(s.length>0){const i=s.map(o=>o.matchingKeys);return{canOptimize:!0,matchingKeys:ul(i)}}return{canOptimize:!1,matchingKeys:new Set}}function gl(t,e){if(t.type!=="func"||t.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const n=[];for(const s of t.args){const i=Oi(s,e);i.canOptimize&&n.push(i)}if(n.length>0){const s=n.map(r=>r.matchingKeys);return{canOptimize:!0,matchingKeys:fl(s)}}return{canOptimize:!1,matchingKeys:new Set}}function ml(t,e){if(t.type!=="func"||t.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const n=t.args[0],s=t.args[1];if(n.type==="ref"&&s.type==="val"&&Array.isArray(s.value)){const i=n.path,r=s.value,o=xn(e,i);if(o){if(o.supports("in"))return{canOptimize:!0,matchingKeys:o.lookup("in",r)};if(o.supports("eq")){const c=new Set;for(const a of r){const l=o.lookup("eq",a);for(const f of l)c.add(f)}return{canOptimize:!0,matchingKeys:c}}}}return{canOptimize:!1,matchingKeys:new Set}}function bo(t){return t.config.autoIndex==="eager"}function In(t,e,n,s,i){if(So(e)||!bo(n))return;const r=s??{..._o,...n.compareOptions};if(!Array.from(n.indexes.values()).find(c=>c.matchesField(e)&&c.matchesCompareOptions(r)))try{n.createIndex(c=>{let a=c;for(const l of e)a=a[l];return a},{name:`auto:${e.join(".")}`,options:i?{compareFn:i,compareOptions:r}:{}})}catch(c){console.warn(`${n.id?`[${n.id}] `:""}Failed to create auto-index for field path "${e.join(".")}":`,c)}}function _l(t,e){if(!bo(e))return;const n=wl(t);for(const{fieldName:s,fieldPath:i}of n)In(s,i,e)}function wl(t){const e=[];function n(s){if(s.type!=="func")return;const i=s;if(i.name==="and"){for(const l of i.args)n(l);return}if(!["eq","gt","gte","lt","lte","in"].includes(i.name)||i.args.length<1||i.args[0].type!=="ref")return;const c=i.args[0].path;if(c.length===0)return;const a=c.join("_");e.push({fieldName:a,fieldPath:c})}return n(t),e}class Sl extends Map{constructor(e,n){super(n),this.defaultValue=e}get(e){return this.has(e)?super.get(e):this.defaultValue()}update(e,n){const s=this.get(e),i=n(s);return this.set(e,i),i}}const Ds=3e4;function js(t,e){if(e.length<=Ds)t.push(...e);else for(let n=0;n<e.length;n+=Ds){const s=e.slice(n,n+Ds);t.push(...s)}}function bl(t,e,n){let s=0,i=t.length;for(;s<i;){const r=Math.floor((s+i)/2),o=n(t[r],e);if(o<0)s=r+1;else if(o>0)i=r;else return r}return s}class vl{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(e){if(typeof e!="object"||e===null){const n=String(e);let s=0;for(let i=0;i<n.length;i++){const r=n.charCodeAt(i);s=(s<<5)-s+r,s=s&s}return s}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"?`str_${String(e)}`:`obj_${this.getId(e)}`}}const Ks=new vl;function Cl(t,e){const[n,s]=t,[i,r]=e,o=[...Tn(n,Math.min(s,i)),...Tn(Math.max(n,r),s)],c=[...Tn(i,Math.min(r,n)),...Tn(Math.max(i,s),r)];return{onlyInA:o,onlyInB:c}}function Tn(t,e){const n=[];for(let s=t;s<e;s++)n.push(s);return n}function Qs(t,e){return typeof t==typeof e?t<e?-1:t>e?1:0:typeof t=="string"?-1:1}function nn(t){return JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString():n instanceof Date?n.toISOString():n)}const xl=oe(),Il=oe(),Ol=oe(),kl=oe(),El=oe();function oe(){return Math.random()*(2**31-1)>>>0}const vo=new ArrayBuffer(8),Rl=new DataView(vo),He=new Uint8Array(vo);class On{constructor(){this.hash=xl,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(El);const n=e.description;if(!n)return;for(let s=0;s<n.length;s++){const i=n.charCodeAt(s);this.writeByte(i&255),this.writeByte(i>>>8&255)}return}case"string":this.update(Il);for(let n=0;n<e.length;n++){const s=e.charCodeAt(n);this.writeByte(s&255),this.writeByte(s>>>8&255)}return;case"number":Rl.setFloat64(0,e,!0),this.writeByte(He[0]),this.writeByte(He[1]),this.writeByte(He[2]),this.writeByte(He[3]),this.writeByte(He[4]),this.writeByte(He[5]),this.writeByte(He[6]),this.writeByte(He[7]);return;case"bigint":{let n=e;for(n<0n?(n=-n,this.update(kl)):this.update(Ol);n>0n;)this.writeByte(Number(n&0xffn)),n>>=8n;e===0n&&this.writeByte(0);return}default:throw new 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}}const Al=oe(),Tl=oe(),Pl=oe(),Ml=oe(),$l=oe(),Dl=oe(),jl=oe(),Kl=oe(),Fl=oe(),Bl=oe(),Ll=oe(),Vl=oe(),Nl=oe(),zl=new Set(["Temporal.Duration","Temporal.Instant","Temporal.PlainDate","Temporal.PlainDateTime","Temporal.PlainMonthDay","Temporal.PlainTime","Temporal.PlainYearMonth","Temporal.ZonedDateTime"]);function Wl(t){const e=t[Symbol.toStringTag];return typeof e=="string"&&zl.has(e)}const Ul=128,sn=new WeakMap;function pe(t){const e=new On;return Co(e,t),e.digest()}function ql(t){const e=sn.get(t);if(e!==void 0)return e;let n;if(t instanceof Date)n=Hl(t);else if(typeof Buffer<"u"&&t instanceof Buffer||t instanceof Uint8Array)if(t.byteLength<=Ul)n=Gl(t);else return Ys(t);else{if(t instanceof File)return Ys(t);if(Wl(t))n=Jl(t);else{let s=t,i=Kl;t instanceof Array&&(i=Fl),t instanceof Map&&(i=Bl,s=[...t.entries()]),t instanceof Set&&(i=Ll,s=[...t.entries()]),n=Ql(s,i)}}return sn.set(t,n),n}function Hl(t){const e=new On;return e.update(jl),e.update(t.getTime()),e.digest()}function Gl(t){const e=new On;e.update(Vl),e.update(t.byteLength);for(let n=0;n<t.byteLength;n++)e.writeByte(t[n]);return e.digest()}function Jl(t){const e=new On;return e.update(Nl),e.update(t[Symbol.toStringTag]),e.update(t.toString()),e.digest()}function Ql(t,e){const n=new On;n.update(e);const s=Object.keys(t);s.sort(Zl);for(const i of s)n.update($l),n.update(i),Co(n,t[i]);return n.digest()}function Co(t,e){if(e===null){t.update(Pl);return}switch(typeof e){case"undefined":t.update(Ml);return;case"boolean":t.update(e?Al:Tl);return;case"number":t.update(isNaN(e)?NaN:e===0?0:e);return;case"bigint":case"string":case"symbol":t.update(e);return;case"object":t.update(Yl(e));return;case"function":t.update(Ys(e));return;default:console.warn(`Ignored input during hashing because it is of type ${typeof e} which is not supported`)}}function Yl(t){let e=sn.get(t);return e===void 0&&(e=ql(t)),e}let mr=1;function Ys(t){let e=sn.get(t);return e===void 0&&(e=mr^Dl,mr++,sn.set(t,e)),e}function Zl(t,e){return t.localeCompare(e)}var ae,st,xo,Nn;const Me=class Me{constructor(e=[]){P(this,st);P(this,ae);K(this,ae,e)}toString(e=!1){return`MultiSet(${JSON.stringify(S(this,ae),null,e?2:void 0)})`}toJSON(){return JSON.stringify(Array.from(this.getInner()))}static fromJSON(e){return new Me(JSON.parse(e))}map(e){return new Me(S(this,ae).map(([n,s])=>[e(n),s]))}filter(e){return new Me(S(this,ae).filter(([n,s])=>e(n)))}negate(){return new Me(S(this,ae).map(([e,n])=>[e,-n]))}concat(e){const n=[];return js(n,S(this,ae)),js(n,e.getInner()),new Me(n)}consolidate(){var e;if(S(this,ae).length>0){const n=(e=S(this,ae)[0])==null?void 0:e[0];if(Array.isArray(n)&&n.length===2)return ie(this,st,xo).call(this)}return ie(this,st,Nn).call(this)}extend(e){const n=e instanceof Me?e.getInner():e;js(S(this,ae),n)}add(e,n){n!==0&&S(this,ae).push([e,n])}getInner(){return S(this,ae)}};ae=new WeakMap,st=new WeakSet,xo=function(){const e=new Map,n=new Map,s=r=>{if(r.length!==2)throw new Error("Expected tuple of length 2");const[o,c]=r;return`${Ks.getStringId(o)}|${Ks.getStringId(c)}`};for(const[r,o]of S(this,ae)){if(!Array.isArray(r)||r.length!==2)return ie(this,st,Nn).call(this);const[c,a]=r;if(typeof c!="string"&&typeof c!="number")return ie(this,st,Nn).call(this);let l;Array.isArray(a)&&a.length===2?l=s(a):l=Ks.getStringId(a);const f=c+"|"+l;e.set(f,(e.get(f)||0)+o),n.has(f)||n.set(f,r)}const i=[];for(const[r,o]of e)o!==0&&i.push([n.get(r),o]);return new Me(i)},Nn=function(){const e=new Sl(()=>0),n=new Map;let s=!1,i=!1,r=!1;for(const[a,l]of S(this,ae))if(typeof a=="string")s=!0;else if(typeof a=="number")i=!0;else{r=!0;break}const o=r||s&&i;for(const[a,l]of S(this,ae)){const f=o?pe(a):a;o&&!n.has(f)&&n.set(f,a),e.update(f,u=>u+l)}const c=[];for(const[a,l]of e.entries())if(l!==0){const f=o?n.get(a):a;c.push([f,l])}return new Me(c)};let _e=Me;var ht;class Xl{constructor(e){P(this,ht);K(this,ht,e)}drain(){const e=[...S(this,ht)].reverse();return S(this,ht).length=0,e}isEmpty(){return S(this,ht).length===0}}ht=new WeakMap;var un;class Ee{constructor(){P(this,un,[])}sendData(e){e instanceof _e||(e=new _e(e));for(const n of S(this,un))n.unshift(e)}newReader(){const e=[];return S(this,un).push(e),new Xl(e)}}un=new WeakMap;class Io{constructor(e,n,s){this.id=e,this.inputs=n,this.output=s}hasPendingWork(){return this.inputs.some(e=>!e.isEmpty())}}class xt extends Io{constructor(e,n,s){super(e,[n],s),this.id=e}inputMessages(){return this.inputs[0].drain()}}class Oo extends Io{constructor(e,n,s,i){super(e,[n,s],i),this.id=e}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}}class ki extends xt{run(){for(const e of this.inputMessages())this.output.sendData(this.inner(e))}}var Mt,ms,$t,pt,zt;class eu{constructor(){P(this,pt);P(this,Mt,[]);P(this,ms,0);P(this,$t,!1)}getNextOperatorId(){return ie(this,pt,zt).call(this),Hi(this,ms)._++}newInput(){ie(this,pt,zt).call(this);const e=new Ee;return new tu(this,e)}addOperator(e){ie(this,pt,zt).call(this),S(this,Mt).push(e)}finalize(){ie(this,pt,zt).call(this),K(this,$t,!0)}step(){if(!S(this,$t))throw new Error("Graph not finalized");for(const e of S(this,Mt))e.run()}pendingWork(){return S(this,Mt).some(e=>e.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}}Mt=new WeakMap,ms=new WeakMap,$t=new WeakMap,pt=new WeakSet,zt=function(){if(S(this,$t))throw new Error("Graph already finalized")};var fn,Dt;class Re{constructor(e,n){P(this,fn);P(this,Dt);K(this,fn,e),K(this,Dt,n)}connectReader(){return S(this,Dt).newReader()}get writer(){return S(this,Dt)}get graph(){return S(this,fn)}pipe(...e){return e.reduce((n,s)=>s(n),this)}}fn=new WeakMap,Dt=new WeakMap;class tu extends Re{sendData(e){this.writer.sendData(e)}}class nu extends Oo{run(){for(const e of this.inputAMessages())this.output.sendData(e);for(const e of this.inputBMessages())this.output.sendData(e)}}function ko(t){return e=>{if(e.graph!==t.graph)throw new Error("Cannot concat streams from different graphs");const n=new Re(e.graph,new Ee),s=new nu(e.graph.getNextOperatorId(),e.connectReader(),t.connectReader(),n.writer);return e.graph.addOperator(s),n}}class su extends xt{run(){const e=this.inputMessages();if(e.length===0)return;const n=new _e;for(const i of e)n.extend(i);const s=n.consolidate();s.getInner().length>0&&this.output.sendData(s)}}function Eo(){return t=>{const e=new Re(t.graph,new Ee),n=new su(t.graph.getNextOperatorId(),t.connectReader(),e.writer);return t.graph.addOperator(n),e}}const Wt=Symbol("NO_PREFIX");class _r extends Map{addValue(e,n){if(n===0)return this.size===0;const s=Jt(e),i=this.get(s);if(zn(i)){const[r,o]=i;if(Jt(r)!==s)throw new Error("Mismatching prefixes, this should never happen");if(r===e||pe(r)===pe(e)){const a=o+n;a===0?this.delete(s):this.set(s,[e,a])}else{const a=new Ut;a.set(pe(r),i),a.set(pe(e),[e,n]),this.set(s,a)}}else i===void 0?this.set(s,[e,n]):i.addValue(e,n)&&this.delete(s);return this.size===0}}class Ut extends Map{addValue(e,n){if(n===0)return this.size===0;const s=pe(e),i=this.get(s);if(i){const[,r]=i,o=r+n;o===0?this.delete(s):this.set(s,[e,o])}else this.set(s,[e,n]);return this.size===0}}var ee,Ve,_s,Ro;const Ui=class Ui{constructor(){P(this,_s);P(this,ee);P(this,Ve,new Map);K(this,ee,new Map)}static fromMultiSets(e){const n=new Ui;for(const s of e)for(const[i,r]of s.getInner()){const[o,c]=i;n.addValue(o,[c,r])}return n}toString(e=!1){return`Index(${JSON.stringify([...this.entries()],void 0,e?2:void 0)})`}get size(){return S(this,ee).size}has(e){return S(this,ee).has(e)}hasPresence(e){return(S(this,Ve).get(e)||0)!==0}getConsolidatedMultiplicity(e){return S(this,Ve).get(e)||0}getPresenceKeys(){return S(this,Ve).keys()}get(e){return[...this.getIterator(e)]}*getIterator(e){const n=S(this,ee).get(e);if(zn(n))yield n;else{if(n===void 0)return;if(n instanceof Ut)for(const s of n.values())yield s;else for(const s of n.values())if(zn(s))yield s;else for(const i of s.values())yield i}}*entries(){for(const e of S(this,ee).keys())for(const n of this.getIterator(e))yield[e,n]}*entriesIterators(){for(const e of S(this,ee).keys())yield[e,this.getIterator(e)]}addValue(e,n){const[s,i]=n;if(i===0)return;const r=(S(this,Ve).get(e)||0)+i;r===0?S(this,Ve).delete(e):S(this,Ve).set(e,r);const o=S(this,ee).get(e);if(o===void 0){S(this,ee).set(e,n);return}if(zn(o)){ie(this,_s,Ro).call(this,e,o,s,i);return}if(o instanceof Ut){const c=Jt(s);if(c!==Wt){const a=new _r;a.set(Wt,o),a.set(c,n),S(this,ee).set(e,a)}else o.addValue(s,i)&&S(this,ee).delete(e)}else o.addValue(s,i)&&S(this,ee).delete(e)}append(e){for(const[n,s]of e.entries())this.addValue(n,s)}join(e){const n=[];if(this.size<=e.size)for(const[s,i]of this.entriesIterators()){if(!e.has(s))continue;const r=e.get(s);for(const[o,c]of i)for(const[a,l]of r)c!==0&&l!==0&&n.push([[s,[o,a]],c*l])}else for(const[s,i]of e.entriesIterators()){if(!this.has(s))continue;const r=this.get(s);for(const[o,c]of i)for(const[a,l]of r)l!==0&&c!==0&&n.push([[s,[a,o]],l*c])}return new _e(n)}};ee=new WeakMap,Ve=new WeakMap,_s=new WeakSet,Ro=function(e,n,s,i){const[r,o]=n;if(r===s){const l=o+i;l===0?S(this,ee).delete(e):S(this,ee).set(e,[s,l]);return}const c=Jt(s),a=Jt(r);if(a===c&&(r===s||pe(r)===pe(s))){const l=o+i;l===0?S(this,ee).delete(e):S(this,ee).set(e,[s,l]);return}if(a===Wt&&c===Wt){const l=new Ut;l.set(pe(r),n),l.set(pe(s),[s,i]),S(this,ee).set(e,l)}else{const l=new _r;if(a===c){const f=new Ut;f.set(pe(r),n),f.set(pe(s),[s,i]),l.set(a,f)}else l.set(a,n),l.set(c,[s,i]);S(this,ee).set(e,l)}};let tt=Ui;function Jt(t){return Array.isArray(t)&&(typeof t[0]=="string"||typeof t[0]=="number"||typeof t[0]=="bigint")?t[0]:Wt}function zn(t){return Array.isArray(t)}var dn,yt,hn;class iu extends xt{constructor(n,s,i,r){super(n,s,i);P(this,dn,new tt);P(this,yt,new tt);P(this,hn);K(this,hn,r)}run(){const n=new Set;for(const i of this.inputMessages())for(const[r,o]of i.getInner()){const[c,a]=r;S(this,dn).addValue(c,[a,o]),n.add(c)}const s=[];for(const i of n){const r=S(this,dn).get(i),o=S(this,yt).get(i),c=S(this,hn).call(this,r),a=new Map,l=new Map;for(const[f,u]of c){const y=a.get(f)??0;a.set(f,y+u)}for(const[f,u]of o){const y=l.get(f)??0;l.set(f,y+u)}for(const[f,u]of l)a.has(f)||(s.push([[i,f],-u]),S(this,yt).addValue(i,[f,-u]));for(const[f,u]of a)l.has(f)||u!==0&&(s.push([[i,f],u]),S(this,yt).addValue(i,[f,u]));for(const[f,u]of a){const y=l.get(f);if(y!==void 0){const p=u-y;p!==0&&(s.push([[i,f],p]),S(this,yt).addValue(i,[f,p]))}}}s.length>0&&this.output.sendData(new _e(s))}}dn=new WeakMap,yt=new WeakMap,hn=new WeakMap;function Ao(t){return e=>{const n=new Re(e.graph,new Ee),s=new iu(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}var gt,Qe;class ru extends xt{constructor(n,s,i,r=o=>o){super(n,s,i);P(this,gt);P(this,Qe);K(this,gt,r),K(this,Qe,new Map)}run(){var i;const n=new Map;for(const r of this.inputMessages())for(const[o,c]of r.getInner()){const a=pe(S(this,gt).call(this,o)),f=(((i=n.get(a))==null?void 0:i[0])??S(this,Qe).get(a)??0)+c;n.set(a,[f,o])}const s=[];for(const[r,[o,c]]of n.entries()){const a=S(this,Qe).get(r)??0;o===0?S(this,Qe).delete(r):S(this,Qe).set(r,o),a<=0&&o>0?s.push([[pe(S(this,gt).call(this,c)),c[1]],1]):a>0&&o<=0&&s.push([[pe(S(this,gt).call(this,c)),c[1]],-1])}s.length>0&&this.output.sendData(new _e(s))}}gt=new WeakMap,Qe=new WeakMap;function ou(t=e=>e){return e=>{const n=new Re(e.graph,new Ee),s=new ru(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}var pn;class cu extends ki{constructor(n,s,i,r){super(n,s,i);P(this,pn);K(this,pn,r)}inner(n){return n.filter(S(this,pn))}}pn=new WeakMap;function je(t){return e=>{const n=new Re(e.graph,new Ee),s=new cu(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}const au="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Rt(t,e,n){const s=n[0];if(e!=null&&t>=e)throw new Error(t+" >= "+e);if(t.slice(-1)===s||e&&e.slice(-1)===s)throw new Error("trailing zero");if(e){let o=0;for(;(t[o]||s)===e[o];)o++;if(o>0)return e.slice(0,o)+Rt(t.slice(o),e.slice(o),n)}const i=t?n.indexOf(t[0]):0,r=e!=null?n.indexOf(e[0]):n.length;if(r-i>1){const o=Math.round(.5*(i+r));return n[o]}else return e&&e.length>1?e.slice(0,1):n[i]+Rt(t.slice(1),null,n)}function To(t){if(t.length!==Po(t[0]))throw new Error("invalid integer part of order key: "+t)}function Po(t){if(t>="a"&&t<="z")return t.charCodeAt(0)-97+2;if(t>="A"&&t<="Z")return 90-t.charCodeAt(0)+2;throw new Error("invalid order key head: "+t)}function qt(t){const e=Po(t[0]);if(e>t.length)throw new Error("invalid order key: "+t);return t.slice(0,e)}function wr(t,e){if(t==="A"+e[0].repeat(26))throw new Error("invalid order key: "+t);const n=qt(t);if(t.slice(n.length).slice(-1)===e[0])throw new Error("invalid order key: "+t)}function Sr(t,e){To(t);const[n,...s]=t.split("");let i=!0;for(let r=s.length-1;i&&r>=0;r--){const o=e.indexOf(s[r])+1;o===e.length?s[r]=e[0]:(s[r]=e[o],i=!1)}if(i){if(n==="Z")return"a"+e[0];if(n==="z")return null;const r=String.fromCharCode(n.charCodeAt(0)+1);return r>"a"?s.push(e[0]):s.pop(),r+s.join("")}else return n+s.join("")}function lu(t,e){To(t);const[n,...s]=t.split("");let i=!0;for(let r=s.length-1;i&&r>=0;r--){const o=e.indexOf(s[r])-1;o===-1?s[r]=e.slice(-1):(s[r]=e[o],i=!1)}if(i){if(n==="a")return"Z"+e.slice(-1);if(n==="A")return null;const r=String.fromCharCode(n.charCodeAt(0)-1);return r<"Z"?s.push(e.slice(-1)):s.pop(),r+s.join("")}else return n+s.join("")}function uu(t,e,n=au){if(t!=null&&wr(t,n),e!=null&&wr(e,n),t!=null&&e!=null&&t>=e)throw new Error(t+" >= "+e);if(t==null){if(e==null)return"a"+n[0];const a=qt(e),l=e.slice(a.length);if(a==="A"+n[0].repeat(26))return a+Rt("",l,n);if(a<e)return a;const f=lu(a,n);if(f==null)throw new Error("cannot decrement any more");return f}if(e==null){const a=qt(t),l=t.slice(a.length),f=Sr(a,n);return f??a+Rt(l,null,n)}const s=qt(t),i=t.slice(s.length),r=qt(e),o=e.slice(r.length);if(s===r)return s+Rt(i,o,n);const c=Sr(s,n);if(c==null)throw new Error("cannot increment any more");return c<e?c:s+Rt(i,null,n)}function br(t,e){return[t,e]}function vr(t){return t[0]}function Cr(t){return t[1]}function Mo(t){return([e,n],[s,i])=>{const r=t(n,i);return r!==0?r:Qs(e,s)}}var te,yn,le,fe,gn,Zs;class Ei{constructor(e,n,s){P(this,gn);P(this,te,[]);P(this,yn);P(this,le);P(this,fe);K(this,le,e),K(this,fe,e+n),K(this,yn,s)}get size(){const e=S(this,le),n=S(this,fe)-S(this,le),s=S(this,te).length-e;return Math.max(0,Math.min(n,s))}move({offset:e,limit:n}){const s=S(this,le),i=S(this,fe)-S(this,le),r=[S(this,le),S(this,fe)===1/0?S(this,le)+this.size:S(this,fe)];K(this,le,e??s),K(this,fe,S(this,le)+(n??i));const o=[S(this,le),S(this,fe)===1/0?Math.max(S(this,le)+this.size,r[1]):S(this,fe)],{onlyInA:c,onlyInB:a}=Cl(r,o),l=[];a.forEach(u=>{const y=S(this,te)[u];y&&l.push(y)});const f=[];return c.forEach(u=>{const y=S(this,te)[u];y&&f.push(y)}),{moveIns:l,moveOuts:f,changes:c.length+a.length>0}}insert(e){const n={moveIn:null,moveOut:null},s=ie(this,gn,Zs).call(this,e),i=s===0?null:Cr(S(this,te)[s-1]),r=s===S(this,te).length?null:Cr(S(this,te)[s]),o=uu(i,r),c=br(e,o);if(S(this,te).splice(s,0,c),s<S(this,fe)){const a=Math.max(s,S(this,le));a<S(this,te).length&&(n.moveIn=S(this,te)[a],S(this,fe)<S(this,te).length&&(n.moveOut=S(this,te)[S(this,fe)]))}return n}delete(e){const n={moveIn:null,moveOut:null},s=ie(this,gn,Zs).call(this,e),[i]=S(this,te).splice(s,1);if(s<S(this,fe)){if(n.moveOut=i,s<S(this,le)){const o=S(this,le)-1;o<S(this,te).length?n.moveOut=S(this,te)[o]:n.moveOut=null}const r=S(this,fe)-1;r<S(this,te).length&&(n.moveIn=S(this,te)[r])}return n}}te=new WeakMap,yn=new WeakMap,le=new WeakMap,fe=new WeakMap,gn=new WeakSet,Zs=function(e){return bl(S(this,te),br(e,""),(n,s)=>S(this,yn).call(this,vr(n),vr(s)))};var Ye,$e,ws,Do;class $o{constructor(e){P(this,ws);P(this,Ye,new Map);P(this,$e);K(this,$e,e)}get size(){return S(this,$e).size}get isEmpty(){return S(this,Ye).size===0&&S(this,$e).size===0}processElement(e,n,s){const{oldMultiplicity:i,newMultiplicity:r}=ie(this,ws,Do).call(this,e,s);return i<=0&&r>0?S(this,$e).insert([e,n]):i>0&&r<=0?S(this,$e).delete([e,n]):{moveIn:null,moveOut:null}}move(e){if(!(S(this,$e)instanceof Ei))throw new Error("Cannot move B+-tree implementation of TopK with fractional index");return S(this,$e).move(e)}}Ye=new WeakMap,$e=new WeakMap,ws=new WeakSet,Do=function(e,n){if(n===0){const r=S(this,Ye).get(e)??0;return{oldMultiplicity:r,newMultiplicity:r}}const s=S(this,Ye).get(e)??0,i=s+n;return i===0?S(this,Ye).delete(e):S(this,Ye).set(e,i),{oldMultiplicity:s,newMultiplicity:i}};function ss(t,e){if(t){const[[n,s],i]=t;e.push([[n,[s,i]],1])}}function is(t,e){if(t){const[[n,s],i]=t;e.push([[n,[s,i]],-1])}}var Ze,mn,_n,mt,_t,Oe,jo,Ko,Fo,Bo,Lo;class fu extends xt{constructor(n,s,i,r,o){var c,a;super(n,s,i);P(this,Oe);P(this,Ze,new Map);P(this,mn);P(this,_n);P(this,mt);P(this,_t);K(this,mn,o.groupKeyFn),K(this,_t,o.limit??1/0),K(this,mt,o.offset??0),K(this,_n,Mo(r)),(c=o.setSizeCallback)==null||c.call(o,()=>ie(this,Oe,jo).call(this)),(a=o.setWindowFn)==null||a.call(o,ie(this,Oe,Bo).bind(this))}createTopK(n,s,i){return new Ei(n,s,i)}run(){const n=[];for(const s of this.inputMessages())for(const[i,r]of s.getInner()){const[o,c]=i;ie(this,Oe,Lo).call(this,o,c,r,n)}n.length>0&&this.output.sendData(new _e(n))}}Ze=new WeakMap,mn=new WeakMap,_n=new WeakMap,mt=new WeakMap,_t=new WeakMap,Oe=new WeakSet,jo=function(){let n=0;for(const s of S(this,Ze).values())n+=s.size;return n},Ko=function(n){let s=S(this,Ze).get(n);if(!s){const i=this.createTopK(S(this,mt),S(this,_t),S(this,_n));s=new $o(i),S(this,Ze).set(n,s)}return s},Fo=function(n,s){s.isEmpty&&S(this,Ze).delete(n)},Bo=function({offset:n,limit:s}){n!==void 0&&K(this,mt,n),s!==void 0&&K(this,_t,s);const i=[];let r=!1;for(const o of S(this,Ze).values()){const c=o.move({offset:S(this,mt),limit:S(this,_t)});c.moveIns.forEach(a=>ss(a,i)),c.moveOuts.forEach(a=>is(a,i)),c.changes&&(r=!0)}r&&this.output.sendData(new _e(i))},Lo=function(n,s,i,r){const o=S(this,mn).call(this,n,s),c=ie(this,Oe,Ko).call(this,o),a=c.processElement(n,s,i);ss(a.moveIn,r),is(a.moveOut,r),ie(this,Oe,Fo).call(this,o,c)};function du(t,e){return n=>{const s=new Re(n.graph,new Ee),i=new fu(n.graph.getNextOperatorId(),n.connectReader(),s.writer,t,e);return n.graph.addOperator(i),s}}var Xe,et,De;class hu extends Oo{constructor(n,s,i,r,o="inner"){super(n,s,i,r);P(this,Xe,new tt);P(this,et,new tt);P(this,De);K(this,De,o)}run(){const n=tt.fromMultiSets(this.inputAMessages()),s=tt.fromMultiSets(this.inputBMessages());if(n.size===0&&s.size===0)return;const i=new _e;S(this,De)!=="anti"&&this.emitInnerResults(n,s,i),(S(this,De)==="left"||S(this,De)==="full"||S(this,De)==="anti")&&this.emitLeftOuterResults(n,s,i),(S(this,De)==="right"||S(this,De)==="full")&&this.emitRightOuterResults(n,s,i),S(this,Xe).append(n),S(this,et).append(s),i.getInner().length>0&&this.output.sendData(i)}emitInnerResults(n,s,i){n.size>0&&i.extend(n.join(S(this,et))),s.size>0&&i.extend(S(this,Xe).join(s)),n.size>0&&s.size>0&&i.extend(n.join(s))}emitLeftOuterResults(n,s,i){if(n.size>0)for(const[r,o]of n.entriesIterators()){const c=S(this,et).getConsolidatedMultiplicity(r),a=s.getConsolidatedMultiplicity(r);if(c+a===0)for(const[f,u]of o)u!==0&&i.add([r,[f,null]],u)}if(s.size>0)for(const r of s.getPresenceKeys()){const o=S(this,et).getConsolidatedMultiplicity(r),c=s.getConsolidatedMultiplicity(r);if(c===0)continue;const a=o+c;if(o===0==(a===0))continue;const l=o===0;for(const[f,u]of S(this,Xe).getIterator(r))u!==0&&i.add([r,[f,null]],l?-u:+u)}}emitRightOuterResults(n,s,i){if(s.size>0)for(const[r,o]of s.entriesIterators()){const c=S(this,Xe).getConsolidatedMultiplicity(r),a=n.getConsolidatedMultiplicity(r);if(c+a===0)for(const[f,u]of o)u!==0&&i.add([r,[null,f]],u)}if(n.size>0)for(const r of n.getPresenceKeys()){const o=S(this,Xe).getConsolidatedMultiplicity(r),c=n.getConsolidatedMultiplicity(r);if(c===0)continue;const a=o+c;if(o===0==(a===0))continue;const l=o===0;for(const[f,u]of S(this,et).getIterator(r))u!==0&&i.add([r,[null,f]],l?-u:+u)}}}Xe=new WeakMap,et=new WeakMap,De=new WeakMap;function Vo(t,e="inner"){return n=>{if(n.graph!==t.graph)throw new Error("Cannot join streams from different graphs");const s=new Re(n.graph,new Ee),i=new hu(n.graph.getNextOperatorId(),n.connectReader(),t.connectReader(),s.writer,e);return n.graph.addOperator(i),s}}var wn;class pu extends ki{constructor(n,s,i,r){super(n,s,i);P(this,wn);K(this,wn,r)}inner(n){return n.map(S(this,wn))}}wn=new WeakMap;function J(t){return e=>{const n=new Re(e.graph,new Ee),s=new pu(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}var Sn;class yu extends xt{constructor(n,s,i,r){super(n,s,i);P(this,Sn);K(this,Sn,r)}run(){for(const n of this.inputMessages())S(this,Sn).call(this,n),this.output.sendData(n)}}Sn=new WeakMap;function Xs(t){return e=>{const n=new Re(e.graph,new Ee),s=new yu(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}var bn;class gu extends ki{constructor(n,s,i,r){super(n,s,i);P(this,bn);K(this,bn,r)}inner(n){return S(this,bn).call(this,n),n}}bn=new WeakMap;function No(t){return e=>{const n=new Re(e.graph,new Ee),s=new gu(e.graph.getNextOperatorId(),e.connectReader(),n.writer,t);return e.graph.addOperator(s),n}}var wt;class mu extends xt{constructor(n,s,i,r,o){var f,u;super(n,s,i);P(this,wt);const c=o.limit??1/0,a=o.offset??0,l=this.createTopK(a,c,Mo(r));K(this,wt,new $o(l)),(f=o.setSizeCallback)==null||f.call(o,()=>S(this,wt).size),(u=o.setWindowFn)==null||u.call(o,this.moveTopK.bind(this))}createTopK(n,s,i){return new Ei(n,s,i)}moveTopK({offset:n,limit:s}){const i=[],r=S(this,wt).move({offset:n,limit:s});r.moveIns.forEach(o=>ss(o,i)),r.moveOuts.forEach(o=>is(o,i)),r.changes&&this.output.sendData(new _e(i))}run(){const n=[];for(const s of this.inputMessages())for(const[i,r]of s.getInner()){const[o,c]=i;this.processElement(o,c,r,n)}n.length>0&&this.output.sendData(new _e(n))}processElement(n,s,i,r){const o=S(this,wt).processElement(n,s,i);ss(o.moveIn,r),is(o.moveOut,r)}}wt=new WeakMap;function _u(t,e){const n=e||{};return s=>{const i=new Re(s.graph,new Ee),r=new mu(s.graph.getNextOperatorId(),s.connectReader(),i.writer,t,n);return s.graph.addOperator(r),i}}function xr(t){return"pipe"in t}function Ir(t,e={}){const n=Object.fromEntries(Object.entries(e).filter(([s,i])=>!xr(i)));return Object.fromEntries(Object.entries(e).filter(([s,i])=>xr(i))),s=>{const i="__original_key__";return s.pipe(J(c=>{const a=t(c),l=nn(a),f={};f[i]=a;for(const[u,y]of Object.entries(n))f[u]=y.preMap(c);return[l,f]})).pipe(Ao(c=>{var u,y;let a=0;for(const[p,h]of c)a+=h;if(a<=0)return[];const l={},f=(y=(u=c[0])==null?void 0:u[0])==null?void 0:y[i];l[i]=f;for(const[p,h]of Object.entries(n)){const d=c.map(([g,w])=>[g[p],w]);l[p]=h.reduce(d)}return[[l,1]]})).pipe(J(([c,a])=>{const l=a[i],f={};Object.assign(f,l);for(const[u,y]of Object.entries(n))y.postMap?f[u]=y.postMap(a[u]):f[u]=a[u];return[c,f]}))}}function wu(t=e=>e){return{preMap:e=>t(e),reduce:e=>{let n=0;for(const[s,i]of e)n+=s*i;return n}}}function Su(t=e=>e){return{preMap:e=>t(e)==null?0:1,reduce:e=>{let n=0;for(const[s,i]of e)n+=s*i;return n}}}function bu(t=e=>e){return{preMap:e=>({sum:t(e),count:0}),reduce:e=>{let n=0,s=0;for(const[i,r]of e)n+=i.sum*r,s+=r;return{sum:n,count:s}},postMap:e=>e.sum/e.count}}function vu(t){const e=t??(n=>n);return{preMap:n=>e(n),reduce:n=>{let s;for(const[i,r]of n)(!s||i&&i<s)&&(s=i);return s}}}function Cu(t){const e=t??(n=>n);return{preMap:n=>e(n),reduce:n=>{let s;for(const[i,r]of n)(!s||i&&i>s)&&(s=i);return s}}}const xu={sum:wu,count:Su,avg:bu,min:vu,max:Cu};function Iu(t,e){const n=e.limit??1/0,s=e.offset??0,i=e.setSizeCallback,r=e.setWindowFn,o=e.groupKeyFn,c=e.comparator??((a,l)=>a===l?0:a<l?-1:1);return a=>a.pipe(du((l,f)=>c(t(l),t(f)),{limit:n,offset:s,setSizeCallback:i,setWindowFn:r,groupKeyFn:o}),Eo())}function Ou(t,e,n){const s=(n==null?void 0:n.limit)??1/0,i=(n==null?void 0:n.offset)??0,r=n==null?void 0:n.setSizeCallback,o=n==null?void 0:n.setWindowFn,c=(n==null?void 0:n.comparator)??((a,l)=>a===l?0:a<l?-1:1);return a=>a.pipe(t((l,f)=>c(e(l),e(f)),{limit:s,offset:i,setSizeCallback:r,setWindowFn:o}),Eo())}function ku(t,e){return Ou(_u,t,e)}const Fs="__virtual_synced__",Bs="__virtual_has_local__",ei="__group_key_";function Or(t){let e=!1,n=!0,s=!1;for(const[i,r]of Object.entries(t)){if(i==="$selected"||r===null||typeof r!="object")continue;const o=r,c="$synced"in o,a="$origin"in o;!c&&!a||(e=!0,o.$synced===!1&&(n=!1),o.$origin==="local"&&(s=!0))}return{synced:e?n:!0,hasLocal:s}}const{sum:Eu,count:Ru,avg:Au,min:Tu,max:Pu}=xu;function Mu(t,e){const n=new Map,s=[...t];if(!e)return{selectToGroupByIndex:n,groupByExpressions:s};for(const[i,r]of Object.entries(e)){if(r.type==="agg"||we(r))continue;const o=s.findIndex(c=>rn(r,c));if(o===-1)throw new Na(i);n.set(i,o)}return{selectToGroupByIndex:n,groupByExpressions:s}}function kr(t,e,n,s,i,r,o){const c={[Fs]:{preMap:([,h])=>Or(h).synced,reduce:h=>{for(const[d,g]of h)if(!d&&g>0)return!1;return!0}},[Bs]:{preMap:([,h])=>Or(h).hasLocal,reduce:h=>{for(const[d,g]of h)if(d&&g>0)return!0;return!1}}};if(e.length===0){const h=c,d={},g={value:0};if(s){for(const[C,m]of Object.entries(s))if(m.type==="agg")h[C]=Pn(m);else if(we(m)){const{transformed:b,extracted:v}=ut(m,g);for(const[x,I]of Object.entries(v))h[x]=Pn(I);d[C]=on(b)}}const w=o?([,C])=>{var m;return{__singleGroup:!0,__correlationKey:(m=C==null?void 0:C[o])==null?void 0:m.__correlationKey}}:()=>({__singleGroup:!0});if(t=t.pipe(Ir(w,h)),t=t.pipe(J(([,C])=>{const b={...C.$selected||{}};if(s){for(const[E,k]of Object.entries(s))k.type==="agg"&&(b[E]=C[E]);Er(b,C,d)}const v=o?C.__correlationKey:void 0,x=v!==void 0?`single_group_${nn(v)}`:"single_group",I={...C,$selected:b},M=C[Fs],O=C[Bs];return I.$synced=M??!0,I.$origin=O?"local":"remote",I.$key=x,I.$collectionId=r??I.$collectionId,o&&v!==void 0&&(I[o]={__correlationKey:v}),[x,I]})),n&&n.length>0)for(const C of n){const m=or(C),b=rs(m,s||{},"$selected"),v=q(b);t=t.pipe(je(([,x])=>{const I={$selected:x.$selected};return Tt(v(I))}))}if(i&&i.length>0)for(const C of i)t=t.pipe(je(([,m])=>{const b={$selected:m.$selected};return Tt(C(b))}));return t}const a=Mu(e,s),l=e.map(h=>q(h)),f=([,h])=>{var w;const d={...h};delete d.$selected;const g={};for(let C=0;C<e.length;C++){const m=l[C],b=m(d);g[`__key_${C}`]=b}return o&&(g.__correlationKey=(w=h==null?void 0:h[o])==null?void 0:w.__correlationKey),g},u=c,y={},p={value:0};if(s){for(const[h,d]of Object.entries(s))if(d.type==="agg")u[h]=Pn(d);else if(we(d)){const{transformed:g,extracted:w}=ut(d,p);for(const[C,m]of Object.entries(w))u[C]=Pn(m);y[h]=on(Wn(g,e))}}if(t=t.pipe(Ir(f,u)),t=t.pipe(J(([,h])=>{const d=h.$selected||{},g={};if(s){for(const[I,M]of Object.entries(s))if(M.type==="agg")g[I]=h[I];else if(!y[I]){const O=a.selectToGroupByIndex.get(I);O!==void 0?g[I]=h[`__key_${O}`]:g[I]=d[I]}Er(g,h,y,e.length)}else for(let I=0;I<e.length;I++)g[`__key_${I}`]=h[`__key_${I}`];const w=o?h.__correlationKey:void 0,C=[];for(let I=0;I<e.length;I++)C.push(h[`__key_${I}`]);w!==void 0&&C.push(w);const m=C.length===1?C[0]:nn(C),b={...h,$selected:g},v=h[Fs],x=h[Bs];return b.$synced=v??!0,b.$origin=x?"local":"remote",b.$key=m,b.$collectionId=r??b.$collectionId,o&&w!==void 0&&(b[o]={__correlationKey:w}),[m,b]})),n&&n.length>0)for(const h of n){const d=or(h),g=rs(d,s||{}),w=q(g);t=t.pipe(je(([,C])=>{const m={$selected:C.$selected};return w(m)}))}if(i&&i.length>0)for(const h of i)t=t.pipe(je(([,d])=>{const g={$selected:d.$selected};return Tt(h(g))}));return t}function rn(t,e){var n,s,i,r;if(!t||!e||t.type!==e.type)return!1;switch(t.type){case"ref":return!t.path||!e.path||t.path.length!==e.path.length?!1:t.path.every((o,c)=>o===e.path[c]);case"val":return t.value===e.value;case"func":return t.name===e.name&&((n=t.args)==null?void 0:n.length)===((s=e.args)==null?void 0:s.length)&&(t.args||[]).every((o,c)=>rn(o,e.args[c]));case"agg":return t.name===e.name&&((i=t.args)==null?void 0:i.length)===((r=e.args)==null?void 0:r.length)&&(t.args||[]).every((o,c)=>rn(o,e.args[c]));default:return!1}}function Pn(t){const e=q(t.args[0]),n=([,r])=>{const o=e(r);return typeof o=="number"?o:o!=null?Number(o):0},s=([,r])=>{const o=e(r);return typeof o=="number"||typeof o=="string"||typeof o=="bigint"||o instanceof Date?o:o!=null?Number(o):0},i=([,r])=>e(r);switch(t.name.toLowerCase()){case"sum":return Eu(n);case"count":return Ru(i);case"avg":return Au(n);case"min":return Tu(s);case"max":return Pu(s);default:throw new za(t.name)}}function rs(t,e,n="$selected"){switch(t.type){case"agg":{const s=t;for(const[i,r]of Object.entries(e))if(r.type==="agg"&&ju(s,r))return new G([n,i]);throw new Wa(s.name)}case"func":{const s=t,i=s.args.map(r=>rs(r,e));return new ye(s.name,i)}case"ref":return t;case"val":return t;default:throw new Ua(t.type)}}function Er(t,e,n,s=0){for(const i of Object.keys(e))i.startsWith("__agg_")&&(t[i]=e[i]);for(let i=0;i<s;i++)t[`${ei}${i}`]=e[`__key_${i}`];for(const[i,r]of Object.entries(n))t[i]=r({$selected:t});for(const i of Object.keys(t))(i.startsWith("__agg_")||i.startsWith(ei))&&delete t[i]}function we(t){return Os(t)?t.branches.some(n=>we(n.condition)||we(n.value))||t.defaultValue!==void 0&&we(t.defaultValue):Is(t)?Object.values(t).some(e=>we(e)):Ie(t)?t.type==="agg"?!0:t.type==="func"&&"args"in t?t.args.some(e=>we(e)):!1:!1}function ut(t,e){if(t.type==="includesSubquery")return{transformed:t,extracted:{}};if(t.type==="agg"){const n=`__agg_${e.value++}`;return{transformed:new G(["$selected",n]),extracted:{[n]:t}}}if(t.type==="func"){const n={},s=t.args.map(i=>{const r=ut(i,e);return Object.assign(n,r.extracted),r.transformed});return{transformed:new ye(t.name,s),extracted:n}}if(Os(t)){const n={},s=t.branches.map(r=>{const o=ut(r.condition,e),c=ut(r.value,e);return Object.assign(n,o.extracted,c.extracted),{condition:o.transformed,value:c.transformed}}),i=t.defaultValue===void 0?void 0:ut(t.defaultValue,e);return i&&Object.assign(n,i.extracted),{transformed:new he(s,i==null?void 0:i.transformed),extracted:n}}if(Is(t)){const n={},s={};for(const[i,r]of Object.entries(t)){const o=ut(r,e);Object.assign(n,o.extracted),s[i]=o.transformed}return{transformed:s,extracted:n}}return{transformed:t,extracted:{}}}function Wn(t,e){if(Os(t))return new he(t.branches.map(n=>({condition:ti(n.condition,e),value:Wn(n.value,e)})),t.defaultValue===void 0?void 0:Wn(t.defaultValue,e));if(Is(t)){const n={};for(const[s,i]of Object.entries(t))n[s]=Wn(i,e);return n}return!Ie(t)||t.type==="includesSubquery"||t.type==="agg"?t:ti(t,e)}function ti(t,e){if(t.type==="ref"){const n=e.findIndex(s=>rn(t,s));return n===-1?t:new G(["$selected",`${ei}${n}`])}return t.type==="func"?new ye(t.name,t.args.map(n=>ti(n,e))):t}function on(t){return Os(t)?Du(t):t.type==="includesSubquery"?()=>null:Is(t)?$u(t):Ie(t)?q(t):()=>t}function $u(t){const e=Object.entries(t).map(([n,s])=>{if(n.startsWith("__SPREAD_SENTINEL__")){const i=n.slice(19),r=i.lastIndexOf("__"),o=r>=0?i.slice(0,r):i,a=typeof s=="object"&&"type"in s&&s.type==="ref"?s:new G(o.split("."));return{key:n,spread:!0,value:q(a)}}return{key:n,spread:!1,value:on(s)}});return n=>{const s={};for(const i of e){const r=i.value(n);i.spread?r&&typeof r=="object"&&Object.assign(s,r):s[i.key]=r}return s}}function Du(t){const e=t.branches.map(s=>({condition:q(s.condition),value:on(s.value)})),n=t.defaultValue===void 0?void 0:on(t.defaultValue);return s=>{for(const i of e)if(xs(i.condition(s)))return i.value(s);return n!==void 0?n(s):null}}function Is(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)&&!t.__refProxy&&!Ie(t)}function Os(t){return t instanceof he||t!=null&&typeof t=="object"&&t.type==="conditionalSelect"}function ju(t,e){return t.name===e.name&&t.args.length===e.args.length&&t.args.every((n,s)=>rn(n,e.args[s]))}function Ku(t,e,n,s,i,r,o,c,a,l){const f=n.map(d=>{const g=rs(d.expression,s,"$selected");return{compiledExpression:q(g),compareOptions:ni(d,i)}}),u=d=>{const g=d;return n.length>1?f.map(w=>w.compiledExpression(g)):n.length===1?f[0].compiledExpression(g):null},y=(d,g)=>{if(n.length>1){const w=d,C=g;for(let m=0;m<n.length;m++){const b=f[m],x=Gt(b.compareOptions)(w[m],C[m]);if(x!==0)return x}return w.length-C.length}if(n.length===1){const w=f[0];return Gt(w.compareOptions)(d,g)}return el(d,g)};let p,h;if(c&&!l&&t.from.type!=="unionFrom"&&t.from.type!=="unionAll"){let d,g,w,C=t.from.alias;const m=n[0],b=m.expression;if(b.type==="ref"){const v=tn(t,b,i);if(v){g=v.collection;const x=v.path[0],I=ni(m,g);if(x){const M=Gt(I);In(x,v.path,g,I,M)}if(w=q(new G(v.path),!0),d=xn(g,v.path,I),d!=null&&d.supports("gt")||(d=void 0),!d){const M=g.id,O=v.path.join(".");console.warn(`[TanStack DB]${M?` [${M}]`:""} orderBy with limit requires an index on "${O}" for efficient lazy loading. Falling back to loading all data. Consider creating an index on the collection with collection.createIndex((row) => row.${O}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`)}C=b.path.length>1?String(b.path[0]):t.from.alias}}if(w){const x=n.every(E=>E.expression.type==="ref")?n.map(E=>{const k=E.expression,V=tn(t,k,i);return q(V?new G(V.path):E.expression,!0)}):void 0;h={alias:C,offset:a??0,limit:c,comparator:(E,k)=>{if(n.length===1){const V=E&&w(E),F=k&&w(k);return y(V,F)}if(x){const V=F=>F&&x.map(qe=>qe(F));return y(V(E),V(k))}return 0},valueExtractorForRawRow:E=>{if(n.length===1)return w(E);if(x)return x.map(k=>k(E))},firstColumnValueExtractor:w,index:d,orderBy:n};const O=(g==null?void 0:g.id)??i.id;r[O]=h,d&&(p=E=>{r[O].dataNeeded=()=>{const k=E();return Math.max(0,h.limit-k)}})}}return l?e.pipe(Iu(u,{limit:c,offset:a,comparator:y,setSizeCallback:p,groupKeyFn:l,setWindowFn:d=>{o(g=>{d(g),h&&(h.offset=g.offset??h.offset,h.limit=g.limit??h.limit)})}})):e.pipe(ku(u,{limit:c,offset:a,comparator:y,setSizeCallback:p,setWindowFn:d=>{o(g=>{d(g),h&&(h.offset=g.offset??h.offset,h.limit=g.limit??h.limit)})}}))}function ni(t,e){return t.compareOptions.stringSort!==void 0?t.compareOptions:{...e.compareOptions,direction:t.compareOptions.direction,nulls:t.compareOptions.nulls}}function Fu(t,e={}){const n=s=>{const i=[];for(const[r,o]of t.entries())((s==null?void 0:s(o))??!0)&&i.push({type:"insert",key:r,value:o});return i};if(e.limit!==void 0&&!e.orderBy)throw new Error("limit cannot be used without orderBy");if(e.orderBy){const s=e.where?Qt(e.where):void 0,i=Lu(t,e.orderBy,e.limit,s,e.optimizedOnly);if(i===void 0)return;const r=[];for(const o of i){const c=t.get(o);c!==void 0&&r.push({type:"insert",key:o,value:c})}return r}if(!e.where)return n();try{const s=e.where,i=dl(s,t);if(i.canOptimize){const r=[];for(const o of i.matchingKeys){const c=t.get(o);c!==void 0&&r.push({type:"insert",key:o,value:c})}return r}else{if(e.optimizedOnly)return;const r=Qt(s);return n(r)}}catch(s){console.warn(`${t.id?`[${t.id}] `:""}Error processing where clause, falling back to full scan:`,s);const i=Qt(e.where);return e.optimizedOnly?void 0:n(i)}}function Qt(t){const e=wo(t);return n=>{try{const s=e(n);return Tt(s)}catch{return!1}}}function Bu(t,e){const n=Qt(e.whereExpression);return s=>{const i=[];for(const r of s)if(r.type==="insert")n(r.value)&&i.push(r);else if(r.type==="update"){const o=n(r.value),c=r.previousValue?n(r.previousValue):!1;o&&c?i.push(r):o&&!c?i.push({...r,type:"insert"}):!o&&c&&i.push({...r,type:"delete",value:r.previousValue})}else n(r.value)&&i.push(r);(i.length>0||s.length===0)&&t(i)}}function Lu(t,e,n,s,i){if(e.length===1){const a=e[0],l=a.expression;if(l.type==="ref"){const u=l.path,y=ni(a,t);In(u[0],u,t,y);const p=xn(t,u,y);if(p&&p.supports("gt")){const h=d=>{const g=t.get(d);return g===void 0?!1:(s==null?void 0:s(g))??!0};return p.takeFromStart(n??p.keyCount,h)}}}if(i)return;const r=[];for(const[a,l]of t.entries())((s==null?void 0:s(l))??!0)&&r.push({key:a,value:l});const o=(a,l)=>{for(const f of e){const u=Gt(f.compareOptions),y=Rr(a.value,f.expression),p=Rr(l.value,f.expression),h=u(y,p);if(h!==0)return h}return 0};r.sort(o);const c=r.map(a=>a.key);return n!==void 0?c.slice(0,n):c}function Rr(t,e){if(e.type==="ref"){const n=e;let s=t;for(const i of n.path)s=s==null?void 0:s[i];return s}else return e.type==="val"?e.value:wo(e)(t)}class Ar{constructor(e){this.map=new Map,this.sortedKeys=[],this.comparator=e}indexOf(e,n){let s=0,i=this.sortedKeys.length;if(!this.comparator){for(;s<i;){const r=Math.floor((s+i)/2),o=this.sortedKeys[r],c=Qs(e,o);if(c<0)i=r;else if(c>0)s=r+1;else return r}return s}for(;s<i;){const r=Math.floor((s+i)/2),o=this.sortedKeys[r],c=this.map.get(o),a=this.comparator(n,c);if(a<0)i=r;else if(a>0)s=r+1;else{const l=Qs(e,o);if(l<0)i=r;else if(l>0)s=r+1;else return r}}return s}set(e,n){if(this.map.has(e)){const i=this.map.get(e),r=this.indexOf(e,i);this.sortedKeys.splice(r,1)}const s=this.indexOf(e,n);return this.sortedKeys.splice(s,0,e),this.map.set(e,n),this}get(e){return this.map.get(e)}delete(e){if(this.map.has(e)){const n=this.map.get(e),s=this.indexOf(e,n);return this.sortedKeys.splice(s,1),this.map.delete(e)}return!1}has(e){return this.map.has(e)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(const e of this.sortedKeys)yield[e,this.map.get(e)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(const e of this.sortedKeys)yield this.map.get(e)}).call(this)}forEach(e){for(const n of this.sortedKeys)e(this.map.get(n),n,this.map)}}const Un="__tanstack_db_direct";class Vu{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=()=>{var c;let n=!1;for(const a of this.transactions.values())if(a.state==="persisting"){n=!0;break}const{committedSyncedTransactions:s,uncommittedSyncedTransactions:i,hasTruncateSync:r,hasImmediateSync:o}=this.pendingSyncedTransactions.reduce((a,l)=>(l.committed?(a.committedSyncedTransactions.push(l),l.truncate&&(a.hasTruncateSync=!0),l.immediate&&(a.hasImmediateSync=!0)):a.uncommittedSyncedTransactions.push(l),a),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!n||r||o){this.isCommittingSyncTransactions=!0;const a=new Map(this.rowOrigins),l=new Map(this.optimisticUpserts),f=new Set(this.optimisticDeletes),u=r?(c=s.find(m=>m.truncate))==null?void 0:c.optimisticSnapshot:null;let y,p;const h=new Set;for(const m of s){for(const b of m.operations)h.add(b.key);for(const[b]of m.rowMetadataWrites)h.add(b)}let d=this.preSyncVisibleState;if(d.size===0){d=new Map;for(const m of h){const b=this.get(m);b!==void 0&&d.set(m,b)}}const g=[],w=this.config.sync.rowUpdateMode||"partial",C=new Map;for(const m of this.transactions.values())if(m.state==="completed")for(const b of m.mutations)this.isThisCollection(b.collection)&&b.optimistic&&C.set(b.key,{type:b.type,value:b.modified});for(const m of s){if(m.truncate){const b=new Set([...this.syncedData.keys(),...(u==null?void 0:u.upserts.keys())||[]]);for(const v of b){if(u!=null&&u.deletes.has(v))continue;const x=(u==null?void 0:u.upserts.get(v))||this.syncedData.get(v);x!==void 0&&g.push({type:"delete",key:v,value:x})}y=new Set(this.pendingLocalChanges),p=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(const v of h)d.delete(v);this._events.emit("truncate",{type:"truncate",collection:this.collection})}for(const b of m.operations){const v=b.key;this.syncedKeys.add(v);const x=this.isLocalOnly||this.pendingLocalChanges.has(v)||this.pendingLocalOrigins.has(v)||(y==null?void 0:y.has(v))===!0||(p==null?void 0:p.has(v))===!0?"local":"remote";switch(b.type){case"insert":this.syncedData.set(v,b.value),this.rowOrigins.set(v,x),this.pendingLocalChanges.delete(v),this.pendingLocalOrigins.delete(v),this.pendingOptimisticUpserts.delete(v),this.pendingOptimisticDeletes.delete(v),this.pendingOptimisticDirectUpserts.delete(v),this.pendingOptimisticDirectDeletes.delete(v);break;case"update":{if(w==="partial"){const I=Object.assign({},this.syncedData.get(v),b.value);this.syncedData.set(v,I)}else this.syncedData.set(v,b.value);this.rowOrigins.set(v,x),this.pendingLocalChanges.delete(v),this.pendingLocalOrigins.delete(v),this.pendingOptimisticUpserts.delete(v),this.pendingOptimisticDeletes.delete(v),this.pendingOptimisticDirectUpserts.delete(v),this.pendingOptimisticDirectDeletes.delete(v);break}case"delete":this.syncedData.delete(v),this.syncedMetadata.delete(v),this.rowOrigins.delete(v),this.pendingLocalChanges.delete(v),this.pendingLocalOrigins.delete(v),this.pendingOptimisticUpserts.delete(v),this.pendingOptimisticDeletes.delete(v),this.pendingOptimisticDirectUpserts.delete(v),this.pendingOptimisticDirectDeletes.delete(v);break}}for(const[b,v]of m.rowMetadataWrites){if(v.type==="delete"){this.syncedMetadata.delete(b);continue}this.syncedMetadata.set(b,v.value)}for(const[b,v]of m.collectionMetadataWrites){if(v.type==="delete"){this.syncedCollectionMetadata.delete(b);continue}this.syncedCollectionMetadata.set(b,v.value)}}if(r){const m=new Set;for(const x of s)for(const I of x.operations)(I.type==="insert"||I.type==="update")&&m.add(I.key);const b=new Map(u.upserts),v=new Set(u.deletes);for(const[x,I]of b)if(!v.has(x))if(m.has(x)){let M=!1;for(let O=g.length-1;O>=0;O--){const E=g[O];if(E.key===x&&E.type==="insert"){E.value=I,M=!0;break}}M||g.push({type:"insert",key:x,value:I})}else g.push({type:"insert",key:x,value:I});if(g.length>0&&v.size>0){const x=[];for(const I of g)I.type==="insert"&&v.has(I.key)||x.push(I);g.length=0,g.push(...x)}this.lifecycle.status!=="ready"&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,r&&u){for(const[m,b]of u.upserts)this.optimisticUpserts.set(m,b);for(const m of u.deletes)this.optimisticDeletes.add(m)}for(const m of this.transactions.values())if(!["completed","failed"].includes(m.state)){for(const b of m.mutations)if(this.isThisCollection(b.collection)&&b.optimistic)switch(b.type){case"insert":case"update":this.optimisticUpserts.set(b.key,b.modified),this.optimisticDeletes.delete(b.key);break;case"delete":this.optimisticUpserts.delete(b.key),this.optimisticDeletes.add(b.key);break}}for(const m of this.pendingOptimisticDirectUpserts)if(!h.has(m)){if(h.add(m),!d.has(m)){const b=l.get(m);b!==void 0&&d.set(m,b)}this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m)}for(const m of this.pendingOptimisticDirectDeletes)h.has(m)||h.add(m),this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear();for(const m of h){const b=d.get(m),v=this.get(m),x=this.getVirtualPropsSnapshotForState(m,{rowOrigins:a,optimisticUpserts:l,optimisticDeletes:f,completedOptimisticKeys:C}),I=this.getVirtualPropsSnapshotForState(m),M=x.$synced!==I.$synced||x.$origin!==I.$origin,O=b!==void 0?gr(b,m,this.collection.id,()=>x.$synced,()=>x.$origin):void 0,E=C.get(m);let k=!1;E&&(E.type==="delete"&&b!==void 0&&v===void 0&&Ke(E.value,b)||v!==void 0&&Ke(E.value,v))&&(k=!0);const V=M&&b!==void 0&&v!==void 0&&Ke(b,v);if(!(k&&!V))if(b===void 0&&v!==void 0){const F=C.get(m);if(F){const qe=F.value,En=gr(qe,m,this.collection.id,()=>x.$synced,()=>x.$origin);g.push({type:"update",key:m,value:v,previousValue:En})}else g.push({type:"insert",key:m,value:v})}else b!==void 0&&v===void 0?g.push({type:"delete",key:m,value:O??b}):b!==void 0&&v!==void 0&&(!Ke(b,v)||V)&&g.push({type:"update",key:m,value:v,previousValue:O??b})}this.size=this.calculateSize(),g.length>0&&this.indexes.updateIndexes(g),this.changes.emitEvents(g,!0),this.pendingSyncedTransactions=i,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=e,this.transactions=new Ar((n,s)=>n.compareCreatedAt(s)),this.syncedData=new Ar(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,n){return{$synced:(n==null?void 0:n.$synced)??this.isRowSynced(e),$origin:(n==null?void 0:n.$origin)??this.getRowOrigin(e),$key:(n==null?void 0:n.$key)??e,$collectionId:(n==null?void 0:n.$collectionId)??this.collection.id}}getVirtualPropsSnapshotForState(e,n){var o;if(this.isLocalOnly)return this.createVirtualPropsSnapshot(e,{$synced:!0,$origin:"local"});const s=(n==null?void 0:n.optimisticUpserts)??this.optimisticUpserts,i=(n==null?void 0:n.optimisticDeletes)??this.optimisticDeletes,r=s.has(e)||i.has(e)||((o=n==null?void 0:n.completedOptimisticKeys)==null?void 0:o.has(e))===!0;return this.createVirtualPropsSnapshot(e,{$synced:!r,$origin:r?"local":((n==null?void 0:n.rowOrigins)??this.rowOrigins).get(e)??"remote"})}enrichWithVirtualPropsSnapshot(e,n){const s=e,i=s.$synced??n.$synced,r=s.$origin??n.$origin,o=s.$key??n.$key,c=s.$collectionId??n.$collectionId,a=this.virtualPropsCache.get(e);if(a&&a.synced===i&&a.origin===r&&a.key===o&&a.collectionId===c)return a.enriched;const l={...e,$synced:i,$origin:r,$key:o,$collectionId:c};return this.virtualPropsCache.set(e,{synced:i,origin:r,key:o,collectionId:c,enriched:l}),l}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(e,n){return this.enrichWithVirtualPropsSnapshot(e,this.createVirtualPropsSnapshot(n))}enrichChangeMessage(e){const{__virtualProps:n}=e,s=n!=null&&n.value?this.enrichWithVirtualPropsSnapshot(e.value,n.value):this.enrichWithVirtualProps(e.value,e.key),i=e.previousValue?n!=null&&n.previousValue?this.enrichWithVirtualPropsSnapshot(e.previousValue,n.previousValue):this.enrichWithVirtualProps(e.previousValue,e.key):void 0;return{key:e.key,type:e.type,value:s,previousValue:i,metadata:e.metadata}}getWithVirtualProps(e){const n=this.get(e);if(n!==void 0)return this.enrichWithVirtualProps(n,e)}get(e){const{optimisticDeletes:n,optimisticUpserts:s,syncedData:i}=this;if(!n.has(e))return s.has(e)?s.get(e):i.get(e)}has(e){const{optimisticDeletes:n,optimisticUpserts:s,syncedData:i}=this;return n.has(e)?!1:s.has(e)?!0:i.has(e)}*keys(){const{syncedData:e,optimisticDeletes:n,optimisticUpserts:s}=this;for(const i of e.keys())n.has(i)||(yield i);for(const i of s.keys())!e.has(i)&&!n.has(i)&&(yield i)}*values(){for(const e of this.keys()){const n=this.get(e);n!==void 0&&(yield n)}}*entries(){for(const e of this.keys()){const n=this.get(e);n!==void 0&&(yield[e,n])}}*[Symbol.iterator](){for(const[e,n]of this.entries())yield[e,n]}forEach(e){let n=0;for(const[s,i]of this.entries())e(i,s,n++)}map(e){const n=[];let s=0;for(const[i,r]of this.entries())n.push(e(r,i,s++));return n}isThisCollection(e){return e===this.collection}recomputeOptimisticState(e=!1){if(this.isCommittingSyncTransactions&&!e)return;const n=new Map(this.optimisticUpserts),s=new Set(this.optimisticDeletes),i=new Map(this.rowOrigins);for(const u of this.transactions.values()){const y=u.metadata[Un]===!0;if(u.state==="completed"){for(const p of u.mutations)if(this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.add(p.key),!!p.optimistic))switch(p.type){case"insert":case"update":this.pendingOptimisticUpserts.set(p.key,p.modified),this.pendingOptimisticDeletes.delete(p.key),y?(this.pendingOptimisticDirectUpserts.add(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break;case"delete":this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.add(p.key),y?(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.add(p.key)):(this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key));break}}else if(u.state==="failed")for(const p of u.mutations)this.isThisCollection(p.collection)&&(this.pendingLocalOrigins.delete(p.key),p.optimistic&&(this.pendingOptimisticUpserts.delete(p.key),this.pendingOptimisticDeletes.delete(p.key),this.pendingOptimisticDirectUpserts.delete(p.key),this.pendingOptimisticDirectDeletes.delete(p.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const r=new Set;for(const u of this.pendingSyncedTransactions)for(const y of u.operations)r.add(y.key);const o=[];for(const[u,y]of this.pendingOptimisticUpserts)r.has(u)||this.pendingOptimisticDirectUpserts.has(u)?this.optimisticUpserts.set(u,y):o.push(u);for(const u of o)this.pendingOptimisticUpserts.delete(u),this.pendingLocalOrigins.delete(u);const c=[];for(const u of this.pendingOptimisticDeletes)r.has(u)||this.pendingOptimisticDirectDeletes.has(u)?this.optimisticDeletes.add(u):c.push(u);for(const u of c)this.pendingOptimisticDeletes.delete(u),this.pendingLocalOrigins.delete(u);const a=[];for(const u of this.transactions.values())["completed","failed"].includes(u.state)||a.push(u);for(const u of a)for(const y of u.mutations)if(this.isThisCollection(y.collection)&&(this.pendingLocalChanges.add(y.key),y.optimistic))switch(y.type){case"insert":case"update":this.optimisticUpserts.set(y.key,y.modified),this.optimisticDeletes.delete(y.key);break;case"delete":this.optimisticUpserts.delete(y.key),this.optimisticDeletes.add(y.key);break}this.size=this.calculateSize();const l=[];this.collectOptimisticChanges(n,s,i,l);const f=l.filter(u=>!!(!this.recentlySyncedKeys.has(u.key)||e));if(this.pendingSyncedTransactions.length>0&&!e){const u=new Set;for(const p of this.pendingSyncedTransactions)for(const h of p.operations)u.add(h.key);const y=f.filter(p=>!(p.type==="delete"&&u.has(p.key)&&!a.some(d=>d.mutations.some(g=>this.isThisCollection(g.collection)&&g.key===p.key))));y.length>0&&this.indexes.updateIndexes(y),this.changes.emitEvents(y,e)}else f.length>0&&this.indexes.updateIndexes(f),this.changes.emitEvents(f,e)}calculateSize(){const e=this.syncedData.size,n=Array.from(this.optimisticDeletes).filter(i=>this.syncedData.has(i)&&!this.optimisticUpserts.has(i)).length,s=Array.from(this.optimisticUpserts.keys()).filter(i=>!this.syncedData.has(i)).length;return e-n+s}collectOptimisticChanges(e,n,s,i){const r=new Set([...e.keys(),...this.optimisticUpserts.keys(),...n,...this.optimisticDeletes]);for(const o of r){const c=this.get(o),a=this.getPreviousValue(o,e,n),l=this.getVirtualPropsSnapshotForState(o,{rowOrigins:s,optimisticUpserts:e,optimisticDeletes:n}),f=this.getVirtualPropsSnapshotForState(o);a!==void 0&&c===void 0?i.push({type:"delete",key:o,value:a,__virtualProps:{value:l}}):a===void 0&&c!==void 0?i.push({type:"insert",key:o,value:c,__virtualProps:{value:f}}):a!==void 0&&c!==void 0&&a!==c&&i.push({type:"update",key:o,value:c,previousValue:a,__virtualProps:{value:f,previousValue:l}})}}getPreviousValue(e,n,s){if(!s.has(e))return n.has(e)?n.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;const e=new Set;for(const n of this.pendingSyncedTransactions)for(const s of n.operations)e.add(s.key);for(const n of e)this.recentlySyncedKeys.add(n);for(const n of e)if(!this.preSyncVisibleState.has(n)){const s=this.get(n);s!==void 0&&this.preSyncVisibleState.set(n,s)}}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 zo(){const t=new Map;function e(n){const s=n.join(".");if(t.has(s))return t.get(s);const i=new Proxy({},{get(r,o,c){if(o==="__refProxy")return!0;if(o==="__path")return n;if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,c);const a=[...n,String(o)];return e(a)},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?!0:Reflect.has(r,o)},ownKeys(r){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(r,o){return o==="__refProxy"||o==="__path"||o==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(r,o)}});return t.set(s,i),i}return e([])}function lt(t){const e=new Map;let n=0;function s(r){const o=r.join(".");if(e.has(o))return e.get(o);const c=new Proxy({},{get(a,l,f){if(l==="__refProxy")return!0;if(l==="__path")return r;if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(a,l,f);const u=[...r,String(l)];return s(u)},has(a,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(a,l)},ownKeys(a){const l=++n,f=`__SPREAD_SENTINEL__${r.join(".")}__${l}`;return Object.prototype.hasOwnProperty.call(a,f)||Object.defineProperty(a,f,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(a)},getOwnPropertyDescriptor(a,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(a,l)}});return e.set(o,c),c}return new Proxy({},{get(r,o,c){if(o==="__refProxy")return!0;if(o==="__path")return[];if(o==="__type")return;if(typeof o=="symbol")return Reflect.get(r,o,c);const a=String(o);if(t.includes(a)||t.includes("*"))return s([a])},has(r,o){return o==="__refProxy"||o==="__path"||o==="__type"||typeof o=="string"&&t.includes(o)?!0:Reflect.has(r,o)},ownKeys(r){return[...t,"__refProxy","__path","__type"]},getOwnPropertyDescriptor(r,o){if(o==="__refProxy"||o==="__path"||o==="__type")return{enumerable:!1,configurable:!0};if(typeof o=="string"&&t.includes(o))return{enumerable:!0,configurable:!0}}})}function Tr(t){const e=lt(t),n=new Map;function s(r){const o=r.join(".");if(n.has(o))return n.get(o);const c=new Proxy({},{get(a,l,f){if(l==="__refProxy")return!0;if(l==="__path")return["$selected",...r];if(l==="__type")return;if(typeof l=="symbol")return Reflect.get(a,l,f);const u=[...r,String(l)];return s(u)},has(a,l){return l==="__refProxy"||l==="__path"||l==="__type"?!0:Reflect.has(a,l)},ownKeys(a){return Reflect.ownKeys(a)},getOwnPropertyDescriptor(a,l){return l==="__refProxy"||l==="__path"||l==="__type"?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(a,l)}});return n.set(o,c),c}const i=s([]);return new Proxy(e,{get(r,o,c){return o==="$selected"?i:Reflect.get(r,o,c)},has(r,o){return o==="$selected"?!0:Reflect.has(r,o)},ownKeys(r){return[...Reflect.ownKeys(r),"$selected"]},getOwnPropertyDescriptor(r,o){return o==="$selected"?{enumerable:!0,configurable:!0,value:i}:Reflect.getOwnPropertyDescriptor(r,o)}})}function Q(t){if(qn(t))return new G(t.__path);if(t&&typeof t=="object"&&(t.__brand==="ToArrayWrapper"||t.__brand==="ConcatToArrayWrapper"||t.__brand==="CaseWhenWrapper"||t.__brand==="MaterializeWrapper")){const e=t.__brand==="ToArrayWrapper"?"toArray()":t.__brand==="ConcatToArrayWrapper"?"concat(toArray())":t.__brand==="CaseWhenWrapper"?"caseWhen()":"materialize()";throw new Error(`${e} cannot be used inside expressions (e.g., coalesce(), eq(), not()). Use ${e} directly as a select field value instead.`)}return t&&typeof t=="object"&&"type"in t&&(t.type==="func"||t.type==="ref"||t.type==="val"||t.type==="agg")?t:new de(t)}function qn(t){return t&&typeof t=="object"&&t.__refProxy===!0}function Pt(t,e){return new ye("eq",[Q(t),Q(e)])}function Pr(t,e){return new ye("gt",[Q(t),Q(e)])}function Nu(t,e){return new ye("gte",[Q(t),Q(e)])}function si(t,e){return new ye("lt",[Q(t),Q(e)])}function ii(t,e,...n){const s=[t,e,...n];return new ye("and",s.map(i=>Q(i)))}function zu(t,e,...n){const s=[t,e,...n];return new ye("or",s.map(i=>Q(i)))}function Wo(t,e){return new ye("in",[Q(t),Q(e)])}class Mr{constructor(e){this.query=e,this.__brand="ToArrayWrapper"}}class $r{constructor(e){this.query=e,this.__brand="ConcatToArrayWrapper"}}class Dr{constructor(e){this.args=e,this.__brand="CaseWhenWrapper"}}class Wu{constructor(e){this.query=e,this.__brand="MaterializeWrapper"}}class Uo{constructor(){this.listeners=new Map}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>{var s;(s=this.listeners.get(e))==null||s.delete(n)}}once(e,n){const s=this.on(e,i=>{n(i),s()});return s}off(e,n){var s;(s=this.listeners.get(e))==null||s.delete(n)}waitFor(e,n){return new Promise((s,i)=>{let r;const o=this.on(e,c=>{r&&(clearTimeout(r),r=void 0),s(c),o()});n&&(r=setTimeout(()=>{r=void 0,o(),i(new Error(`Timeout waiting for event ${String(e)}`))},n))})}emitInner(e,n){var s;(s=this.listeners.get(e))==null||s.forEach(i=>{try{i(n)}catch(r){queueMicrotask(()=>{throw r})}})}clearListeners(){this.listeners.clear()}}function Uu(t,e){if(e.length===0||t.length===0)return;if(t.length===1){const{expression:s,compareOptions:i}=t[0];return(i.direction==="asc"?Pr:si)(s,new de(e[0]))}const n=[];for(let s=0;s<t.length&&s<e.length;s++){const i=t[s],r=e[s],o=[];for(let l=0;l<s;l++){const f=t[l],u=e[l];o.push(Pt(f.expression,new de(u)))}const a=(i.compareOptions.direction==="asc"?Pr:si)(i.expression,new de(r));if(o.length===0)n.push(a);else{const l=[...o,a];n.push(l.reduce((f,u)=>ii(f,u)))}}return n.length===1?n[0]:n.reduce((s,i)=>zu(s,i))}class qu extends Uo{constructor(e,n,s){super(),this.collection=e,this.callback=n,this.options=s,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,s.onUnsubscribe&&this.on("unsubscribed",r=>s.onUnsubscribe(r)),s.whereExpression&&_l(s.whereExpression,this.collection);const i=r=>{n(r),this.trackSentKeys(r)};this.callback=i,this.filteredCallback=s.whereExpression?Bu(this.callback,s):this.callback,this.truncateCleanup=this.collection.on("truncate",()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){const e=[...this.loadedSubsets],n=this.collection._sync.syncLoadSubsetFn!==null;if(e.length===0||!n){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(const s of e){const i=this.collection._sync.loadSubset(s);this.loadedSubsets.push(s),this.trackLoadSubsetPromise(i),i instanceof Promise&&(this.pendingTruncateRefetches.add(i),i.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(i),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;const 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;const n=this._status;this._status=e,this.emitInner("status:change",{type:"status:change",subscription:this,previousStatus:n,status:e});const s=`status:${e}`;this.emitInner(s,{type:s,subscription:this,previousStatus:n,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){const n=this.filterAndFlipChanges(e);this.isBufferingForTruncate?n.length>0&&this.truncateBuffer.push(n):this.filteredCallback(n)}requestSnapshot(e){var a;if(this.loadedInitialState)return!1;const n={where:this.options.whereExpression,optimizedOnly:(e==null?void 0:e.optimizedOnly)??!1};if(e){if("where"in e){const l=e.where;if(n.where){const f=n.where,u=ii(f,l);n.where=u}else n.where=l}}else this.loadedInitialState=!0;const s={where:n.where,subscription:this,orderBy:e==null?void 0:e.orderBy,limit:e==null?void 0:e.limit},i=this.collection._sync.loadSubset(s);(a=e==null?void 0:e.onLoadSubsetResult)==null||a.call(e,i),this.loadedSubsets.push(s),((e==null?void 0:e.trackLoadSubsetPromise)??!0)&&this.trackLoadSubsetPromise(i);const o=this.collection.currentStateAsChanges(n);if(o===void 0)return!1;const c=o.filter(l=>!this.sentKeys.has(l.key));for(const l of c)this.sentKeys.add(l.key);return this.snapshotSent=!0,this.callback(c),!0}requestLimitedSnapshot({orderBy:e,limit:n,minValues:s,offset:i,trackLoadSubsetPromise:r=!0,onLoadSubsetResult:o}){if(!n)throw new Error("limit is required");if(!this.orderByIndex)throw new Error("Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.");const c=s!==void 0&&s.length>0,l=s==null?void 0:s[0],f=this.orderByIndex,u=this.options.whereExpression,y=u?Qt(u):void 0,p=O=>{if(O!==void 0&&this.sentKeys.has(O))return!1;const E=this.collection.get(O);return E===void 0?!1:(y==null?void 0:y(E))??!0};let h=l;const d=[];let g=[];if(c){const{expression:O}=e[0],E=this.collection.currentStateAsChanges({where:Pt(O,new de(l))});if(E){const k=E.map(F=>F.key).filter(F=>!this.sentKeys.has(F)&&p(F));g.push(...k);const V=f.take(n-g.length,l,p);g.push(...V)}else g=f.take(n,l,p)}else g=f.takeFromStart(n,p);const w=()=>Math.max(n-d.length,0),C=()=>g.length===0,m=e[0].expression,b=m.type==="ref"?q(new G(m.path),!0):null;for(;w()>0&&!C();){const O=new Set;for(const E of g){const k=this.collection.get(E);d.push({type:"insert",key:E,value:k}),h=b?b(k):k,O.add(E)}g=f.take(w(),h,p)}const v=this.limitedSnapshotRowCount;for(const O of d)this.sentKeys.add(O.key);this.callback(d),this.limitedSnapshotRowCount+=d.length,d.length>0&&(this.lastSentKey=d[d.length-1].key);let x;if(s!==void 0&&s.length>0){const O=Uu(e,s);if(O){const{expression:E}=e[0],k=s[0];let V;if(k instanceof Date){const F=new Date(k.getTime()+1);V=ii(Nu(E,new de(k)),si(E,new de(F)))}else V=Pt(E,new de(k));x={whereFrom:O,whereCurrent:V,lastKey:this.lastSentKey}}}const I={where:u,limit:n,orderBy:e,cursor:x,offset:i??v,subscription:this},M=this.collection._sync.loadSubset(I);o==null||o(M),this.loadedSubsets.push(I),r&&this.trackLoadSubsetPromise(M)}filterAndFlipChanges(e){if(this.loadedInitialState||this.skipFiltering)return e;const n=this.isBufferingForTruncate,s=[];for(const i of e){let r=i;if(this.sentKeys.has(i.key)){if(i.type==="insert")continue;i.type==="delete"&&this.sentKeys.delete(i.key)}else{if(i.type==="update")r={...i,type:"insert",previousValue:void 0};else if(i.type==="delete"&&!n)continue;this.sentKeys.add(i.key)}s.push(r)}return s}trackSentKeys(e){if(!(this.loadedInitialState||this.skipFiltering)){for(const n of e)n.type==="delete"?this.sentKeys.delete(n.key):this.sentKeys.add(n.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){var e;(e=this.truncateCleanup)==null||e.call(this),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(const n of this.loadedSubsets)this.collection._sync.unloadSubset(n);this.loadedSubsets=[],this.emitInner("unsubscribed",{type:"unsubscribed",subscription:this}),this.clearListeners()}}class Hu{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(const e of this.changeSubscriptions)e.emitEvents([])}enrichChangeWithVirtualProps(e){return this.state.enrichChangeMessage(e)}emitEvents(e,n=!1){if(this.shouldBatchEvents&&!n){this.batchedEvents.push(...e);return}let s=e;if(n&&(this.batchedEvents.length>0&&(s=[...this.batchedEvents,...e]),this.batchedEvents=[],this.shouldBatchEvents=!1),s.length===0)return;const i=s.map(r=>this.enrichChangeWithVirtualProps(r));for(const r of this.changeSubscriptions)r.emitEvents(i)}subscribeChanges(e,n={}){if(this.addSubscriber(),n.where&&n.whereExpression)throw new Error("Cannot specify both 'where' and 'whereExpression' options. Use one or the other.");const{where:s,...i}=n;let r=i.whereExpression;if(s){const c=zo(),a=s(c);r=Q(a)}const o=new qu(this.collection,e,{...i,whereExpression:r,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(o)}});return n.onStatusChange&&o.on("status:change",n.onStatusChange),n.includeInitialState?o.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:n.orderBy,limit:n.limit,onLoadSubsetResult:n.onLoadSubsetResult}):n.includeInitialState===!1&&o.markAllStateAsSeen(),this.changeSubscriptions.add(o),o}addSubscriber(){const 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(){const e=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new na;this.events.emitSubscribersChange(this.activeSubscribersCount,e)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}const Gu=t=>setTimeout(()=>{t({didTimeout:!0,timeRemaining:()=>50})},0),Ju=t=>{clearTimeout(t)},Qu=typeof window<"u"&&"requestIdleCallback"in window?(t,e)=>window.requestIdleCallback(t,e):(t,e)=>Gu(t),Ls=typeof window<"u"&&"cancelIdleCallback"in window?t=>window.cancelIdleCallback(t):Ju,qo=class Le{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return Le.instance||(Le.instance=new Le),Le.instance}schedule(e,n,s){const i=Date.now()+n;this.tasks.set(e,{executeAt:i,callback:s}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(e){this.tasks.delete(e)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let e=1/0;for(const s of this.tasks.values())s.executeAt<e&&(e=s.executeAt);const n=Math.max(0,e-Date.now());this.timeoutId=setTimeout(()=>this.process(),n)}process(){this.timeoutId=null;const e=Date.now();for(const[n,s]of this.tasks.entries())if(e>=s.executeAt){this.tasks.delete(n);try{s.callback()}catch(i){console.error("Error in CleanupQueue task:",i)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){Le.instance&&(Le.instance.timeoutId!==null&&clearTimeout(Le.instance.timeoutId),Le.instance=null)}};qo.instance=null;let Vs=qo;class Yu{constructor(e,n){this.status="idle",this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=e,this.id=n}setDeps(e){this.indexes=e.indexes,this.events=e.events,this.changes=e.changes,this.sync=e.sync,this.state=e.state}validateStatusTransition(e,n){if(e===n)return;if(!{idle:["loading","error","cleaned-up"],loading:["ready","error","cleaned-up"],ready:["cleaned-up","error"],error:["cleaned-up","idle"],"cleaned-up":["loading","error"]}[e].includes(n))throw new ea(e,n,this.id)}setStatus(e,n=!1){if(e==="ready"&&!n)throw new Cn(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,e);const s=this.status;this.status=e,this.events.emitStatusChange(e,s)}validateCollectionUsable(e){switch(this.status){case"error":throw new Xc(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||(this.hasReceivedFirstCommit=!0);const e=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],e.forEach(n=>n())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){const e=this.config.gcTime??3e5;e<=0||!Number.isFinite(e)||Vs.getInstance().schedule(this,e,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Vs.getInstance().cancel(this),this.idleCallbackId!==null&&(Ls(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Ls(this.idleCallbackId),this.idleCallbackId=Qu(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(),Vs.getInstance().cancel(this),this.hasBeenReady=!1;const s=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],s.forEach(i=>{try{i()}catch(r){console.error(`${this.config.id?`[${this.config.id}] `:""}Error in onFirstReady callback during cleanup:`,r)}}),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&&(Ls(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const Ri=Symbol("liveQueryInternal");class Zu{constructor(e,n){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.config=e,this.id=n,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{const e=Xu(this.config.sync.sync({collection:this.collection,begin:n=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:n==null?void 0:n.immediate})},write:n=>{const s=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!s)throw new Ts;if(s.committed)throw new Ps;let i;"key"in n?i=n.key:i=this.config.getKey(n.value),this.state.pendingLocalChanges.has(i)&&this.state.pendingLocalOrigins.add(i);let r=n.type;if(n.type==="insert"){const c=this.state.syncedData.has(i),a=s.deletedKeys.has(i),l=s.truncate===!0;if(c&&!a&&!l){const f=this.state.syncedData.get(i);if(f!==void 0&&Ke(f,n.value))r="update";else{const p=this.config.utils[Ri];throw new oa(i,this.id,{hasCustomGetKey:(p==null?void 0:p.hasCustomGetKey)??!1,hasJoins:(p==null?void 0:p.hasJoins)??!1,hasDistinct:(p==null?void 0:p.hasDistinct)??!1})}}}const o={...n,type:r,key:i};s.operations.push(o),r==="delete"?(s.deletedKeys.add(i),s.rowMetadataWrites.set(i,{type:"delete"})):r==="insert"?o.metadata!==void 0?s.rowMetadataWrites.set(i,{type:"set",value:o.metadata}):s.rowMetadataWrites.set(i,{type:"delete"}):o.metadata!==void 0&&s.rowMetadataWrites.set(i,{type:"set",value:o.metadata})},commit:()=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new Sa;if(n.committed)throw new ba;n.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!n)throw new Ts;if(n.committed)throw new Ps;n.operations=[],n.deletedKeys.clear(),n.rowMetadataWrites.clear(),n.truncate=!0,n.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}));if(this.syncCleanupFn=(e==null?void 0:e.cleanup)??null,this.syncLoadSubsetFn=(e==null?void 0:e.loadSubset)??null,this.syncUnloadSubsetFn=(e==null?void 0:e.unloadSubset)??null,this.syncMode==="on-demand"&&!this.syncLoadSubsetFn)throw new bt(`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(){const e=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!e)throw new Ts;if(e.committed)throw new Ps;return e}createSyncMetadataApi(){return{row:{get:e=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],s=n==null?void 0:n.rowMetadataWrites.get(e);if(s)return s.type==="delete"?void 0:s.value;if(!(n!=null&&n.truncate))return this.state.syncedMetadata.get(e)},set:(e,n)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:"set",value:n})},delete:e=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(e,{type:"delete"})}},collection:{get:e=>{const n=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],s=n==null?void 0:n.collectionMetadataWrites.get(e);return s?s.type==="delete"?void 0:s.value:this.state.syncedCollectionMetadata.get(e)},set:(e,n)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:"set",value:n})},delete:e=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(e,{type:"delete"})},list:e=>{const n=new Map(this.state.syncedCollectionMetadata),s=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(s)for(const[i,r]of s.collectionMetadataWrites)r.type==="delete"?n.delete(i):n.set(i,r.value);return Array.from(n.entries()).filter(([i])=>e?i.startsWith(e):!0).map(([i,r])=>({key:i,value:r}))}}}}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,n)=>{if(this.lifecycle.status==="ready"){e();return}if(this.lifecycle.status==="error"){n(new ta);return}if(this.lifecycle.onFirstReady(()=>{e()}),this.lifecycle.status==="idle"||this.lifecycle.status==="cleaned-up")try{this.startSync()}catch(s){n(s);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(e){const n=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(e),n&&this._events.emit("loadingSubset:change",{type:"loadingSubset:change",collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:"start"}),e.finally(()=>{const s=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(e);this.pendingLoadSubsetPromises.delete(e),s&&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){const n=this.syncLoadSubsetFn(e);if(n instanceof Promise)return this.trackLoadPromise(n),n}return!0}unloadSubset(e){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(e)}cleanup(){try{this.syncCleanupFn&&(this.syncCleanupFn(),this.syncCleanupFn=null)}catch(e){queueMicrotask(()=>{if(e instanceof Error){const n=new hr(this.id,e);throw n.cause=e,n.stack=e.stack,n}else throw new hr(this.id,e)})}this.preloadPromise=null}}function Xu(t){if(typeof t=="function")return{cleanup:t};if(typeof t=="object")return t}const jr=1;function Hn(t,e){return t===e?0:t<e?-1:1}function ef(t){return{kind:"constructor",...t.name?{name:t.name}:{}}}function Je(t){if(t==null)return t;switch(typeof t){case"string":case"boolean":return t;case"number":return Number.isFinite(t)?t:null;case"bigint":return{__type:"bigint",value:t.toString()};case"function":case"symbol":return;case"undefined":return}if(Array.isArray(t))return t.map(s=>Je(s)??null);if(t instanceof Date)return{__type:"date",value:t.toISOString()};if(t instanceof Set)return{__type:"set",values:Array.from(t).map(i=>Je(i)??null).sort((i,r)=>Hn(dt(i),dt(r)))};if(t instanceof Map)return{__type:"map",entries:Array.from(t.entries()).map(([i,r])=>({key:Je(i)??null,value:Je(r)??null})).sort((i,r)=>Hn(dt(i.key),dt(r.key)))};if(t instanceof RegExp)return{__type:"regexp",value:t.toString()};const e={},n=Object.entries(t).sort(([s],[i])=>Hn(s,i));for(const[s,i]of n){const r=Je(i);r!==void 0&&(e[s]=r)}return e}function dt(t){return t===null?"null":Array.isArray(t)?`[${t.map(dt).join(",")}]`:typeof t!="object"?JSON.stringify(t):`{${Object.keys(t).sort((s,i)=>Hn(s,i)).map(s=>`${JSON.stringify(s)}:${dt(t[s])}`).join(",")}}`}function tf(t,e,n,s,i){const r=ef(s),o=Je(e)??null,c=Je(i),l=Je({signatureVersion:jr,expression:o,options:c??null})??null,f=dt(l);return{signatureVersion:jr,signature:f,indexId:t,name:n,expression:e,resolver:r,...c===void 0?{}:{options:c}}}function ri(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>ri(n));const e={};for(const[n,s]of Object.entries(t))e[n]=ri(s);return e}function nf(t){return JSON.parse(JSON.stringify(t))}class sf{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,n={}){this.lifecycle.validateCollectionUsable("createIndex");const s=++this.indexCounter,i=zo(),r=e(i),o=Q(r),c=n.indexType??this.defaultIndexType;if(!c)throw new bt(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection:
|
|
8
|
+
import { BasicIndex } from '@tanstack/db'
|
|
9
|
+
createCollection({ defaultIndexType: BasicIndex, ... })`);const a=new c(s,o,n.name,n.options);a.build(this.state.entries()),this.indexes.set(s,a);const l=tf(s,o,n.name,c,n.options);return this.indexMetadata.set(s,l),this.events.emitIndexAdded(l),a}removeIndex(e){this.lifecycle.validateCollectionUsable("removeIndex");const n=typeof e=="number"?e:e.id,s=this.indexes.get(n);if(!s||typeof e!="number"&&s!==e)return!1;this.indexes.delete(n);const i=this.indexMetadata.get(n);return this.indexMetadata.delete(n),i&&this.events.emitIndexRemoved(i),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((e,n)=>e.indexId-n.indexId).map(e=>({...e,expression:nf(e.expression),resolver:{...e.resolver},...e.options===void 0?{}:{options:ri(e.options)}}))}updateIndexes(e){for(const n of this.indexes.values())for(const s of e)switch(s.type){case"insert":n.add(s.key,s.value);break;case"update":s.previousValue?n.update(s.key,s.previousValue,s.value):n.add(s.key,s.value);break;case"delete":n.remove(s.key,s.value);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}var rf={};const of=new Set(["find","findLast","findIndex","findLastIndex","filter","map","flatMap","forEach","some","every","reduce","reduceRight"]),cf=new Set(["pop","push","shift","unshift","splice","sort","reverse","fill","copyWithin"]),af=new Set(["set","delete","clear","add"]),lf=new Set(["entries","keys","values","forEach"]);function Ai(t){return t!==null&&typeof t=="object"&&!(t instanceof Date)&&!(t instanceof RegExp)&&!nt(t)}function uf(t,e,n,s){if(of.has(t))return function(...i){const r=i[0];if(typeof r!="function")return e.apply(n.copy_,i);const o=(l,f)=>{if(Ai(l)){const u={tracker:n,prop:String(f)},{proxy:y}=s(l,u);return y}return l},c=function(l,f,u){const y=o(l,f);return r.call(this,y,f,u)};if(t==="reduce"||t==="reduceRight"){const l=function(f,u,y,p){const h=o(u,y);return r.call(this,f,h,y,p)};return e.apply(n.copy_,[l,...i.slice(1)])}const a=e.apply(n.copy_,[c,...i.slice(1)]);if((t==="find"||t==="findLast")&&a&&typeof a=="object"){const l=n.copy_.indexOf(a);if(l!==-1)return o(a,l)}return t==="filter"&&Array.isArray(a)?a.map(l=>{const f=n.copy_.indexOf(l);return f!==-1?o(l,f):l}):a}}function ff(t,e){return function(){const n=t.copy_;let s=0;return{next(){if(s>=n.length)return{done:!0,value:void 0};const i=n[s];let r=i;if(Ai(i)){const o={tracker:t,prop:String(s)},{proxy:c}=e(i,o);r=c}return s++,{done:!1,value:r}},[Symbol.iterator](){return this}}}}function Kr(t,e,n){return function(...s){const i=t.apply(e.copy_,s);return n(e),i}}function df(t,e,n,s,i,r,o){if(lf.has(t)||e===Symbol.iterator)return function(...a){const l=n.apply(i.copy_,a);if(t==="forEach"){const u=a[0];if(typeof u=="function"){const y=function(p,h,d){const g=u.call(this,p,h,d);return o(i),g};return n.apply(s,[y,...a.slice(1)])}}if(t==="entries"||t==="values"||t===Symbol.iterator.toString()||e===Symbol.iterator){const u=l,y=new Map;if(t==="values"&&s instanceof Map)for(const[h,d]of i.copy_.entries())y.set(d,h);const p=new Map;if(s instanceof Set)for(const h of i.copy_.values())p.set(h,h);return{next(){const h=u.next();if(!h.done&&h.value&&typeof h.value=="object"){if(t==="entries"&&Array.isArray(h.value)&&h.value.length===2){if(h.value[1]&&typeof h.value[1]=="object"){const d=h.value[0],g={tracker:i,prop:d,updateMap:C=>{i.copy_ instanceof Map&&i.copy_.set(d,C)}},{proxy:w}=r(h.value[1],g);h.value[1]=w}}else if(t==="values"||t===Symbol.iterator.toString()||e===Symbol.iterator)if(t==="values"&&s instanceof Map){const d=y.get(h.value);if(d!==void 0){const g={tracker:i,prop:d,updateMap:C=>{i.copy_ instanceof Map&&i.copy_.set(d,C)}},{proxy:w}=r(h.value,g);h.value=w}}else if(s instanceof Set){const d=h.value,g={tracker:i,prop:d,updateSet:C=>{i.copy_ instanceof Set&&(i.copy_.delete(d),i.copy_.add(C),p.set(d,C))}},{proxy:w}=r(h.value,g);h.value=w}else{const d=Symbol("iterator-value"),{proxy:g}=r(h.value,{tracker:i,prop:d});h.value=g}}return h},[Symbol.iterator](){return this}}}return l}}function D(...t){const e=typeof window<"u"&&typeof localStorage<"u";e&&localStorage.getItem("DEBUG")==="true"?console.log("[proxy]",...t):!e&&typeof process<"u"&&rf.DEBUG==="true"&&console.log("[proxy]",...t)}function Ne(t,e=new WeakMap){if(t==null||typeof t!="object")return t;if(e.has(t))return e.get(t);if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp)return new RegExp(t.source,t.flags);if(Array.isArray(t)){const i=[];return e.set(t,i),t.forEach((r,o)=>{i[o]=Ne(r,e)}),i}if(ArrayBuffer.isView(t)&&!(t instanceof DataView)){const i=Object.getPrototypeOf(t).constructor,r=new i(t.length);e.set(t,r);for(let o=0;o<t.length;o++)r[o]=t[o];return r}if(t instanceof Map){const i=new Map;return e.set(t,i),t.forEach((r,o)=>{i.set(o,Ne(r,e))}),i}if(t instanceof Set){const i=new Set;return e.set(t,i),t.forEach(r=>{i.add(Ne(r,e))}),i}if(nt(t))return t;const n={};e.set(t,n);for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=Ne(t[i],e));const s=Object.getOwnPropertySymbols(t);for(const i of s)n[i]=Ne(t[i],e);return n}let Fr=0;function hf(){return Fr+=1,Fr}function Ti(t,e){const n=new Map;function s(u,y){if(D("Object ID:",u.constructor.name),n.has(u))return n.get(u);{const p=Ti(u,y);return n.set(u,p),p}}const i=new Map,r={copy_:Ne(t),originalObject:Ne(t),proxyCount:hf(),modified:!1,assigned_:{},parent:e,target:t};D("createChangeProxy called for target",t,r.proxyCount);function o(u){u.modified||(u.modified=!0),u.parent&&(D("propagating change to parent"),"updateMap"in u.parent?u.parent.updateMap(u.copy_):"updateSet"in u.parent?u.parent.updateSet(u.copy_):(u.parent.tracker.copy_[u.parent.prop]=u.copy_,u.parent.tracker.assigned_[u.parent.prop]=!0),o(u.parent.tracker))}function c(u){if(D("checkIfReverted called with assigned keys:",Object.keys(u.assigned_)),Object.keys(u.assigned_).length===0&&Object.getOwnPropertySymbols(u.assigned_).length===0)return D("No assigned properties, returning true"),!0;for(const p in u.assigned_)if(u.assigned_[p]===!0){const h=u.copy_[p],d=u.originalObject[p];if(D(`Checking property ${String(p)}, current:`,h,"original:",d),!Ke(h,d))return D(`Property ${String(p)} is different, returning false`),!1}else if(u.assigned_[p]===!1)return D(`Property ${String(p)} was deleted, returning false`),!1;const y=Object.getOwnPropertySymbols(u.assigned_);for(const p of y)if(u.assigned_[p]===!0){const h=u.copy_[p],d=u.originalObject[p];if(!Ke(h,d))return D("Symbol property is different, returning false"),!1}else if(u.assigned_[p]===!1)return D("Symbol property was deleted, returning false"),!1;return D("All properties match original values, returning true"),!0}function a(u,y){D("checkParentStatus called for child prop:",y);const p=c(u);D("Parent checkIfReverted returned:",p),p&&(D("Parent is fully reverted, clearing tracking"),u.modified=!1,u.assigned_={},u.parent&&(D("Continuing up the parent chain"),a(u.parent.tracker,u.parent.prop)))}function l(u){if(D("createObjectProxy",u),i.has(u))return D("proxyCache found match"),i.get(u);const y=new Proxy(u,{get(p,h){D("get",p,h);const d=r.copy_[h]??r.originalObject[h],g=r.originalObject[h];D("value (at top of proxy get)",d);const w=Object.getOwnPropertyDescriptor(p,h);if(w!=null&&w.get)return d;if(typeof d=="function"){if(Array.isArray(p)){const C=h.toString();if(cf.has(C))return Kr(d,r,o);const m=uf(C,d,r,s);if(m)return m;if(h===Symbol.iterator)return ff(r,s)}if(p instanceof Map||p instanceof Set){const C=h.toString();if(af.has(C))return Kr(d,r,o);const m=df(C,h,d,p,r,s,o);if(m)return m}return d.bind(p)}if(Ai(d)){const C={tracker:r,prop:String(h)},{proxy:m}=s(g,C);return i.set(d,m),m}return d},set(p,h,d){const g=r.copy_[h];if(D(`set called for property ${String(h)}, current:`,g,"new:",d),Ke(g,d))D("Value unchanged, not tracking");else{const w=r.originalObject[h],C=Ke(d,w);if(D("value:",d,"original:",w,"isRevertToOriginal:",C),C){D(`Reverting property ${String(h)} to original value`),delete r.assigned_[h.toString()],D(`Updating copy with original value for ${String(h)}`),r.copy_[h]=Ne(w),D("Checking if all properties reverted");const m=c(r);D("All reverted:",m),m?(D("All properties reverted, clearing tracking"),r.modified=!1,r.assigned_={},e&&(D("Updating parent for property:",e.prop),a(e.tracker,e.prop))):(D("Some properties still changed, keeping modified flag"),r.modified=!0)}else D(`Setting new value for property ${String(h)}`),r.copy_[h]=d,r.assigned_[h.toString()]=!0,D("Marking object and ancestors as modified",r),o(r)}return!0},defineProperty(p,h,d){const g=Reflect.defineProperty(p,h,d);return g&&"value"in d&&(r.copy_[h]=Ne(d.value),r.assigned_[h.toString()]=!0,o(r)),g},getOwnPropertyDescriptor(p,h){return Reflect.getOwnPropertyDescriptor(p,h)},preventExtensions(p){return Reflect.preventExtensions(p)},isExtensible(p){return Reflect.isExtensible(p)},deleteProperty(p,h){D("deleteProperty",p,h);const d=typeof h=="symbol"?h.toString():h;if(d in p){const g=d in r.originalObject,w=Reflect.deleteProperty(p,h);return w&&(g?(r.assigned_[d]=!1,o(r)):(delete r.assigned_[d],Object.keys(r.assigned_).length===0&&Object.getOwnPropertySymbols(r.assigned_).length===0?r.modified=!1:r.modified=!0)),w}return!0}});return i.set(u,y),y}return{proxy:l(r.copy_),getChanges:()=>{if(D("getChanges called, modified:",r.modified),D(r),!r.modified)return D("Object not modified, returning empty object"),{};if(typeof r.copy_!="object"||Array.isArray(r.copy_)||Object.keys(r.assigned_).length===0)return r.copy_;const u={};for(const y in r.copy_)r.assigned_[y]===!0&&y in r.copy_&&(u[y]=r.copy_[y]);return D("Returning copy:",u),u}}}function pf(t){const e=t.map(n=>Ti(n));return{proxies:e.map(n=>n.proxy),getChanges:()=>e.map(n=>n.getChanges())}}function yf(t,e){const{proxy:n,getChanges:s}=Ti(t);return e(n),s()}function gf(t,e){const{proxies:n,getChanges:s}=pf(t);return e(n),s()}function mf(){let t,e,n=!0;return{promise:new Promise((i,r)=>{t=o=>{n=!1,i(o)},e=o=>{n=!1,r(o)}}),resolve:t,reject:e,isPending:()=>n}}function _f(t){return typeof t=="object"&&t!==null&&typeof t.hasPendingGraphRun=="function"}class wf{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(e){let n=this.contexts.get(e);return n||(n={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(e,n)),n}schedule({contextId:e,jobId:n,dependencies:s,run:i}){if(typeof e>"u"){i();return}const r=this.getOrCreateContext(e);if(r.jobs.has(n)||r.queue.push(n),r.jobs.set(n,i),s){const o=new Set(s);o.delete(n),r.dependencies.set(n,o)}else r.dependencies.has(n)||r.dependencies.set(n,new Set);r.completed.delete(n)}flush(e){const n=this.contexts.get(e);if(!n)return;const{queue:s,jobs:i,dependencies:r,completed:o}=n;for(;s.length>0;){let c=!1;const a=s.length;for(let l=0;l<a;l++){const f=s.shift(),u=i.get(f);if(!u){r.delete(f),o.delete(f);continue}const y=r.get(f);let p=!y;if(y){p=!0;for(const h of y){if(h===f)continue;const d=_f(h)&&h.hasPendingGraphRun(e);if(i.has(h)&&!o.has(h)||!i.has(h)&&d){p=!1;break}}}p?(i.delete(f),r.delete(f),u(),o.add(f),c=!0):s.push(f)}if(!c)throw new Error(`Scheduler detected unresolved dependencies for context ${String(e)}.`)}this.contexts.delete(e)}flushAll(){for(const e of Array.from(this.contexts.keys()))this.flush(e)}clear(e){this.contexts.delete(e),this.clearListeners.forEach(n=>n(e))}onClear(e){return this.clearListeners.add(e),()=>this.clearListeners.delete(e)}hasPendingJobs(e){const n=this.contexts.get(e);return!!n&&n.jobs.size>0}clearJob(e,n){const s=this.contexts.get(e);s&&(s.jobs.delete(n),s.dependencies.delete(n),s.completed.delete(n),s.queue=s.queue.filter(i=>i!==n),s.jobs.size===0&&this.contexts.delete(e))}}const os=new wf,cs=[];let cn=[],Sf=0;function bf(t,e){switch(`${t.type}-${e.type}`){case"insert-update":return{...t,type:"insert",original:{},modified:e.modified,changes:{...t.changes,...e.changes},key:t.key,globalKey:t.globalKey,metadata:e.metadata??t.metadata,syncMetadata:{...t.syncMetadata,...e.syncMetadata},mutationId:e.mutationId,updatedAt:e.updatedAt};case"insert-delete":return null;case"update-delete":return e;case"update-update":return{...e,original:t.original,changes:{...t.changes,...e.changes},metadata:e.metadata??t.metadata,syncMetadata:{...t.syncMetadata,...e.syncMetadata}};case"delete-delete":case"insert-insert":return e;default:{const n=`${t.type}-${e.type}`;throw new Error(`Unhandled mutation combination: ${n}`)}}}function Mn(t){const e=new If(t);return cs.push(e),e}function Gn(){if(cn.length>0)return cn.slice(-1)[0]}function vf(t){os.clear(t.id),cn.push(t)}function Cf(t){try{os.flush(t.id)}finally{cn=cn.filter(e=>e.id!==t.id)}}function xf(t){const e=cs.findIndex(n=>n.id===t.id);e!==-1&&cs.splice(e,1)}class If{constructor(e){if(typeof e.mutationFn>"u")throw new ga;this.id=e.id??crypto.randomUUID(),this.mutationFn=e.mutationFn,this.state="pending",this.mutations=[],this.isPersisted=mf(),this.autoCommit=e.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=Sf++,this.metadata=e.metadata??{}}setState(e){this.state=e,(e==="completed"||e==="failed")&&xf(this)}mutate(e){if(this.state!=="pending")throw new ma;vf(this);try{e()}finally{Cf(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(e){for(const n of e){const s=this.mutations.findIndex(i=>i.globalKey===n.globalKey);if(s>=0){const i=this.mutations[s],r=bf(i,n);r===null?this.mutations.splice(s,1):this.mutations[s]=r}else this.mutations.push(n)}}rollback(e){var s;const n=(e==null?void 0:e.isSecondaryRollback)??!1;if(this.state==="completed")throw new _a;if(this.setState("failed"),!n){const i=new Set;this.mutations.forEach(r=>i.add(r.globalKey));for(const r of cs)r.state==="pending"&&r.mutations.some(o=>i.has(o.globalKey))&&r.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject((s=this.error)==null?void 0:s.error),this.touchCollection(),this}touchCollection(){const e=new Set;for(const n of this.mutations)e.has(n.collection.id)||(n.collection._state.onTransactionStateChange(),n.collection._state.pendingSyncedTransactions.length>0&&n.collection._state.commitPendingTransactions(),e.add(n.collection.id))}async commit(){if(this.state!=="pending")throw new wa;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){const n=e instanceof Error?e:new Error(String(e));throw this.error={message:n.message,error:n},this.rollback(),n}return this}compareCreatedAt(e){const n=this.createdAt.getTime()-e.createdAt.getTime();return n!==0?n:this.sequenceNumber-e.sequenceNumber}}class Of{constructor(e,n){this.insert=(s,i)=>{this.lifecycle.validateCollectionUsable("insert");const r=this.state,o=Gn();if(!o&&!this.config.onInsert)throw new ha;const c=Array.isArray(s)?s:[s],a=[],l=new Set;if(c.forEach(f=>{var d,g;const u=this.validateData(f,"insert"),y=this.config.getKey(u);if(this.state.has(y)||l.has(y))throw new ra(y);l.add(y);const p=this.generateGlobalKey(y,f),h={mutationId:crypto.randomUUID(),original:{},modified:u,changes:Object.fromEntries(Object.keys(f).map(w=>[w,u[w]])),globalKey:p,key:y,metadata:i==null?void 0:i.metadata,syncMetadata:((g=(d=this.config.sync).getSyncMetadata)==null?void 0:g.call(d))||{},optimistic:(i==null?void 0:i.optimistic)??!0,type:"insert",createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(h)}),o)return o.applyMutations(a),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;{const f=Mn({metadata:{[Un]:!0},mutationFn:async u=>await this.config.onInsert({transaction:u.transaction,collection:this.collection})});return f.applyMutations(a),this.markPendingLocalOrigins(a),f.commit().catch(()=>{}),r.transactions.set(f.id,f),r.scheduleTransactionCleanup(f),r.recomputeOptimisticState(!0),f}},this.delete=(s,i)=>{const r=this.state;this.lifecycle.validateCollectionUsable("delete");const o=Gn();if(!o&&!this.config.onDelete)throw new ya;if(Array.isArray(s)&&s.length===0)throw new fa;const c=Array.isArray(s)?s:[s],a=[];for(const f of c){if(!this.state.has(f))throw new da(f);const u=this.generateGlobalKey(f,this.state.get(f)),y={mutationId:crypto.randomUUID(),original:this.state.get(f),modified:this.state.get(f),changes:this.state.get(f),globalKey:u,key:f,metadata:i==null?void 0:i.metadata,syncMetadata:r.syncedMetadata.get(f)||{},optimistic:(i==null?void 0:i.optimistic)??!0,type:"delete",createdAt:new Date,updatedAt:new Date,collection:this.collection};a.push(y)}if(o)return o.applyMutations(a),r.transactions.set(o.id,o),r.scheduleTransactionCleanup(o),r.recomputeOptimisticState(!0),o;const l=Mn({autoCommit:!0,metadata:{[Un]:!0},mutationFn:async f=>this.config.onDelete({transaction:f.transaction,collection:this.collection})});return l.applyMutations(a),this.markPendingLocalOrigins(a),l.commit().catch(()=>{}),r.transactions.set(l.id,l),r.scheduleTransactionCleanup(l),r.recomputeOptimisticState(!0),l},this.id=n,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 Zc}validateData(e,n,s){if(!this.config.schema)return e;const i=this.ensureStandardSchema(this.config.schema);if(n==="update"&&s){const o=this.state.get(s);if(o&&e&&typeof e=="object"&&typeof o=="object"){const c=Object.assign({},o,e),a=i["~standard"].validate(c);if(a instanceof Promise)throw new lr;if("issues"in a&&a.issues){const y=a.issues.map(p=>{var h;return{message:p.message,path:(h=p.path)==null?void 0:h.map(d=>String(d))}});throw new ar(n,y)}const l=a.value,f=Object.keys(e);return Object.fromEntries(f.map(y=>[y,l[y]]))}}const r=i["~standard"].validate(e);if(r instanceof Promise)throw new lr;if("issues"in r&&r.issues){const o=r.issues.map(c=>{var a;return{message:c.message,path:(a=c.path)==null?void 0:a.map(l=>String(l))}});throw new ar(n,o)}return r.value}generateGlobalKey(e,n){if(typeof e!="string"&&typeof e!="number")throw typeof e>"u"?new sa(n):new ia(e,n);return`KEY::${this.id}/${e}`}markPendingLocalOrigins(e){for(const n of e)this.state.pendingLocalOrigins.add(n.key)}update(e,n,s){if(typeof e>"u")throw new ca;const i=this.state;this.lifecycle.validateCollectionUsable("update");const r=Gn();if(!r&&!this.config.onUpdate)throw new pa;const o=Array.isArray(e),c=o?e:[e];if(o&&c.length===0)throw new aa;const a=typeof n=="function"?n:s,l=typeof n=="function"?{}:n,f=c.map(h=>{const d=this.state.get(h);if(!d)throw new la(h);return d});let u;o?u=gf(f,a):u=[yf(f[0],a)];const y=c.map((h,d)=>{const g=u[d];if(!g||Object.keys(g).length===0)return null;const w=f[d],C=this.validateData(g,"update",h),m=Object.assign({},w,C),b=this.config.getKey(w),v=this.config.getKey(m);if(b!==v)throw new ua(b,v);const x=this.generateGlobalKey(v,m);return{mutationId:crypto.randomUUID(),original:w,modified:m,changes:Object.fromEntries(Object.keys(g).map(I=>[I,m[I]])),globalKey:x,key:h,metadata:l.metadata,syncMetadata:i.syncedMetadata.get(h)||{},optimistic:l.optimistic??!0,type:"update",createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(y.length===0){const h=Mn({mutationFn:async()=>{}});return h.commit().catch(()=>{}),i.scheduleTransactionCleanup(h),h}if(r)return r.applyMutations(y),i.transactions.set(r.id,r),i.scheduleTransactionCleanup(r),i.recomputeOptimisticState(!0),r;const p=Mn({metadata:{[Un]:!0},mutationFn:async h=>this.config.onUpdate({transaction:h.transaction,collection:this.collection})});return p.applyMutations(y),this.markPendingLocalOrigins(y),p.commit().catch(()=>{}),i.transactions.set(p.id,p),i.scheduleTransactionCleanup(p),i.recomputeOptimisticState(!0),p}}class kf extends Uo{constructor(){super()}setDeps(e){this.collection=e.collection}emit(e,n){this.emitInner(e,n)}emitStatusChange(e,n){this.emit("status:change",{type:"status:change",collection:this.collection,previousStatus:n,status:e});const s=`status:${e}`;this.emit(s,{type:s,collection:this.collection,previousStatus:n,status:e})}emitSubscribersChange(e,n){this.emit("subscribers:change",{type:"subscribers:change",collection:this.collection,previousSubscriberCount:n,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 At(t){const e=new Ho(t);return t.utils?e.utils=t.utils:e.utils={},e}class Ho{constructor(e){if(this.utils={},this.deferDataRefresh=null,this.insert=(n,s)=>this._mutations.insert(n,s),this.delete=(n,s)=>this._mutations.delete(n,s),!e)throw new Qc;if(!e.sync)throw new Yc;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 bt(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it:
|
|
10
|
+
import { BasicIndex } from '@tanstack/db'
|
|
11
|
+
createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new Hu,this._events=new kf,this._indexes=new sf,this._lifecycle=new Yu(e,this.id),this._mutations=new Of(e,this.id),this._state=new Vu(e),this._sync=new Zu(e,this.id),this.comparisonOpts=Ef(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(const e of this._state.keys()){const n=this.get(e);n!==void 0&&(yield n)}}*entries(){for(const e of this._state.keys()){const n=this.get(e);n!==void 0&&(yield[e,n])}}*[Symbol.iterator](){yield*this.entries()}forEach(e){let n=0;for(const[s,i]of this.entries())e(i,s,n++)}map(e){const n=[];let s=0;for(const[i,r]of this.entries())n.push(e(r,i,s++));return n}getKeyFromItem(e){return this.config.getKey(e)}createIndex(e,n={}){return this._indexes.createIndex(e,n)}removeIndex(e){return this._indexes.removeIndex(e)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(e,n,s){return this._mutations.validateData(e,n,s)}get compareOptions(){return{...this.comparisonOpts}}update(e,n,s){return this._mutations.update(e,n,s)}get state(){const e=new Map;for(const[n,s]of this.entries())e.set(n,s);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 Fu(this,e)}subscribeChanges(e,n={}){return this._changes.subscribeChanges(e,n)}on(e,n){return this._events.on(e,n)}once(e,n){return this._events.once(e,n)}off(e,n){this._events.off(e,n)}waitFor(e,n){return this._events.waitFor(e,n)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}function Ef(t){if(t.defaultStringCollation){const e=t.defaultStringCollation;return{stringSort:e.stringSort??"locale",locale:e.stringSort==="locale"?e.locale:void 0,localeOptions:e.stringSort==="locale"?e.localeOptions:void 0}}else return{stringSort:"locale"}}function Go(t){if(t.from.type==="unionAll")return{optimizedQuery:{...t,from:new Bt(t.from.queries.map(c=>Go(c).optimizedQuery))},sourceWhereClauses:new Map};const e=Rf(t);let n=t,s,i=0;const r=10;for(;i<r&&!Ke(n,s);)s=n,n=as(n),i++;return{optimizedQuery:oi(n),sourceWhereClauses:e}}function Rf(t){const e=new Map;if(!t.where||t.where.length===0)return e;const s=ci(t.where).map(o=>Qo(o)),i=Yo(s),r=Jo(t);for(const[o,c]of i.singleSource)Af(t,o)&&!r.has(o)&&e.set(o,c);return e}function Af(t,e){for(const n of $i(t.from))if(n.alias===e)return n.type==="collectionRef";if(t.join){for(const n of t.join)if(n.from.alias===e)return n.from.type==="collectionRef"}return!1}function Jo(t){const e=new Set;if(t.join){const n=new Set($i(t.from).map(s=>s.alias));for(const s of t.join){const i=s.from.alias;if((s.type==="left"||s.type==="full")&&e.add(i),s.type==="right"||s.type==="full")for(const r of n)e.add(r);n.add(i)}}return e}function as(t){var n;const e={...t,from:Zo(t.from),join:(n=t.join)==null?void 0:n.map(s=>({...s,from:s.from.type==="queryRef"?new Te(as(s.from.query),s.from.alias):s.from}))};return Tf(e)}function Tf(t){if(!t.where||t.where.length===0||t.from.type==="unionFrom")return t;if(!t.join||t.join.length===0){if(t.where.length>1){const c=ci(t.where),a=us(c);return{...t,where:[a]}}return t}const e=t.where.filter(c=>!cr(c)),s=ci(e).map(c=>Qo(c)),i=Yo(s),r=$f(t,i),o=t.where.filter(c=>cr(c));return o.length>0&&(r.where=[...r.where||[],...o]),r}function oi(t){var e;return{...t,from:ls(t.from),join:(e=t.join)==null?void 0:e.map(n=>({...n,from:Pf(n.from)}))}}function ls(t){if(t.type==="unionFrom")return new vn(t.sources.map(n=>ls(n)));if(t.type==="unionAll")return new Bt(t.queries.map(n=>oi(n)));if(t.type==="collectionRef")return t;const e=oi(t.query);if(Mf(e)){const n=ls(e.from);if(n.type==="collectionRef")return new en(n.collection,t.alias);if(n.type==="queryRef")return new Te(n.query,t.alias)}return new Te(e,t.alias)}function Pf(t){return ls(t)}function Mf(t){return(!t.where||t.where.length===0)&&!t.select&&(!t.groupBy||t.groupBy.length===0)&&(!t.having||t.having.length===0)&&(!t.orderBy||t.orderBy.length===0)&&(!t.join||t.join.length===0)&&t.limit===void 0&&t.offset===void 0&&!t.fnSelect&&(!t.fnWhere||t.fnWhere.length===0)&&(!t.fnHaving||t.fnHaving.length===0)}function ci(t){const e=[];for(const n of t){const s=bi(n);e.push(...Pi(s))}return e}function Pi(t){if(t.type==="func"&&t.name==="and"){const e=[];for(const n of t.args)e.push(...Pi(n));return e}else return[t]}function Qo(t){const e=new Set;let n=!1;function s(i){switch(i.type){case"ref":if(i.path&&i.path.length>0){const r=i.path[0];r&&(e.add(r),i.path.length===1&&(n=!0))}break;case"func":i.args&&i.args.forEach(s);break;case"val":break;case"agg":i.args&&i.args.forEach(s);break}}return s(t),{expression:t,touchedSources:e,hasNamespaceOnlyRef:n}}function Yo(t){const e=new Map,n=[];for(const r of t)if(r.touchedSources.size===1&&!r.hasNamespaceOnlyRef){const o=Array.from(r.touchedSources)[0];e.has(o)||e.set(o,[]),e.get(o).push(r.expression)}else(r.touchedSources.size>1||r.hasNamespaceOnlyRef)&&n.push(r.expression);const s=new Map;for(const[r,o]of e)s.set(r,us(o));const i=n.length>0?us(n):void 0;return{singleSource:s,multiSource:i}}function $f(t,e){const n=new Set,s=Jo(t),i=new Map;for(const[u,y]of e.singleSource)s.has(u)||i.set(u,y);const r=Xo(t.from,i,n),o=t.join?t.join.map(u=>({...u,from:ec(u.from,i,n)})):void 0,c=[];e.multiSource&&c.push(e.multiSource);const a=s.size>0;for(const[u,y]of e.singleSource)n.has(u)?a&&c.push(Gc(y)):c.push(y);const l=c.length>1?[us(c.flatMap(u=>Pi(bi(u))))]:c;return{select:t.select,groupBy:t.groupBy?[...t.groupBy]:void 0,having:t.having?[...t.having]:void 0,orderBy:t.orderBy?[...t.orderBy]:void 0,limit:t.limit,offset:t.offset,distinct:t.distinct,fnSelect:t.fnSelect,fnWhere:t.fnWhere?[...t.fnWhere]:void 0,fnHaving:t.fnHaving?[...t.fnHaving]:void 0,from:r,join:o,where:l.length>0?l:[]}}function ft(t){return{from:Mi(t.from),select:t.select,join:t.join?t.join.map(e=>({type:e.type,left:e.left,right:e.right,from:Df(e.from)})):void 0,where:t.where?[...t.where]:void 0,groupBy:t.groupBy?[...t.groupBy]:void 0,having:t.having?[...t.having]:void 0,orderBy:t.orderBy?[...t.orderBy]:void 0,limit:t.limit,offset:t.offset,fnSelect:t.fnSelect,fnWhere:t.fnWhere?[...t.fnWhere]:void 0,fnHaving:t.fnHaving?[...t.fnHaving]:void 0}}function Mi(t){return t.type==="collectionRef"?new en(t.collection,t.alias):t.type==="queryRef"?new Te(ft(t.query),t.alias):t.type==="unionAll"?new Bt(t.queries.map(e=>ft(e))):new vn(t.sources.map(e=>Mi(e)))}function Df(t){return Mi(t)}function Zo(t){return t.type==="queryRef"?new Te(as(t.query),t.alias):t.type==="unionFrom"?new vn(t.sources.map(e=>Zo(e))):t.type==="unionAll"?new Bt(t.queries.map(e=>as(e))):t}function $i(t){return t.type==="unionFrom"?t.sources:t.type==="unionAll"?[]:[t]}function jf(t){var e;return(e=$i(t.from)[0])==null?void 0:e.alias}function Xo(t,e,n){if(t.type==="unionFrom")return new vn(t.sources.map(o=>ec(o,e,n)));if(t.type==="unionAll")return new Bt(t.queries.map(o=>ft(o)));const s=e.get(t.alias);if(!s)return t.type==="collectionRef"?new en(t.collection,t.alias):new Te(ft(t.query),t.alias);if(t.type==="collectionRef"){const o={from:new en(t.collection,t.alias),where:[s]};return n.add(t.alias),new Te(o,t.alias)}if(!Nf(t.query,s,t.alias))return new Te(ft(t.query),t.alias);if(Wf(t.query,s,t.alias))return new Te(ft(t.query),t.alias);const i=t.query.where||[],r={...ft(t.query),where:[...i,s]};return n.add(t.alias),new Te(r,t.alias)}function ec(t,e,n){return Xo(t,e,n)}function Kf(t,e,n){return t.select?tc(t.select)||zf(t.select,e,n):!1}function Ff(t){return t.groupBy&&t.groupBy.length>0}function Bf(t){return t.having&&t.having.length>0}function Lf(t){return t.orderBy&&t.orderBy.length>0&&(t.limit!==void 0||t.offset!==void 0)}function Vf(t){return t.fnSelect||t.fnWhere&&t.fnWhere.length>0||t.fnHaving&&t.fnHaving.length>0}function Nf(t,e,n){return!(Kf(t,e,n)||Ff(t)||Bf(t)||Lf(t)||Vf(t))}function tc(t){for(const e of Object.values(t))if(typeof e=="object"){const n=e;if(n.type==="agg"||!("type"in n)&&tc(n))return!0}return!1}function Di(t){const e=[];if(t==null||typeof t!="object")return e;switch(t.type){case"ref":e.push(t);break;case"func":case"agg":for(const n of t.args??[])e.push(...Di(n));break}return e}function zf(t,e,n){const s=new Set;for(const[r,o]of Object.entries(t))r.startsWith("__SPREAD_SENTINEL__")||o instanceof G||s.add(r);const i=Di(e);for(const r of i){const o=r.path;if(!Array.isArray(o)||o.length<2)continue;const c=o[0],a=o[1];if(c===n&&s.has(a))return!0}return!1}function Wf(t,e,n){const s=Di(e);if(s.every(r=>r.path[0]!==n))return!1;if(t.fnSelect)return!0;const i=t.select;if(!i)return!1;for(const r of s){const o=r.path;if(o.length<2||o[0]!==n)continue;const c=i[o[1]];if(!c)continue;if(!(c instanceof G)||c.path.length<2)return!0;const[a,l]=c.path,f=jf(t);if(a!==n&&a!==f||l!==o[1])return!0}return!1}function us(t){if(t.length===0)throw new Ha;return t.length===1?t[0]:new ye("and",t)}function nc(t,e,n,s,i,r){if(e.type==="unionFrom")return Ki(t,s);if(e.type==="queryRef"&&ai(e.query.from)){const a=ji(e.query,n,s);return Fi(a)}if(!i)return[];const o=ic(s);if(!o)return[];const c=tn(t,o,i);return c?[{alias:r[n]||n,collection:c.collection,path:c.path}]:[]}function ai(t){return t.type==="unionFrom"?!0:t.type==="queryRef"?ai(t.query.from):t.type==="unionAll"?t.queries.some(e=>ai(e.from)):!1}function ji(t,e,n){if(!n||typeof n!="object"||!("type"in n))return[];const s=n;if(s.type==="func"&&s.name==="coalesce")return Fi(s.args.flatMap(r=>ji(t,e,r)));const i=ic(s);return!i||i.path[0]!==e?[]:sc(t,new G(i.path.slice(1)))}function Ki(t,e){if(!e||typeof e!="object"||!("type"in e))return[];const n=e;return n.type==="ref"?sc(t,n):n.type==="func"&&n.name==="coalesce"?Fi(n.args.flatMap(s=>Ki(t,s))):[]}function sc(t,e){var r;if(e.path.length===0)return[];if(e.path.length===1){const o=e.path[0],c=(r=t.select)==null?void 0:r[o];return c?Ki(t,c):[]}const[n,...s]=e.path,i=Uf(t,n);return i?i.type==="collectionRef"?[{alias:i.alias,collection:i.collection,path:s}]:i.query.limit||i.query.offset?[]:ji(i.query,i.alias,e):[]}function Uf(t,e){if(t.join){for(const i of t.join)if(i.from.alias===e)return i.from}const n=t.from;return(n.type==="unionFrom"?n.sources:n.type==="unionAll"?[]:[n]).find(i=>i.alias===e)}function Fi(t){const e=new Set,n=[];for(const s of t){const i=`${s.alias}:${s.path.join(".")}`;e.has(i)||(e.add(i),n.push(s))}return n}function ic(t){if(t instanceof G)return t;if(t&&typeof t=="object"&&"type"in t&&t.type==="ref"&&Array.isArray(t.path))return new G(t.path)}function qf(t,e,n,s,i,r,o,c,a,l,f,u,y,p,h,d,g,w,C){let m=t;for(const b of e)m=Hf(m,b,n,s,i,r,o,c,a,l,f,u,y,p,h,d,g,w,C);return m}function Hf(t,e,n,s,i,r,o,c,a,l,f,u,y,p,h,d,g,w,C){const m=e.from.type==="collectionRef",{alias:b,input:v,collectionId:x}=Jf(e.from,r,a,l,f,u,y,p,o,c,d,g,w,C);n[b]=v,m&&(g[b]=x);const I=a[s],M=a[x];if(!I)throw new dr(s);if(!M)throw new dr(x);const{activeSource:O,lazySource:E}=Zf(e.type,I,M),k=Object.keys(n),{mainExpr:V,joinedExpr:F}=Gf(e.left,e.right,k,b,h.from.type==="unionAll"),qe=q(V),En=q(F);let Lt=t.pipe(J(([T,R])=>[Et(qe(R)),[T,R]])),It=v.pipe(J(([T,R])=>{const $={[b]:R};return[Et(En($)),[T,$]]}));if(!["inner","left","right","full"].includes(e.type))throw new Da(e.type);if(O){const T=O==="main"?e.from:h.from,R=T.type==="queryRef"&&(T.query.limit||T.query.offset),$=T.type==="unionAll",A=O==="main"?F:V,Z=O==="main"?b:i,H=$?[]:nc(h,T,Z,A,E,w);if(!R&&H.length>0){for(const L of H)u.add(L.alias);const j=O==="main"?Lt:It;for(const L of H){const X=L.path[0];X&&In(X,L.path,L.collection)}const B=j.pipe(No(L=>{const X=[...new Set(L.getInner().map(([[se]])=>se).filter(se=>se!=null))];if(X.length!==0)for(const se of H){const ve=l[se.alias];if(!ve)throw new Ga(se.alias,Z,se.collection.id,Object.keys(l));if(ve.hasLoadedInitialState())continue;const Vt=new G(se.path);if(!ve.requestSnapshot({where:Wo(Vt,X),optimizedOnly:!0})){const W=se.collection.id,U=se.path.join(".");console.warn(`[TanStack DB]${W?` [${W}]`:""} Join requires an index on "${U}" for efficient loading. Falling back to loading all data. Consider creating an index on the collection with collection.createIndex((row) => row.${U}) or enable auto-indexing with autoIndex: 'eager' and a defaultIndexType.`),ve.requestSnapshot()}}}));O==="main"?Lt=B:It=B}}return Lt.pipe(Vo(It,e.type),Yf(e.type))}function Gf(t,e,n,s,i=!1){const r=n.filter(y=>y!==s),o=li(t),c=li(e),a=o.has(s),l=c.has(s),f=[...o].filter(y=>r.includes(y)||i&&y!==s),u=[...c].filter(y=>r.includes(y)||i&&y!==s);if(f.length>0&&!a&&l&&u.length===0)return{mainExpr:t,joinedExpr:e};if(a&&f.length===0&&u.length>0&&!l)return{mainExpr:e,joinedExpr:t};throw o.size===0||c.size===0?new Ka:o.size===1&&c.size===1&&[...o][0]===[...c][0]?new ja([...o][0]):f.length===0?new Fa([...o][0]):l?new La:new Ba(s)}function li(t){switch(t.type){case"ref":return new Set(t.path[0]?[t.path[0]]:[]);case"func":{const e=new Set;for(const n of t.args)for(const s of li(n))e.add(s);return e}default:return new Set}}function Jf(t,e,n,s,i,r,o,c,a,l,f,u,y,p){switch(t.type){case"collectionRef":{const h=e[t.alias];if(!h)throw new mo(t.alias,t.collection.id,Object.keys(e));return u[t.alias]=t.collection.id,{alias:t.alias,input:h,collectionId:t.collection.id}}case"queryRef":{const h=l.get(t.query)||t.query,d=f(h,e,n,s,i,r,o,c,a,l);Object.assign(u,d.aliasToCollectionId),Object.assign(y,d.aliasRemapping);const g=l.has(t.query),w=Qf(t.query);if(!(!g&&w!==void 0&&t.alias===w))for(const[x,I]of d.sourceWhereClauses)p.set(x,I);const m=Object.keys(d.aliasToCollectionId).find(x=>d.aliasToCollectionId[x]===d.collectionId);m&&m!==t.alias&&(y[t.alias]=m);const v=d.pipeline.pipe(J(x=>{const[I,[M,O]]=x;return[I,M]}));return{alias:t.alias,input:v,collectionId:d.collectionId}}default:throw new Va(t.type)}}function Qf(t){var e;if(t.from.type==="unionFrom")return(e=t.from.sources[0])==null?void 0:e.alias;if(t.from.type!=="unionAll")return t.from.alias}function Yf(t){return function(e){return e.pipe(je(n=>{const[s,[i,r]]=n,o=i==null?void 0:i[1],c=r==null?void 0:r[1];return t==="inner"?!!(o&&c):t==="left"?!!o:t==="right"?!!c:!0}),J(n=>{const[s,[i,r]]=n,o=i==null?void 0:i[0],c=i==null?void 0:i[1],a=r==null?void 0:r[0],l=r==null?void 0:r[1],f={};return c&&Object.assign(f,c),l&&Object.assign(f,l),[`[${o},${a}]`,f]}))}}function Zf(t,e,n){switch(t){case"left":return{activeSource:"main",lazySource:n};case"right":return{activeSource:"joined",lazySource:e};case"inner":return e.size<n.size?{activeSource:"main",lazySource:n}:{activeSource:"joined",lazySource:e};default:return{activeSource:void 0,lazySource:void 0}}}function ui(t){return t instanceof de?t.value:t}function rc(t,e,n){const s=t.source(e);if(s&&typeof s=="object"){let i=n;const r=t.targetPath;if(r.length===0)for(const[o,c]of Object.entries(s))n[o]=ui(c);else for(let o=0;o<r.length;o++){const c=r[o];if(o===r.length-1){const a=i[c]??(i[c]={});if(typeof a=="object")for(const[l,f]of Object.entries(s))a[l]=ui(f)}else{const a=i[c];(a==null||typeof a!="object")&&(i[c]={}),i=i[c]}}}}function oc(t,e,n){const s=t.alias.split(".");if(s.length===1)n[t.alias]=t.compiled(e);else{let i=n;for(let r=0;r<s.length-1;r++){const o=s[r],c=i[o];(c==null||typeof c!="object")&&(i[o]={}),i=i[o]}i[s[s.length-1]]=ui(t.compiled(e))}}function Xf([t,e],n){const s={};for(const i of n)i.kind==="merge"?rc(i,e,s):oc(i,e,s);return[t,{...e,$selected:s}]}function ed(t,e,n){const s=[];return Bi([],e,s),t.pipe(J(i=>Xf(i,s)))}function td(t){const e=[];return Bi([],t,e),n=>{const s={};for(const i of e)i.kind==="merge"?rc(i,n,s):oc(i,n,s);return s}}function Br(t){return t==null?()=>t:uc(t)?we(t)?()=>null:cc(t):t instanceof de?()=>t.value:t.type==="includesSubquery"?()=>null:lc(t)?td(t):ac(t)||we(t)?()=>null:Ie(t)?q(t):()=>t}function cc(t){const e=t.branches.map(s=>({condition:q(s.condition),value:Br(s.value)})),n=t.defaultValue===void 0?void 0:Br(t.defaultValue);return s=>{for(const i of e)if(xs(i.condition(s)))return i.value(s);return n!==void 0?n(s):null}}function ac(t){return t.type==="agg"}function lc(t){return t&&typeof t=="object"&&!Ie(t)}function Bi(t,e,n){for(const[s,i]of Object.entries(e)){if(s.startsWith("__SPREAD_SENTINEL__")){const o=s.slice(19),c=o.lastIndexOf("__"),a=c>=0?o.slice(0,c):o,l=i&&typeof i=="object"&&"type"in i&&i.type==="ref";if(a.includes(".")||l){const f=[...t],u=l?i:new G(a.split(".")),y=q(u);n.push({kind:"merge",targetPath:f,source:y})}else{const f=a,u=[...t];n.push({kind:"merge",targetPath:u,source:y=>y[f]})}continue}const r=i;if(uc(r)){if(we(r)){n.push({kind:"field",alias:[...t,s].join("."),compiled:()=>null});continue}n.push({kind:"field",alias:[...t,s].join("."),compiled:cc(r)});continue}if(r&&r.type==="includesSubquery"){n.push({kind:"field",alias:[...t,s].join("."),compiled:()=>null});continue}if(lc(r)){Bi([...t,s],r,n);continue}if(ac(r)||we(r))n.push({kind:"field",alias:[...t,s].join("."),compiled:()=>null});else{if(r===void 0||!Ie(r)){n.push({kind:"field",alias:[...t,s].join("."),compiled:()=>r});continue}if(r instanceof de){const o=r.value;n.push({kind:"field",alias:[...t,s].join("."),compiled:()=>o})}else n.push({kind:"field",alias:[...t,s].join("."),compiled:q(r)})}}}function uc(t){return t instanceof he||t!=null&&typeof t=="object"&&t.type==="conditionalSelect"&&Array.isArray(t.branches)}const Se=Symbol("includesRouting"),Li=Symbol("fnSelectState"),Ns=Symbol("skipInclude");function an(t,e,n,s,i,r,o,c,a=new WeakMap,l=new WeakMap,f,u){const y=a.get(t);if(y)return y;Jn(t);const{optimizedQuery:p,sourceWhereClauses:h}=Go(t);let d=p;l.set(d,t),fs(d,t,l);const g={...e},w={},C={},m={},{alias:b,collectionId:v,pipeline:x,sources:I,sourceIncludes:M,directIncludes:O,isUnionFrom:E}=sd(d.from,g,n,s,i,r,o,c,a,l,w,C,h);Object.assign(m,I);let k=x;if(!E&&f&&u){const T=m[b];let R=T;const $=u.path.slice(1);R=T.pipe(J(([H,j])=>[hd(j,$),[H,j]])).pipe(Vo(f,"inner")).pipe(je(([H,[j]])=>j!=null),J(([H,[j,B]])=>{const[L,X]=j,se={...X,__correlationKey:H};return B!=null&&(se.__parentContext=B),[B!=null?`${String(L)}::${JSON.stringify(B)}`:L,se]})),m[b]=R,k=fi(R,b)}if(d.join&&d.join.length>0&&(k=qf(k,d.join,m,v,b,g,a,l,n,s,i,r,o,c,t,an,w,C,h)),d.where&&d.where.length>0)for(const T of d.where){const R=bi(T),$=q(R);k=k.pipe(je(([A,Z])=>Tt($(Z))))}if(d.fnWhere&&d.fnWhere.length>0)for(const T of d.fnWhere)k=k.pipe(je(([R,$])=>Tt(T($))));const V=d.select?[]:[...O],F=[];for(const{sourceAlias:T,include:R}of M){const $=d.select!=null?ad(d.select,T,R.resultPath):d.fnSelect?[]:[{path:[T,...R.resultPath],guards:[]}];if($.length!==0)for(const{path:A,guards:Z}of $){const H=Qn(`${T}.${A.join(".")}`,F),j=Z.map(B=>({condition:q(B.condition),expected:B.expected}));V.push({...R,fieldName:H,resultPath:A}),F.push({fieldName:H,getRouting:B=>{var L,X;return kt(j,B)?((X=(L=B[T])==null?void 0:L[Se])==null?void 0:X[R.fieldName])??{correlationKey:null,parentContext:null}:{correlationKey:null,parentContext:null}}})}}if(d.select&&O.length>0)for(const T of O){const R=ld(d.select,T.resultPath);for(const{path:$,guards:A}of R){const Z=Qn($.join("."),F),H=A.map(j=>({condition:q(j.condition),expected:j.expected}));V.push({...T,fieldName:Z,resultPath:$}),F.push({fieldName:Z,getRouting:j=>{var B;return kt(H,j)?((B=j[Se])==null?void 0:B[T.fieldName])??{correlationKey:null,parentContext:null}:{correlationKey:null,parentContext:null}}})}}if(d.select){const T=fd(d.select);T.length>0&&(d={...d,select:{...d.select}});for(const{key:R,path:$,subquery:A,guards:Z}of T){const H=Qn(R,F),j=q(A.correlationField),B=Z.map(W=>({condition:q(W.condition),expected:W.expected}));let L;if(A.parentProjection&&A.parentProjection.length>0){const W=A.parentProjection.map(U=>({alias:U.path[0],field:U.path.slice(1),compiled:q(U)}));L=k.pipe(J(([U,me])=>{if(!kt(B,me))return[Ns,null];const ue={};for(const ce of W){ue[ce.alias]||(ue[ce.alias]={});const Ce=ce.compiled(me);let rt=ue[ce.alias];for(let Ae=0;Ae<ce.field.length-1;Ae++)rt[ce.field[Ae]]||(rt[ce.field[Ae]]={}),rt=rt[ce.field[Ae]];rt[ce.field[ce.field.length-1]]=Ce}return[j(me),ue]}))}else L=k.pipe(J(([W,U])=>kt(B,U)?[j(U),null]:[Ns,null]));L=L.pipe(je(([W])=>W!==Ns)),L=L.pipe(Ao(W=>W.map(([U,me])=>[U,me>0?1:0])));const X=A.childCorrelationField.path[0],se=A.query.from.type==="collectionRef"?A.query.from.collection:void 0,ve=nc(A.query,A.query.from,X,A.childCorrelationField,se,C);if(ve.length>0){for(const W of ve)r.add(W.alias);for(const W of ve){const U=W.path[0];U&&In(U,W.path,W.collection)}L=L.pipe(No(W=>{const U=[...new Set(W.getInner().map(([[me]])=>me).filter(me=>me!=null))];if(U.length!==0)for(const me of ve){const ue=s[me.alias];if(!ue||ue.hasLoadedInitialState())continue;const ce=new G(me.path);ue.requestSnapshot({where:Wo(ce,U)})}}))}const Vt=A.parentFilters&&A.parentFilters.length>0?{...A.query,where:[...A.query.where||[],...A.parentFilters]}:A.query,Ot=an(Vt,g,n,s,i,r,o,c,a,l,L,A.childCorrelationField);Object.assign(w,Ot.aliasToCollectionId),Object.assign(C,Ot.aliasRemapping);for(const[W,U]of Ot.sourceWhereClauses)h.set(W,U);if(V.push({pipeline:Ot.pipeline,fieldName:H,resultPath:$,correlationField:A.correlationField,childCorrelationField:A.childCorrelationField,hasOrderBy:!!(A.query.orderBy&&A.query.orderBy.length>0),childCompilationResult:Ot,parentProjection:A.parentProjection,materialization:A.materialization,scalarField:A.scalarField}),A.parentProjection&&A.parentProjection.length>0){const W=A.parentProjection.map(ue=>({alias:ue.path[0],field:ue.path.slice(1),compiled:q(ue)})),U=j,me=B;F.push({fieldName:H,getRouting:ue=>{if(!kt(me,ue))return{correlationKey:null,parentContext:null};const ce={};for(const Ce of W){ce[Ce.alias]||(ce[Ce.alias]={});const rt=Ce.compiled(ue);let Ae=ce[Ce.alias];for(let Nt=0;Nt<Ce.field.length-1;Nt++)Ae[Ce.field[Nt]]||(Ae[Ce.field[Nt]]={}),Ae=Ae[Ce.field[Nt]];Ae[Ce.field[Ce.field.length-1]]=rt}return{correlationKey:U(ue),parentContext:ce}}})}else{const W=B;F.push({fieldName:H,getRouting:U=>kt(W,U)?{correlationKey:j(U),parentContext:null}:{correlationKey:null,parentContext:null}})}d={...d,select:dd(d.select,$)}}}if(d.distinct&&!d.fnSelect&&!d.select&&d.from.type!=="unionAll")throw new Oa;if(d.fnSelect&&d.groupBy&&d.groupBy.length>0)throw new ka;d.fnSelect?k=k.pipe(J(([T,R])=>{const $=d.fnSelect(R);if($&&typeof $=="object"){const A=R[Se];A&&($[Se]=A),O.length>0&&Object.defineProperty($,Li,{value:{sourceRow:R,fnSelect:d.fnSelect},enumerable:!0,configurable:!0})}return[T,{...R,$selected:$}]})):d.select?k=ed(k,d.select):k=k.pipe(J(([T,R])=>{const $=!E&&!d.join&&!d.groupBy?R[b]:R;return[T,{...R,$selected:$}]})),F.length>0&&(k=k.pipe(J(([T,R])=>{const $={};for(const{fieldName:A,getRouting:Z}of F)$[A]=Z(R);return R.$selected[Se]=$,[T,R]})));const qe=f?b:void 0;if(d.groupBy&&d.groupBy.length>0?k=kr(k,d.groupBy,d.having,d.select,d.fnHaving,v,qe):d.select&&Object.values(d.select).some(R=>R.type==="agg"||we(R))&&(k=kr(k,[],d.having,d.select,d.fnHaving,v,qe)),d.having&&(!d.groupBy||d.groupBy.length===0)&&!(d.select?Object.values(d.select).some(R=>R.type==="agg"):!1))throw new Ra;if(d.fnHaving&&d.fnHaving.length>0&&(!d.groupBy||d.groupBy.length===0))for(const T of d.fnHaving)k=k.pipe(je(([R,$])=>T($)));if(d.distinct&&(k=k.pipe(ou(([T,R])=>R.$selected))),d.orderBy&&d.orderBy.length>0){const T=f&&(d.limit!==void 0||d.offset!==void 0)?(H,j)=>{var X;const B=(X=j==null?void 0:j[b])==null?void 0:X.__correlationKey,L=j==null?void 0:j.__parentContext;return L!=null?JSON.stringify([B,L]):B}:void 0,A=Ku(t,k,d.orderBy,d.select||{},n[v],o,c,d.limit,d.offset,T).pipe(J(([H,[j,B]])=>{var se;const L=j.$selected,X=Vr(di(L),j);if(f){const ve=(se=j[b])==null?void 0:se.__correlationKey,Vt=j.__parentContext??null;return delete X.__correlationKey,delete X.__parentContext,[H,[X,B,ve,Vt]]}return[H,[X,B]]})),Z={collectionId:v,pipeline:A,sourceWhereClauses:h,aliasToCollectionId:w,aliasRemapping:C,includes:V.length>0?V:void 0};return a.set(t,Z),Z}else if(d.limit!==void 0||d.offset!==void 0)throw new Aa;const Lt=k.pipe(J(([T,R])=>{var Z;const $=R.$selected,A=Vr(di($),R);if(f){const H=(Z=R[b])==null?void 0:Z.__correlationKey,j=R.__parentContext??null;return delete A.__correlationKey,delete A.__parentContext,[T,[A,void 0,H,j]]}return[T,[A,void 0]]})),It={collectionId:v,pipeline:Lt,sourceWhereClauses:h,aliasToCollectionId:w,aliasRemapping:C,includes:V.length>0?V:void 0};return a.set(t,It),It}function nd(t){const e=new Set;for(const n of Kt(t.from))n.type==="collectionRef"&&e.add(n.alias);if(t.join)for(const n of t.join)n.from.type==="collectionRef"&&e.add(n.from.alias);return e}function Jn(t,e=new Set){const n=nd(t);for(const i of n)if(e.has(i))throw new Ta(i,Array.from(e));const s=new Set([...e,...n]);if(t.from.type==="unionAll")for(const i of t.from.queries)Jn(i,s);else for(const i of Kt(t.from))i.type==="queryRef"&&Jn(i.query,s);if(t.join)for(const i of t.join)i.from.type==="queryRef"&&Jn(i.from.query,s)}function sd(t,e,n,s,i,r,o,c,a,l,f,u,y){if(t.type==="unionAll")return id(t,e,n,s,i,r,o,c,a,l,f,u,y);if(t.type!=="unionFrom"){const{alias:C,input:m,collectionId:b,sourceIncludes:v}=Lr(t,e,n,s,i,r,o,c,a,l,f,u,y);return{alias:C,pipeline:fi(m,C),collectionId:b,sources:{[C]:m},sourceIncludes:v,directIncludes:[],isUnionFrom:!1}}if(t.sources.length===0)throw new Ci("empty unionFrom");const p={},h=[];let d,g="",w="";for(const C of t.sources){const{alias:m,input:b,collectionId:v,sourceIncludes:x}=Lr(C,e,n,s,i,r,o,c,a,l,f,u,y);g||(g=m,w=v),p[m]=b,h.push(...x);const I=fi(b,m).pipe(J(([M,O])=>[`${m}:${fc(M)}`,O]));d=d?d.pipe(ko(I)):I}return{alias:g,pipeline:d,collectionId:w,sources:p,sourceIncludes:h,directIncludes:[],isUnionFrom:!0}}function id(t,e,n,s,i,r,o,c,a,l,f,u,y){if(t.queries.length===0)throw new Ci("empty unionAll");const p={},h=[],d=[];let g,w="";const C=new Set;for(let m=0;m<t.queries.length;m++){const b=t.queries[m];for(const I of od(b)){if(C.has(I.alias))throw new Error(`Duplicate source alias "${I.alias}" in unionAll query branches. Use distinct aliases in each branch before passing them to unionAll().`);C.add(I.alias)}const v=an(b,e,n,s,i,r,o,c,a,l);w||(w=v.collectionId),Object.assign(f,v.aliasToCollectionId),Object.assign(u,v.aliasRemapping),d.push(...v.includes??[]),Object.assign(p,e);for(const[I,M]of v.sourceWhereClauses)y.set(I,M);const x=v.pipeline.pipe(J(([I,[M]])=>[`${m}:${fc(I)}`,M]));g=g?g.pipe(ko(x)):x}return{alias:"",pipeline:g,collectionId:w,sources:p,sourceIncludes:h,directIncludes:d,isUnionFrom:!0}}function fi(t,e){return t.pipe(J(([n,s])=>{const{__parentContext:i,...r}=s,o={[e]:r};return i&&(Object.assign(o,i),o.__parentContext=i),[n,o]}))}function fc(t){return typeof t=="string"?`string:${t}`:typeof t=="number"?`number:${String(t)}`:typeof t=="bigint"?`bigint:${String(t)}`:`${typeof t}:${JSON.stringify(t)}`}function Lr(t,e,n,s,i,r,o,c,a,l,f,u,y){var p;switch(t.type){case"collectionRef":{const h=e[t.alias];if(!h)throw new mo(t.alias,t.collection.id,Object.keys(e));return f[t.alias]=t.collection.id,{alias:t.alias,input:h,collectionId:t.collection.id,sourceIncludes:[]}}case"queryRef":{const h=l.get(t.query)||t.query,d=an(h,e,n,s,i,r,o,c,a,l);Object.assign(f,d.aliasToCollectionId),Object.assign(u,d.aliasRemapping);const g=l.has(t.query),w=cd(t.query.from);if(!(!g&&t.alias===w))for(const[x,I]of d.sourceWhereClauses)y.set(x,I);const m=Object.keys(d.aliasToCollectionId).find(x=>d.aliasToCollectionId[x]===d.collectionId);m&&m!==t.alias&&(u[t.alias]=m);const v=d.pipeline.pipe(J(x=>{const[I,[M,O]]=x,E=di(M);return[I,E]}));return{alias:t.alias,input:v,collectionId:d.collectionId,sourceIncludes:((p=d.includes)==null?void 0:p.map(x=>({sourceAlias:t.alias,include:x})))??[]}}default:throw new Ci(t.type)}}function rd(t){return t instanceof de||t&&typeof t=="object"&&"type"in t&&t.type==="val"}function di(t){return rd(t)?t.value:t}function Vr(t,e){if(!t||typeof t!="object")return t;let n=!1;for(const s of Js)if(t[s]==null&&s in e){n=!0;break}if(!n)return t;for(const s of Js)t[s]==null&&s in e&&(t[s]=e[s]);return t}function fs(t,e,n){if(ud(t.from,e.from,n),t.join&&e.join)for(let s=0;s<t.join.length&&s<e.join.length;s++){const i=t.join[s],r=e.join[s];i.from.type==="queryRef"&&r.from.type==="queryRef"&&(n.set(i.from.query,r.from.query),fs(i.from.query,r.from.query,n))}}function Kt(t){return t.type==="unionFrom"?t.sources:t.type==="unionAll"?[]:[t]}function od(t){var e;return[...Kt(t.from),...((e=t.join)==null?void 0:e.map(n=>n.from))??[]]}function cd(t){var e;return((e=Kt(t)[0])==null?void 0:e.alias)??""}function ad(t,e,n){const s=[e,...n];return dc(t,s)}function ld(t,e){return dc(t,e)}function dc(t,e){const n=[],s=(o,c,a)=>{for(const[l,f]of Object.entries(o)){if(l.startsWith("__SPREAD_SENTINEL__")){i(l,f,c,a);continue}r(f,[...c,l],a)}},i=(o,c,a,l)=>{const f=o.slice(19),u=f.lastIndexOf("__"),y=u>=0?f.slice(0,u):f,h=c&&typeof c=="object"&&"type"in c&&c.type==="ref"?c.path:y.split(".").filter(Boolean);Nr(e,h)&&n.push({path:[...a,...e.slice(h.length)],guards:l})},r=(o,c,a)=>{if(o instanceof G&&Nr(e,o.path)){n.push({path:[...c,...e.slice(o.path.length)],guards:a});return}if(o instanceof he){const l=[];for(const f of o.branches)r(f.value,c,[...a,...l,{condition:f.condition,expected:!0}]),l.push({condition:f.condition,expected:!1});o.defaultValue!==void 0&&r(o.defaultValue,c,[...a,...l]);return}kn(o)&&s(o,c,a)};return s(t,[],[]),n}function Nr(t,e){return e.length<=t.length&&e.every((n,s)=>t[s]===n)}function ud(t,e,n){if(t.type==="unionAll"&&e.type==="unionAll"){for(let r=0;r<t.queries.length&&r<e.queries.length;r++){const o=t.queries[r],c=e.queries[r];n.set(o,c),fs(o,c,n)}return}const s=Kt(t),i=Kt(e);for(let r=0;r<s.length&&r<i.length;r++){const o=s[r],c=i[r];o.type==="queryRef"&&c.type==="queryRef"&&(n.set(o.query,c.query),fs(o.query,c.query,n))}}function fd(t){const e=[];for(const[n,s]of Object.entries(t))n.startsWith("__SPREAD_SENTINEL__")||(s instanceof Pe?e.push({key:pc([n],e),path:[n],subquery:s,guards:[]}):s instanceof he?hc(s,[n],[],e):kn(s)&&yc(s,n));return e}function hc(t,e,n,s){const i=[];for(const r of t.branches)hi(r.value,e,[...n,...i,{condition:r.condition,expected:!0}],s),i.push({condition:r.condition,expected:!1});t.defaultValue!==void 0&&hi(t.defaultValue,e,[...n,...i],s)}function hi(t,e,n,s){if(t instanceof Pe){const i=pc(e,s);s.push({key:i,path:e,subquery:t,guards:n});return}if(t instanceof he){hc(t,e,n,s);return}if(kn(t))for(const[i,r]of Object.entries(t))i.startsWith("__SPREAD_SENTINEL__")||hi(r,[...e,i],n,s)}function pc(t,e){return Qn(t.join("."),e)}function Qn(t,e){const n=r=>e.some(o=>(o.key??o.fieldName)===r);if(!n(t))return t;let s=e.length,i=`${t}#${s}`;for(;n(i);)s++,i=`${t}#${s}`;return i}function kn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)&&!Ie(t)}function yc(t,e){for(const[n,s]of Object.entries(t))if(!n.startsWith("__SPREAD_SENTINEL__")){if(s instanceof Pe)throw new Error(`Includes subqueries must be at the top level of select(). Found nested includes at "${e}.${n}".`);kn(s)&&yc(s,`${e}.${n}`)}}function dd(t,e){return ds(t,e,new de(null)).value}function ds(t,e,n){if(e.length===0)return hs(t,n);if(t instanceof he)return gc(t,e,n);if(!kn(t))return{value:t,replaced:!1};if(e.length===1){const o=e[0],c=hs(t[o],n);return c.replaced?{value:{...t,[o]:c.value},replaced:!0}:{value:t,replaced:!1}}const[s,...i]=e,r=ds(t[s],i,n);return r.replaced?{value:{...t,[s]:r.value},replaced:!0}:{value:t,replaced:!1}}function hs(t,e){return t instanceof Pe?{value:e,replaced:!0}:t instanceof he?gc(t,[],e):{value:t,replaced:!1}}function gc(t,e,n){let s=!1;const i=t.branches.map(o=>{const c=e.length===0?hs(o.value,n):ds(o.value,e,n);return c.replaced?(s=!0,{...o,value:c.value}):o});let r=t.defaultValue;if(t.defaultValue!==void 0){const o=e.length===0?hs(t.defaultValue,n):ds(t.defaultValue,e,n);o.replaced&&(s=!0,r=o.value)}return s?{value:new he(i,r),replaced:!0}:{value:t,replaced:!1}}function hd(t,e){let n=t;for(const s of e){if(n==null)return n;n=n[s]}return n}function kt(t,e){return t.every(n=>xs(n.condition(e))===n.expected)}function Vi(t,e){const n=t.type;if(n==="val")return new de(t.value);if(n==="ref"){const s=t.path;if(Array.isArray(s)){if(s[0]===e&&s.length>1)return new G(s.slice(1));if(s.length===1&&s[0]!==void 0)return new G([s[0]])}return new G(Array.isArray(s)?s:[String(s)])}else{const s=[];for(const i of t.args){const r=Vi(i,e);s.push(r)}return new ye(t.name,s)}}function Ni(t,e){return t.map(s=>{const i=Vi(s.expression,e);return{...s,expression:i}})}const mc=new WeakMap;function pd(t){var e,n,s;return(s=(n=(e=t.utils)==null?void 0:e[Ri])==null?void 0:n.getBuilder)==null?void 0:s.call(n)}function yd(t,e){mc.set(t,e)}function gd(t){return mc.get(t)}const zr="unionAll clause";class N{constructor(e={}){this.query={},this.query={...e}}_createRefForSource(e,n){const s=this._createRefsForSource(e,n);if(s.length!==1)throw new ur(n);return s[0]}_createRefsForSource(e,n){if(typeof e=="string")throw new An(n,"string");let s;try{s=Object.keys(e)}catch{const r=e===null?"null":"undefined";throw new An(n,r)}if(Array.isArray(e))throw new An(n,"array");if(s.length===0)throw new An(n,"empty object");if(n!==zr&&s.length!==1)throw new ur(n);const i=[];for(const r of s){const o=e[r];let c;if(o instanceof Ho)c=new en(o,r);else if(o instanceof N){const a=o._getQuery();if(!a.from)throw new va(n);c=new Te(a,r)}else throw new Ca(r);i.push([r,c])}return i}from(e){const[,n]=this._createRefForSource(e,"from clause");return new N({...this.query,from:n})}unionAll(e,...n){if(e instanceof N)return new N({...this.query,from:new Bt([e,...n].map(r=>r._getQuery()))});const s=this._createRefsForSource(e,zr),i=s.length===1?s[0][1]:new vn(s.map(r=>r[1]));return new N({...this.query,from:i})}join(e,n,s="left"){const[i,r]=this._createRefForSource(e,"join clause"),c=[...this._getCurrentAliases(),i],a=lt(c),l=n(a);let f,u;if(l.type==="func"&&l.name==="eq"&&l.args.length===2)f=l.args[0],u=l.args[1];else throw new xa;const y={from:r,type:s,left:f,right:u},p=this.query.join||[];return new N({...this.query,join:[...p,y]})}leftJoin(e,n){return this.join(e,n,"left")}rightJoin(e,n){return this.join(e,n,"right")}innerJoin(e,n){return this.join(e,n,"inner")}fullJoin(e,n){return this.join(e,n,"full")}where(e){const n=this._getCurrentAliases(),s=lt(n),i=e(s),r=qn(i)?Q(i):i;if(!Ie(r))throw new fr(Wr(r));const o=this.query.where||[];return new N({...this.query,where:[...o,r]})}having(e){const n=this._getCurrentAliases(),s=this.query.select||this.query.fnSelect?Tr(n):lt(n),i=e(s),r=qn(i)?Q(i):i;if(!Ie(r))throw new fr(Wr(r));const o=this.query.having||[];return new N({...this.query,having:[...o,r]})}select(e){const n=this._getCurrentAliases(),s=lt(n);let i=e(s);qn(i)&&i.__path.length===1&&(i={[`__SPREAD_SENTINEL__${i.__path[0]}__0`]:!0});const r=ps(i,n);return new N({...this.query,select:r,fnSelect:void 0})}orderBy(e,n="asc"){const s=this._getCurrentAliases(),i=this.query.select||this.query.fnSelect?Tr(s):lt(s),r=e(i),o=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},c=f=>({expression:Q(f),compareOptions:o}),a=Array.isArray(r)?r.map(f=>c(f)):[c(r)],l=this.query.orderBy||[];return new N({...this.query,orderBy:[...l,...a]})}groupBy(e){const n=this._getCurrentAliases(),s=lt(n),i=e(s),r=Array.isArray(i)?i.map(c=>Q(c)):[Q(i)],o=this.query.groupBy||[];return new N({...this.query,groupBy:[...o,...r]})}limit(e){return new N({...this.query,limit:e})}offset(e){return new N({...this.query,offset:e})}distinct(){return new N({...this.query,distinct:!0})}findOne(){return new N({...this.query,singleResult:!0})}_getCurrentAliases(){const e=[];if(this.query.from&&(this.query.from.type==="unionFrom"?e.push(...this.query.from.sources.map(n=>n.alias)):this.query.from.type==="unionAll"?e.push("*"):e.push(this.query.from.alias)),this.query.join)for(const n of this.query.join)e.push(n.from.alias);return e}get fn(){const e=this;return{select(n){return new N({...e.query,select:void 0,fnSelect:n})},where(n){return new N({...e.query,fnWhere:[...e.query.fnWhere||[],n]})},having(n){return new N({...e.query,fnHaving:[...e.query.fnHaving||[],n]})}}}_getQuery(){if(!this.query.from)throw new Ia;return this.query}}function Wr(t){return t===null?"null":t===void 0?"undefined":typeof t=="object"?"object":typeof t}function md(t){return t===void 0?Q(null):t instanceof go||t instanceof ye||t instanceof G||t instanceof de?t:Q(t)}function _c(t){return t!==null&&typeof t=="object"&&!Ie(t)&&!t.__refProxy}function ps(t,e=[],n){if(t instanceof N){if(!n)throw new Error("Conditional include branch is missing a field name");return ot(t,n,e,"collection")}if(t instanceof Mr){if(!(t.query instanceof N))throw new Error("toArray() must wrap a subquery builder");if(!n)throw new Error("Conditional toArray() branch is missing a field name");return ot(t.query,n,e,"array")}if(t instanceof $r){if(!(t.query instanceof N))throw new Error("concat(toArray(...)) must wrap a subquery builder");if(!n)throw new Error("Conditional concat(toArray(...)) branch is missing a field name");return ot(t.query,n,e,"concat")}if(t instanceof Dr)return Ur(t,e,n);if(!_c(t))return md(t);const s={};for(const[i,r]of Object.entries(t)){if(typeof i=="string"&&i.startsWith("__SPREAD_SENTINEL__")){s[i]=r;continue}if(r instanceof N){s[i]=ot(r,i,e,"collection");continue}if(r instanceof Mr){if(!(r.query instanceof N))throw new Error("toArray() must wrap a subquery builder");s[i]=ot(r.query,i,e,"array");continue}if(r instanceof $r){if(!(r.query instanceof N))throw new Error("concat(toArray(...)) must wrap a subquery builder");s[i]=ot(r.query,i,e,"concat");continue}if(r instanceof Wu){if(!(r.query instanceof N))throw new Error("materialize() must wrap a subquery builder");const c=r.query._getQuery().singleResult?"singleton":"array";s[i]=ot(r.query,i,e,c);continue}if(r instanceof Dr){s[i]=Ur(r,e,i);continue}s[i]=ps(r,e,i)}return s}function Ur(t,e,n){const s=t.args;if(s.length<2)throw new Error("caseWhen() requires at least two arguments");const i=s.length%2===1,r=Math.floor(s.length/2),o=[];for(let a=0;a<r;a++)o.push({condition:Q(s[a*2]),value:ps(s[a*2+1],e,n)});const c=i?ps(s[s.length-1],e,n):void 0;return new he(o,c)}function zi(t){const e=[];switch(t.type){case"ref":e.push(t);break;case"func":for(const n of t.args??[])e.push(...zi(n));break}return e}function _d(t,e){const n=typeof t=="object"&&"expression"in t?t.expression:t;return zi(n).some(s=>s.path[0]!=null&&e.includes(s.path[0]))}function ot(t,e,n,s){const i=t._getQuery(),r=wc(i);let o,c,a=-1,l=-1;if(i.where)for(let m=0;m<i.where.length;m++){const b=i.where[m],v=typeof b=="object"&&"expression"in b?b.expression:b;if(v.type==="func"&&v.name==="eq"&&v.args.length===2){const x=qr(v.args[0],v.args[1],n,r);if(x){o=x.parentRef,c=x.childRef,a=m;break}}if(v.type==="func"&&v.name==="and"&&v.args.length>=2){for(let x=0;x<v.args.length;x++){const I=v.args[x];if(I.type==="func"&&I.name==="eq"&&I.args.length===2){const M=qr(I.args[0],I.args[1],n,r);if(M){o=M.parentRef,c=M.childRef,a=m,l=x;break}}}if(o)break}}if(!o||!c||a===-1)throw new Error(`Includes subquery for "${e}" 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))`);const f=[...i.where];if(l>=0){const m=f[a],v=(typeof m=="object"&&"expression"in m?m.expression:m).args.filter((x,I)=>I!==l);if(v.length===1){const x=typeof m=="object"&&"expression"in m&&m.residual;f[a]=x?{expression:v[0],residual:!0}:v[0]}else{const x=new ye("and",v),I=typeof m=="object"&&"expression"in m&&m.residual;f[a]=I?{expression:x,residual:!0}:x}}else f.splice(a,1);const u=[],y=[];for(const m of f)_d(m,n)?y.push(m):u.push(m);let p;if(y.length>0){const m=new Set;p=[];for(const b of y){const v=typeof b=="object"&&"expression"in b?b.expression:b;for(const x of zi(v))x.path[0]!=null&&n.includes(x.path[0])&&!m.has(x.path.join("."))&&(m.add(x.path.join(".")),p.push(x))}}const h={...i,where:u.length>0?u:void 0},d=h.select,g=d===void 0||_c(d);let w=h,C;if(s==="concat"&&(d===void 0||g))throw new Error(`concat(toArray(...)) for "${e}" requires the subquery to select a scalar value`);if(!g){if(s==="collection")throw new Error(`Includes subquery for "${e}" must select an object when materializing as a Collection`);C=Hc,w={...h,select:{[C]:d}}}return new Pe(w,o,c,e,y.length>0?y:void 0,p,s,C)}function wc(t){const e=new Set(wd(t.from));if(t.join)for(const n of t.join)e.add(n.from.alias);return[...e]}function wd(t){return t.type==="unionFrom"?t.sources.map(e=>e.alias):t.type==="unionAll"?t.queries.flatMap(e=>wc(e)):[t.alias]}function qr(t,e,n,s){if(t.type==="ref"&&e.type==="ref"){const i=t.path[0],r=e.path[0];if(i&&r&&n.includes(i)&&s.includes(r))return{parentRef:t,childRef:e};if(i&&r&&n.includes(r)&&s.includes(i))return{parentRef:e,childRef:t}}}function Sd(t){const e=t(new N);return Sc(e)}function Sc(t){return t._getQuery()}function bd(t){const e={};function n(c){if(c.type==="collectionRef")e[c.collection.id]=c.collection;else if(c.type==="queryRef")s(c.query);else if(c.type==="unionFrom")for(const a of c.sources)n(a);else if(c.type==="unionAll")for(const a of c.queries)s(a)}function s(c){if(c.from&&n(c.from),c.join&&Array.isArray(c.join))for(const a of c.join)a.from&&n(a.from);c.select&&i(c.select)}function i(c){for(const[a,l]of Object.entries(c))typeof a=="string"&&a.startsWith("__SPREAD_SENTINEL__")||(l instanceof Pe?s(l.query):l instanceof he?r(l):ln(l)&&i(l))}function r(c){for(const a of c.branches)o(a.value);c.defaultValue!==void 0&&o(c.defaultValue)}function o(c){c instanceof Pe?s(c.query):c instanceof he?r(c):ln(c)&&i(c)}return s(t),e}function Yn(t){const e=t.from;if(e.type==="collectionRef")return e.collection;if(e.type==="queryRef")return Yn(e.query);if(e.type==="unionFrom")return Yn({from:e.sources[0]});if(e.type==="unionAll")return Yn(e.queries[0]);throw new Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(t)}`)}function vd(t){const e=new Map;function n(c){if(c){if(c.type==="collectionRef"){const{id:a}=c.collection,l=e.get(a);l?l.add(c.alias):e.set(a,new Set([c.alias]))}else if(c.type==="queryRef")o(c.query);else if(c.type==="unionFrom")for(const a of c.sources)n(a);else if(c.type==="unionAll")for(const a of c.queries)o(a)}}function s(c){for(const[a,l]of Object.entries(c))typeof a=="string"&&a.startsWith("__SPREAD_SENTINEL__")||(l instanceof Pe?o(l.query):l instanceof he?i(l):ln(l)&&s(l))}function i(c){for(const a of c.branches)r(a.value);c.defaultValue!==void 0&&r(c.defaultValue)}function r(c){c instanceof Pe?o(c.query):c instanceof he?i(c):ln(c)&&s(c)}function o(c){if(c){if(n(c.from),c.join)for(const a of c.join)n(a.from);c.select&&s(c.select)}}return o(t),e}function ln(t){return!(t===null||typeof t!="object"||t instanceof Pe||Ie(t)||t.__refProxy)}function Cd(t){const e=typeof t.query=="function"?Sd(t.query):Sc(t.query);if(e.select&&!ln(e.select))throw new Ea;return e}function xd(t,e){const n=[];for(const s of e){const i=s.key;s.type==="insert"?n.push([[i,s.value],1]):s.type==="update"?(n.push([[i,s.previousValue],-1]),n.push([[i,s.value],1])):n.push([[i,s.value],-1])}return n.length!==0&&t.sendData(new _e(n)),n.length}function*Id(t){for(const e of t)e.type==="update"?(yield{type:"delete",key:e.key,value:e.previousValue},yield{type:"insert",key:e.key,value:e.value}):yield e}function Od(t,e){const n=[];for(const s of t){if(s.type==="insert"){if(e.has(s.key))continue;e.add(s.key)}else s.type==="delete"&&e.delete(s.key);n.push(s)}return n}function kd(t,e,n,s){let i=e,r=!1;for(const o of t){if(o.type==="delete")continue;const c=!n.has(o.key);i===void 0||s(i,o.value)<0?(i=o.value,r=!0):c&&(r=!0)}return{biggest:i,shouldResetLoadKey:r}}function Ed(t,e){const{orderBy:n,limit:s,offset:i}=t,r=s!==void 0&&i!==void 0?s+i:s,o=n?Ni(n,e):void 0,c=(o==null?void 0:o.every(a=>{const l=a.expression;if(l.type!=="ref")return!1;const f=l.path;return Array.isArray(f)&&f.length===1}))??!1;return{orderBy:c?o:void 0,limit:c?r:void 0}}function Rd(t,e,n,s,i){const{orderBy:r,valueExtractorForRawRow:o,offset:c}=t,a=e?o(e):void 0;let l;a!==void 0&&(l=Array.isArray(a)?a:[a]);const f=nn({minValues:l??null,offset:c,limit:i});if(n===f)return;const u=Ni(r,s);return{minValues:l,normalizedOrderBy:u,loadRequestKey:f}}const $n=Symbol.for("@tanstack/db.collection-config-builder");class Ad{constructor(e,n,s,i){this.alias=e,this.collectionId=n,this.collection=s,this.collectionConfigBuilder=i,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){const e=this.getWhereClauseForAlias();if(e){const n=Vi(e,this.alias);return this.subscribeToChanges(n)}return this.subscribeToChanges()}subscribeToChanges(e){const n=this.getOrderByInfo(),s=c=>{c instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(c)},i=c=>{const a=c.subscription;if(c.status==="loadingSubset")this.ensureLoadingPromise(a);else{const l=this.subscriptionLoadingPromises.get(a);l&&(this.subscriptionLoadingPromises.delete(a),l.resolve())}};let r;if(n)r=this.subscribeToOrderedChanges(e,n,i,s);else{const c=!this.collectionConfigBuilder.isLazyAlias(this.alias);r=this.subscribeToMatchingChanges(e,c,i)}r.status==="loadingSubset"&&this.ensureLoadingPromise(r);const o=()=>{const c=this.subscriptionLoadingPromises.get(r);c&&(this.subscriptionLoadingPromises.delete(r),c.resolve()),r.unsubscribe()};return this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(o),r}sendChangesToPipeline(e,n){const s=Array.isArray(e)?e:[...e],i=Od(s,this.sentToD2Keys),r=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],c=xd(r,i)>0?n:void 0;this.collectionConfigBuilder.scheduleGraphRun(c,{alias:this.alias})}subscribeToMatchingChanges(e,n,s){const i=a=>{this.sendChangesToPipeline(a)},r=Ed(this.collectionConfigBuilder.query,this.alias),o=n?a=>{a instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(a)}:void 0;return this.collection.subscribeChanges(i,{...n&&{includeInitialState:n},whereExpression:e,onStatusChange:s,orderBy:r.orderBy,limit:r.limit,onLoadSubsetResult:o})}subscribeToOrderedChanges(e,n,s,i){const{orderBy:r,offset:o,limit:c,index:a}=n,l=d=>{d instanceof Promise&&(this.pendingOrderedLoadPromise=d,d.finally(()=>{this.pendingOrderedLoadPromise===d&&(this.pendingOrderedLoadPromise=void 0)})),i(d)};this.orderedLoadSubsetResult=l;const f={},u=d=>{const g=Array.isArray(d)?d:[...d];this.trackSentValues(g,n.comparator);const w=Id(g);this.sendChangesToPipelineWithTracking(w,f.current)},y=this.collection.subscribeChanges(u,{whereExpression:e,onStatusChange:s});f.current=y;const p=this.collection.on("truncate",()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});y.on("unsubscribed",()=>{p()});const h=Ni(r,this.alias);return a?(y.setOrderByIndex(a),y.requestLimitedSnapshot({limit:o+c,orderBy:h,trackLoadSubsetPromise:!1,onLoadSubsetResult:l})):y.requestSnapshot({orderBy:h,limit:o+c,trackLoadSubsetPromise:!1,onLoadSubsetResult:l}),y}loadMoreIfNeeded(e){const n=this.getOrderByInfo();if(!n)return!0;const{dataNeeded:s,index:i}=n;if(!s||!i||this.pendingOrderedLoadPromise)return!0;const r=s();return r>0&&this.loadNextItems(r,e),!0}sendChangesToPipelineWithTracking(e,n){if(!this.getOrderByInfo()){this.sendChangesToPipeline(e);return}const i=n;i[$n]??(i[$n]=this.loadMoreIfNeeded.bind(this,n)),this.sendChangesToPipeline(e,i[$n])}loadNextItems(e,n){const s=this.getOrderByInfo();if(!s)return;const i=Rd(s,this.biggest,this.lastLoadRequestKey,this.alias,e);i&&(this.lastLoadRequestKey=i.loadRequestKey,n.requestLimitedSnapshot({orderBy:i.normalizedOrderBy,limit:e,minValues:i.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}))}getWhereClauseForAlias(){const e=this.collectionConfigBuilder.sourceWhereClausesCache;if(e)return e.get(this.alias)}getOrderByInfo(){const e=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(e&&e.alias===this.alias)return e}trackSentValues(e,n){const s=kd(e,this.biggest,this.sentToD2Keys,n);this.biggest=s.biggest,s.shouldResetLoadKey&&(this.lastLoadRequestKey=void 0)}ensureLoadingPromise(e){if(this.subscriptionLoadingPromises.has(e))return;let n;const s=new Promise(i=>{n=i});this.subscriptionLoadingPromises.set(e,{resolve:n}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(s)}}let Td=0;class Pd{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-${++Td}`,this.query=Cd({query:e.query}),this.collections=bd(this.query);const n=vd(this.query);this.collectionByAlias={};for(const[s,i]of n.entries()){const r=this.collections[s];if(r)for(const o of i)this.collectionByAlias[o]=r}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=bc(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??Yn(this.query).compareOptions,this.compileBasePipeline()}hasJoins(e){if(e.join&&e.join.length>0)return!0;if(e.from.type==="queryRef"){if(this.hasJoins(e.from.query))return!0}else if(e.from.type==="unionFrom"){for(const n of e.from.sources)if(n.type==="queryRef"&&this.hasJoins(n.query))return!0}else if(e.from.type==="unionAll"){for(const n of e.from.queries)if(this.hasJoins(n))return!0}return!1}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),[Ri]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(e){var n,s;if(!this.windowFn)throw new Qa;return this.currentWindow=e,this.windowFn(e),(n=this.maybeRunGraphFn)==null||n.call(this),(s=this.liveQueryCollection)!=null&&s.isLoadingSubset?new Promise(i=>{const r=this.liveQueryCollection.on("loadingSubset:change",o=>{o.isLoadingSubset||(r(),i())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(e){const n=this.compiledAliasToCollectionId[e];if(n)return n;const s=this.collectionByAlias[e];if(s)return s.id;throw new Error(`Unknown source alias "${e}"`)}isLazyAlias(e){return this.lazySources.has(e)}maybeRunGraph(e){var n;if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("maybeRunGraph called without active sync session. This should not happen.");this.isGraphRunning=!0;try{const{begin:s,commit:i}=this.currentSyncConfig,r=this.currentSyncState;if(this.isInErrorState)return;if(r.subscribedToAllCollections){let o=!1;for(;r.graph.pendingWork();)r.graph.run(),(n=r.flushPendingChanges)==null||n.call(r),e==null||e(),o=!0;o||e==null||e(),r.messagesCount===0&&(s(),i()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(e,n){var a;const s=(n==null?void 0:n.contextId)??((a=Gn())==null?void 0:a.id),i=(n==null?void 0:n.jobId)??this,r=(()=>{if(n!=null&&n.dependencies)return n.dependencies;const l=new Set(this.builderDependencies);if(n!=null&&n.alias){const f=this.aliasDependencies[n.alias];if(f)for(const u of f)l.add(u)}return l.delete(this),Array.from(l)})();if(s)for(const l of r)typeof l.scheduleGraphRun=="function"&&l.scheduleGraphRun(void 0,{contextId:s});if(!this.currentSyncConfig||!this.currentSyncState)throw new Error("scheduleGraphRun called without active sync session. This should not happen.");let o=s?this.pendingGraphRuns.get(s):void 0;o||(o={loadCallbacks:new Set},s&&this.pendingGraphRuns.set(s,o)),e&&o.loadCallbacks.add(e);const c=s?void 0:o;os.schedule({contextId:s,jobId:i,dependencies:r,run:()=>this.executeGraphRun(s,c)})}clearPendingGraphRun(e){this.pendingGraphRuns.delete(e)}hasPendingGraphRun(e){return this.pendingGraphRuns.has(e)}executeGraphRun(e,n){const s=n??(e?this.pendingGraphRuns.get(e):void 0);if(e&&this.pendingGraphRuns.delete(e),!s||!this.currentSyncConfig||!this.currentSyncState)return;this.incrementRunCount();const i=()=>{let r=!0,o;if(s.loadCallbacks.forEach(c=>{try{r=c()&&r}catch(a){r=!1,o??(o=a)}}),o)throw o;return r};this.maybeRunGraph(i)}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;const n={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},s=this.extendPipelineWithChangeProcessing(e,n);this.currentSyncState=s,this.unsubscribeFromSchedulerClears=os.onClear(o=>{this.clearPendingGraphRun(o)});const i=e.collection.on("loadingSubset:change",o=>{o.isLoadingSubset||this.updateLiveQueryStatus(e)});n.unsubscribeCallbacks.add(i);const r=this.subscribeToAllCollections(e,s);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(r),this.scheduleGraphRun(r),()=>{var o;n.unsubscribeCallbacks.forEach(c=>c()),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(c=>delete this.subscriptions[c]),this.compiledAliasToCollectionId={},(o=this.unsubscribeFromSchedulerClears)==null||o.call(this),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new eu,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(s=>[s,this.graphCache.newInput()]));const e=an(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,s=>{this.windowFn=s});this.pipelineCache=e.pipeline,this.sourceWhereClausesCache=e.sourceWhereClauses,this.compiledAliasToCollectionId=e.aliasToCollectionId,this.includesCache=e.includes;const n=Object.keys(this.compiledAliasToCollectionId).filter(s=>!Object.hasOwn(this.inputsCache,s));if(n.length>0)throw new Ja(n)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(e,n){const{begin:s,commit:i}=e,{graph:r,inputs:o,pipeline:c}=this.maybeCompileBasePipeline();let a=new Map;c.pipe(Xs(f=>{const u=f.getInner();n.messagesCount+=u.length,u.reduce(Ld,a)}));const l=this.setupIncludesOutput(this.includesCache,n);return n.flushPendingChanges=()=>{const f=a.size>0,u=xc(l);if(!f&&!u)return;let y=a;if(this.config.getKey){const p=new Map;for(const[,h]of a){const d=this.config.getKey(h.value),g=p.get(d);g?(g.inserts+=h.inserts,g.deletes+=h.deletes,h.inserts>0&&(g.value=h.value,h.orderByIndex!==void 0&&(g.orderByIndex=h.orderByIndex))):p.set(d,{...h})}y=p}f&&(s(),y.forEach(this.applyChanges.bind(this,e)),i()),a=new Map,Zn(l,e.collection,this.id,f?y:null,e)},r.finalize(),n.graph=r,n.inputs=o,n.pipeline=c,n}setupIncludesOutput(e,n){return!e||e.length===0?[]:e.map(s=>{const i={fieldName:s.fieldName,resultPath:s.resultPath,childCorrelationField:s.childCorrelationField,hasOrderBy:s.hasOrderBy,materialization:s.materialization,scalarField:s.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return s.pipeline.pipe(Xs(r=>{const o=r.getInner();n.messagesCount+=o.length;for(const[[c,a],l]of o){const[f,u,y,p]=a,h=Ft(y,p);let d=i.pendingChildChanges.get(h);d||(d=new Map,i.pendingChildChanges.set(h,d));const g=d.get(c)||{deletes:0,inserts:0,value:f,orderByIndex:u};l<0?g.deletes+=Math.abs(l):l>0&&(g.inserts+=l,g.value=f),d.set(c,g)}})),s.childCompilationResult.includes&&(i.nestedSetups=vc(s.childCompilationResult.includes,n),i.nestedRoutingIndex=new Map,i.nestedRoutingReverseIndex=new Map),i})}applyChanges(e,n,s){const{write:i,collection:r}=e,{deletes:o,inserts:c,value:a,orderByIndex:l}=n;if(this.resultKeys.set(a,s),l!==void 0&&this.orderByIndices.set(a,l),c&&o===0)i({value:a,type:"insert"});else if(c>o||c===o&&r.has(r.getKeyFromItem(a)))i({value:a,type:"update"});else if(o>0)i({value:a,type:"delete"});else throw new Error(`Could not apply changes: ${JSON.stringify(n)}. This should never happen.`)}handleSourceStatusChange(e,n,s){const{status:i}=s;if(i==="error"){this.transitionToError(`Source collection '${n}' entered error state`);return}if(i==="cleaned-up"){this.transitionToError(`Source collection '${n}' 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){var o,c;const{markReady:n}=e;if(this.isInErrorState)return;const s=(o=this.currentSyncState)==null?void 0:o.subscribedToAllCollections,i=this.allCollectionsReady(),r=(c=this.liveQueryCollection)==null?void 0:c.isLoadingSubset;s&&i&&!r&&n()}transitionToError(e){var n;this.isInErrorState=!0,console.error(`[Live Query Error] ${e}`),(n=this.liveQueryCollection)==null||n._lifecycle.setStatus("error")}allCollectionsReady(){return Object.values(this.collections).every(e=>e.isReady())}subscribeToAllCollections(e,n){const s=Object.entries(this.compiledAliasToCollectionId);if(s.length===0)throw new Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);const i=s.map(([o,c])=>{const a=this.collectionByAlias[o]??this.collections[c],l=gd(a);l&&l!==this?(this.aliasDependencies[o]=[l],this.builderDependencies.add(l)):this.aliasDependencies[o]=[];const f=new Ad(o,c,a,this),u=a.on("status:change",h=>{this.handleSourceStatusChange(e,c,h)});n.unsubscribeCallbacks.add(u);const y=f.subscribe();return this.subscriptions[o]=y,f.loadMoreIfNeeded.bind(f,y)}),r=()=>(i.map(o=>o()),!0);return n.subscribedToAllCollections=!0,r}}function bc(t){return(e,n)=>{const s=t.get(e),i=t.get(n);return s&&i?s<i?-1:s>i?1:0:0}}function Hr(t){return t.materialization!=="collection"}function Gr(t,e){if(!e)return t.materialization==="array"?[]:t.materialization==="concat"?"":void 0;if(t.materialization==="collection")return e.collection;const n=[...e.collection.toArray],s=t.scalarField?n.map(i=>i==null?void 0:i[t.scalarField]):n;return t.materialization==="array"?s:t.materialization==="singleton"?s[0]:s.map(i=>String(i??"")).join("")}function vc(t,e){return t.map(n=>{const s=new Map;n.pipeline.pipe(Xs(r=>{const o=r.getInner();e.messagesCount+=o.length;for(const[[c,a],l]of o){const[f,u,y,p]=a,h=Ft(y,p);let d=s.get(h);d||(d=new Map,s.set(h,d));const g=d.get(c)||{deletes:0,inserts:0,value:f,orderByIndex:u};l<0?g.deletes+=Math.abs(l):l>0&&(g.inserts+=l,g.value=f),d.set(c,g)}}));const i={compilationResult:n,buffer:s};return n.childCompilationResult.includes&&(i.nestedSetups=vc(n.childCompilationResult.includes,e)),i})}function Md(t){return t.map(e=>{const n={fieldName:e.compilationResult.fieldName,resultPath:e.compilationResult.resultPath,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&&(n.nestedSetups=e.nestedSetups,n.nestedRoutingIndex=new Map,n.nestedRoutingReverseIndex=new Map),n})}function $d(t){const e=new Set;if(!t.nestedSetups)return e;for(let n=0;n<t.nestedSetups.length;n++){const s=t.nestedSetups[n],i=[];for(const[r,o]of s.buffer){const c=t.nestedRoutingIndex.get(r);if(c===void 0)continue;const a=t.childRegistry.get(c);if(!a||!a.includesStates)continue;const l=a.includesStates[n];for(const[f,u]of o){let y=l.pendingChildChanges.get(r);y||(y=new Map,l.pendingChildChanges.set(r,y));const p=y.get(f);p?(p.inserts+=u.inserts,p.deletes+=u.deletes,u.inserts>0&&(p.value=u.value,u.orderByIndex!==void 0&&(p.orderByIndex=u.orderByIndex))):y.set(f,{...u})}e.add(c),i.push(r)}for(const r of i)s.buffer.delete(r)}return e}function Dd(t,e,n){var s,i;if(t.nestedSetups){for(const r of t.nestedSetups)for(const[,o]of n)if(o.inserts>0){const c=(s=o.value[Se])==null?void 0:s[r.compilationResult.fieldName],a=c==null?void 0:c.correlationKey,l=(c==null?void 0:c.parentContext)??null,f=Ft(a,l);if(a!=null){t.nestedRoutingIndex.set(f,e);let u=t.nestedRoutingReverseIndex.get(e);u||(u=new Set,t.nestedRoutingReverseIndex.set(e,u)),u.add(f)}}else if(o.deletes>0&&o.inserts===0){const c=(i=o.value[Se])==null?void 0:i[r.compilationResult.fieldName],a=c==null?void 0:c.correlationKey,l=(c==null?void 0:c.parentContext)??null,f=Ft(a,l);if(a!=null){t.nestedRoutingIndex.delete(f);const u=t.nestedRoutingReverseIndex.get(e);u&&(u.delete(f),u.size===0&&t.nestedRoutingReverseIndex.delete(e))}}}}function jd(t,e){if(!t.nestedRoutingReverseIndex)return;const n=t.nestedRoutingReverseIndex.get(e);if(n){for(const s of n)t.nestedRoutingIndex.delete(s);t.nestedRoutingReverseIndex.delete(e)}}function Cc(t){for(const e of t)if(e.buffer.size>0||e.nestedSetups&&Cc(e.nestedSetups))return!0;return!1}function Ft(t,e){return e==null?t:JSON.stringify([t,e])}function Jr(t,e,n,s,i){const r=new WeakMap,o=s?new WeakMap:null;let c=null;const a=o?bc(o):void 0,f={collection:At({id:`__child-collection:${t}-${e}-${nn(n)}`,getKey:u=>r.get(u),compare:a,sync:{rowUpdateMode:"full",sync:u=>(c=u,()=>{c=null})},startSync:!0,gcTime:0}),get syncMethods(){return c},resultKeys:r,orderByIndices:o};return i&&(f.includesStates=Md(i)),f}function Zn(t,e,n,s,i){var r,o;for(const c of t){if(s){for(const[p,h]of s)if(h.inserts>0){const d=h.value,g=(r=d[Se])==null?void 0:r[c.fieldName],w=g==null?void 0:g.correlationKey,C=(g==null?void 0:g.parentContext)??null,m=Ft(w,C);if(w!=null){if(!c.childRegistry.has(m)){const I=Jr(n,c.fieldName,m,c.hasOrderBy,c.nestedSetups);c.childRegistry.set(m,I)}let b=c.correlationToParentKeys.get(m);b||(b=new Set,c.correlationToParentKeys.set(m,b)),b.add(p);const v=Gr(c,c.childRegistry.get(m));Xn(d,c.resultPath,v);const x=e.get(p);x&&x!==d&&Xn(x,c.resultPath,v)}}}const a=Hr(c)?new Set(c.pendingChildChanges.keys()):null,l=new Map;if(c.pendingChildChanges.size>0){for(const[p,h]of c.pendingChildChanges){let d=c.childRegistry.get(p);if(d||(d=Jr(n,c.fieldName,p,c.hasOrderBy,c.nestedSetups),c.childRegistry.set(p,d)),c.materialization==="collection"&&Kd(e,c.resultPath,p,c.correlationToParentKeys,d.collection),d.syncMethods){d.syncMethods.begin();for(const[g,w]of h)d.resultKeys.set(w.value,g),d.orderByIndices&&w.orderByIndex!==void 0&&d.orderByIndices.set(w.value,w.orderByIndex),w.inserts>0&&w.deletes===0?d.syncMethods.write({value:w.value,type:"insert"}):w.inserts>w.deletes||w.inserts===w.deletes&&d.syncMethods.collection.has(d.syncMethods.collection.getKeyFromItem(w.value))?d.syncMethods.write({value:w.value,type:"update"}):w.deletes>0&&d.syncMethods.write({value:w.value,type:"delete"});d.syncMethods.commit()}Dd(c,p,h),l.set(p,{entry:d,childChanges:h})}c.pendingChildChanges.clear()}const f=$d(c);for(const[,{entry:p,childChanges:h}]of l)p.includesStates&&Zn(p.includesStates,p.collection,p.collection.id,h,p.syncMethods);for(const p of f){if(l.has(p))continue;const h=c.childRegistry.get(p);h!=null&&h.includesStates&&Zn(h.includesStates,h.collection,h.collection.id,null,h.syncMethods)}const u=new Set;if(c.nestedSetups)for(const[p,h]of c.childRegistry)l.has(p)||f.has(p)||h.includesStates&&xc(h.includesStates)&&(Zn(h.includesStates,h.collection,h.collection.id,null,h.syncMethods),u.add(p));const y=Hr(c)?new Set([...a||[],...f,...u]):null;if(i&&y&&y.size>0){const p=[];for(const h of y){const d=c.correlationToParentKeys.get(h);if(!d)continue;const g=c.childRegistry.get(h);for(const w of d){const C=e.get(w);if(C){const m=Yr(C,c.resultPath);Xn(C,c.resultPath,Gr(c,g));const b=Yr(C,c.resultPath);p.push({type:"update",key:w,value:b,previousValue:m})}}}p.length>0&&e._changes.emitEvents(p,!0)}if(s){for(const[p,h]of s)if(h.deletes>0&&h.inserts===0){const d=(o=h.value[Se])==null?void 0:o[c.fieldName],g=d==null?void 0:d.correlationKey,w=(d==null?void 0:d.parentContext)??null,C=Ft(g,w);if(g!=null){const m=c.correlationToParentKeys.get(C);m&&(m.delete(p),m.size===0&&(jd(c,C),c.childRegistry.delete(C),c.correlationToParentKeys.delete(C)))}}}}if(s)for(const[,c]of s)delete c.value[Se]}function xc(t){for(const e of t)if(e.pendingChildChanges.size>0||e.nestedSetups&&Cc(e.nestedSetups))return!0;return!1}function Kd(t,e,n,s,i){const r=s.get(n);if(r)for(const o of r){const c=t.get(o);c&&Xn(c,e,i)}}function Xn(t,e,n){const s=Ic(t);if(!s){Qr(t,e,n);return}Qr(s.sourceRow,e,n),Fd(t,s)}function Ic(t){return t[Li]}function Fd(t,e){const n=t,s=e.sourceRow,i=n[Se]??s[Se],r=e.fnSelect(e.sourceRow);if(!(!r||typeof r!="object")){for(const o of Object.keys(t))delete t[o];Object.assign(t,r),i&&(n[Se]=i),Object.defineProperty(t,Li,{value:e,enumerable:!0,configurable:!0})}}function Qr(t,e,n){if(e.length===0)return;let s=t;for(let i=0;i<e.length-1;i++){const r=e[i],o=s[r];(o==null||typeof o!="object")&&(s[r]={}),s=s[r]}s[e[e.length-1]]=n}function Yr(t,e){return Ic(t)?{...t}:Bd(t,e)}function Bd(t,e){const n={...t};let s=t,i=n;for(let r=0;r<e.length-1;r++){const o=e[r],c=s==null?void 0:s[o];if(c==null||typeof c!="object")return n;const a=Array.isArray(c)?[...c]:{...c};i[o]=a,s=c,i=a}return n}function Ld(t,[[e,n],s]){const[i,r]=n,o=t.get(e)||{deletes:0,inserts:0,value:i,orderByIndex:r};return s<0?o.deletes+=Math.abs(s):s>0&&(o.inserts+=s,o.value=i,r!==void 0&&(o.orderByIndex=r)),t.set(e,o),t}function Zr(t){return new Pd(t).getConfig()}function zs(t){if(typeof t=="function"){const n=Zr({query:t});return Xr(n)}else{const e=t,n=Zr(e);return e.utils&&(n.utils={...n.utils,...e.utils}),Xr(n)}}function Xr(t){const e=At(t),n=pd(t);return n&&yd(e,n),e}function Vd(t){const e=new Set,n=new Set;let s=[],i="connecting",r=null,o=!1;function c(f){s.push(f);for(const u of[...e])u(f)}function a(f){i=f;for(const u of[...n])u(f)}function l(){r||o||(r=t.subscribe(c,a))}return{get status(){return i},subscribe(f,u){if(o)return()=>{};e.add(f),u&&n.add(u);for(const y of s)f(y);return u==null||u(i),l(),()=>{e.delete(f),u&&n.delete(u)}},close(){o=!0,r==null||r(),r=null,e.clear(),n.clear(),s=[]}}}function Dn(t){const{source:e,projection:n}=t;return{id:n.id,getKey:n.getKey,startSync:t.startSync??!0,sync:{sync:({begin:s,write:i,commit:r,truncate:o,markReady:c})=>{const a=new Map,l=u=>{const y=n.project(u,p=>a.get(p));if(y.length!==0){s();for(const p of y)p.type==="reset"?(a.clear(),o()):p.type==="delete"?(a.delete(p.key),i({type:"delete",key:p.key})):(a.set(n.getKey(p.value),p.value),i({type:p.type,value:p.value}));r()}},f=e.subscribe(l);return c(),f}}}}function ys(t,e,n){return`${t}:${e}:${n}`}function Nd(){return{id:"scenes",getKey:t=>t.id,project(t,e){switch(t.type){case"scene:start":return[{type:"insert",value:{id:ys(t.runId,t.teamIndex,t.name),runId:t.runId,name:t.name,file:t.file,actors:t.actors.slice(),status:"running",startTime:t.timestamp,endTime:null,duration:null,error:null,team:t.team,teamIndex:t.teamIndex}}];case"scene:end":{const n=e(ys(t.runId,t.teamIndex,t.name));return n?[{type:"update",value:{...n,status:t.status,endTime:t.timestamp,duration:t.duration,error:t.error??null}}]:[]}default:return[]}}}}function zd(){let t=0;return{id:"assertions",getKey:e=>e.id,project(e){return e.type==="assertion"?[{type:"insert",value:{id:`${e.runId}:${t++}`,runId:e.runId,actor:e.actor??null,description:e.description,result:e.result,timestamp:e.timestamp,sceneId:e.scene!==void 0&&e.teamIndex!==void 0?ys(e.runId,e.teamIndex,e.scene):null}}]:[]}}}function Wd(t,e){if(t.sceneId)return t.sceneId;if(!t.actor)return null;for(const n of e)if(n.runId===t.runId&&n.actors.includes(t.actor)&&!(t.timestamp<n.startTime)&&!(n.endTime!==null&&t.timestamp>n.endTime))return n.id;return null}function Ud(){let t=0;const e=new Map,n=(s,i)=>JSON.stringify([s,i]);return{id:"actions",getKey:s=>s.id,project(s,i){if(s.type==="action:start"){const r=`${s.runId}:${t++}`;e.set(n(s.actor,s.action),r);const o=s.scene!==void 0&&s.teamIndex!==void 0?ys(s.runId,s.teamIndex,s.scene):null;return[{type:"insert",value:{id:r,runId:s.runId,actor:s.actor,action:s.action,target:s.target??null,startTime:s.timestamp,endTime:null,duration:null,error:null,status:"running",sceneId:o,timestamp:s.timestamp}}]}if(s.type==="action:end"){const r=n(s.actor,s.action),o=e.get(r);if(o===void 0)return[];e.delete(r);const c=i(o);return c?[{type:"update",value:{...c,endTime:s.timestamp,duration:s.duration,error:s.error??null,status:s.error?"error":"success"}}]:[]}return[]}}}function qd(){return{id:"runs",getKey:t=>t.id,project(t,e){var n,s;switch(t.type){case"run:start":return[{type:"insert",value:{id:t.runId,startTime:t.timestamp,endTime:null,duration:null,status:"running",sceneCount:t.sceneCount,completed:0,failed:0}}];case"scene:end":{const i=e(t.runId);if(!i)return[];const r=t.status==="completed";return[{type:"update",value:{...i,completed:i.completed+(r?1:0),failed:i.failed+(r?0:1)}}]}case"run:end":{const i=e(t.runId);return i?[{type:"update",value:{...i,status:"finished",endTime:t.timestamp,duration:t.duration,completed:((n=t.summary)==null?void 0:n.completed)??i.completed,failed:((s=t.summary)==null?void 0:s.failed)??i.failed}}]:[]}default:return[]}}}}function Hd(t,e=[]){const n=t.reduce((s,i)=>!s||i.startTime>s.startTime?i:s,void 0);if(n)return n.id;if(e.length!==0)return e.reduce((s,i)=>i.startTime>s.startTime?i:s).runId}function gs(t,e){const n=new Map;for(const s of t){const i=Wd(s,e);if(i===null)continue;const r=n.get(i);r?r.push(s):n.set(i,[s])}return n}function Gd(t){return t.status==="running"?"running":t.status==="error"?"error":t.duration!=null&&t.duration>500?"slow":"success"}function Jd(t){var a,l,f,u,y,p;const e=gs(t.actions,t.scenes),n=gs(t.assertions,t.scenes),s=t.scenes.map(h=>{const d=h.actors.map(w=>({actor:w,items:[]})),g=w=>{let C=d.find(m=>m.actor===w);return C||(C={actor:w,items:[]},d.push(C)),C};for(const w of(e.get(h.id)??[]).slice().sort((C,m)=>C.startTime-m.startTime))g(w.actor).items.push({action:w.action,target:w.target??void 0,startTime:w.startTime,endTime:w.endTime,duration:w.duration,error:w.error,status:Gd(w)});return{name:h.name,file:h.file,actors:h.actors.slice(),lanes:d,assertions:(n.get(h.id)??[]).map(w=>({actor:w.actor??void 0,description:w.description,result:w.result,timestamp:w.timestamp})),startTime:h.startTime,endTime:h.endTime,status:h.status,duration:h.duration??void 0,error:h.error??void 0,team:h.team,teamIndex:h.teamIndex}}),i=[...new Set(t.scenes.map(h=>{var d;return(d=h.team)==null?void 0:d.name}).filter(h=>!!h))],r=((a=t.run)==null?void 0:a.completed)??s.filter(h=>h.status==="completed").length,o=((l=t.run)==null?void 0:l.failed)??s.filter(h=>h.status!=="completed"&&h.status!=="running").length,c=t.run?t.run.status==="running":s.some(h=>h.status==="running");return{scenes:s,currentSceneIndex:null,runStartTime:((f=t.run)==null?void 0:f.startTime)??((u=t.scenes[0])==null?void 0:u.startTime)??null,passCount:r,failCount:o,sceneCount:Math.max(((y=t.run)==null?void 0:y.sceneCount)??0,s.length),teams:i,running:c,endDurationMs:((p=t.run)==null?void 0:p.duration)??null}}function Qd(t){return t.scenes.filter(e=>e.status!=="running").length}function Yd({state:t,send:e}){return _("div",{class:"root",children:[_(Zd,{state:t,send:e}),_("main",{children:t.scenes.length===0?_("div",{class:"waiting",children:[_("h2",{children:"Waiting for scene run…"}),_("p",{children:["Run ",_("code",{children:"scenetest"})," to see the live timeline here."]})]}):t.scenes.map(n=>_(Xd,{scene:n,send:e},n.name))})]})}function Zd({state:t,send:e}){const[n,s]=be(""),[,i]=be(0),r=t.running;We(()=>{if(!r)return;const u=setInterval(()=>i(y=>y+1),200);return()=>clearInterval(u)},[r]);const o=Qd(t),c=t.endDurationMs!=null?`${t.endDurationMs}ms`:t.runStartTime?`${Date.now()-t.runStartTime}ms`:"—",a=t.sceneCount>0?Math.round(o/t.sceneCount*100):0,l=t.failCount>0?"progress has-failures":o===t.sceneCount&&t.sceneCount>0?"progress done":"progress",f=()=>e({type:"run:replay",...n?{team:n}:{}});return _("header",{class:r?"running":"",children:[_("h1",{children:[_("span",{class:"logo",children:"S"})," Scenetest Dashboard"]}),_("button",{class:"replay-all-btn",disabled:r,onClick:f,children:"▶ Replay All"}),_("label",{class:"team-select-wrap",children:["Team:",_("select",{value:n,onChange:u=>s(u.target.value),children:[_("option",{value:"",children:"all teams"}),t.teams.map(u=>_("option",{value:u,children:u},u))]})]}),_("button",{onClick:()=>e({type:"run:pause"}),children:"❚❚ Pause"}),_("button",{class:"stop-btn",onClick:()=>e({type:"run:stop"}),children:"■ Stop"}),_("div",{class:"spacer"}),_("div",{class:"stats",children:[_("div",{class:"stat",children:[_("span",{class:"label",children:"Scenes:"}),_("span",{class:"value",children:[o,"/",t.sceneCount]})]}),_("div",{class:"stat pass",children:[_("span",{class:"label",children:"Pass:"}),_("span",{class:"value",children:t.passCount})]}),_("div",{class:"stat fail",children:[_("span",{class:"label",children:"Fail:"}),_("span",{class:"value",children:t.failCount})]}),_("div",{class:"stat",children:[_("span",{class:"label",children:"Time:"}),_("span",{class:"value",children:c})]}),_("div",{class:"conn "+t.connection,title:"SSE "+t.connection})]}),t.sceneCount>0?_("div",{class:l,children:_("div",{class:"progress-fill",style:`width:${a}%`})}):null]})}function Xd({scene:t,send:e}){var o;const[n,s]=be(!1),i=t.status==="completed"?"✓":t.status==="running"?"◷":"✗",r=()=>{th(eh(t)),s(!0),setTimeout(()=>s(!1),1200)};return _("div",{class:"scene "+(t.status==="failed"||t.status==="timeout"?"failed":""),children:[_("div",{class:"scene-head",children:[_("span",{class:"scene-status "+t.status,children:i}),_("span",{class:"scene-name",children:t.name}),t.file?_("span",{class:"scene-file",children:t.file}):null,(o=t.team)!=null&&o.name?_("span",{class:"scene-team",children:t.team.name}):null,t.duration!=null?_("span",{class:"scene-dur",children:[t.duration,"ms"]}):null,_("button",{class:"copy-btn"+(n?" copied":""),title:"Copy scene summary",onClick:r,children:n?"✓ Copied":"⧉ Copy"}),t.file?_("button",{class:"copy-btn",onClick:()=>e({type:"run:replay",file:t.file}),children:"▶ Replay"}):null]}),_("div",{class:"lanes",children:t.lanes.map(c=>_("div",{class:"lane",children:[_("span",{class:"lane-actor",children:c.actor}),_("div",{class:"lane-items",children:c.items.map((a,l)=>_("span",{class:"pill "+a.status,title:a.error??"",children:[a.action,a.target?_("span",{class:"tgt",children:[" ",a.target]}):null]},l))})]},c.actor))}),t.assertions.length>0?_("div",{class:"assertions",children:t.assertions.map((c,a)=>_("div",{class:"assert "+(c.result?"ok":"bad"),children:[_("span",{class:"mark",children:c.result?"✓":"✗"}),c.actor?_("span",{class:"who",children:["[",c.actor,"]"]}):null,_("span",{children:c.description})]},a))}):null,t.error?_("div",{class:"scene-error",children:t.error}):null]})}function eh(t){const e=[`Scene: ${t.name}`];t.file&&e.push(`File: ${t.file}`),t.status&&e.push(`Status: ${t.status}`),t.duration!=null&&e.push(`Duration: ${t.duration}ms`);const n=[];for(const i of t.lanes)for(const r of i.items)r.error&&n.push(` ✗ ${r.action}${r.target?`(${r.target})`:""} — ${r.error}`);t.error&&!n.some(i=>i.includes(t.error))&&n.push(` ✗ ${t.error}`),n.length>0&&e.push("","Errors:",...n);const s=t.assertions.filter(i=>!i.result);return s.length>0&&e.push("","Failed assertions:",...s.map(i=>` ✗ [${i.actor??""}] ${i.description}`)),e.join(`
|
|
12
|
+
`)}function th(t){var e;typeof navigator<"u"&&((e=navigator.clipboard)!=null&&e.writeText)?navigator.clipboard.writeText(t).catch(()=>eo(t)):eo(t)}function eo(t){if(typeof document>"u")return;const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{document.execCommand("copy")}catch{}document.body.removeChild(e)}const pi={scenes:[],summary:{scenes:0,completed:0,failed:0,assertions:{total:0,passed:0,failed:0},warnings:0}};function Oc(t){return t==="completed"}function kc(t){return t!=="completed"&&t!=="running"}function nh(t){const{run:e,scenes:n,assertions:s,actions:i}=t,r=gs(s,n),o=gs(i,n),c=n.map(l=>({id:l.id,name:l.name,file:l.file,status:l.status,duration:l.duration,error:l.error,team:l.team,teamIndex:l.teamIndex,actors:l.actors,assertions:(r.get(l.id)??[]).map(f=>({result:f.result,description:f.description,actor:f.actor,timestamp:f.timestamp})),timeline:(o.get(l.id)??[]).slice().sort((f,u)=>f.startTime-u.startTime).map(f=>({actor:f.actor,action:f.status==="running"?f.action+" (in flight)":f.action,target:f.target??void 0,duration:f.duration,error:f.error}))})),a={scenes:Math.max((e==null?void 0:e.sceneCount)??0,c.length),completed:(e==null?void 0:e.completed)??c.filter(l=>Oc(l.status)).length,failed:(e==null?void 0:e.failed)??c.filter(l=>kc(l.status)).length,assertions:{total:s.length,passed:s.filter(l=>l.result).length,failed:s.filter(l=>!l.result).length},warnings:0};return{scenes:c,summary:a}}const ct=t=>typeof t=="object"&&t!==null,at=(t,e="")=>typeof t=="string"?t:e,xe=t=>typeof t=="number"?t:null;function sh(t){if(!ct(t))return pi;const n=(Array.isArray(t.scenes)?t.scenes:[]).filter(ct).map((o,c)=>{const a=ct(o.team)?o.team:{},l=xe(o.teamIndex)??0;return{id:`${at(o.name,"scene")}:${l}:${c}`,name:at(o.name,"(unnamed)"),file:at(o.file),line:xe(o.line)??void 0,status:at(o.status,"completed"),duration:xe(o.duration),error:typeof o.error=="string"?o.error:null,team:a,teamIndex:l,actors:Array.isArray(o.actors)?o.actors.filter(f=>typeof f=="string"):[],assertions:(Array.isArray(o.assertions)?o.assertions:[]).filter(ct).map(f=>({result:f.result===!0,description:at(f.description),actor:typeof f.actor=="string"?f.actor:null,timestamp:xe(f.timestamp)??0})),timeline:(Array.isArray(o.timeline)?o.timeline:[]).filter(ct).map(f=>({actor:at(f.actor),action:at(f.action),target:typeof f.target=="string"?f.target:void 0,duration:xe(f.duration),error:typeof f.error=="string"?f.error:null}))}}),s=ct(t.summary)?t.summary:{},i=ct(s.assertions)?s.assertions:{},r={scenes:xe(s.scenes)??n.length,completed:xe(s.completed)??n.filter(o=>Oc(o.status)).length,failed:xe(s.failed)??n.filter(o=>kc(o.status)).length,assertions:{total:xe(i.total)??0,passed:xe(i.passed)??0,failed:xe(i.failed)??0},warnings:xe(s.warnings)??0};return{scenes:n,summary:r}}function jn(t){const[e,n]=be(()=>t.toArray);return We(()=>{n(t.toArray);const s=t.subscribeChanges(()=>n(t.toArray));return()=>s.unsubscribe()},[t]),e}function ih(t,e){const n=e??" no-run",s=t.scenes,i=t.assertions,r=t.actions;return{scenes:zs(o=>o.from({scene:s}).where(({scene:c})=>Pt(c.runId,n)).orderBy(({scene:c})=>c.startTime)),assertions:zs(o=>o.from({assertion:i}).where(({assertion:c})=>Pt(c.runId,n))),actions:zs(o=>o.from({action:r}).where(({action:c})=>Pt(c.runId,n)).orderBy(({action:c})=>c.startTime))}}function Ec(t){const e=jn(t.runs),n=Hd(e),s=n?e.find(a=>a.id===n):void 0,i=Ue(()=>ih(t,n),[t.scenes,t.assertions,t.actions,n]),r=jn(i.scenes),o=jn(i.assertions),c=jn(i.actions);return{runId:n,run:s,scenes:r,assertions:o,actions:c}}const Rc=["failed","timeout","running","completed"];function Wi(t){if(!t)return"";const e=t.replace(/\\/g,"/").split("/");return e.length>2?"…/"+e.slice(-2).join("/"):t}function Ac(t){return t==="completed"?"✓":t==="running"?"◐":t==="timeout"?"⏱":"✗"}function ks(t){var e;return((e=t.team)==null?void 0:e.name)||"team "+t.teamIndex}function rh(t,e,n,s){const i=Ec(t),r=Ue(()=>nh(i),[i.runId,i.run,i.scenes,i.assertions,i.actions]),[o,c]=be(pi);return We(()=>{if(n==="live")return;c(pi);let a=!0;return fetch(`${s}/runs/${encodeURIComponent(n)}`).then(l=>l.ok?l.json():null).then(l=>{a&&l&&c(sh(l))}).catch(()=>{}),()=>{a=!1}},[n,s]),n==="live"?{snap:r,connection:e}:{snap:o,connection:"idle"}}function oh({collections:t,connection:e,base:n}){const[s,i]=be(()=>new URLSearchParams(location.search).get("run")||"live"),[r,o]=be([]),[c,a]=be({text:"",statuses:new Set(Rc),groupBy:"status"}),[l,f]=be(null),{snap:u,connection:y}=rh(t,e,s,n);We(()=>{fetch(`${n}/runs`).then(h=>h.ok?h.json():null).then(h=>{h&&o(h.runs||[])}).catch(()=>{})},[n]),We(()=>{const h=new URLSearchParams(location.search);h.set("run",s),history.replaceState(null,"",location.pathname+"?"+h.toString()),f(null)},[s]);const p=u.scenes.find(h=>h.id===l);return _("div",{class:"runner",children:[_(ch,{runs:r,runId:s,onRunChange:i,connection:y,summary:u.summary,scenes:u.scenes}),_("main",{children:[_(ah,{scenes:u.scenes,selected:l,onSelect:f}),_(lh,{scenes:u.scenes,filters:c,onFilters:a,selected:l,onSelect:f,runId:s}),_(fh,{scene:p,base:n})]})]})}function ch({runs:t,runId:e,onRunChange:n,connection:s,summary:i,scenes:r}){const o=r.filter(a=>a.status==="completed").length,c=i.assertions;return _("div",{class:"runner-bar",children:[_("div",{class:"run-picker",children:[_("label",{for:"run-select",children:"Run"}),_("select",{id:"run-select",value:e,onChange:a=>n(a.target.value),children:[_("option",{value:"live",children:"Live (current run)"}),t.map(a=>_("option",{value:a.id,children:[new Date(a.mtime).toLocaleString()," — ",a.id]},a.id))]}),_("span",{class:"conn "+s,title:s})]}),_("div",{class:"status-bar",children:[_("span",{children:["scenes ",o,"/",i.scenes||r.length]}),_("span",{class:"ok",children:["✓ ",c.passed]}),_("span",{class:"fail",children:["✗ ",c.failed]})]})]})}function ah({scenes:t,selected:e,onSelect:n}){const s=Ue(()=>{const i=new Map;for(const r of t){const o=r.file||"(no file)";i.has(o)||i.set(o,[]),i.get(o).push(r)}return i},[t]);return _("aside",{class:"tree",children:[...s.entries()].map(([i,r])=>{const o=r.filter(c=>c.status!=="completed"&&c.status!=="running").length;return _("div",{children:[_("div",{class:"tree-file",title:i,children:[_("span",{children:Wi(i)}),o?_("span",{class:"fail",children:o}):null]}),r.map(c=>_("div",{class:"tree-scene "+c.status+(c.id===e?" selected":""),onClick:()=>n(c.id),children:c.name},c.id))]},i)})})}function lh({scenes:t,filters:e,onFilters:n,selected:s,onSelect:i,runId:r}){const o=Ue(()=>{const l=e.text.toLowerCase();return t.filter(f=>e.statuses.has(f.status)?l?[f.name,f.file,...f.assertions.map(y=>y.description),f.error||""].join(" ").toLowerCase().includes(l):!0:!1)},[t,e]),c=Ue(()=>uh(o,e.groupBy),[o,e.groupBy]),a=Wc(l=>{const f=new Set(e.statuses);f.has(l)?f.delete(l):f.add(l),n({...e,statuses:f})},[e,n]);return _("section",{class:"list-pane",children:[_("div",{class:"filters",children:[_("input",{type:"search",placeholder:"Filter by scene, file, or assertion…",value:e.text,onInput:l=>n({...e,text:l.target.value})}),_("div",{class:"chips",children:Rc.map(l=>_("button",{class:"chip"+(e.statuses.has(l)?" on":""),"data-status":l,onClick:()=>a(l),children:l[0].toUpperCase()+l.slice(1)},l))}),_("select",{class:"group-by",value:e.groupBy,onChange:l=>n({...e,groupBy:l.target.value}),children:[_("option",{value:"none",children:"No grouping"}),_("option",{value:"file",children:"Group by file"}),_("option",{value:"status",children:"Group by status"}),_("option",{value:"team",children:"Group by team"})]}),_(yi,{label:"Copy all failures",getText:()=>hh(t,r)}),_(yi,{label:"Copy all",subtle:!0,getText:()=>Pc(t,r)})]}),_("div",{class:"list",children:c.length===0?_("div",{class:"group-header",children:"No scenes match the current filters."}):c.map(l=>_("div",{children:[e.groupBy!=="none"?_("div",{class:"group-header",children:[l.key||""," · ",l.items.length]}):null,l.items.map(f=>_("div",{class:"row"+(f.id===s?" selected":""),onClick:()=>i(f.id),children:[_("span",{class:"icon "+f.status,children:Ac(f.status)}),_("span",{class:"name",children:f.name}),_("span",{class:"row-team",title:"Team running this scene",children:ks(f)}),_("span",{class:"meta",children:[f.assertions.filter(u=>!u.result).length>0?_("span",{class:"icon failed",children:"✗"}):null," ",f.assertions.length," check",f.assertions.length===1?"":"s",f.duration?" · "+f.duration+"ms":""]}),_("span",{class:"file",children:Wi(f.file)})]},f.id))]},l.key))})]})}function uh(t,e){if(e==="none")return[{key:"",items:t}];const n=new Map;for(const i of t){let r="";e==="file"?r=i.file||"(no file)":e==="status"?r=i.status:e==="team"&&(r=ks(i)),n.has(r)||n.set(r,[]),n.get(r).push(i)}const s=[...n.keys()];if(e==="status"){const i={failed:0,timeout:1,running:2,completed:3};s.sort((r,o)=>(i[r]??99)-(i[o]??99))}else s.sort();return s.map(i=>({key:i,items:n.get(i)}))}function fh({scene:t,base:e}){if(!t)return _("aside",{class:"detail",children:_("div",{class:"empty",children:"Select a scene on the left to see error details, timeline, and the spec snippet for reproducing it manually."})});const n=t.status!=="completed"&&t.status!=="running",s=["team "+ks(t),t.duration?t.duration+"ms":"",t.status].filter(Boolean),i=`${e.replace(/__scenetest$/,"")}__open-in-editor?file=`+encodeURIComponent(t.file)+(t.line?"&line="+t.line:"");return _("aside",{class:"detail",children:[_("div",{class:"actions",children:[_(yi,{label:"Copy",getText:()=>Tc(t)}),t.file?_("a",{class:"btn subtle",href:i,children:"Open in editor"}):null]}),_("h3",{children:[n?_("span",{class:"icon failed",children:"✗"}):null," ",t.name]}),_("div",{class:"meta-row",children:[s.map((r,o)=>_("span",{class:"pill",children:r},o)),t.file?_("span",{class:"pill",title:t.file,children:[Wi(t.file),t.line?":"+t.line:""]}):null]}),t.error?_("div",{class:"err",children:t.error}):null,_("h4",{children:"Assertions"}),_("ul",{class:"alist",children:t.assertions.length===0?_("li",{children:"No assertions recorded."}):t.assertions.map((r,o)=>_("li",{class:r.result?"pass":"fail",children:[r.result?"✓":"✗"," ",r.description]},o))}),_("h4",{children:"Timeline"}),_("ul",{class:"timeline",children:t.timeline.length===0?_("li",{children:"(no timeline)"}):t.timeline.map((r,o)=>_("li",{class:r.error?"err-step":"",children:[r.actor,": ",r.action,r.target?" "+r.target:"",r.duration!=null?" ("+r.duration+"ms)":"",r.error?" — "+r.error:""]},o))}),_("h4",{children:"Spec snippet"}),_(dh,{file:t.file,line:t.line,base:e})]})}function dh({file:t,line:e,base:n}){const[s,i]=be({status:"idle"});if(We(()=>{if(!t){i({status:"no-file"});return}const a=new AbortController;i({status:"loading"});const l=`${n}/source?file=`+encodeURIComponent(t)+"&line="+(e||1)+"&context=20";return fetch(l,{signal:a.signal}).then(async f=>f.ok?{status:"loaded",data:await f.json()}:{status:"missing",code:f.status}).then(f=>i(f)).catch(f=>{f.name!=="AbortError"&&i({status:"error"})}),()=>a.abort()},[t,e,n]),s.status==="no-file")return _("div",{class:"empty",children:"No source file recorded."});if(s.status==="loading")return _("div",{class:"empty",children:"Loading…"});if(s.status==="missing")return _("div",{class:"empty",children:["Source not available (",s.code,")."]});if(s.status==="error")return _("div",{class:"empty",children:"Could not load source."});if(s.status!=="loaded")return null;const{start:r,lines:o}=s.data,c=e||r;return _("pre",{class:"snippet",children:o.map((a,l)=>{const f=r+l;return _("div",{class:"row-line"+(f===c?" hl":""),children:[_("span",{class:"ln",children:f}),a]},f)})})}function yi({label:t,getText:e,subtle:n}){const[s,i]=be(!1),r=zc(null);We(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=()=>{navigator.clipboard.writeText(e()).then(()=>{i(!0),r.current=setTimeout(()=>i(!1),1500)})},c="btn"+(n?" subtle":"")+(s?" copied":"");return _("button",{class:c,onClick:o,children:s?"Copied!":t})}function Tc(t){const e=t.status==="completed"?"PASSED":t.status==="timeout"?"TIMEOUT":t.status==="running"?"RUNNING":"FAILED",n=[];if(n.push(Ac(t.status)+" "+t.name+" — "+e),n.push(" File: "+t.file+(t.line?":"+t.line:"")),n.push(" Team: "+ks(t)+(t.duration?" · "+t.duration+"ms":"")),t.error&&n.push(" Error: "+t.error),t.assertions.length){n.push(" Assertions:");for(const s of t.assertions)n.push(" "+(s.result?"✓":"✗")+" "+s.description)}if(t.timeline.length){n.push(" Timeline:");for(const s of t.timeline)n.push(" "+s.actor+": "+s.action+(s.target?" "+s.target:"")+(s.duration!=null?" ("+s.duration+"ms)":"")+(s.error?" — "+s.error:""))}return n.join(`
|
|
13
|
+
`)}function Pc(t,e){const n=t.filter(i=>i.status!=="completed"&&i.status!=="running");return["Scenetest — "+(e||"live"),n.length+" failing scene(s)",""].join(`
|
|
14
|
+
`)+`
|
|
15
|
+
`+t.map(i=>Tc(i)).join(`
|
|
16
|
+
|
|
17
|
+
`)}function hh(t,e){const n=t.filter(s=>s.status!=="completed"&&s.status!=="running");return Pc(n.length?n:t,e)}function ph(t){const e={};return t!=null&&t.bg&&(e["--st-bg"]=t.bg),t!=null&&t.accent&&(e["--st-accent"]=t.accent),t!=null&&t.font&&(e["--st-font"]=t.font),t!=null&&t.fontSize&&(e["--st-font-size"]=t.fontSize),e}function yh(t){const e=Ue(()=>{const i=Vd(t);return{source:i,scenes:At(Dn({source:i,projection:Nd()})),assertions:At(Dn({source:i,projection:zd()})),actions:At(Dn({source:i,projection:Ud()})),runs:At(Dn({source:i,projection:qd()}))}},[t]),[n,s]=be("connecting");return We(()=>{const i=e.source.subscribe(()=>{},s);return()=>{i(),e.source.close()}},[e]),{store:e,connection:n}}const St="/__scenetest";function Ws(t){return t.startsWith(`${St}/runner`)?"runner":t.startsWith(`${St}/waterfall`)?"waterfall":"home"}const Yt={home:St,runner:`${St}/runner`,waterfall:`${St}/waterfall`};function gh({transport:t,theme:e}){const{store:n,connection:s}=yh(t),[i,r]=be(()=>Ws(location.pathname));We(()=>{const l=()=>r(Ws(location.pathname));return window.addEventListener("popstate",l),()=>window.removeEventListener("popstate",l)},[]);const o=l=>{var y;const f=(y=l.target)==null?void 0:y.closest("a"),u=f==null?void 0:f.getAttribute("href");!u||!u.startsWith(St)||l.metaKey||l.ctrlKey||l.shiftKey||l.altKey||l.button!==0||(l.preventDefault(),history.pushState(null,"",u+location.search),r(Ws(u)))},c=l=>{t.sendCommand(l)},a=l=>"tab"+(i===l?" active":"");return _("div",{class:"scenetest-dashboard",style:ph(e),onClick:o,children:[_("nav",{class:"dashboard-nav",children:[_("h1",{children:[_("span",{class:"logo",children:"🎬"})," Scenetest"]}),_("div",{class:"tabs",children:[_("a",{class:a("home"),href:Yt.home,children:"Home"}),_("a",{class:a("runner"),href:Yt.runner,children:"Runner"}),_("a",{class:a("waterfall"),href:Yt.waterfall,children:"Waterfall"})]})]}),_("div",{class:"view",children:i==="home"?_(mh,{}):i==="runner"?_(oh,{collections:n,connection:s,base:St}):_(_h,{collections:n,connection:s,send:c})})]})}function mh(){return _("div",{class:"index",children:[_("h1",{children:[_("span",{class:"logo",children:"🎬"})," Scenetest"]}),_("p",{class:"lede",children:"Pick a view."}),_("div",{class:"cards",children:[_("a",{class:"card",href:Yt.runner,children:[_("div",{class:"name",children:"Scene runner →"}),_("div",{class:"desc",children:"Live and past runs: scene tree, status, failure log, spec snippets."})]}),_("a",{class:"card",href:Yt.waterfall,children:[_("div",{class:"name",children:"Waterfall →"}),_("div",{class:"desc",children:"Live timeline of actors and inline check() / should() assertions."})]})]})]})}function _h({collections:t,connection:e,send:n}){const s=Ec(t),r={...Ue(()=>Jd(s),[s.runId,s.run,s.scenes,s.assertions,s.actions]),connection:e};return _("div",{class:"waterfall-host",children:_(Yd,{state:r,send:n})})}function wh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Sh(t){return typeof t=="string"}function bh(t){return typeof t=="number"&&Number.isFinite(t)}function vh(t){return wh(t)&&Sh(t.type)&&bh(t.timestamp)}function Ch(t={}){const e=(t.base??"/__scenetest").replace(/\/+$/,"");return{subscribe(n,s){const i=new EventSource(`${e}/events`),r=o=>s==null?void 0:s(o);return r("connecting"),i.onopen=()=>r("connected"),i.onerror=()=>r("disconnected"),i.onmessage=o=>{let c;try{c=JSON.parse(o.data)}catch{return}vh(c)&&n(c)},()=>i.close()},async sendCommand(n){const s=(i,r)=>fetch(`${e}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)});switch(n.type){case"run:replay":{const i={};n.file&&(i.file=n.file),n.team&&(i.team=n.team),await s("/replay",i);return}case"run:stop":await s("/stop");return;case"run:pause":case"run:resume":await s("/pause");return}}}}const to=document.getElementById("root");to&&Lc(_(gh,{transport:Ch()}),to);
|