@instantdb/react-common 0.22.47-experimental.sync-table.19154203588.1 → 0.22.47-experimental.sync-table.19174988015.1
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/standalone/index.js
CHANGED
|
@@ -3832,7 +3832,7 @@ function nr(t) {
|
|
|
3832
3832
|
}, e;
|
|
3833
3833
|
}, {});
|
|
3834
3834
|
}
|
|
3835
|
-
const Xr = "v0.22.47-experimental.sync-table.
|
|
3835
|
+
const Xr = "v0.22.47-experimental.sync-table.19174988015.1";
|
|
3836
3836
|
function hu(t, e) {
|
|
3837
3837
|
return {
|
|
3838
3838
|
info: t ? (...n) => console.info(...n, e()) : () => {
|
|
@@ -4392,7 +4392,7 @@ class ju {
|
|
|
4392
4392
|
subscribe(e, n) {
|
|
4393
4393
|
const r = N(e);
|
|
4394
4394
|
return this.callbacks[r] = this.callbacks[r] || [], this.callbacks[r].push(n), this.initSubscription(e, r, n), (i) => {
|
|
4395
|
-
this.unsubscribe(r, n, i);
|
|
4395
|
+
this.unsubscribe(r, n, i == null ? void 0 : i.keepSubscription);
|
|
4396
4396
|
};
|
|
4397
4397
|
}
|
|
4398
4398
|
unsubscribe(e, n, r) {
|
|
@@ -6113,6 +6113,9 @@ class Zu {
|
|
|
6113
6113
|
queryOnce(e, n) {
|
|
6114
6114
|
return this._reactor.queryOnce(e, n);
|
|
6115
6115
|
}
|
|
6116
|
+
_syncTableExperimental(e, n) {
|
|
6117
|
+
return this._reactor.subscribeTable(e, n);
|
|
6118
|
+
}
|
|
6116
6119
|
}
|
|
6117
6120
|
function pr(t) {
|
|
6118
6121
|
if (!t)
|
|
@@ -27,10 +27,10 @@ Check the top-level render call using <`+w+">.")}return b}}function Jr(l,b){{if(
|
|
|
27
27
|
<%s {...props} />
|
|
28
28
|
React keys must be passed directly to JSX without using spread:
|
|
29
29
|
let props = %s;
|
|
30
|
-
<%s key={someKey} {...props} />`,un,be,sa,be),Xr[be+un]=!0}}return l===i?ea(U):Xu(U),U}}function ta(l,b,w){return ei(l,b,w,!0)}function na(l,b,w){return ei(l,b,w,!1)}var ra=na,ia=ta;je.Fragment=i,je.jsx=ra,je.jsxs=ia}(),je}var ri={};ri.NODE_ENV==="production"?dt.exports=ti():dt.exports=ni();var ze=dt.exports;function N(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=N(t[n]);for(let i=0;i<r.length;i++)e^=r.charCodeAt(i),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const i=n[r],s=N(i);e^=parseInt(s,16),e*=16777619,e=e>>>0;const o=N(t[i]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return N(String(t))}const M={Remove:"remove",Replace:"replace",Add:"add"},dn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),ii=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Ke=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ft={};function Ie(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function fn(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function lt(t){return Object.getPrototypeOf(t)===Set.prototype}function ht(t){return Object.getPrototypeOf(t)===Map.prototype}function J(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function de(t){return!!E(t)}function E(t){return typeof t!="object"?null:t==null?void 0:t[dn]}function pt(t){var e;const n=E(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function ee(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!(e!=null&&e.mark)&&((n=e.mark(t,Y))===Y.immutable||typeof n=="function")}function ln(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=E(se(n,t.key));if(r!==null&&(r==null?void 0:r.original)!==t.original)return null;const i=t.parent.type===3,s=i?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(i&&n.size>s||Ie(n,s)))return null;e.push(s)}if(t.parent)return ln(t.parent,e);e.reverse();try{si(t.copy,e)}catch{return null}return e}function fe(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function se(t,e){return fe(t)===2?t.get(e):t[e]}function Pe(t,e,n){fe(t)===2?t.set(e,n):t[e]=n}function yt(t,e){const n=E(t);return(n?J(n):t)[e]}function oe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function bt(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function le(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function si(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=se(fe(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function oi(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const ui=Object.prototype.propertyIsEnumerable;function hn(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!lt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!ht(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e!=null&&e.mark&&(n=e.mark(t,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return oi(t);if(typeof n=="function"){if(e.enablePatches||e.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(i=>{r[i]=t[i]}),Object.getOwnPropertySymbols(t).forEach(i=>{ui.call(t,i)&&(r[i]=t[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function z(t){t.copy||(t.copy=hn(t.original,t.options))}function Re(t){if(!ee(t))return pt(t);if(Array.isArray(t))return t.map(Re);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,i])=>[r,Re(i)]);if(!ht(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(Re);if(!lt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=Re(t[n]);return e}function qe(t){return de(t)?Re(t):t}function re(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&re(t.parent))}function pn(){throw new Error("Cannot modify frozen object")}function _e(t,e,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const u=r.indexOf(o);if(o&&typeof o=="object"&&u!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${i.slice(0,u).map((c,d)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const a=r[d];return typeof c=="object"&&(a instanceof Map||a instanceof Set)?Array.from(a.keys()).indexOf(c):c}).join("/")}`);r.push(o),i.push(e)}else r.push(o)}if(Object.isFrozen(t)||de(t)){r.pop(),i.pop();return}switch(fe(t)){case 2:for(const[u,c]of t)_e(u,u,n,r,i),_e(c,u,n,r,i);t.set=t.clear=t.delete=pn;break;case 3:for(const u of t)_e(u,u,n,r,i);t.add=t.clear=t.delete=pn;break;case 1:Object.freeze(t);let o=0;for(const u of t)_e(u,o,n,r,i),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(u=>{const c=t[u];_e(c,u,n,r,i)})}r.pop(),i.pop()}function _t(t,e){const n=fe(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const i of t)e(r,i,t),r+=1}else t.forEach((r,i)=>e(i,r,t))}function yn(t,e,n){if(de(t)||!ee(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,i=r?new Map:void 0;if(e.add(t),_t(t,(s,o)=>{var u;if(de(o)){const c=E(o);z(c);const d=!((u=c.assignedMap)===null||u===void 0)&&u.size||c.operated?c.copy:c.original;Pe(r?i:t,s,d)}else yn(o,e,n)}),i){const s=t,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ai(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&yn(se(n,e),t.finalities.handledSet,t.options)}function gt(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(pt(e))}))}function Tt(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const s=ln(t);s&&e(t,s,n,r)}t.finalized=!0}}function wt(t,e,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const c=t.type===3?t.setMap:t.copy;if(oe(se(c,e),n)){let d=i.original;i.copy&&(d=i.copy),gt(t),Tt(t,r,s,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(u=t.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,t.options.updatedValues.set(d,i.original)),Pe(c,e,d)}}),t.options.enableAutoFreeze&&i.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),ee(n,t.options)&&t.finalities.draft.push(()=>{const s=t.type===3?t.setMap:t.copy;oe(se(s,e),n)&&ai(t,e)})}function ci(t,e,n,r,i){let{original:s,assignedMap:o,options:u}=t,c=t.copy;c.length<s.length&&([s,c]=[c,s],[n,r]=[r,n]);for(let d=0;d<s.length;d+=1)if(o.get(d.toString())&&c[d]!==s[d]){const a=e.concat([d]),f=le(a,i);n.push({op:M.Replace,path:f,value:qe(c[d])}),r.push({op:M.Replace,path:f,value:qe(s[d])})}for(let d=s.length;d<c.length;d+=1){const a=e.concat([d]),f=le(a,i);n.push({op:M.Add,path:f,value:qe(c[d])})}if(s.length<c.length){const{arrayLengthAssignment:d=!0}=u.enablePatches;if(d){const a=e.concat(["length"]),f=le(a,i);r.push({op:M.Replace,path:f,value:s.length})}else for(let a=c.length;s.length<a;a-=1){const f=e.concat([a-1]),h=le(f,i);r.push({op:M.Remove,path:h})}}}function di({original:t,copy:e,assignedMap:n},r,i,s,o){n.forEach((u,c)=>{const d=se(t,c),a=qe(se(e,c)),f=u?Ie(t,c)?M.Replace:M.Add:M.Remove;if(oe(d,a)&&f===M.Replace)return;const h=r.concat(c),p=le(h,o);i.push(f===M.Remove?{op:f,path:p}:{op:f,path:p,value:a}),s.push(f===M.Add?{op:M.Remove,path:p}:f===M.Remove?{op:M.Add,path:p,value:d}:{op:M.Replace,path:p,value:d})})}function fi({original:t,copy:e},n,r,i,s){let o=0;t.forEach(u=>{if(!e.has(u)){const c=n.concat([o]),d=le(c,s);r.push({op:M.Remove,path:d,value:u}),i.unshift({op:M.Add,path:d,value:u})}o+=1}),o=0,e.forEach(u=>{if(!t.has(u)){const c=n.concat([o]),d=le(c,s);r.push({op:M.Add,path:d,value:u}),i.unshift({op:M.Remove,path:d,value:u})}o+=1})}function Me(t,e,n,r){const{pathAsArray:i=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return di(t,e,n,r,i);case 1:return ci(t,e,n,r,i);case 3:return fi(t,e,n,r,i)}}const Be=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!ee(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},St={get size(){return J(E(this)).size},has(t){return J(E(this)).has(t)},set(t,e){const n=E(this),r=J(n);return(!r.has(t)||!oe(r.get(t),e))&&(z(n),re(n),n.assignedMap.set(t,!0),n.copy.set(t,e),wt(n,t,e,Me)),this},delete(t){if(!this.has(t))return!1;const e=E(this);return z(e),re(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=E(this);if(this.size){z(t),re(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=E(this);J(n).forEach((r,i)=>{t.call(e,this.get(i),i,this)})},get(t){var e,n;const r=E(this),i=J(r).get(t),s=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,i,Y))===Y.mutable;if(r.options.strict&&Be(i,r.options,s),s||r.finalized||!ee(i,r.options)||i!==r.original.get(t))return i;const o=ft.createDraft({original:i,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return z(r),r.copy.set(t,o),o},keys(){return J(E(this)).keys()},values(){const t=this.keys();return{[Ke]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[Ke]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[Ke](){return this.entries()}},li=Reflect.ownKeys(St),bn=(t,e,{isValuesIterator:n})=>()=>{var r,i;const s=e.next();if(s.done)return s;const o=s.value;let u=t.setMap.get(o);const c=E(u),d=((i=(r=t.options).mark)===null||i===void 0?void 0:i.call(r,u,Y))===Y.mutable;if(t.options.strict&&Be(o,t.options,d),!d&&!c&&ee(o,t.options)&&!t.finalized&&t.original.has(o)){const a=ft.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,a),u=a}else c&&(u=c.proxy);return{done:!1,value:n?u:[u,u]}},Qe={get size(){return E(this).setMap.size},has(t){const e=E(this);if(e.setMap.has(t))return!0;z(e);const n=E(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=E(this);return this.has(t)||(z(e),re(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),wt(e,t,t,Me)),this},delete(t){if(!this.has(t))return!1;const e=E(this);z(e),re(e);const n=E(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=E(this);z(t),re(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=E(this);z(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:bn(t,e,{isValuesIterator:!0})}},entries(){const t=E(this);z(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:bn(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[Ke](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(Qe,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const hi=Reflect.ownKeys(Qe),_n=new WeakSet,gn={get(t,e,n){var r,i;const s=(r=t.copy)===null||r===void 0?void 0:r[e];if(s&&_n.has(s))return s;if(e===dn)return t;let o;if(t.options.mark){const d=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(d,Y),o===Y.mutable)return t.options.strict&&Be(d,t.options,!0),d}const u=J(t);if(u instanceof Map&&li.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(St,"size").get.call(t.proxy);const d=St[e];if(d)return d.bind(t.proxy)}if(u instanceof Set&&hi.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Qe,"size").get.call(t.proxy);const d=Qe[e];if(d)return d.bind(t.proxy)}if(!Ie(u,e)){const d=fn(u,e);return d?"value"in d?d.value:(i=d.get)===null||i===void 0?void 0:i.call(t.proxy):void 0}const c=u[e];if(t.options.strict&&Be(c,t.options),t.finalized||!ee(c,t.options))return c;if(c===yt(t.original,e)){if(z(t),t.copy[e]=mt({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const d=E(t.copy[e]);return z(d),re(d),d.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(t.type===1&&e!=="length"&&!(Number.isInteger(i=Number(e))&&i>=0&&(e===0||i===0||String(i)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const s=fn(J(t),e);if(s!=null&&s.set)return s.set.call(t.proxy,n),!0;const o=yt(J(t),e),u=E(o);return u&&oe(u.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(oe(n,o)&&(n!==void 0||Ie(t.original,e))||(z(t),re(t),Ie(t.original,e)&&oe(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,wt(t,e,n,Me)),!0)},has(t,e){return e in J(t)},ownKeys(t){return Reflect.ownKeys(J(t))},getOwnPropertyDescriptor(t,e){const n=J(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?gn.set.call(this,t,e,void 0,t.proxy):(yt(t.original,e)!==void 0||e in t.original?(z(t),re(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function mt(t){const{original:e,parentDraft:n,key:r,finalities:i,options:s}=t,o=fe(e),u={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(u.key=r);const{proxy:c,revoke:d}=Proxy.revocable(o===1?Object.assign([],u):u,gn);if(i.revoke.push(d),_n.add(c),u.proxy=c,n){const a=n;a.finalities.draft.push((f,h)=>{var p,y;const _=E(c);let T=a.type===3?a.setMap:a.copy;const g=se(T,r),S=E(g);if(S){let m=S.original;S.operated&&(m=pt(g)),gt(S),Tt(S,Me,f,h),a.options.enableAutoFreeze&&(a.options.updatedValues=(p=a.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,a.options.updatedValues.set(m,S.original)),Pe(T,r,m)}(y=_.callbacks)===null||y===void 0||y.forEach(m=>{m(f,h)})})}else{const a=E(c);a.finalities.draft.push((f,h)=>{gt(a),Tt(a,Me,f,h)})}return c}ft.createDraft=mt;function pi(t,e,n,r,i){var s;const o=E(t),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:t,c=!!e.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const d=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&bt(o),i&&_e(d,d,o==null?void 0:o.options.updatedValues),[d,n&&c?[{op:M.Replace,path:[],value:e[0]}]:n,r&&c?[{op:M.Replace,path:[],value:u}]:r]}function yi(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;e.enablePatches&&(i=[],s=[]);const u=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,Y))===Y.mutable||!ee(t,e)?t:mt({original:t,parentDraft:null,finalities:r,options:e});return[u,(c=[])=>{const[d,a,f]=pi(u,c,i,s,e.enableAutoFreeze);return e.enablePatches?[d,a,f]:d}]}function vt(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:i=!0}=t;_t(n,(s,o,u)=>{const c=E(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const d=c.original;if(u instanceof Set){const a=Array.from(u);u.clear(),a.forEach(f=>u.add(s===f?d:f))}else Pe(u,s,d)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,vt(t))}),i&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function Tn(t){var e;const n=E(t);if(!ee(t,n==null?void 0:n.options))return t;const r=fe(t);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?ht(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):hn(t,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=t;if(_t(i,(o,u)=>{if(n&&oe(se(n.original,o),u))return;const c=Tn(u);c!==u&&(i===t&&s(),Pe(i,o,c))}),r===3){const o=(e=n==null?void 0:n.original)!==null&&e!==void 0?e:i;return lt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function wn(t){if(!de(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return Tn(t)}const Ot=(t=>function e(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...R){return e(O,F=>n.call(this,F,...R),r)};const c=n,d=r;let a=i;if(typeof r!="function"&&(a=r),a!==void 0&&Object.prototype.toString.call(a)!=="[object Object]")throw new Error(`Invalid options: ${a}, 'options' should be an object.`);a=Object.assign(Object.assign({},t),a);const f=de(c)?wn(c):c,h=Array.isArray(a.mark)?(O,R)=>{for(const F of a.mark){if(typeof F!="function")throw new Error(`Invalid mark: ${F}, 'mark' should be a function.`);const K=F(O,R);if(K)return K}}:a.mark,p=(s=a.enablePatches)!==null&&s!==void 0?s:!1,y=(o=a.strict)!==null&&o!==void 0?o:!1,T={enableAutoFreeze:(u=a.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:y,enablePatches:p};if(!ee(f,T)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[g,S]=yi(f,T);if(typeof r!="function"){if(!ee(f,T))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[g,S]}let m;try{m=d(g)}catch(O){throw bt(E(g)),O}const D=O=>{const R=E(g);if(!de(O)){if(O!==void 0&&!oe(O,g)&&(R!=null&&R.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const K=O==null?void 0:O[ii];if(K){const Ne=K[0];return T.strict&&typeof O=="object"&&O!==null&&vt({rootDraft:R,value:O,useRawReturn:!0}),S([Ne])}if(O!==void 0)return typeof O=="object"&&O!==null&&vt({rootDraft:R,value:O}),S([O])}if(O===g||O===void 0)return S([]);const F=E(O);if(T===F.options){if(F.operated)throw new Error("Cannot return a modified child draft.");return S([wn(O)])}return S([O])};return m instanceof Promise?m.then(D,O=>{throw bt(E(g)),O}):D(m)})();Object.prototype.constructor.toString();function Sn(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&Object.keys(t).every(i=>e.hasOwnProperty(i))}function mn(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>e.hasOwnProperty(n)&&t[n]===e[n])}function Ge(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:Sn(t,e)?Object.keys(t).every(n=>Ge(t[n],e[n])):!1}function Et(t){if(!De(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function vn(t,e){if(!De(t)||!De(e))return e;const n=Object.assign({},t);for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const i=De(t[r])&&De(e[r]);n[r]=i?vn(t[r],e[r]):e[r]}return n}function De(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bi(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const o=e[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[s+1]=="number"?[]:{}),r=r[o]}const i=e[e.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function On(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const s=e[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof e[i+1]=="number"?[]:{}),r=r[s]}r[e[e.length-1]]=n}function En(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}En(t[n],r),_i(t[n])&&delete t[n]}}function _i(t){return t&&Object.keys(t).length===0}const An=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,gi={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function Ti(t){return new Date(t)}function wi(t){return new Date(t+"Z")}const Si=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function mi(t){const e=t.match(Si);if(!e)return null;const[n,r,i,s]=e;return r<=0||i<=0||s<=0?null:r>999?new Date(Date.UTC(r,i-1,s,0,0,0,0)):new Date(Date.UTC(s,r-1,i,0,0,0,0))}function vi(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function Oi(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function Ei(t){return new Date(t)}function Ai(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Ci(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function ki(t){const[e,n]=t.split(", "),[r,i,s]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,u,c,d,a]=o;return u=Number(u),c=Number(c),d=Number(d),a==="PM"&&u!==12?u+=12:a==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,c,d))}function ji(t){switch(t){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function Ii(t){const e=t.match(An);if(!e)return null;const[n]=e,r=gi[n],i=new Date(t.replace(An,"Z"));return new Date(i.getTime()-r*1e3)}const Pi=[mi,Oi,Ai,ki,Ei,wi,Ci,vi,Ti,ji,Ii];function Ri(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function At(t){for(const e of Pi){const n=Ri(e,t);if(n)return n}return null}function Mi(t){try{const e=JSON.parse(t);return typeof e=="string"?At(e):null}catch{return null}}function He(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=At(t)||Mi(t)||At(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}function Di(t){return t.cardinality==="one"}function Ct(t){return t["value-type"]==="ref"}function kt(t){return t["value-type"]==="blob"}function ge(t,e){return t[e]}function xe(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function te(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&te(t.get(n),r)}function B(t,e,n){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.set(e[0],n);return}const[r,...i]=e;let s=t.get(r);s||(s=new Map,t.set(r,s)),B(s,i,n)}function Cn(t,e,n){const r=new Map,i=new Map,s=new Map;for(const o of e){let[u,c,d,a]=o;const f=ge(t,c);if(!f){console.warn("no such attr",u,t);continue}f["checked-data-type"]==="date"&&n&&(d=He(d),o[2]=d),Ct(f)&&B(s,[d,c,u],o),B(r,[u,c,d],o),B(i,[c,u,d],o)}return{eav:r,aev:i,vae:s}}function kn(t){const e=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(t)){const o=s["forward-identity"],[u,c,d]=o,a=s["reverse-identity"];if(B(r,[c,d],s),kt(s)&&B(e,[c,d],s),s["primary?"]&&B(n,[c],s),a){const[f,h,p]=a;B(i,[h,p],s)}}return{blobAttrs:e,primaryKeys:n,forwardIdents:r,revIdents:i}}function jn(t){return{__type:t.__type,attrs:t.attrs,triples:Q(t.eav,3),cardinalityInference:t.cardinalityInference,linkIndex:t.linkIndex,useDateObjects:t.useDateObjects}}function In(t){return Ye(t.attrs,t.triples,t.cardinalityInference,t.linkIndex,t.useDateObjects)}function xi(t,e){return xe(t.eav,[e])!==void 0}function jt(t){t.attrIndexes=kn(t.attrs)}function Ye(t,e,n,r,i){const s=Cn(t,e,i);return s.useDateObjects=i,s.attrs=t,s.attrIndexes=kn(t),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function $e(t,e){var n,r;let i;if(Array.isArray(e[0])){const[o,u]=e[0],c=t.aev.get(o);if(!c)return null;i=(n=Q(c,2).find(a=>a[2]===u))===null||n===void 0?void 0:n[0]}else i=e[0];if(!i)return null;const s=e[2];if(Array.isArray(s)&&s.length===2&&t.aev.get(s[0])){const[o,u]=s,c=t.aev.get(o);if(!c)return null;const a=(r=Q(c,2).find(_=>_[2]===u))===null||r===void 0?void 0:r[0];if(!a)return null;const[f,h,p,...y]=e;return[i,h,a,...y]}else{const[o,...u]=e;return[i,...u]}}function Pn(t,e){const n=$e(t,e);if(!n)return;const[r,i,s]=n,o=ge(t.attrs,i);o&&(te(t.eav,[r,i,s]),te(t.aev,[i,r,s]),Ct(o)&&te(t.vae,[s,i,r]))}let $i=0;function Rn(t,e,n){const[r,i,s]=n;let o;const u=xe(t.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+$i++}function Mn(t,e){var n;const r=$e(t,e);if(!r)return;let[i,s,o]=r;const u=ge(t.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&t.useDateObjects&&(o=He(o));const c=xe(t.eav,[i,s,o]),d=(n=c==null?void 0:c[3])!==null&&n!==void 0?n:Rn(t,u,r),a=[i,s,o,d];Di(u)?(B(t.eav,[i,s],new Map([[o,a]])),B(t.aev,[s,i],new Map([[o,a]]))):(B(t.eav,[i,s,o],a),B(t.aev,[s,i,o],a)),Ct(u)&&B(t.vae,[o,s,i],a)}function Ui(t,e){var n;const r=$e(t,e);if(!r)return;const[i,s,o]=r,u=ge(t.attrs,s);if(!u)return;if(!kt(u))throw new Error("merge operation is not supported for links");const c=xe(t.eav,[i,s]);if(!c)return;const d=(n=c.values().next())===null||n===void 0?void 0:n.value;if(!d)return;const a=d[2],f=vn(a,o),h=[i,s,f,Rn(t,u,d)];B(t.eav,[i,s],new Map([[f,h]]))}function It(t,e){var n,r;const[i,s]=e,o=$e(t,[i]);if(!o)return;const[u]=o,c=t.eav.get(u);if(c){for(const a of c.keys()){const f=t.attrs[a];f&&f["on-delete-reverse"]==="cascade"&&Q(c.get(a),1).forEach(([h,p,y])=>{var _;return It(t,[y,(_=f["reverse-identity"])===null||_===void 0?void 0:_[1]])}),(!s||!f||((n=f["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(te(t.aev,[a,u]),te(t.eav,[u,a]))}c.size===0&&te(t.eav,[u])}const d=t.vae.get(u)&&Q(t.vae.get(u),2);d&&d.forEach(a=>{var f,h,p;const[y,_,T]=a,g=t.attrs[_];(!s||!g||((f=g["reverse-identity"])===null||f===void 0?void 0:f[1])===s)&&(te(t.eav,[y,_,T]),te(t.aev,[_,y,T]),te(t.vae,[T,_,y])),g&&g["on-delete"]==="cascade"&&((h=g["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&It(t,[y,(p=g["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=t.vae.get(u))===null||r===void 0?void 0:r.size)===0&&te(t.vae,[u])}function Dn(t,e){const n=Cn(t.attrs,e,t.useDateObjects);Object.keys(n).forEach(r=>{t[r]=n[r]})}function Li(t,[e]){t.attrs[e.id]=e,jt(t)}function xn(t){return Q(t.eav,3)}function Fi(t,[e]){if(!t.attrs[e])return;const n=xn(t).filter(([r,i])=>i!==e);delete t.attrs[e],jt(t),Dn(t,n)}function Ni(t,[e]){const n=t.attrs[e.id];n&&(t.attrs[e.id]=Object.assign(Object.assign({},n),e),jt(t),Dn(t,xn(t)))}function Vi(t,e){const[n,...r]=e;switch(n){case"add-triple":Mn(t,r);break;case"deep-merge-triple":Ui(t,r);break;case"retract-triple":Pn(t,r);break;case"delete-entity":It(t,r);break;case"add-attr":Li(t,r);break;case"delete-attr":Fi(t,r);break;case"update-attr":Ni(t,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function Q(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())Q(r,e-1,n);return n}function Je(t,e,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of e.keys())n.$not!==u&&s.push(e.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:c,reverse:d}=n.$isNull;if(d)for(const a of e.keys()){const f=t.vae.get(a),h=!f||((r=f.get(u))===null||r===void 0?void 0:r.get(null))||!f.get(u);(c?h:!h)&&s.push(e.get(a))}else{const a=t.aev.get(u);for(const f of e.keys()){const h=!a||((i=a.get(f))===null||i===void 0?void 0:i.get(null))||!a.get(f);(c?h:!h)&&s.push(e.get(f))}}return s}if(n!=null&&n.$comparator)return Q(e,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const c=e.get(u);c&&s.push(c)}return s}function Wi(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function zi(t,[e,n,r]){var i,s;switch(Wi(e,n,r)){case"e":{const u=t.eav.get(e);return Q(u,2)}case"ea":{const u=(i=t.eav.get(e))===null||i===void 0?void 0:i.get(n);return Q(u,1)}case"eav":{const u=(s=t.eav.get(e))===null||s===void 0?void 0:s.get(n);return u?Je(t,u,r):[]}case"ev":{const u=t.eav.get(e);if(!u)return[];const c=[];for(const d of u.values())c.push(...Je(t,d,r));return c}case"a":{const u=t.aev.get(n);return Q(u,2)}case"av":{const u=t.aev.get(n);if(!u)return[];const c=[];for(const d of u.values())c.push(...Je(t,d,r));return c}case"v":{const u=[];for(const c of t.eav.values())for(const d of c.values())u.push(...Je(t,d,r));return u}default:return Q(t.eav,3)}}function Ki(t,e,n){var r;const i={};for(const[s,o]of e.entries()){const u=(r=t.eav.get(n))===null||r===void 0?void 0:r.get(o.id),c=Q(u,1);for(const d of c)i[s]=d[2]}return i}function Te(t,e,n){var r;return(r=t.attrIndexes.forwardIdents.get(e))===null||r===void 0?void 0:r.get(n)}function $n(t,e,n){var r;return(r=t.attrIndexes.revIdents.get(e))===null||r===void 0?void 0:r.get(n)}function qi(t,e){return t.attrIndexes.blobAttrs.get(e)}function Un(t,e){var n;const r=t.attrIndexes.primaryKeys.get(e);return r||((n=t.attrIndexes.forwardIdents.get(e))===null||n===void 0?void 0:n.get("id"))}function Bi(t,e){const n=$e(t,e);if(!n)return;const[r,i,s]=n;if(ge(t.attrs,i))return xe(t.eav,[r,i])}function Qi(t,e){const n=e.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const c=u==null?void 0:u.mode;if(c!=="create"&&c!=="update")return!0;let d=!1;const a=ge(t.attrs,s);if(a){const f=Un(t,a["forward-identity"][1]);d=!!Bi(t,[i,f.id,i])}return!(c==="create"&&d||c==="update"&&!d)});return Ot(t,r=>{n.forEach(i=>{Vi(r,i)})})}function Gi(t){return typeof t=="string"&&t.startsWith("?")}function Hi(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return Fn(r,e,n)}return Object.assign(Object.assign({},n),{[t]:e})}function Ln(t,e,n){return t===e?n:null}function Yi(t){switch(typeof t){case"string":return t.startsWith("?")?Hi:Ln;default:return Ln}}const Ji=["in","$in","$not","$isNull","$comparator"];function Zi(t){for(const e of Ji)if(t.hasOwnProperty(e))return!0;return!1}function Fn(t,e,n){return n?typeof t=="object"?Zi(t)?n:null:Yi(t)(t,e,n):null}function Xi(t,e,n){return t.reduce((r,i,s)=>{const o=e[s];return Fn(i,o,r)},n)}function es(t,e,n){return rs(t,e,n).map(r=>Xi(e,r,n)).filter(r=>r)}function ts(t,e,n){return e.or?e.or.patterns.flatMap(r=>Pt(t,r,n)):e.and?e.and.patterns.reduce((r,i)=>Pt(t,i,r),n):n.flatMap(r=>es(t,e,r))}function Pt(t,e,n=[{}]){return e.reduce((r,i)=>ts(t,i,r),n)}function Rt(t,e){return Array.isArray(e)?e.map(n=>Rt(t,n)):Gi(e)?t[e]:e}function ns(t,{find:e,where:n}){return Pt(t,n).map(i=>Rt(i,e))}function rs(t,e,n){return zi(t,Rt(n,e))}const is=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function we(t){return typeof t=="string"&&is.test(t)}const V=[];for(let t=0;t<256;++t)V.push((t+256).toString(16).slice(1));function ss(t,e=0){return(V[t[e+0]]+V[t[e+1]]+V[t[e+2]]+V[t[e+3]]+"-"+V[t[e+4]]+V[t[e+5]]+"-"+V[t[e+6]]+V[t[e+7]]+"-"+V[t[e+8]]+V[t[e+9]]+"-"+V[t[e+10]]+V[t[e+11]]+V[t[e+12]]+V[t[e+13]]+V[t[e+14]]+V[t[e+15]]).toLowerCase()}let Mt;const os=new Uint8Array(16);function us(){if(!Mt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Mt=crypto.getRandomValues.bind(crypto)}return Mt(os)}const Nn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function as(t,e,n){var i;if(Nn.randomUUID&&!t)return Nn.randomUUID();t=t||{};const r=t.random??((i=t.rng)==null?void 0:i.call(t))??us();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ss(r)}function Vn(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function cs(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function ds(t,e){return cs(Vn(t),Vn(e))}function L(){return as()}function fs(t,e){return t.localeCompare(e)}function ls(){let t=fs;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const hs=ls();let ps=0;function Ue(t){return Ze(`_${t}`,ps++)}function Ze(t,e){return`?${t}-${e}`}class Se extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function ys(t,e){const n=Un(t,e);if(!n)throw new Se(`Could not find id attr for ${e}`);return n}function Wn(t,e,n,r){return[bs(t,e,n,r)]}function bs(t,e,n,r){return[t(n,r),ys(e,n).id,t(n,r),t("time",r)]}function _s(t,e,n){return t.map(r=>r===e?n:r)}function zn(t,e,n,r,i){const s=Te(e,n,i),o=$n(e,n,i),u=s||o;if(!u)throw new Se(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[c,d]=u["forward-identity"],[a,f]=u["reverse-identity"],h=r+1,p=s?[t(d,r),u.id,t(f,h),Ue("time")]:[t(d,h),u.id,t(f,r),Ue("time")];return[s?f:d,h,p,u,!!s]}function Kn(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,t?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function gs(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";if(e.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(e.$gt)}:function(i){return i[2]>e.$gt}};if(e.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(e.$gte)}:function(i){return i[2]>=e.$gte}};if(e.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(e.$lt)}:function(i){return i[2]<e.$lt}};if(e.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(e.$lte)}:function(i){return i[2]<=e.$lte}};if(e.hasOwnProperty("$like")){const r=Kn(!0,e.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(e.hasOwnProperty("$ilike")){const r=Kn(!1,e.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return e}function Ts(t,e,n,r,i,s){const o=Te(e,n,i),u=$n(e,n,i),c=o||u;if(!c)throw new Se(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const d=Te(e,n,"id");if(!d)throw new Se(`No attr for etype = ${n} label = id`);return[t(n,r),d.id,{$isNull:{attrId:c.id,isNull:s.$isNull,reverse:!o}},Ue("time")]}return o?[t(n,r),c.id,gs(c,s),Ue("time")]:[s,c.id,t(n,r),Ue("time")]}function ws(t,e,n,r,i){const[s,o,u]=i.reduce((c,d)=>{const[a,f,h]=c,[p,y,_]=zn(t,e,a,f,d);return[p,y,[...h,_]]},[n,r,[]]);return[s,o,u]}function Dt(t,e,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[c,d,a]=ws(t,e,n,r,o),f=Ts(t,e,c,d,u,s);return a.concat([f])}function Ss(t,e){return e?[e].concat(t):t}function ms([t,e]){return t==="or"&&Array.isArray(e)}function vs([t,e]){return t==="and"&&Array.isArray(e)}function Os(t,e,n){return(r,i)=>{const s=t(r,i);return e==s?s:`${s}-${n}`}}function qn(t,e,n,r,i,s){const o=t(r,i),u=s.map((c,d)=>{const a=Os(t,o,d);return Qn(a,n,r,i,c)});return{[e]:{patterns:u,joinSym:o}}}function Es(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function Bn(t,e,n,r,i){return Es(i).map(s=>Dt(t,e,n,r,s,{$isNull:!0}))}function Qn(t,e,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(ms([s,o]))return qn(t,"or",e,n,r,o);if(vs([s,o]))return qn(t,"and",e,n,r,o);if(s==="$entityIdStartsWith")return[];const u=s.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o=Object.assign(Object.assign({},o),{$not:o.$ne}),delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const c=Dt(t,e,n,r,u,o),d=Bn(t,e,n,r,u);return[{or:{patterns:[c,...d],joinSym:t(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Bn(t,e,n,r,u),joinSym:t(n,r)}}]:Dt(t,e,n,r,u,o)})}function As(t,e,n,r){const i=Ze;return r?Qn(i,t,e,n,r).concat(Wn(i,t,e,n)):Wn(i,t,e,n)}function Cs(t,e,n){return[t(e,n),t("time",n)]}function ks(t,e,n,r,i,s){const[o,u,c,d,a]=zn(t,e,n,r,i),f=_s(c,t(n,r),s);return[o,u,f,d,a]}function js(t,e,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([c,d]){return o.map(function(h){var p,y,_;const T=!!(e.cardinalityInference&&(!((_=(y=(p=e.linkIndex)===null||p===void 0?void 0:p[n])===null||y===void 0?void 0:y[h])===null||_===void 0)&&_.isSingular));try{const[g,S,m]=ks(t,e,n,r,h,c),D=Hn(e,{etype:g,level:S,form:i[h],join:m}),O=T?D[0]:D;return{[h]:O}}catch(g){if(g instanceof Se)return{[h]:T?void 0:[]};throw g}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},d)}):Object.values(s)}function Is(t,e,n){return n==="string"?hs(t,e):t>e?1:-1}function Xe([t,e],[n,r],i){return e===r||e==null&&r==null?ds(t,n):r==null?1:e==null?-1:Is(e,r,i)}function xt(t){return t==null?t:new Date(t).getTime()}function Ps(t,e,n,r){var i;const[s,o,u,c]=t,d=n==="desc"?1:-1;if(((i=e["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return Xe(r,[s,c],null)===d;const[a,f]=r,h=e["checked-data-type"],p=h==="date"?xt(f):f,y=h==="date"?xt(u):u;return Xe([a,p],[s,y],h)===d}function Rs(t,e){const n=e[1];return t.attrs[n]}function Ms(t,e,n){const r=Object.keys(n)[0];return Te(t,e,r)}function Ds(t,e,n,r){if(n)return Rs(t,n);if(r)return Ms(t,e,r)}function xs(t,e,n){var r,i;if(!Array.isArray(n.fields))return qi(t,e);const s=new Map;for(const o of n.fields){const u=Te(t,e,o),c=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];c&&kt(u)&&s.set(c,u)}if(!s.has("id")){const o=Te(t,e,"id"),u=(i=o==null?void 0:o["forward-identity"])===null||i===void 0?void 0:i[2];u&&s.set(u,o)}return s}function $s(t,{etype:e,pageInfo:n,dq:r,form:i}){var s,o;const u=(s=i==null?void 0:i.$)===null||s===void 0?void 0:s.order,c=Gn(i),d=Us(i);let a=ns(t,r);const f=n==null?void 0:n["start-cursor"],h=Ds(t,e,f,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const _=h["checked-data-type"]==="date",T=h.id;a=a.map(([g])=>{var S,m,D,O,R;let F=(R=(O=(D=(m=(S=t.eav.get(g))===null||S===void 0?void 0:S.get(T))===null||m===void 0?void 0:m.values())===null||D===void 0?void 0:D.next())===null||O===void 0?void 0:O.value)===null||R===void 0?void 0:R[2];return _&&(F=xt(F)),[g,F]})}a.sort(d==="asc"?function(T,g){return Xe(T,g,h==null?void 0:h["checked-data-type"])}:function(T,g){return Xe(g,T,h==null?void 0:h["checked-data-type"])});let p={};const y=xs(t,e,r);for(const _ of a){const[T]=_;if(p[T]||!c&&f&&h&&Ps(f,h,d,_))continue;const g=Ki(t,y,T);g&&(p[T]=g)}return p}function Us(t){var e;const n=(e=t.$)===null||e===void 0?void 0:e.order;return n&&n[Object.keys(n)[0]]||"asc"}function Gn(t){var e,n,r;const i=(e=t.$)===null||e===void 0?void 0:e.offset,s=(n=t.$)===null||n===void 0?void 0:n.before,o=(r=t.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Ls(t,{etype:e,level:n,form:r,join:i,pageInfo:s}){var o,u,c,d,a;if(!Gn(r)&&(!s||!s["start-cursor"]))return[];const f=Ss(As(t,e,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=Cs(Ze,e,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,y=$s(t,{etype:e,pageInfo:s,form:r,dq:{where:f,find:h,fields:p}}),_=((c=r.$)===null||c===void 0?void 0:c.limit)||((d=r.$)===null||d===void 0?void 0:d.first)||((a=r.$)===null||a===void 0?void 0:a.last);if(_!=null){n>0&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const T=Object.entries(y);return T.length<=_?y:Object.fromEntries(T.slice(0,_))}return y}function Fs(t,e){try{return Ls(t,e)}catch(n){if(n instanceof Se)return{};throw n}}function Hn(t,e){const n=Fs(t,e);return js(Ze,t,e,n)}function Ns(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function Yn({store:t,pageInfo:e,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,c){return n!=null&&n[c]||c==="$$ruleParams"||(u[c]=Hn(t,{etype:c,form:r[c],level:0,pageInfo:e==null?void 0:e[c]})),u},{})};return e&&(s.pageInfo=Ns(e)),n&&(s.aggregate=n),s}function Vs(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const Ws=Vs();function $t(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return t;if(Ws.has(s))return(o,u)=>$t(t,e,[...n,u?[s,t,e,o,u]:[s,t,e,o]])}})}function et(t){return t.startsWith("lookup__")}function Jn(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function zs(t){return new Proxy({__etype:t},{get(e,n){if(n==="__etype")return t;const r=n;return et(r)?$t(t,Jn(r),[]):$t(t,r,[])}})}function Ut(){return new Proxy({},{get(t,e){return zs(e)}})}Ut();function Ks(t){return t.__ops}function qs(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,i=[];for(const o of e){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,d]=o;i.push([n[c],d])}else i.push(o)}const[s]=e;if((s==="add-triple"||s==="retract-triple")&&r.has(e[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function W(t,e,n){return Object.values(t).find(r=>{const[i,s,o]=r["forward-identity"];return s===e&&o===n})}function he(t,e,n){return Object.values(t).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===e&&u===n})}function Bs(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function Lt(t,e,n){return n.indexOf(".")!==-1&&!W(t,e,n)}function Ft(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function Qs(t,e,n){if(!Lt(t,e,n))return W(t,e,n);const r=Ft(n),i=W(t,e,r)||he(t,e,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Nt(t){return typeof t=="string"&&!et(t)?null:typeof t=="string"&&et(t)?Jn(t):Bs(t)}function G(t,e,n){const r=Nt(n);if(r===null)return n;const[i,s]=r,o=Qs(t,e,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function Zn(t,e,n,r){const i=G(t,e,n);return Array.isArray(i)?[["add-triple",i,W(t,e,"id").id,i]].concat(r):r}function Gs({attrs:t},[e,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],c=W(t,e,s),d=he(t,e,s);return u.map(a=>c?["add-triple",G(t,e,n),c.id,G(t,c["reverse-identity"][1],a)]:["add-triple",G(t,d["forward-identity"][1],a),d.id,G(t,e,n)])});return Zn(t,e,n,i)}function Hs({attrs:t},[e,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],c=W(t,e,s),d=he(t,e,s);return u.map(a=>c?["retract-triple",G(t,e,n),c.id,G(t,c["reverse-identity"][1],a)]:["retract-triple",G(t,d["forward-identity"][1],a),d.id,G(t,e,n)])});return Zn(t,e,n,i)}function Ys(t,e,n){if(Array.isArray(n)){const[r,i]=n;for(const s of t||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,c,d]of Q(o,2))if(d===i)return!0}}}else for(const r of t||[]){const i=r==null?void 0:r.eav.get(n);if(i){for(const s of i.keys())if(r.attrs[s]["forward-identity"][1]==e)return!0}}return!1}function Xn({stores:t,attrs:e},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Ys(t,n,r)?{mode:"update"}:null}function Js(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s);return[["id",d]].concat(Object.entries(c)).map(([f,h])=>{const p=W(r,i,f);return p["checked-data-type"]==="date"&&t.useDateObjects&&(h=He(h)),["add-triple",d,p.id,h,{mode:"create"}]})}function Zs(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s),a=Xn(t,[i,d,o,u]);return[["id",d]].concat(Object.entries(c)).map(([h,p])=>{const y=W(r,i,h);return y["checked-data-type"]==="date"&&t.useDateObjects&&(p=He(p)),["add-triple",d,y.id,p,...a?[a]:[]]})}function Xs({attrs:t},[e,n]){return[["delete-entity",G(t,e,n),e]]}function eo(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s),a=Xn(t,[i,d,o,u]),f=Object.entries(c).map(([p,y])=>{const _=W(r,i,p);return["deep-merge-triple",d,_.id,y,...a?[a]:[]]});return[["add-triple",d,W(r,i,"id").id,d,...a?[a]:[]]].concat(f)}function to({attrs:t},[e,n,r]){return[["rule-params",G(t,e,n),e,r]]}function no(t){const[e,n,r,i,s]=t;if(!i)return t;const o=Object.assign({},i);return delete o.id,[e,n,r,o,...s?[s]:[]]}function ro(t,e){const[n,...r]=no(e);switch(n){case"merge":return eo(t,r);case"create":return Js(t,r);case"update":return Zs(t,r);case"link":return Gs(t,r);case"unlink":return Hs(t,r);case"delete":return Xs(t,r);case"ruleParams":return to(t,r);default:throw new Error(`unsupported action ${n}`)}}function io(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function so(t,e,n){var r,i;const s=(i=(r=t.entities[e])===null||r===void 0?void 0:r.attrs)===null||i===void 0?void 0:i[n];if(n==="id")return null;if(!s)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,c=io(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":c}}function tt(t,e,n,r){const i=t?so(t,e,n):null,s=L(),u=[L(),e,n];return Object.assign(Object.assign({id:s,"forward-identity":u,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}function oo(t,e,n){return Object.values(t.links).find(i=>i.forward.on===e&&i.forward.label===n||i.reverse.on===e&&i.reverse.label===n)}function uo(t,e,n){const r=oo(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[L(),i.on,i.label],"reverse-identity":[L(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function er(t,e,n,r){const i=t?uo(t,e,n):null,s=L(),o=[L(),e,n],u=[L(),n,e];return Object.assign(Object.assign({id:s,"forward-identity":o,"reverse-identity":u,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}const ao=new Set(["create","update","merge","link","unlink"]),co=new Set(["link","unlink"]),fo=new Set(["create","update","merge"]),lo=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Vt={"unique?":!0,"index?":!0},ho=Object.assign(Object.assign({},Vt),{cardinality:"one"});function po(t){const e=[],[n,r,i,s]=t;if(!lo.has(n))return e;const o=Nt(i);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[u,c]of Object.entries(s)){const d=Array.isArray(c)?c:[c];for(const a of d){const f=Nt(a);f&&e.push({etype:r,lookupPair:f,linkLabel:u})}}return e}function yo({attrs:t,schema:e},n){var r,i;const[s,o,u]=[new Set,Object.assign({},t),[]];function c(f){o[f.id]=f,u.push(["add-attr",f]),s.add(f.id)}function d(f){f!=null&&f.isUnsynced&&!s.has(f.id)&&(u.push(["add-attr",f]),s.add(f.id))}function a(f,h){const p=W(o,f,h),y=he(o,f,h);d(p),d(y),!p&&!y&&c(er(e,f,h,ho))}for(const f of n)for(const{etype:h,lookupPair:p,linkLabel:y}of po(f)){const _=p[0];if(y){a(h,y);const T=W(o,h,y),g=he(o,h,y);d(T),d(g);const S=((r=T==null?void 0:T["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=g==null?void 0:g["forward-identity"])===null||i===void 0?void 0:i[1])||y;if(Lt(o,S,_))a(S,Ft(_));else{const m=W(o,S,_);m||c(tt(e,S,_,Vt)),d(m)}}else if(Lt(o,h,_))a(h,Ft(_));else{const T=W(o,h,_);T||c(tt(e,h,_,Vt)),d(T)}}for(const f of n){const[h,p,y,_]=f;if(ao.has(h)){const T=W(o,p,"id");d(T),T||c(tt(e,p,"id",{"unique?":!0}));for(const g of Object.keys(_)){const S=W(o,p,g);if(d(S),fo.has(h)&&(S||c(tt(e,p,g,g==="id"?{"unique?":!0}:null))),co.has(h)){const m=he(o,p,g);!S&&!m&&c(er(e,p,g)),d(m)}}}}return[o,u]}function bo(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>Ks(c)),[i,s]=yo(t,r),o=Object.assign(Object.assign({},t),{attrs:i}),u=r.flatMap(c=>ro(o,c));return[...s,...u]}var tr=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class nr{constructor(e){this.dbName=e,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;e(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(e){return tr(this,void 0,void 0,function*(){const n=yield this._dbPromise;return new Promise((r,i)=>{const u=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);u.onerror=c=>{i(c)},u.onsuccess=c=>{u.result?r(u.result):r(null)}})})}setItem(e,n){return tr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const c=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,e);c.onerror=d=>{s(d)},c.onsuccess=d=>{i()}})})}}var _o=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class rr{static getIsOnline(){return _o(this,void 0,void 0,function*(){return navigator.onLine})}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class me extends Error{constructor(e,n){super(e),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,me),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var go=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class nt extends me{constructor(e){var n;const r=((n=e.body)===null||n===void 0?void 0:n.message)||`API Error (${e.status})`;super(r,e.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,nt),this.name="InstantAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function ne(t,e){return go(this,void 0,void 0,function*(){const n=yield fetch(t,e),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new nt({status:n.status,body:r}))})}var ve=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function To({apiURI:t,appId:e,email:n}){return ne(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}function wo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,email:r,code:i,refreshToken:s}){return yield ne(`${e}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Object.assign({"app-id":n,email:r,code:i},s?{"refresh-token":s}:{}))})})}function So(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,refreshToken:r}){return yield ne(`${e}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function mo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n}){return yield ne(`${e}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function ir(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield ne(`${e}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,code:r,code_verifier:i,refresh_token:s})})})}function vo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield ne(`${e}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,nonce:r,id_token:i,client_name:s,refresh_token:o})})})}function Oo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,refreshToken:r}){return yield ne(`${e}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var Le=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Eo(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const c={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(c["content-disposition"]=u),yield ne(`${e}/storage/upload`,{method:"PUT",headers:c,body:i})})}function Ao(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,refreshToken:i}){const{data:s}=yield ne(`${e}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function Co(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield ne(`${e}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({app_id:n,filename:r})});return o})}function ko(t,e){return Le(this,void 0,void 0,function*(){return(yield fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok})}function jo(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,refreshToken:i}){const{data:s}=yield ne(`${e}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Wt=!1,sr=!1,or=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Wt=!!window.localStorage.getItem("devBackend"),sr=!!window.localStorage.getItem("__instantLogging"),or=!!window.localStorage.getItem("__devtoolLocalDash"));function ur(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function Io(t,e,n){var r,i;const s={peers:{}};if(e&&"user"in e?e.user:!0){const u=ur((r=t.user)!==null&&r!==void 0?r:{},e==null?void 0:e.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=t.peers)!==null&&i!==void 0?i:{})){const c=(e==null?void 0:e.peers)===void 0,d=Array.isArray(e==null?void 0:e.peers)&&(e==null?void 0:e.peers.includes(u));if(c||d){const a=ur(t.peers[u],e==null?void 0:e.keys);s.peers[u]=Object.assign(Object.assign({},a),{peerId:u})}}return s}function Po(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!mn(t.user,e.user))||!Sn(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!mn(t.peers[r],e.peers[r]))return!0;return!1}class ar{constructor(){this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}var Fe=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Ro(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}class zt{constructor(e,n,r,i,s=d=>d,o=d=>d,u=100,c=1e3){this._subs=[],this._nextSave=null,this._persister=e,this._key=n,this._onMerge=i,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=s,this.parse=o,this._saveThrottleMs=u,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=c,this._load()}_getFromStorage(){return Fe(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(e){return console.error(`Unable to read from storage for key=${this._key}`,e),null}})}_load(){return Fe(this,void 0,void 0,function*(){const e=yield this._getFromStorage();this._isLoading=!1;const n=this._onMerge(e,this.currentValue);n&&(this.currentValue=n);for(const r of this._loadedCbs)r()})}waitForLoaded(){return Fe(this,void 0,void 0,function*(){if(!this._isLoading)return;yield new Promise(n=>{this._loadedCbs.push(n)})})}isLoading(){return this._isLoading}version(){return this._version}waitForSync(){return Fe(this,void 0,void 0,function*(){if(!this._nextSave)return;yield new Promise(n=>{this._pendingSaveCbs.push(n)})})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const e of this._pendingSaveCbs)e();this._pendingSaveCbs.length=0}flush(){return Fe(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(e){if(this._nextSave){e&&this._pendingSaveCbs.push(e);return}this._nextSave=setTimeout(()=>{Ro(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(e,n){this._version++,this.currentValue=e(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue);return this.currentValue}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}}function cr(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)e.push(u);cr(n["child-nodes"],e)})}function dr(t){const e=[];return cr(t,e),e}function fr(t){return Object.values(t.links).reduce((e,n)=>{var r,i,s,o;return(r=e[s=n.forward.on])!==null&&r!==void 0||(e[s]={}),e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=e[o=n.reverse.on])!==null&&i!==void 0||(e[o]={}),e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e},{})}const lr="v0.22.47-experimental.sync-table.19154203588.1";function Mo(t,e){return{info:t?(...n)=>console.info(...n,e()):()=>{},debug:t?(...n)=>console.debug(...n,e()):()=>{},error:t?(...n)=>console.error(...n,e()):()=>{}}}class ue{constructor(e,n,r,i={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new ue(this.valueType,!1,this.isIndexed,this.config)}optional(){return new ue(this.valueType,!1,this.isIndexed,this.config)}unique(){return new ue(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new ue(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class P extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const hr=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Do=t=>t.valueType||"unknown",pr=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},xo=(t,e,n,r,i,s,o)=>{const u=s.valueType==="json",c=(d,a,f)=>{if(!pr(f,a,u))throw new P(`Invalid value for operator '${d}' on attribute '${r}' in entity '${i}'. Expected ${a}, but received: ${typeof f}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new P(`Operator '${t}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof e}`,o);for(const d of e)c(t,n,d);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!s.isIndexed)throw new P(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;default:throw new P(`Unknown operator '${t}' for attribute '${r}' in entity '${i}'`,o)}},Oe=(t,e,n,r,i)=>{const s=Do(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){if(o)return;const c=t;for(const[d,a]of Object.entries(c))xo(d,a,s,e,r,n,`${i}.${d}`)}else if(!pr(t,s,o))throw new P(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${s}, but received: ${typeof t}`,i)},$o=(t,e,n,r,i)=>{const s=t.split(".");if(s.length<2)throw new P(`Invalid dot notation path '${t}'. Must contain at least one dot.`,i);let o=n;for(let a=0;a<s.length-1;a++){const f=s[a],h=r.entities[o];if(!h)throw new P(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,i);const p=h.links[f];if(!p){const y=Object.keys(h.links);throw new P(`Link '${f}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${y.length>0?y.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],c=r.entities[o];if(!c)throw new P(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,i);if(u==="id"){if(typeof e=="string"&&!we(e))throw new P(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,i);Oe(e,t,new ue("string",!1,!0),n,i);return}const d=c.attrs[u];if(Object.keys(c.links).includes(u)){if(typeof e=="string"&&!we(e))throw new P(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${e}`,i);Oe(e,t,new ue("string",!1,!0),n,i);return}if(!d){const a=Object.keys(c.attrs);throw new P(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${a.length>0?a.join(", ")+", id":"id"}`,i)}Oe(e,t,d,n,i)},yr=(t,e,n,r)=>{for(const[i,s]of Object.entries(t)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const d of s)typeof d=="object"&&d!==null&&yr(d,e,n,`${r}.${i}[${d}]`);continue}if(i==="id"){Oe(s,"id",new ue("string",!1,!0),e,`${r}.id`);continue}if(i.includes(".")){$o(i,s,e,n,`${r}.${i}`);continue}const o=n.entities[e];if(!o)continue;const u=o.attrs[i],c=o.links[i];if(!u&&!c){const d=Object.keys(o.attrs),a=Object.keys(o.links);throw new P(`Attribute or link '${i}' does not exist on entity '${e}'. Available attributes: ${d.length>0?d.join(", "):"none"}. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${i}`)}if(u)Oe(s,i,u,e,`${r}.${i}`);else if(c){if(typeof s=="string"&&!we(s))throw new P(`Invalid value for link '${i}' in entity '${e}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const d=new ue("string",!1,!0);Oe(s,i,d,e,`${r}.${i}`)}}},Uo=(t,e,n,r,i=0)=>{for(const o of Object.keys(t))if(!hr.includes(o))throw new P(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${hr.join(", ")}. Found: ${o}`,r);const s=["offset","before","after","first","last"];for(const o of s)if(t[o]!==void 0&&i>0)throw new P(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new P(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);yr(t.where,e,n,r?`${r}.where`:"where")}},br=(t,e,n,r,i=0)=>{var s;if(!t||typeof t!="object")throw new P(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const o of Object.keys(t))if(o!=="$"){if(n&&!(o in n.entities[e].links)){const c=Object.keys(n.entities[e].links);throw new P(`Link '${o}' does not exist on entity '${e}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${o}`)}const u=t[o];if(typeof u=="object"&&u!==null){const c=(s=n==null?void 0:n.entities[e].links[o])===null||s===void 0?void 0:s.entityName;c&&br(u,c,n,`${r}.${o}`,i+1)}}else{const u=t[o];if(typeof u!="object"||u===null)throw new P(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof u}`,`${r}.$`);Uo(u,e,n,`${r}.$`,i)}},_r=(t,e)=>{if(typeof t!="object"||t===null)throw new P(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new P(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const i=Object.keys(e.entities);throw new P(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}br(n[r],r,e,r,0)}}},gr=t=>typeof t!="string"?!1:et(t)?!0:we(t);class Z extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const Tr=t=>t.length>0?t.join(", "):"none",Lo=(t,e)=>new Z(`Entity '${t}' does not exist in schema. Available entities: ${Tr(e)}`),wr={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},Fo=(t,e)=>{var n,r;return t==null?!0:(r=(n=wr[e.valueType])===null||n===void 0?void 0:n.call(wr,t))!==null&&r!==void 0?r:!1},Sr=(t,e)=>{const n=e.entities[t];if(!n)throw Lo(t,Object.keys(e.entities));return n},Kt=(t,e,n)=>{const r=Sr(t,n);if(typeof e!="object"||e===null)throw new Z(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[i,s]of Object.entries(e)){if(i==="id")continue;const o=r.attrs[i];if(o&&!Fo(s,o))throw new Z(`Invalid value for attribute '${i}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof s}`)}},mr=(t,e,n)=>{const r=Sr(t,n);if(typeof e!="object"||e===null)throw new Z(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[i,s]of Object.entries(e)){if(!r.links[i]){const u=Object.keys(r.links);throw new Z(`Link '${i}' does not exist on entity '${t}'. Available links: ${Tr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!gr(u))throw new Z(`Invalid entity ID in link '${i}' for entity '${t}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!gr(s))throw new Z(`Invalid UUID in link '${i}' for entity '${t}'. Expected a UUID, but received: ${s}`)}}},No={create:Kt,update:Kt,merge:Kt,link:mr,unlink:mr,delete:()=>{}},Vo=(t,e)=>{if(!e)return;const[n,r,i,s]=t;if(!Array.isArray(i)&&!we(i))throw new Z(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new Z(`Entity name must be a string, but received: ${typeof r}`);const o=No[n];o&&s!==void 0&&o(r,s,e)},Wo=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new Z(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new Z(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new Z(`Transaction operation must be an array, but received: ${typeof i}`);Vo(i,e)}}};var vr=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};let Or=0;class Er{constructor(e){this.type="ws",this.id=`${this.type}_${Or++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(e){return this.conn.send(JSON.stringify(e))}}class zo{constructor(e,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Or++}`,this.url=n,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const i=JSON.parse(r.data);if(i.op==="sse-init"){this.initParams={machineId:i["machine-id"],sessionId:i["session-id"],sseToken:i["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:i})},this.conn.onerror=r=>{this.handleError()}}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}postMessages(e){return vr(this,void 0,void 0,function*(){try{(yield fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:e})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return vr(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const e=this.sendQueue;this.sendQueue=[];const n=this.postMessages(e);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(e){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(e),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var Ar=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Ko(t,e){for(const n in t){const r=t[n];for(const i of r.entities||[])i.store=In(i.store)}return t}function qo(t){const e={};for(const n in t){const r=t[n];if(r.entities){const i=[];for(const s of r.entities)i.push({store:jn(s.store),entity:s.entity});e[n]=Object.assign(Object.assign({},r),{entities:i})}else e[n]=r}return e}function Bo(t,e){const n={};for(const[r,i]of Object.entries(e))n[r]=i;if(t)for(const[r,i]of Object.entries(t))n[r]=i;return n}function qt(t,e){const n=Object.keys(t.query)[0];return Yn({store:e,pageInfo:null,aggregate:null},t.query).data[n][0]}function Cr(t,e){for(const{action:n,triple:r}of e)switch(n){case"added":Mn(t,r);break;case"removed":Pn(t,r);break}}function Qo(t,e){var n,r,i,s;const o={};for(const{action:u,triple:c}of e){const[d,a,f]=c,h=(r=(n=t.attrs[a])===null||n===void 0?void 0:n["forward-identity"])===null||r===void 0?void 0:r[2];if(!h)continue;const p=(i=o[d])!==null&&i!==void 0?i:{};o[d]=p;const y=(s=p[h])!==null&&s!==void 0?s:{};switch(p[h]=y,u){case"added":y.newValue=f;break;case"removed":y.oldValue===void 0&&(y.oldValue=f);break}}return o}var Ee;(function(t){t.InitialSyncBatch="InitialSyncBatch",t.InitialSyncComplete="InitialSyncComplete",t.LoadFromStorage="LoadFromStorage",t.SyncTransaction="SyncTransaction",t.Error="Error"})(Ee||(Ee={}));class Go{constructor(e,n,r,i,s){this.callbacks={},this.idToHash={},this.trySend=e,this.config=r,this.log=i,this.createStore=s,this.subs=new zt(n,"subs",{},Bo,qo,o=>Ko(o,this.config.useDateObjects))}beforeUnload(){this.subs.flush()}subscribe(e,n){const r=N(e);return this.callbacks[r]=this.callbacks[r]||[],this.callbacks[r].push(n),this.initSubscription(e,r,n),i=>{this.unsubscribe(r,n,i)}}unsubscribe(e,n,r){const i=(this.callbacks[e]||[]).filter(s=>s!==n);if(this.callbacks[e]=i,!i.length){if(delete this.callbacks[e],r)return;const s=this.subs.currentValue[e];s!=null&&s.state&&this.clearSubscriptionData(s.state.subscriptionId),this.subs.set(o=>(delete o[e],o))}}sendStart(e){this.trySend(L(),{op:"start-sync",q:e})}sendResync(e,n){this.idToHash[n.subscriptionId]=e.hash,this.trySend(n.subscriptionId,{op:"resync-table","subscription-id":n.subscriptionId,"tx-id":n.txId,token:n.token})}sendRemove(e){this.trySend(L(),{op:"remove-sync","subscription-id":e.subscriptionId})}initSubscription(e,n,r){return Ar(this,void 0,void 0,function*(){yield this.subs.waitForLoaded();const i=this.subs.currentValue[n];if(i&&i.state&&i.state.txId){this.sendResync(i,i.state),i.entities&&r&&r({type:Ee.LoadFromStorage,data:i.entities.map(s=>s.entity)});return}this.subs.set(s=>(s[n]={query:e,hash:n},s)),this.sendStart(e)})}flushPending(){return Ar(this,void 0,void 0,function*(){yield this.subs.waitForLoaded();for(const e of Object.keys(this.callbacks)){const n=this.subs.currentValue[e];n?yield this.initSubscription(n.query,n.hash):this.log.error("Missing sub for hash in flushPending",e)}})}onStartSyncOk(e){const n=e["subscription-id"],r=e.q,i=N(r);this.idToHash[n]=i,this.subs.set(s=>{const o=s[i];return o?(o.state={subscriptionId:n,token:e.token},s):(this.log.error("Missing sub for hash",i,"subscription-id",n,"query",r),s)})}notifyCbs(e,n){for(const r of this.callbacks[e]||[])r(n)}onSyncLoadBatch(e){const n=e["subscription-id"],r=e["join-rows"],i=this.idToHash[n];if(!i){this.log.error("Missing hash for subscription",e);return}const s=[],u=this.subs.set(c=>{var d;const a=c[i];if(!a)return this.log.error("Missing sub for hash",i,e),c;const f=(d=a.entities)!==null&&d!==void 0?d:[];a.entities=f;for(const h of r){const p=this.createStore(h),y=qt(a,p);f.push({store:p,entity:y}),s.push(y)}return c})[i];u.entities&&this.notifyCbs(i,{type:Ee.InitialSyncBatch,data:u.entities.map(c=>c.entity),batch:s})}onSyncInitFinish(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(i=>{const s=i[r];if(!s)return this.log.error("Missing sub for hash",r,e),i;const o=s.state;return o?(o.txId=e["tx-id"],i):(this.log.error("Sub never set init, missing result",s,e),i)})}onSyncUpdateTriples(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(i=>{var s;const o=i[r];if(!o)return this.log.error("Missing sub for hash",r,e),i;const u=o.state;if(!u)return this.log.error("Missing state for sub",o,e),i;for(const c of e.txes){if(u.txId>=c["tx-id"])continue;u.txId=c["tx-id"];const d=[],a={};for(const _ of c.changes){const T=(s=a[_.triple[0]])!==null&&s!==void 0?s:[];a[_.triple[0]]=T,T.push(_)}const f=o.entities||[];o.entities=f;const h=[];e:for(const[_,T]of Object.entries(a))for(const[g,S]of Object.entries(f))if(xi(S.store,_)){Cr(S.store,T);const m=qt(o,S.store),D=Qo(S.store,T)[_];for(const[O,{oldValue:R,newValue:F}]of Object.entries(D||{}))R===F&&delete D[O];m?(h.push({oldEntity:S.entity,newEntity:m,changedFields:D||{}}),S.entity=m):d.push(g),delete a[_];continue e}const p=[];for(const[_,T]of Object.entries(a)){const g=this.createStore([]);Cr(g,T);const S=qt(o,g);if(!S){this.log.error("No entity found after applying change",{sub:o,changes:T,store:g});continue}f.push({store:g,entity:S}),p.push(S)}const y=[];for(const _ of d.sort().reverse())y.push(f[_].entity),f.splice(_,1);this.notifyCbs(r,{type:Ee.SyncTransaction,data:f.map(_=>_.entity),added:p,removed:y,updated:h})}return i})}clearSubscriptionData(e){const n=this.idToHash[e];if(n){delete this.idToHash[e];const r=this.subs.currentValue[n];if(r.state&&this.sendRemove(r.state),this.subs.set(i=>(delete i[n],i)),r)return r}}onStartSyncError(e){const n=N(e["original-event"].q),r={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa.",status:e.status,type:e.type,hint:e.hint};this.notifyCbs(n,{type:Ee.Error,data:[],error:r})}onResyncError(e){const n=e["original-event"]["subscription-id"],r=this.clearSubscriptionData(n);r&&this.initSubscription(r.query,r.hash)}}var $=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})},Ho=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n};const ae={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Yo=3e4,Jo=3e4,Zo=200,Xo={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},Bt="_instant_oauth_redirect",Qt="currentUser";function eu({transportType:t,appId:e,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new Er(`${r}?app_id=${e}`);switch(t){case"ws":return new Er(`${r}?app_id=${e}`);case"sse":return new zo(i,`${n}/runtime/sse?app_id=${e}`);default:throw new Error("Unknown transport type "+t)}}function tu(){return typeof window<"u"||typeof chrome<"u"}const kr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function nu(t,e){var n;const r=typeof t=="string"?JSON.parse(t):t;for(const i in r){const s=r[i];if(!((n=s==null?void 0:s.result)===null||n===void 0)&&n.store){const o=s.result.store;s.result.store=In(Object.assign(Object.assign({},o),{useDateObjects:e}))}}return r}function ru(t){var e;const n={};for(const r in t){const i=t[r],s=Object.assign({},i);!((e=i.result)===null||e===void 0)&&e.store&&(s.result=Object.assign(Object.assign({},i.result),{store:jn(i.result.store)})),n[r]=s}return n}function jr(t){return[...t].sort((e,n)=>{const[r,i]=e,[s,o]=n,u=i.order||0,c=o.order||0;return u==c?r<s?-1:r>s?1:0:u-c})}class iu{constructor(e,n=nr,r=rr,i,s){var o,u,c;if(this._isOnline=!0,this._isShutdown=!1,this.status=ae.CONNECTING,this.queryCbs={},this.queryOnceDfds={},this.authCbs=[],this.attrsCbs=[],this.mutationErrorCbs=[],this.connectionStatusCbs=[],this.mutationDeferredStore=new Map,this._reconnectTimeoutId=null,this._reconnectTimeoutMs=0,this._transportType="ws",this._wsOk=null,this._localIdPromises={},this._errorMessage=null,this._oauthCallbackResponse=null,this._linkIndex=null,this._rooms={},this._roomsPendingLeave={},this._presence={},this._broadcastQueue=[],this._broadcastSubs={},this._currentUserCached={isLoading:!0,error:void 0,user:void 0},this._beforeUnloadCbs=[],this._dataForQueryCache={},this._inFlightMutationEventIds=new Set,this._onMergeQuerySubs=(d,a)=>{const f=d||{},h=Object.assign({},a);Object.entries(a).forEach(([y,_])=>{var T;const g=(T=f==null?void 0:f[y])===null||T===void 0?void 0:T.result,S=_.result;g&&!S&&(h[y].result=g)}),Object.keys(f).filter(y=>!a[y]).sort((y,_)=>{var T,g;const S=((T=f[y])===null||T===void 0?void 0:T.lastAccessed)||0;return(((g=f[_])===null||g===void 0?void 0:g.lastAccessed)||0)-S}).slice(0,this.queryCacheLimit).forEach(y=>{h[y]=f[y]}),this.querySubs.set(y=>h),this.loadedNotifyAll()},this._onMergePendingMutations=(d,a)=>{const f=new Map([...d.entries(),...a.entries()]);this.pendingMutations.set(p=>f),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,d).forEach(([p,y])=>{!a.has(p)&&!y["tx-id"]&&this._sendMutation(p,y)})},this.getPreviousResult=d=>{const a=N(d);return this.dataForQuery(a)},this.notifyOne=d=>{var a,f;const h=(a=this.queryCbs[d])!==null&&a!==void 0?a:[],p=(f=this._dataForQueryCache[d])===null||f===void 0?void 0:f.data,y=this.dataForQuery(d);y&&(Ge(y,p)||h.forEach(_=>_.cb(y)))},this.notifyOneQueryOnce=d=>{var a;const f=(a=this.queryOnceDfds[d])!==null&&a!==void 0?a:[],h=this.dataForQuery(d);f.forEach(p=>{this._completeQueryOnce(p.q,d,p.dfd),p.dfd.resolve(h)})},this.notifyQueryError=(d,a)=>{(this.queryCbs[d]||[]).forEach(h=>h.cb({error:a}))},this.pushTx=d=>{this.config.disableValidation||Wo(d,this.config.schema);try{const a=bo({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(f=>{var h;return(h=f==null?void 0:f.result)===null||h===void 0?void 0:h.store}),useDateObjects:this.config.useDateObjects},d);return this.pushOps(a)}catch(a){return this.pushOps([],a)}},this.pushOps=(d,a)=>{const f=L(),h=[...this.pendingMutations.currentValue.values()],p=Math.max(0,...h.map(T=>T.order||0))+1,y={op:"transact","tx-steps":d,created:Date.now(),error:a,order:p};this.pendingMutations.set(T=>(T.set(f,y),T));const _=new ar;return this.mutationDeferredStore.set(f,_),this._sendMutation(f,y),this.notifyAll(),_.promise},this._transportOnOpen=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][open]",a.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(ae.OPENED),this.getCurrentUser().then(f=>{var h;this._trySend(L(),{op:"init","app-id":this.config.appId,"refresh-token":(h=f.user)===null||h===void 0?void 0:h.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(f=>{this._log.error("[socket][error]",a.id,f)})},this._transportOnMessage=d=>{const a=d.target,f=d.message;if(this._transport!==a){this._log.info("[socket][message]",a.id,f,"skip; this is no longer the current transport");return}!this._wsOk&&a.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(a.id,d.message)},this._transportOnError=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][error]",a.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",a.id,d)},this._scheduleReconnect=()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)},this._transportOnClose=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][close]",a.id,"skip; this is no longer the current transport");return}this._setStatus(ae.CLOSED);for(const f of Object.values(this._rooms))f.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",a.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",a.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()},this._EventSource=s,this.config=Object.assign(Object.assign({},Xo),e),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._pendingTxCleanupTimeout=(u=this.config.pendingTxCleanupTimeout)!==null&&u!==void 0?u:Jo,this._pendingMutationCleanupThreshold=(c=this.config.pendingMutationCleanupThreshold)!==null&&c!==void 0?c:Zo,this._log=Mo(e.verbose||Wt||sr,()=>this._reactorStats()),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":lr}),this.config.schema&&(this._linkIndex=fr(this.config.schema)),!!tu()){if(!e.appId)throw new Error("Instant must be initialized with an appId.");if(!we(e.appId))throw new Error(`Instant must be initialized with a valid appId. \`${e.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",d=>$(this,void 0,void 0,function*(){var a;try{if(((a=d.data)===null||a===void 0?void 0:a.type)==="auth"){const f=yield this.getCurrentUser();this.updateUser(f.user)}}catch(f){this._log.error("[error] handle broadcast channel",f)}}))),this._initStorage(n),this._syncTable=new Go(this._trySendAuthed.bind(this),this._persister,{useDateObjects:this.config.useDateObjects},this._log,d=>Ye(this.attrs,d,this.config.enableCardinalityInference,this._linkIndex,this.config.useDateObjects)),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(d=>{this._isOnline=d,this._startSocket(),r.listen(a=>{a!==this._isOnline&&(this._log.info("[network] online =",a),this._isOnline=a,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",ae.CLOSED),this._setStatus(ae.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(e){this.config=Object.assign(Object.assign({},this.config),{schema:e,cardinalityInference:!!e}),this._linkIndex=e?fr(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(e){this._persister=new e(`instant_${this.config.appId}_5`),this.querySubs=new zt(this._persister,"querySubs",{},this._onMergeQuerySubs,ru,n=>nu(n,this.config.useDateObjects)),this.pendingMutations=new zt(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const e of this._beforeUnloadCbs)e();this._syncTable.beforeUnload()}_finishTransaction(e,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=e!=="error"&&e!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:e,eventId:n},r)),!!i)if(s)i.resolve({status:e,eventId:n});else if(r.type){const{status:o}=r,u=Ho(r,["status"]);i.reject(new nt({body:u,status:o}))}else i.reject(new me(r.message,r.hint))}_setStatus(e,n){this.status=e,this._errorMessage=n,this.notifyConnectionStatusSubs(e)}_flushEnqueuedRoomData(e){var n,r;const i=(r=(n=this._presence[e])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[e];if(this._broadcastQueue[e]=[],i&&this._trySetPresence(e,i),s)for(const o of s){const{topic:u,roomType:c,data:d}=o;this._tryBroadcast(e,c,u,d)}}_handleReceive(e,n){var r,i,s,o,u,c;const d=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(kr[n.op]||this._log.info("[receive]",e,n.op,n),n.op){case"init-ok":{this._setStatus(ae.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const h of Object.keys(this._rooms)){const p=(i=(r=this._presence[h])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(h,p)}break}case"add-query-exists":{this.notifyOneQueryOnce(N(n.q));break}case"add-query-ok":{const{q:h,result:p}=n,y=N(h),_=(o=(s=p==null?void 0:p[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],T=(c=(u=p==null?void 0:p[0])===null||u===void 0?void 0:u.data)===null||c===void 0?void 0:c.aggregate,g=dr(p),S=Ye(this.attrs,g,d,this._linkIndex,this.config.useDateObjects);this.querySubs.set(m=>(m[y].result={store:S,pageInfo:_,aggregate:T,processedTxId:n["processed-tx-id"]},m)),this._cleanupPendingMutationsQueries(),this.notifyOne(y),this.notifyOneQueryOnce(y),this._cleanupPendingMutationsTimeout();break}case"start-sync-ok":{this._syncTable.onStartSyncOk(n);break}case"sync-load-batch":{this._syncTable.onSyncLoadBatch(n);break}case"sync-init-finish":{this._syncTable.onSyncInitFinish(n);break}case"sync-update-triples":{this._syncTable.onSyncUpdateTriples(n);break}case"refresh-ok":{const{computations:h,attrs:p}=n,y=n["processed-tx-id"];p&&this._setAttrs(p),this._cleanupPendingMutationsTimeout();const _=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,y);_!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>_);const T=jr(_.entries()),g=h.map(S=>{var m,D,O,R;const F=S["instaql-query"],K=S["instaql-result"],Ne=N(F),it=dr(K),Jt=Ye(this.attrs,it,d,this._linkIndex,this.config.useDateObjects),Zt=this._applyOptimisticUpdates(Jt,T,y),st=(D=(m=K==null?void 0:K[0])===null||m===void 0?void 0:m.data)===null||D===void 0?void 0:D["page-info"],ie=(R=(O=K==null?void 0:K[0])===null||O===void 0?void 0:O.data)===null||R===void 0?void 0:R.aggregate;return{hash:Ne,store:Zt,pageInfo:st,aggregate:ie}});g.forEach(({hash:S,store:m,pageInfo:D,aggregate:O})=>{this.querySubs.set(R=>(R[S].result={store:m,pageInfo:D,aggregate:O,processedTxId:y},R))}),this._cleanupPendingMutationsQueries(),g.forEach(({hash:S})=>{this.notifyOne(S)});break}case"transact-ok":{const{"client-event-id":h,"tx-id":p}=n;this._inFlightMutationEventIds.delete(h);const _=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(h);if(!_)break;this.pendingMutations.set(g=>(g.set(h,Object.assign(Object.assign({},g.get(h)),{"tx-id":p,confirmed:Date.now()})),g));const T=_["tx-steps"].filter(([g,...S])=>g==="add-attr").map(([g,S])=>S).concat(Object.values(this.attrs));this._setAttrs(T),this._finishTransaction("synced",h),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const h=n["room-id"];this._trySetRoomConnected(h,!0),this._patchPresencePeers(h,n.edits),this._notifyPresenceSubs(h);break}case"refresh-presence":{const h=n["room-id"];this._trySetRoomConnected(h,!0),this._setPresencePeers(h,n.data),this._notifyPresenceSubs(h);break}case"server-broadcast":{const h=n["room-id"],p=n.topic;this._trySetRoomConnected(h,!0),this._notifyBroadcastSubs(h,p,n);break}case"join-room-ok":{const h=n["room-id"];if(!this._rooms[h]){this._roomsPendingLeave[h]&&(this._tryLeaveRoom(h),delete this._roomsPendingLeave[h]);break}this._trySetRoomConnected(h,!0),this._flushEnqueuedRoomData(h);break}case"leave-room-ok":{const h=n["room-id"];this._trySetRoomConnected(h,!1);break}case"join-room-error":const a=n["room-id"],f=this._rooms[a];f&&(f.error=n.error),this._notifyPresenceSubs(a);break;case"error":this._handleReceiveError(n);break;default:this._log.info("Uknown op",n.op,n);break}}_handleMutationError(e,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(e!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(e,n,r)}}_handleReceiveError(e){var n,r,i,s,o,u,c;console.log("error",e);const d=e["client-event-id"];this._inFlightMutationEventIds.delete(d);const a=this.pendingMutations.currentValue.get(d),f={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(e.hint&&(f.hint=e.hint),a){this._handleMutationError("error",d,e);return}if(!((n=e["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=e["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const y=(i=e["original-event"])===null||i===void 0?void 0:i.q,_=N(y);this.notifyQueryError(N(y),f),this.notifyQueryOnceError(y,_,d,f);return}if(((s=e["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(e.type==="record-not-found"&&((o=e.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(ae.ERRORED,f),this.notifyAll();return}if(((u=e["original-event"])===null||u===void 0?void 0:u.op)==="resync-table"){this._syncTable.onResyncError(e);return}if(((c=e["original-event"])===null||c===void 0?void 0:c.op)==="start-sync"){this._syncTable.onStartSyncError(e);return}const p=Object.assign({},e);delete p.message,delete p.hint,console.error(e.message,p),e.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
30
|
+
<%s key={someKey} {...props} />`,un,be,sa,be),Xr[be+un]=!0}}return l===i?ea(U):Xu(U),U}}function ta(l,b,w){return ei(l,b,w,!0)}function na(l,b,w){return ei(l,b,w,!1)}var ra=na,ia=ta;je.Fragment=i,je.jsx=ra,je.jsxs=ia}(),je}var ri={};ri.NODE_ENV==="production"?dt.exports=ti():dt.exports=ni();var ze=dt.exports;function N(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=N(t[n]);for(let i=0;i<r.length;i++)e^=r.charCodeAt(i),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const i=n[r],s=N(i);e^=parseInt(s,16),e*=16777619,e=e>>>0;const o=N(t[i]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return N(String(t))}const M={Remove:"remove",Replace:"replace",Add:"add"},dn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),ii=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Ke=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ft={};function Ie(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function fn(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function lt(t){return Object.getPrototypeOf(t)===Set.prototype}function ht(t){return Object.getPrototypeOf(t)===Map.prototype}function J(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function de(t){return!!E(t)}function E(t){return typeof t!="object"?null:t==null?void 0:t[dn]}function pt(t){var e;const n=E(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function ee(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!(e!=null&&e.mark)&&((n=e.mark(t,Y))===Y.immutable||typeof n=="function")}function ln(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=E(se(n,t.key));if(r!==null&&(r==null?void 0:r.original)!==t.original)return null;const i=t.parent.type===3,s=i?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(i&&n.size>s||Ie(n,s)))return null;e.push(s)}if(t.parent)return ln(t.parent,e);e.reverse();try{si(t.copy,e)}catch{return null}return e}function fe(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function se(t,e){return fe(t)===2?t.get(e):t[e]}function Pe(t,e,n){fe(t)===2?t.set(e,n):t[e]=n}function yt(t,e){const n=E(t);return(n?J(n):t)[e]}function oe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function bt(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function le(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function si(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=se(fe(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function oi(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const ui=Object.prototype.propertyIsEnumerable;function hn(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!lt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!ht(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e!=null&&e.mark&&(n=e.mark(t,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return oi(t);if(typeof n=="function"){if(e.enablePatches||e.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(i=>{r[i]=t[i]}),Object.getOwnPropertySymbols(t).forEach(i=>{ui.call(t,i)&&(r[i]=t[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function z(t){t.copy||(t.copy=hn(t.original,t.options))}function Re(t){if(!ee(t))return pt(t);if(Array.isArray(t))return t.map(Re);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,i])=>[r,Re(i)]);if(!ht(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(Re);if(!lt(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=Re(t[n]);return e}function qe(t){return de(t)?Re(t):t}function re(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&re(t.parent))}function pn(){throw new Error("Cannot modify frozen object")}function _e(t,e,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const u=r.indexOf(o);if(o&&typeof o=="object"&&u!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${i.slice(0,u).map((c,d)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const a=r[d];return typeof c=="object"&&(a instanceof Map||a instanceof Set)?Array.from(a.keys()).indexOf(c):c}).join("/")}`);r.push(o),i.push(e)}else r.push(o)}if(Object.isFrozen(t)||de(t)){r.pop(),i.pop();return}switch(fe(t)){case 2:for(const[u,c]of t)_e(u,u,n,r,i),_e(c,u,n,r,i);t.set=t.clear=t.delete=pn;break;case 3:for(const u of t)_e(u,u,n,r,i);t.add=t.clear=t.delete=pn;break;case 1:Object.freeze(t);let o=0;for(const u of t)_e(u,o,n,r,i),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(u=>{const c=t[u];_e(c,u,n,r,i)})}r.pop(),i.pop()}function _t(t,e){const n=fe(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const i of t)e(r,i,t),r+=1}else t.forEach((r,i)=>e(i,r,t))}function yn(t,e,n){if(de(t)||!ee(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,i=r?new Map:void 0;if(e.add(t),_t(t,(s,o)=>{var u;if(de(o)){const c=E(o);z(c);const d=!((u=c.assignedMap)===null||u===void 0)&&u.size||c.operated?c.copy:c.original;Pe(r?i:t,s,d)}else yn(o,e,n)}),i){const s=t,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ai(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&yn(se(n,e),t.finalities.handledSet,t.options)}function gt(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(pt(e))}))}function Tt(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const s=ln(t);s&&e(t,s,n,r)}t.finalized=!0}}function wt(t,e,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const c=t.type===3?t.setMap:t.copy;if(oe(se(c,e),n)){let d=i.original;i.copy&&(d=i.copy),gt(t),Tt(t,r,s,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(u=t.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,t.options.updatedValues.set(d,i.original)),Pe(c,e,d)}}),t.options.enableAutoFreeze&&i.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),ee(n,t.options)&&t.finalities.draft.push(()=>{const s=t.type===3?t.setMap:t.copy;oe(se(s,e),n)&&ai(t,e)})}function ci(t,e,n,r,i){let{original:s,assignedMap:o,options:u}=t,c=t.copy;c.length<s.length&&([s,c]=[c,s],[n,r]=[r,n]);for(let d=0;d<s.length;d+=1)if(o.get(d.toString())&&c[d]!==s[d]){const a=e.concat([d]),f=le(a,i);n.push({op:M.Replace,path:f,value:qe(c[d])}),r.push({op:M.Replace,path:f,value:qe(s[d])})}for(let d=s.length;d<c.length;d+=1){const a=e.concat([d]),f=le(a,i);n.push({op:M.Add,path:f,value:qe(c[d])})}if(s.length<c.length){const{arrayLengthAssignment:d=!0}=u.enablePatches;if(d){const a=e.concat(["length"]),f=le(a,i);r.push({op:M.Replace,path:f,value:s.length})}else for(let a=c.length;s.length<a;a-=1){const f=e.concat([a-1]),h=le(f,i);r.push({op:M.Remove,path:h})}}}function di({original:t,copy:e,assignedMap:n},r,i,s,o){n.forEach((u,c)=>{const d=se(t,c),a=qe(se(e,c)),f=u?Ie(t,c)?M.Replace:M.Add:M.Remove;if(oe(d,a)&&f===M.Replace)return;const h=r.concat(c),p=le(h,o);i.push(f===M.Remove?{op:f,path:p}:{op:f,path:p,value:a}),s.push(f===M.Add?{op:M.Remove,path:p}:f===M.Remove?{op:M.Add,path:p,value:d}:{op:M.Replace,path:p,value:d})})}function fi({original:t,copy:e},n,r,i,s){let o=0;t.forEach(u=>{if(!e.has(u)){const c=n.concat([o]),d=le(c,s);r.push({op:M.Remove,path:d,value:u}),i.unshift({op:M.Add,path:d,value:u})}o+=1}),o=0,e.forEach(u=>{if(!t.has(u)){const c=n.concat([o]),d=le(c,s);r.push({op:M.Add,path:d,value:u}),i.unshift({op:M.Remove,path:d,value:u})}o+=1})}function Me(t,e,n,r){const{pathAsArray:i=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return di(t,e,n,r,i);case 1:return ci(t,e,n,r,i);case 3:return fi(t,e,n,r,i)}}const Be=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!ee(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},St={get size(){return J(E(this)).size},has(t){return J(E(this)).has(t)},set(t,e){const n=E(this),r=J(n);return(!r.has(t)||!oe(r.get(t),e))&&(z(n),re(n),n.assignedMap.set(t,!0),n.copy.set(t,e),wt(n,t,e,Me)),this},delete(t){if(!this.has(t))return!1;const e=E(this);return z(e),re(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=E(this);if(this.size){z(t),re(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=E(this);J(n).forEach((r,i)=>{t.call(e,this.get(i),i,this)})},get(t){var e,n;const r=E(this),i=J(r).get(t),s=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,i,Y))===Y.mutable;if(r.options.strict&&Be(i,r.options,s),s||r.finalized||!ee(i,r.options)||i!==r.original.get(t))return i;const o=ft.createDraft({original:i,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return z(r),r.copy.set(t,o),o},keys(){return J(E(this)).keys()},values(){const t=this.keys();return{[Ke]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[Ke]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[Ke](){return this.entries()}},li=Reflect.ownKeys(St),bn=(t,e,{isValuesIterator:n})=>()=>{var r,i;const s=e.next();if(s.done)return s;const o=s.value;let u=t.setMap.get(o);const c=E(u),d=((i=(r=t.options).mark)===null||i===void 0?void 0:i.call(r,u,Y))===Y.mutable;if(t.options.strict&&Be(o,t.options,d),!d&&!c&&ee(o,t.options)&&!t.finalized&&t.original.has(o)){const a=ft.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,a),u=a}else c&&(u=c.proxy);return{done:!1,value:n?u:[u,u]}},Qe={get size(){return E(this).setMap.size},has(t){const e=E(this);if(e.setMap.has(t))return!0;z(e);const n=E(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=E(this);return this.has(t)||(z(e),re(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),wt(e,t,t,Me)),this},delete(t){if(!this.has(t))return!1;const e=E(this);z(e),re(e);const n=E(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=E(this);z(t),re(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=E(this);z(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:bn(t,e,{isValuesIterator:!0})}},entries(){const t=E(this);z(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:bn(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[Ke](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(Qe,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const hi=Reflect.ownKeys(Qe),_n=new WeakSet,gn={get(t,e,n){var r,i;const s=(r=t.copy)===null||r===void 0?void 0:r[e];if(s&&_n.has(s))return s;if(e===dn)return t;let o;if(t.options.mark){const d=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(d,Y),o===Y.mutable)return t.options.strict&&Be(d,t.options,!0),d}const u=J(t);if(u instanceof Map&&li.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(St,"size").get.call(t.proxy);const d=St[e];if(d)return d.bind(t.proxy)}if(u instanceof Set&&hi.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Qe,"size").get.call(t.proxy);const d=Qe[e];if(d)return d.bind(t.proxy)}if(!Ie(u,e)){const d=fn(u,e);return d?"value"in d?d.value:(i=d.get)===null||i===void 0?void 0:i.call(t.proxy):void 0}const c=u[e];if(t.options.strict&&Be(c,t.options),t.finalized||!ee(c,t.options))return c;if(c===yt(t.original,e)){if(z(t),t.copy[e]=mt({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const d=E(t.copy[e]);return z(d),re(d),d.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(t.type===1&&e!=="length"&&!(Number.isInteger(i=Number(e))&&i>=0&&(e===0||i===0||String(i)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const s=fn(J(t),e);if(s!=null&&s.set)return s.set.call(t.proxy,n),!0;const o=yt(J(t),e),u=E(o);return u&&oe(u.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(oe(n,o)&&(n!==void 0||Ie(t.original,e))||(z(t),re(t),Ie(t.original,e)&&oe(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,wt(t,e,n,Me)),!0)},has(t,e){return e in J(t)},ownKeys(t){return Reflect.ownKeys(J(t))},getOwnPropertyDescriptor(t,e){const n=J(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?gn.set.call(this,t,e,void 0,t.proxy):(yt(t.original,e)!==void 0||e in t.original?(z(t),re(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function mt(t){const{original:e,parentDraft:n,key:r,finalities:i,options:s}=t,o=fe(e),u={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(u.key=r);const{proxy:c,revoke:d}=Proxy.revocable(o===1?Object.assign([],u):u,gn);if(i.revoke.push(d),_n.add(c),u.proxy=c,n){const a=n;a.finalities.draft.push((f,h)=>{var p,y;const _=E(c);let T=a.type===3?a.setMap:a.copy;const g=se(T,r),S=E(g);if(S){let m=S.original;S.operated&&(m=pt(g)),gt(S),Tt(S,Me,f,h),a.options.enableAutoFreeze&&(a.options.updatedValues=(p=a.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,a.options.updatedValues.set(m,S.original)),Pe(T,r,m)}(y=_.callbacks)===null||y===void 0||y.forEach(m=>{m(f,h)})})}else{const a=E(c);a.finalities.draft.push((f,h)=>{gt(a),Tt(a,Me,f,h)})}return c}ft.createDraft=mt;function pi(t,e,n,r,i){var s;const o=E(t),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:t,c=!!e.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const d=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&bt(o),i&&_e(d,d,o==null?void 0:o.options.updatedValues),[d,n&&c?[{op:M.Replace,path:[],value:e[0]}]:n,r&&c?[{op:M.Replace,path:[],value:u}]:r]}function yi(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;e.enablePatches&&(i=[],s=[]);const u=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,Y))===Y.mutable||!ee(t,e)?t:mt({original:t,parentDraft:null,finalities:r,options:e});return[u,(c=[])=>{const[d,a,f]=pi(u,c,i,s,e.enableAutoFreeze);return e.enablePatches?[d,a,f]:d}]}function vt(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:i=!0}=t;_t(n,(s,o,u)=>{const c=E(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const d=c.original;if(u instanceof Set){const a=Array.from(u);u.clear(),a.forEach(f=>u.add(s===f?d:f))}else Pe(u,s,d)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,vt(t))}),i&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function Tn(t){var e;const n=E(t);if(!ee(t,n==null?void 0:n.options))return t;const r=fe(t);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?ht(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):hn(t,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=t;if(_t(i,(o,u)=>{if(n&&oe(se(n.original,o),u))return;const c=Tn(u);c!==u&&(i===t&&s(),Pe(i,o,c))}),r===3){const o=(e=n==null?void 0:n.original)!==null&&e!==void 0?e:i;return lt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function wn(t){if(!de(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return Tn(t)}const Ot=(t=>function e(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...R){return e(O,F=>n.call(this,F,...R),r)};const c=n,d=r;let a=i;if(typeof r!="function"&&(a=r),a!==void 0&&Object.prototype.toString.call(a)!=="[object Object]")throw new Error(`Invalid options: ${a}, 'options' should be an object.`);a=Object.assign(Object.assign({},t),a);const f=de(c)?wn(c):c,h=Array.isArray(a.mark)?(O,R)=>{for(const F of a.mark){if(typeof F!="function")throw new Error(`Invalid mark: ${F}, 'mark' should be a function.`);const K=F(O,R);if(K)return K}}:a.mark,p=(s=a.enablePatches)!==null&&s!==void 0?s:!1,y=(o=a.strict)!==null&&o!==void 0?o:!1,T={enableAutoFreeze:(u=a.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:y,enablePatches:p};if(!ee(f,T)&&typeof f=="object"&&f!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[g,S]=yi(f,T);if(typeof r!="function"){if(!ee(f,T))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[g,S]}let m;try{m=d(g)}catch(O){throw bt(E(g)),O}const D=O=>{const R=E(g);if(!de(O)){if(O!==void 0&&!oe(O,g)&&(R!=null&&R.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const K=O==null?void 0:O[ii];if(K){const Ne=K[0];return T.strict&&typeof O=="object"&&O!==null&&vt({rootDraft:R,value:O,useRawReturn:!0}),S([Ne])}if(O!==void 0)return typeof O=="object"&&O!==null&&vt({rootDraft:R,value:O}),S([O])}if(O===g||O===void 0)return S([]);const F=E(O);if(T===F.options){if(F.operated)throw new Error("Cannot return a modified child draft.");return S([wn(O)])}return S([O])};return m instanceof Promise?m.then(D,O=>{throw bt(E(g)),O}):D(m)})();Object.prototype.constructor.toString();function Sn(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&Object.keys(t).every(i=>e.hasOwnProperty(i))}function mn(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>e.hasOwnProperty(n)&&t[n]===e[n])}function Ge(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:Sn(t,e)?Object.keys(t).every(n=>Ge(t[n],e[n])):!1}function Et(t){if(!De(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function vn(t,e){if(!De(t)||!De(e))return e;const n=Object.assign({},t);for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const i=De(t[r])&&De(e[r]);n[r]=i?vn(t[r],e[r]):e[r]}return n}function De(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bi(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const o=e[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[s+1]=="number"?[]:{}),r=r[o]}const i=e[e.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function On(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const s=e[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof e[i+1]=="number"?[]:{}),r=r[s]}r[e[e.length-1]]=n}function En(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}En(t[n],r),_i(t[n])&&delete t[n]}}function _i(t){return t&&Object.keys(t).length===0}const An=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,gi={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function Ti(t){return new Date(t)}function wi(t){return new Date(t+"Z")}const Si=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function mi(t){const e=t.match(Si);if(!e)return null;const[n,r,i,s]=e;return r<=0||i<=0||s<=0?null:r>999?new Date(Date.UTC(r,i-1,s,0,0,0,0)):new Date(Date.UTC(s,r-1,i,0,0,0,0))}function vi(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function Oi(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function Ei(t){return new Date(t)}function Ai(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function Ci(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function ki(t){const[e,n]=t.split(", "),[r,i,s]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,u,c,d,a]=o;return u=Number(u),c=Number(c),d=Number(d),a==="PM"&&u!==12?u+=12:a==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,c,d))}function ji(t){switch(t){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function Ii(t){const e=t.match(An);if(!e)return null;const[n]=e,r=gi[n],i=new Date(t.replace(An,"Z"));return new Date(i.getTime()-r*1e3)}const Pi=[mi,Oi,Ai,ki,Ei,wi,Ci,vi,Ti,ji,Ii];function Ri(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function At(t){for(const e of Pi){const n=Ri(e,t);if(n)return n}return null}function Mi(t){try{const e=JSON.parse(t);return typeof e=="string"?At(e):null}catch{return null}}function He(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=At(t)||Mi(t)||At(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}function Di(t){return t.cardinality==="one"}function Ct(t){return t["value-type"]==="ref"}function kt(t){return t["value-type"]==="blob"}function ge(t,e){return t[e]}function xe(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function te(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&te(t.get(n),r)}function B(t,e,n){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.set(e[0],n);return}const[r,...i]=e;let s=t.get(r);s||(s=new Map,t.set(r,s)),B(s,i,n)}function Cn(t,e,n){const r=new Map,i=new Map,s=new Map;for(const o of e){let[u,c,d,a]=o;const f=ge(t,c);if(!f){console.warn("no such attr",u,t);continue}f["checked-data-type"]==="date"&&n&&(d=He(d),o[2]=d),Ct(f)&&B(s,[d,c,u],o),B(r,[u,c,d],o),B(i,[c,u,d],o)}return{eav:r,aev:i,vae:s}}function kn(t){const e=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(t)){const o=s["forward-identity"],[u,c,d]=o,a=s["reverse-identity"];if(B(r,[c,d],s),kt(s)&&B(e,[c,d],s),s["primary?"]&&B(n,[c],s),a){const[f,h,p]=a;B(i,[h,p],s)}}return{blobAttrs:e,primaryKeys:n,forwardIdents:r,revIdents:i}}function jn(t){return{__type:t.__type,attrs:t.attrs,triples:Q(t.eav,3),cardinalityInference:t.cardinalityInference,linkIndex:t.linkIndex,useDateObjects:t.useDateObjects}}function In(t){return Ye(t.attrs,t.triples,t.cardinalityInference,t.linkIndex,t.useDateObjects)}function xi(t,e){return xe(t.eav,[e])!==void 0}function jt(t){t.attrIndexes=kn(t.attrs)}function Ye(t,e,n,r,i){const s=Cn(t,e,i);return s.useDateObjects=i,s.attrs=t,s.attrIndexes=kn(t),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function $e(t,e){var n,r;let i;if(Array.isArray(e[0])){const[o,u]=e[0],c=t.aev.get(o);if(!c)return null;i=(n=Q(c,2).find(a=>a[2]===u))===null||n===void 0?void 0:n[0]}else i=e[0];if(!i)return null;const s=e[2];if(Array.isArray(s)&&s.length===2&&t.aev.get(s[0])){const[o,u]=s,c=t.aev.get(o);if(!c)return null;const a=(r=Q(c,2).find(_=>_[2]===u))===null||r===void 0?void 0:r[0];if(!a)return null;const[f,h,p,...y]=e;return[i,h,a,...y]}else{const[o,...u]=e;return[i,...u]}}function Pn(t,e){const n=$e(t,e);if(!n)return;const[r,i,s]=n,o=ge(t.attrs,i);o&&(te(t.eav,[r,i,s]),te(t.aev,[i,r,s]),Ct(o)&&te(t.vae,[s,i,r]))}let $i=0;function Rn(t,e,n){const[r,i,s]=n;let o;const u=xe(t.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+$i++}function Mn(t,e){var n;const r=$e(t,e);if(!r)return;let[i,s,o]=r;const u=ge(t.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&t.useDateObjects&&(o=He(o));const c=xe(t.eav,[i,s,o]),d=(n=c==null?void 0:c[3])!==null&&n!==void 0?n:Rn(t,u,r),a=[i,s,o,d];Di(u)?(B(t.eav,[i,s],new Map([[o,a]])),B(t.aev,[s,i],new Map([[o,a]]))):(B(t.eav,[i,s,o],a),B(t.aev,[s,i,o],a)),Ct(u)&&B(t.vae,[o,s,i],a)}function Ui(t,e){var n;const r=$e(t,e);if(!r)return;const[i,s,o]=r,u=ge(t.attrs,s);if(!u)return;if(!kt(u))throw new Error("merge operation is not supported for links");const c=xe(t.eav,[i,s]);if(!c)return;const d=(n=c.values().next())===null||n===void 0?void 0:n.value;if(!d)return;const a=d[2],f=vn(a,o),h=[i,s,f,Rn(t,u,d)];B(t.eav,[i,s],new Map([[f,h]]))}function It(t,e){var n,r;const[i,s]=e,o=$e(t,[i]);if(!o)return;const[u]=o,c=t.eav.get(u);if(c){for(const a of c.keys()){const f=t.attrs[a];f&&f["on-delete-reverse"]==="cascade"&&Q(c.get(a),1).forEach(([h,p,y])=>{var _;return It(t,[y,(_=f["reverse-identity"])===null||_===void 0?void 0:_[1]])}),(!s||!f||((n=f["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(te(t.aev,[a,u]),te(t.eav,[u,a]))}c.size===0&&te(t.eav,[u])}const d=t.vae.get(u)&&Q(t.vae.get(u),2);d&&d.forEach(a=>{var f,h,p;const[y,_,T]=a,g=t.attrs[_];(!s||!g||((f=g["reverse-identity"])===null||f===void 0?void 0:f[1])===s)&&(te(t.eav,[y,_,T]),te(t.aev,[_,y,T]),te(t.vae,[T,_,y])),g&&g["on-delete"]==="cascade"&&((h=g["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&It(t,[y,(p=g["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=t.vae.get(u))===null||r===void 0?void 0:r.size)===0&&te(t.vae,[u])}function Dn(t,e){const n=Cn(t.attrs,e,t.useDateObjects);Object.keys(n).forEach(r=>{t[r]=n[r]})}function Li(t,[e]){t.attrs[e.id]=e,jt(t)}function xn(t){return Q(t.eav,3)}function Fi(t,[e]){if(!t.attrs[e])return;const n=xn(t).filter(([r,i])=>i!==e);delete t.attrs[e],jt(t),Dn(t,n)}function Ni(t,[e]){const n=t.attrs[e.id];n&&(t.attrs[e.id]=Object.assign(Object.assign({},n),e),jt(t),Dn(t,xn(t)))}function Vi(t,e){const[n,...r]=e;switch(n){case"add-triple":Mn(t,r);break;case"deep-merge-triple":Ui(t,r);break;case"retract-triple":Pn(t,r);break;case"delete-entity":It(t,r);break;case"add-attr":Li(t,r);break;case"delete-attr":Fi(t,r);break;case"update-attr":Ni(t,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function Q(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())Q(r,e-1,n);return n}function Je(t,e,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of e.keys())n.$not!==u&&s.push(e.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:c,reverse:d}=n.$isNull;if(d)for(const a of e.keys()){const f=t.vae.get(a),h=!f||((r=f.get(u))===null||r===void 0?void 0:r.get(null))||!f.get(u);(c?h:!h)&&s.push(e.get(a))}else{const a=t.aev.get(u);for(const f of e.keys()){const h=!a||((i=a.get(f))===null||i===void 0?void 0:i.get(null))||!a.get(f);(c?h:!h)&&s.push(e.get(f))}}return s}if(n!=null&&n.$comparator)return Q(e,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const c=e.get(u);c&&s.push(c)}return s}function Wi(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function zi(t,[e,n,r]){var i,s;switch(Wi(e,n,r)){case"e":{const u=t.eav.get(e);return Q(u,2)}case"ea":{const u=(i=t.eav.get(e))===null||i===void 0?void 0:i.get(n);return Q(u,1)}case"eav":{const u=(s=t.eav.get(e))===null||s===void 0?void 0:s.get(n);return u?Je(t,u,r):[]}case"ev":{const u=t.eav.get(e);if(!u)return[];const c=[];for(const d of u.values())c.push(...Je(t,d,r));return c}case"a":{const u=t.aev.get(n);return Q(u,2)}case"av":{const u=t.aev.get(n);if(!u)return[];const c=[];for(const d of u.values())c.push(...Je(t,d,r));return c}case"v":{const u=[];for(const c of t.eav.values())for(const d of c.values())u.push(...Je(t,d,r));return u}default:return Q(t.eav,3)}}function Ki(t,e,n){var r;const i={};for(const[s,o]of e.entries()){const u=(r=t.eav.get(n))===null||r===void 0?void 0:r.get(o.id),c=Q(u,1);for(const d of c)i[s]=d[2]}return i}function Te(t,e,n){var r;return(r=t.attrIndexes.forwardIdents.get(e))===null||r===void 0?void 0:r.get(n)}function $n(t,e,n){var r;return(r=t.attrIndexes.revIdents.get(e))===null||r===void 0?void 0:r.get(n)}function qi(t,e){return t.attrIndexes.blobAttrs.get(e)}function Un(t,e){var n;const r=t.attrIndexes.primaryKeys.get(e);return r||((n=t.attrIndexes.forwardIdents.get(e))===null||n===void 0?void 0:n.get("id"))}function Bi(t,e){const n=$e(t,e);if(!n)return;const[r,i,s]=n;if(ge(t.attrs,i))return xe(t.eav,[r,i])}function Qi(t,e){const n=e.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const c=u==null?void 0:u.mode;if(c!=="create"&&c!=="update")return!0;let d=!1;const a=ge(t.attrs,s);if(a){const f=Un(t,a["forward-identity"][1]);d=!!Bi(t,[i,f.id,i])}return!(c==="create"&&d||c==="update"&&!d)});return Ot(t,r=>{n.forEach(i=>{Vi(r,i)})})}function Gi(t){return typeof t=="string"&&t.startsWith("?")}function Hi(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return Fn(r,e,n)}return Object.assign(Object.assign({},n),{[t]:e})}function Ln(t,e,n){return t===e?n:null}function Yi(t){switch(typeof t){case"string":return t.startsWith("?")?Hi:Ln;default:return Ln}}const Ji=["in","$in","$not","$isNull","$comparator"];function Zi(t){for(const e of Ji)if(t.hasOwnProperty(e))return!0;return!1}function Fn(t,e,n){return n?typeof t=="object"?Zi(t)?n:null:Yi(t)(t,e,n):null}function Xi(t,e,n){return t.reduce((r,i,s)=>{const o=e[s];return Fn(i,o,r)},n)}function es(t,e,n){return rs(t,e,n).map(r=>Xi(e,r,n)).filter(r=>r)}function ts(t,e,n){return e.or?e.or.patterns.flatMap(r=>Pt(t,r,n)):e.and?e.and.patterns.reduce((r,i)=>Pt(t,i,r),n):n.flatMap(r=>es(t,e,r))}function Pt(t,e,n=[{}]){return e.reduce((r,i)=>ts(t,i,r),n)}function Rt(t,e){return Array.isArray(e)?e.map(n=>Rt(t,n)):Gi(e)?t[e]:e}function ns(t,{find:e,where:n}){return Pt(t,n).map(i=>Rt(i,e))}function rs(t,e,n){return zi(t,Rt(n,e))}const is=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function we(t){return typeof t=="string"&&is.test(t)}const V=[];for(let t=0;t<256;++t)V.push((t+256).toString(16).slice(1));function ss(t,e=0){return(V[t[e+0]]+V[t[e+1]]+V[t[e+2]]+V[t[e+3]]+"-"+V[t[e+4]]+V[t[e+5]]+"-"+V[t[e+6]]+V[t[e+7]]+"-"+V[t[e+8]]+V[t[e+9]]+"-"+V[t[e+10]]+V[t[e+11]]+V[t[e+12]]+V[t[e+13]]+V[t[e+14]]+V[t[e+15]]).toLowerCase()}let Mt;const os=new Uint8Array(16);function us(){if(!Mt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Mt=crypto.getRandomValues.bind(crypto)}return Mt(os)}const Nn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function as(t,e,n){var i;if(Nn.randomUUID&&!t)return Nn.randomUUID();t=t||{};const r=t.random??((i=t.rng)==null?void 0:i.call(t))??us();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,ss(r)}function Vn(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function cs(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function ds(t,e){return cs(Vn(t),Vn(e))}function L(){return as()}function fs(t,e){return t.localeCompare(e)}function ls(){let t=fs;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const hs=ls();let ps=0;function Ue(t){return Ze(`_${t}`,ps++)}function Ze(t,e){return`?${t}-${e}`}class Se extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function ys(t,e){const n=Un(t,e);if(!n)throw new Se(`Could not find id attr for ${e}`);return n}function Wn(t,e,n,r){return[bs(t,e,n,r)]}function bs(t,e,n,r){return[t(n,r),ys(e,n).id,t(n,r),t("time",r)]}function _s(t,e,n){return t.map(r=>r===e?n:r)}function zn(t,e,n,r,i){const s=Te(e,n,i),o=$n(e,n,i),u=s||o;if(!u)throw new Se(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[c,d]=u["forward-identity"],[a,f]=u["reverse-identity"],h=r+1,p=s?[t(d,r),u.id,t(f,h),Ue("time")]:[t(d,h),u.id,t(f,r),Ue("time")];return[s?f:d,h,p,u,!!s]}function Kn(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,t?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function gs(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";if(e.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(e.$gt)}:function(i){return i[2]>e.$gt}};if(e.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(e.$gte)}:function(i){return i[2]>=e.$gte}};if(e.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(e.$lt)}:function(i){return i[2]<e.$lt}};if(e.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(e.$lte)}:function(i){return i[2]<=e.$lte}};if(e.hasOwnProperty("$like")){const r=Kn(!0,e.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(e.hasOwnProperty("$ilike")){const r=Kn(!1,e.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return e}function Ts(t,e,n,r,i,s){const o=Te(e,n,i),u=$n(e,n,i),c=o||u;if(!c)throw new Se(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const d=Te(e,n,"id");if(!d)throw new Se(`No attr for etype = ${n} label = id`);return[t(n,r),d.id,{$isNull:{attrId:c.id,isNull:s.$isNull,reverse:!o}},Ue("time")]}return o?[t(n,r),c.id,gs(c,s),Ue("time")]:[s,c.id,t(n,r),Ue("time")]}function ws(t,e,n,r,i){const[s,o,u]=i.reduce((c,d)=>{const[a,f,h]=c,[p,y,_]=zn(t,e,a,f,d);return[p,y,[...h,_]]},[n,r,[]]);return[s,o,u]}function Dt(t,e,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[c,d,a]=ws(t,e,n,r,o),f=Ts(t,e,c,d,u,s);return a.concat([f])}function Ss(t,e){return e?[e].concat(t):t}function ms([t,e]){return t==="or"&&Array.isArray(e)}function vs([t,e]){return t==="and"&&Array.isArray(e)}function Os(t,e,n){return(r,i)=>{const s=t(r,i);return e==s?s:`${s}-${n}`}}function qn(t,e,n,r,i,s){const o=t(r,i),u=s.map((c,d)=>{const a=Os(t,o,d);return Qn(a,n,r,i,c)});return{[e]:{patterns:u,joinSym:o}}}function Es(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function Bn(t,e,n,r,i){return Es(i).map(s=>Dt(t,e,n,r,s,{$isNull:!0}))}function Qn(t,e,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(ms([s,o]))return qn(t,"or",e,n,r,o);if(vs([s,o]))return qn(t,"and",e,n,r,o);if(s==="$entityIdStartsWith")return[];const u=s.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o=Object.assign(Object.assign({},o),{$not:o.$ne}),delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const c=Dt(t,e,n,r,u,o),d=Bn(t,e,n,r,u);return[{or:{patterns:[c,...d],joinSym:t(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Bn(t,e,n,r,u),joinSym:t(n,r)}}]:Dt(t,e,n,r,u,o)})}function As(t,e,n,r){const i=Ze;return r?Qn(i,t,e,n,r).concat(Wn(i,t,e,n)):Wn(i,t,e,n)}function Cs(t,e,n){return[t(e,n),t("time",n)]}function ks(t,e,n,r,i,s){const[o,u,c,d,a]=zn(t,e,n,r,i),f=_s(c,t(n,r),s);return[o,u,f,d,a]}function js(t,e,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([c,d]){return o.map(function(h){var p,y,_;const T=!!(e.cardinalityInference&&(!((_=(y=(p=e.linkIndex)===null||p===void 0?void 0:p[n])===null||y===void 0?void 0:y[h])===null||_===void 0)&&_.isSingular));try{const[g,S,m]=ks(t,e,n,r,h,c),D=Hn(e,{etype:g,level:S,form:i[h],join:m}),O=T?D[0]:D;return{[h]:O}}catch(g){if(g instanceof Se)return{[h]:T?void 0:[]};throw g}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},d)}):Object.values(s)}function Is(t,e,n){return n==="string"?hs(t,e):t>e?1:-1}function Xe([t,e],[n,r],i){return e===r||e==null&&r==null?ds(t,n):r==null?1:e==null?-1:Is(e,r,i)}function xt(t){return t==null?t:new Date(t).getTime()}function Ps(t,e,n,r){var i;const[s,o,u,c]=t,d=n==="desc"?1:-1;if(((i=e["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return Xe(r,[s,c],null)===d;const[a,f]=r,h=e["checked-data-type"],p=h==="date"?xt(f):f,y=h==="date"?xt(u):u;return Xe([a,p],[s,y],h)===d}function Rs(t,e){const n=e[1];return t.attrs[n]}function Ms(t,e,n){const r=Object.keys(n)[0];return Te(t,e,r)}function Ds(t,e,n,r){if(n)return Rs(t,n);if(r)return Ms(t,e,r)}function xs(t,e,n){var r,i;if(!Array.isArray(n.fields))return qi(t,e);const s=new Map;for(const o of n.fields){const u=Te(t,e,o),c=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];c&&kt(u)&&s.set(c,u)}if(!s.has("id")){const o=Te(t,e,"id"),u=(i=o==null?void 0:o["forward-identity"])===null||i===void 0?void 0:i[2];u&&s.set(u,o)}return s}function $s(t,{etype:e,pageInfo:n,dq:r,form:i}){var s,o;const u=(s=i==null?void 0:i.$)===null||s===void 0?void 0:s.order,c=Gn(i),d=Us(i);let a=ns(t,r);const f=n==null?void 0:n["start-cursor"],h=Ds(t,e,f,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const _=h["checked-data-type"]==="date",T=h.id;a=a.map(([g])=>{var S,m,D,O,R;let F=(R=(O=(D=(m=(S=t.eav.get(g))===null||S===void 0?void 0:S.get(T))===null||m===void 0?void 0:m.values())===null||D===void 0?void 0:D.next())===null||O===void 0?void 0:O.value)===null||R===void 0?void 0:R[2];return _&&(F=xt(F)),[g,F]})}a.sort(d==="asc"?function(T,g){return Xe(T,g,h==null?void 0:h["checked-data-type"])}:function(T,g){return Xe(g,T,h==null?void 0:h["checked-data-type"])});let p={};const y=xs(t,e,r);for(const _ of a){const[T]=_;if(p[T]||!c&&f&&h&&Ps(f,h,d,_))continue;const g=Ki(t,y,T);g&&(p[T]=g)}return p}function Us(t){var e;const n=(e=t.$)===null||e===void 0?void 0:e.order;return n&&n[Object.keys(n)[0]]||"asc"}function Gn(t){var e,n,r;const i=(e=t.$)===null||e===void 0?void 0:e.offset,s=(n=t.$)===null||n===void 0?void 0:n.before,o=(r=t.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Ls(t,{etype:e,level:n,form:r,join:i,pageInfo:s}){var o,u,c,d,a;if(!Gn(r)&&(!s||!s["start-cursor"]))return[];const f=Ss(As(t,e,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=Cs(Ze,e,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,y=$s(t,{etype:e,pageInfo:s,form:r,dq:{where:f,find:h,fields:p}}),_=((c=r.$)===null||c===void 0?void 0:c.limit)||((d=r.$)===null||d===void 0?void 0:d.first)||((a=r.$)===null||a===void 0?void 0:a.last);if(_!=null){n>0&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const T=Object.entries(y);return T.length<=_?y:Object.fromEntries(T.slice(0,_))}return y}function Fs(t,e){try{return Ls(t,e)}catch(n){if(n instanceof Se)return{};throw n}}function Hn(t,e){const n=Fs(t,e);return js(Ze,t,e,n)}function Ns(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function Yn({store:t,pageInfo:e,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,c){return n!=null&&n[c]||c==="$$ruleParams"||(u[c]=Hn(t,{etype:c,form:r[c],level:0,pageInfo:e==null?void 0:e[c]})),u},{})};return e&&(s.pageInfo=Ns(e)),n&&(s.aggregate=n),s}function Vs(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const Ws=Vs();function $t(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return t;if(Ws.has(s))return(o,u)=>$t(t,e,[...n,u?[s,t,e,o,u]:[s,t,e,o]])}})}function et(t){return t.startsWith("lookup__")}function Jn(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function zs(t){return new Proxy({__etype:t},{get(e,n){if(n==="__etype")return t;const r=n;return et(r)?$t(t,Jn(r),[]):$t(t,r,[])}})}function Ut(){return new Proxy({},{get(t,e){return zs(e)}})}Ut();function Ks(t){return t.__ops}function qs(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,i=[];for(const o of e){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,d]=o;i.push([n[c],d])}else i.push(o)}const[s]=e;if((s==="add-triple"||s==="retract-triple")&&r.has(e[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function W(t,e,n){return Object.values(t).find(r=>{const[i,s,o]=r["forward-identity"];return s===e&&o===n})}function he(t,e,n){return Object.values(t).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===e&&u===n})}function Bs(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function Lt(t,e,n){return n.indexOf(".")!==-1&&!W(t,e,n)}function Ft(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function Qs(t,e,n){if(!Lt(t,e,n))return W(t,e,n);const r=Ft(n),i=W(t,e,r)||he(t,e,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Nt(t){return typeof t=="string"&&!et(t)?null:typeof t=="string"&&et(t)?Jn(t):Bs(t)}function G(t,e,n){const r=Nt(n);if(r===null)return n;const[i,s]=r,o=Qs(t,e,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function Zn(t,e,n,r){const i=G(t,e,n);return Array.isArray(i)?[["add-triple",i,W(t,e,"id").id,i]].concat(r):r}function Gs({attrs:t},[e,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],c=W(t,e,s),d=he(t,e,s);return u.map(a=>c?["add-triple",G(t,e,n),c.id,G(t,c["reverse-identity"][1],a)]:["add-triple",G(t,d["forward-identity"][1],a),d.id,G(t,e,n)])});return Zn(t,e,n,i)}function Hs({attrs:t},[e,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],c=W(t,e,s),d=he(t,e,s);return u.map(a=>c?["retract-triple",G(t,e,n),c.id,G(t,c["reverse-identity"][1],a)]:["retract-triple",G(t,d["forward-identity"][1],a),d.id,G(t,e,n)])});return Zn(t,e,n,i)}function Ys(t,e,n){if(Array.isArray(n)){const[r,i]=n;for(const s of t||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,c,d]of Q(o,2))if(d===i)return!0}}}else for(const r of t||[]){const i=r==null?void 0:r.eav.get(n);if(i){for(const s of i.keys())if(r.attrs[s]["forward-identity"][1]==e)return!0}}return!1}function Xn({stores:t,attrs:e},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Ys(t,n,r)?{mode:"update"}:null}function Js(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s);return[["id",d]].concat(Object.entries(c)).map(([f,h])=>{const p=W(r,i,f);return p["checked-data-type"]==="date"&&t.useDateObjects&&(h=He(h)),["add-triple",d,p.id,h,{mode:"create"}]})}function Zs(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s),a=Xn(t,[i,d,o,u]);return[["id",d]].concat(Object.entries(c)).map(([h,p])=>{const y=W(r,i,h);return y["checked-data-type"]==="date"&&t.useDateObjects&&(p=He(p)),["add-triple",d,y.id,p,...a?[a]:[]]})}function Xs({attrs:t},[e,n]){return[["delete-entity",G(t,e,n),e]]}function eo(t,e){const{stores:n,attrs:r}=t,[i,s,o,u]=e,c=Et(o),d=G(r,i,s),a=Xn(t,[i,d,o,u]),f=Object.entries(c).map(([p,y])=>{const _=W(r,i,p);return["deep-merge-triple",d,_.id,y,...a?[a]:[]]});return[["add-triple",d,W(r,i,"id").id,d,...a?[a]:[]]].concat(f)}function to({attrs:t},[e,n,r]){return[["rule-params",G(t,e,n),e,r]]}function no(t){const[e,n,r,i,s]=t;if(!i)return t;const o=Object.assign({},i);return delete o.id,[e,n,r,o,...s?[s]:[]]}function ro(t,e){const[n,...r]=no(e);switch(n){case"merge":return eo(t,r);case"create":return Js(t,r);case"update":return Zs(t,r);case"link":return Gs(t,r);case"unlink":return Hs(t,r);case"delete":return Xs(t,r);case"ruleParams":return to(t,r);default:throw new Error(`unsupported action ${n}`)}}function io(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function so(t,e,n){var r,i;const s=(i=(r=t.entities[e])===null||r===void 0?void 0:r.attrs)===null||i===void 0?void 0:i[n];if(n==="id")return null;if(!s)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,c=io(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":c}}function tt(t,e,n,r){const i=t?so(t,e,n):null,s=L(),u=[L(),e,n];return Object.assign(Object.assign({id:s,"forward-identity":u,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}function oo(t,e,n){return Object.values(t.links).find(i=>i.forward.on===e&&i.forward.label===n||i.reverse.on===e&&i.reverse.label===n)}function uo(t,e,n){const r=oo(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[L(),i.on,i.label],"reverse-identity":[L(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function er(t,e,n,r){const i=t?uo(t,e,n):null,s=L(),o=[L(),e,n],u=[L(),n,e];return Object.assign(Object.assign({id:s,"forward-identity":o,"reverse-identity":u,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0},i||{}),r||{})}const ao=new Set(["create","update","merge","link","unlink"]),co=new Set(["link","unlink"]),fo=new Set(["create","update","merge"]),lo=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Vt={"unique?":!0,"index?":!0},ho=Object.assign(Object.assign({},Vt),{cardinality:"one"});function po(t){const e=[],[n,r,i,s]=t;if(!lo.has(n))return e;const o=Nt(i);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[u,c]of Object.entries(s)){const d=Array.isArray(c)?c:[c];for(const a of d){const f=Nt(a);f&&e.push({etype:r,lookupPair:f,linkLabel:u})}}return e}function yo({attrs:t,schema:e},n){var r,i;const[s,o,u]=[new Set,Object.assign({},t),[]];function c(f){o[f.id]=f,u.push(["add-attr",f]),s.add(f.id)}function d(f){f!=null&&f.isUnsynced&&!s.has(f.id)&&(u.push(["add-attr",f]),s.add(f.id))}function a(f,h){const p=W(o,f,h),y=he(o,f,h);d(p),d(y),!p&&!y&&c(er(e,f,h,ho))}for(const f of n)for(const{etype:h,lookupPair:p,linkLabel:y}of po(f)){const _=p[0];if(y){a(h,y);const T=W(o,h,y),g=he(o,h,y);d(T),d(g);const S=((r=T==null?void 0:T["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=g==null?void 0:g["forward-identity"])===null||i===void 0?void 0:i[1])||y;if(Lt(o,S,_))a(S,Ft(_));else{const m=W(o,S,_);m||c(tt(e,S,_,Vt)),d(m)}}else if(Lt(o,h,_))a(h,Ft(_));else{const T=W(o,h,_);T||c(tt(e,h,_,Vt)),d(T)}}for(const f of n){const[h,p,y,_]=f;if(ao.has(h)){const T=W(o,p,"id");d(T),T||c(tt(e,p,"id",{"unique?":!0}));for(const g of Object.keys(_)){const S=W(o,p,g);if(d(S),fo.has(h)&&(S||c(tt(e,p,g,g==="id"?{"unique?":!0}:null))),co.has(h)){const m=he(o,p,g);!S&&!m&&c(er(e,p,g)),d(m)}}}}return[o,u]}function bo(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>Ks(c)),[i,s]=yo(t,r),o=Object.assign(Object.assign({},t),{attrs:i}),u=r.flatMap(c=>ro(o,c));return[...s,...u]}var tr=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class nr{constructor(e){this.dbName=e,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;e(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(e){return tr(this,void 0,void 0,function*(){const n=yield this._dbPromise;return new Promise((r,i)=>{const u=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);u.onerror=c=>{i(c)},u.onsuccess=c=>{u.result?r(u.result):r(null)}})})}setItem(e,n){return tr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const c=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,e);c.onerror=d=>{s(d)},c.onsuccess=d=>{i()}})})}}var _o=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class rr{static getIsOnline(){return _o(this,void 0,void 0,function*(){return navigator.onLine})}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class me extends Error{constructor(e,n){super(e),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,me),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var go=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};class nt extends me{constructor(e){var n;const r=((n=e.body)===null||n===void 0?void 0:n.message)||`API Error (${e.status})`;super(r,e.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,nt),this.name="InstantAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function ne(t,e){return go(this,void 0,void 0,function*(){const n=yield fetch(t,e),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new nt({status:n.status,body:r}))})}var ve=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function To({apiURI:t,appId:e,email:n}){return ne(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}function wo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,email:r,code:i,refreshToken:s}){return yield ne(`${e}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Object.assign({"app-id":n,email:r,code:i},s?{"refresh-token":s}:{}))})})}function So(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,refreshToken:r}){return yield ne(`${e}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function mo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n}){return yield ne(`${e}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function ir(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield ne(`${e}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,code:r,code_verifier:i,refresh_token:s})})})}function vo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield ne(`${e}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,nonce:r,id_token:i,client_name:s,refresh_token:o})})})}function Oo(t){return ve(this,arguments,void 0,function*({apiURI:e,appId:n,refreshToken:r}){return yield ne(`${e}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var Le=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Eo(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const c={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(c["content-disposition"]=u),yield ne(`${e}/storage/upload`,{method:"PUT",headers:c,body:i})})}function Ao(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,refreshToken:i}){const{data:s}=yield ne(`${e}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function Co(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield ne(`${e}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({app_id:n,filename:r})});return o})}function ko(t,e){return Le(this,void 0,void 0,function*(){return(yield fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok})}function jo(t){return Le(this,arguments,void 0,function*({apiURI:e,appId:n,path:r,refreshToken:i}){const{data:s}=yield ne(`${e}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Wt=!1,sr=!1,or=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Wt=!!window.localStorage.getItem("devBackend"),sr=!!window.localStorage.getItem("__instantLogging"),or=!!window.localStorage.getItem("__devtoolLocalDash"));function ur(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function Io(t,e,n){var r,i;const s={peers:{}};if(e&&"user"in e?e.user:!0){const u=ur((r=t.user)!==null&&r!==void 0?r:{},e==null?void 0:e.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=t.peers)!==null&&i!==void 0?i:{})){const c=(e==null?void 0:e.peers)===void 0,d=Array.isArray(e==null?void 0:e.peers)&&(e==null?void 0:e.peers.includes(u));if(c||d){const a=ur(t.peers[u],e==null?void 0:e.keys);s.peers[u]=Object.assign(Object.assign({},a),{peerId:u})}}return s}function Po(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!mn(t.user,e.user))||!Sn(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!mn(t.peers[r],e.peers[r]))return!0;return!1}class ar{constructor(){this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}var Fe=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Ro(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}class zt{constructor(e,n,r,i,s=d=>d,o=d=>d,u=100,c=1e3){this._subs=[],this._nextSave=null,this._persister=e,this._key=n,this._onMerge=i,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=s,this.parse=o,this._saveThrottleMs=u,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=c,this._load()}_getFromStorage(){return Fe(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(e){return console.error(`Unable to read from storage for key=${this._key}`,e),null}})}_load(){return Fe(this,void 0,void 0,function*(){const e=yield this._getFromStorage();this._isLoading=!1;const n=this._onMerge(e,this.currentValue);n&&(this.currentValue=n);for(const r of this._loadedCbs)r()})}waitForLoaded(){return Fe(this,void 0,void 0,function*(){if(!this._isLoading)return;yield new Promise(n=>{this._loadedCbs.push(n)})})}isLoading(){return this._isLoading}version(){return this._version}waitForSync(){return Fe(this,void 0,void 0,function*(){if(!this._nextSave)return;yield new Promise(n=>{this._pendingSaveCbs.push(n)})})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const e of this._pendingSaveCbs)e();this._pendingSaveCbs.length=0}flush(){return Fe(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(e){if(this._nextSave){e&&this._pendingSaveCbs.push(e);return}this._nextSave=setTimeout(()=>{Ro(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(e,n){this._version++,this.currentValue=e(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue);return this.currentValue}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}}function cr(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)e.push(u);cr(n["child-nodes"],e)})}function dr(t){const e=[];return cr(t,e),e}function fr(t){return Object.values(t.links).reduce((e,n)=>{var r,i,s,o;return(r=e[s=n.forward.on])!==null&&r!==void 0||(e[s]={}),e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=e[o=n.reverse.on])!==null&&i!==void 0||(e[o]={}),e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e},{})}const lr="v0.22.47-experimental.sync-table.19174988015.1";function Mo(t,e){return{info:t?(...n)=>console.info(...n,e()):()=>{},debug:t?(...n)=>console.debug(...n,e()):()=>{},error:t?(...n)=>console.error(...n,e()):()=>{}}}class ue{constructor(e,n,r,i={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new ue(this.valueType,!1,this.isIndexed,this.config)}optional(){return new ue(this.valueType,!1,this.isIndexed,this.config)}unique(){return new ue(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new ue(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class P extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const hr=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Do=t=>t.valueType||"unknown",pr=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},xo=(t,e,n,r,i,s,o)=>{const u=s.valueType==="json",c=(d,a,f)=>{if(!pr(f,a,u))throw new P(`Invalid value for operator '${d}' on attribute '${r}' in entity '${i}'. Expected ${a}, but received: ${typeof f}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new P(`Operator '${t}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof e}`,o);for(const d of e)c(t,n,d);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!s.isIndexed)throw new P(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;default:throw new P(`Unknown operator '${t}' for attribute '${r}' in entity '${i}'`,o)}},Oe=(t,e,n,r,i)=>{const s=Do(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){if(o)return;const c=t;for(const[d,a]of Object.entries(c))xo(d,a,s,e,r,n,`${i}.${d}`)}else if(!pr(t,s,o))throw new P(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${s}, but received: ${typeof t}`,i)},$o=(t,e,n,r,i)=>{const s=t.split(".");if(s.length<2)throw new P(`Invalid dot notation path '${t}'. Must contain at least one dot.`,i);let o=n;for(let a=0;a<s.length-1;a++){const f=s[a],h=r.entities[o];if(!h)throw new P(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,i);const p=h.links[f];if(!p){const y=Object.keys(h.links);throw new P(`Link '${f}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${y.length>0?y.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],c=r.entities[o];if(!c)throw new P(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,i);if(u==="id"){if(typeof e=="string"&&!we(e))throw new P(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,i);Oe(e,t,new ue("string",!1,!0),n,i);return}const d=c.attrs[u];if(Object.keys(c.links).includes(u)){if(typeof e=="string"&&!we(e))throw new P(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${e}`,i);Oe(e,t,new ue("string",!1,!0),n,i);return}if(!d){const a=Object.keys(c.attrs);throw new P(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${a.length>0?a.join(", ")+", id":"id"}`,i)}Oe(e,t,d,n,i)},yr=(t,e,n,r)=>{for(const[i,s]of Object.entries(t)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const d of s)typeof d=="object"&&d!==null&&yr(d,e,n,`${r}.${i}[${d}]`);continue}if(i==="id"){Oe(s,"id",new ue("string",!1,!0),e,`${r}.id`);continue}if(i.includes(".")){$o(i,s,e,n,`${r}.${i}`);continue}const o=n.entities[e];if(!o)continue;const u=o.attrs[i],c=o.links[i];if(!u&&!c){const d=Object.keys(o.attrs),a=Object.keys(o.links);throw new P(`Attribute or link '${i}' does not exist on entity '${e}'. Available attributes: ${d.length>0?d.join(", "):"none"}. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${i}`)}if(u)Oe(s,i,u,e,`${r}.${i}`);else if(c){if(typeof s=="string"&&!we(s))throw new P(`Invalid value for link '${i}' in entity '${e}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const d=new ue("string",!1,!0);Oe(s,i,d,e,`${r}.${i}`)}}},Uo=(t,e,n,r,i=0)=>{for(const o of Object.keys(t))if(!hr.includes(o))throw new P(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${hr.join(", ")}. Found: ${o}`,r);const s=["offset","before","after","first","last"];for(const o of s)if(t[o]!==void 0&&i>0)throw new P(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new P(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);yr(t.where,e,n,r?`${r}.where`:"where")}},br=(t,e,n,r,i=0)=>{var s;if(!t||typeof t!="object")throw new P(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const o of Object.keys(t))if(o!=="$"){if(n&&!(o in n.entities[e].links)){const c=Object.keys(n.entities[e].links);throw new P(`Link '${o}' does not exist on entity '${e}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${o}`)}const u=t[o];if(typeof u=="object"&&u!==null){const c=(s=n==null?void 0:n.entities[e].links[o])===null||s===void 0?void 0:s.entityName;c&&br(u,c,n,`${r}.${o}`,i+1)}}else{const u=t[o];if(typeof u!="object"||u===null)throw new P(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof u}`,`${r}.$`);Uo(u,e,n,`${r}.$`,i)}},_r=(t,e)=>{if(typeof t!="object"||t===null)throw new P(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new P(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new P(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const i=Object.keys(e.entities);throw new P(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}br(n[r],r,e,r,0)}}},gr=t=>typeof t!="string"?!1:et(t)?!0:we(t);class Z extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const Tr=t=>t.length>0?t.join(", "):"none",Lo=(t,e)=>new Z(`Entity '${t}' does not exist in schema. Available entities: ${Tr(e)}`),wr={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},Fo=(t,e)=>{var n,r;return t==null?!0:(r=(n=wr[e.valueType])===null||n===void 0?void 0:n.call(wr,t))!==null&&r!==void 0?r:!1},Sr=(t,e)=>{const n=e.entities[t];if(!n)throw Lo(t,Object.keys(e.entities));return n},Kt=(t,e,n)=>{const r=Sr(t,n);if(typeof e!="object"||e===null)throw new Z(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[i,s]of Object.entries(e)){if(i==="id")continue;const o=r.attrs[i];if(o&&!Fo(s,o))throw new Z(`Invalid value for attribute '${i}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof s}`)}},mr=(t,e,n)=>{const r=Sr(t,n);if(typeof e!="object"||e===null)throw new Z(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[i,s]of Object.entries(e)){if(!r.links[i]){const u=Object.keys(r.links);throw new Z(`Link '${i}' does not exist on entity '${t}'. Available links: ${Tr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!gr(u))throw new Z(`Invalid entity ID in link '${i}' for entity '${t}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!gr(s))throw new Z(`Invalid UUID in link '${i}' for entity '${t}'. Expected a UUID, but received: ${s}`)}}},No={create:Kt,update:Kt,merge:Kt,link:mr,unlink:mr,delete:()=>{}},Vo=(t,e)=>{if(!e)return;const[n,r,i,s]=t;if(!Array.isArray(i)&&!we(i))throw new Z(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new Z(`Entity name must be a string, but received: ${typeof r}`);const o=No[n];o&&s!==void 0&&o(r,s,e)},Wo=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new Z(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new Z(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new Z(`Transaction operation must be an array, but received: ${typeof i}`);Vo(i,e)}}};var vr=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};let Or=0;class Er{constructor(e){this.type="ws",this.id=`${this.type}_${Or++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(e){return this.conn.send(JSON.stringify(e))}}class zo{constructor(e,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Or++}`,this.url=n,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const i=JSON.parse(r.data);if(i.op==="sse-init"){this.initParams={machineId:i["machine-id"],sessionId:i["session-id"],sseToken:i["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:i})},this.conn.onerror=r=>{this.handleError()}}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}postMessages(e){return vr(this,void 0,void 0,function*(){try{(yield fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:e})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return vr(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const e=this.sendQueue;this.sendQueue=[];const n=this.postMessages(e);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(e){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(e),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var Ar=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})};function Ko(t,e){for(const n in t){const r=t[n];for(const i of r.entities||[])i.store=In(i.store)}return t}function qo(t){const e={};for(const n in t){const r=t[n];if(r.entities){const i=[];for(const s of r.entities)i.push({store:jn(s.store),entity:s.entity});e[n]=Object.assign(Object.assign({},r),{entities:i})}else e[n]=r}return e}function Bo(t,e){const n={};for(const[r,i]of Object.entries(e))n[r]=i;if(t)for(const[r,i]of Object.entries(t))n[r]=i;return n}function qt(t,e){const n=Object.keys(t.query)[0];return Yn({store:e,pageInfo:null,aggregate:null},t.query).data[n][0]}function Cr(t,e){for(const{action:n,triple:r}of e)switch(n){case"added":Mn(t,r);break;case"removed":Pn(t,r);break}}function Qo(t,e){var n,r,i,s;const o={};for(const{action:u,triple:c}of e){const[d,a,f]=c,h=(r=(n=t.attrs[a])===null||n===void 0?void 0:n["forward-identity"])===null||r===void 0?void 0:r[2];if(!h)continue;const p=(i=o[d])!==null&&i!==void 0?i:{};o[d]=p;const y=(s=p[h])!==null&&s!==void 0?s:{};switch(p[h]=y,u){case"added":y.newValue=f;break;case"removed":y.oldValue===void 0&&(y.oldValue=f);break}}return o}var Ee;(function(t){t.InitialSyncBatch="InitialSyncBatch",t.InitialSyncComplete="InitialSyncComplete",t.LoadFromStorage="LoadFromStorage",t.SyncTransaction="SyncTransaction",t.Error="Error"})(Ee||(Ee={}));class Go{constructor(e,n,r,i,s){this.callbacks={},this.idToHash={},this.trySend=e,this.config=r,this.log=i,this.createStore=s,this.subs=new zt(n,"subs",{},Bo,qo,o=>Ko(o,this.config.useDateObjects))}beforeUnload(){this.subs.flush()}subscribe(e,n){const r=N(e);return this.callbacks[r]=this.callbacks[r]||[],this.callbacks[r].push(n),this.initSubscription(e,r,n),i=>{this.unsubscribe(r,n,i==null?void 0:i.keepSubscription)}}unsubscribe(e,n,r){const i=(this.callbacks[e]||[]).filter(s=>s!==n);if(this.callbacks[e]=i,!i.length){if(delete this.callbacks[e],r)return;const s=this.subs.currentValue[e];s!=null&&s.state&&this.clearSubscriptionData(s.state.subscriptionId),this.subs.set(o=>(delete o[e],o))}}sendStart(e){this.trySend(L(),{op:"start-sync",q:e})}sendResync(e,n){this.idToHash[n.subscriptionId]=e.hash,this.trySend(n.subscriptionId,{op:"resync-table","subscription-id":n.subscriptionId,"tx-id":n.txId,token:n.token})}sendRemove(e){this.trySend(L(),{op:"remove-sync","subscription-id":e.subscriptionId})}initSubscription(e,n,r){return Ar(this,void 0,void 0,function*(){yield this.subs.waitForLoaded();const i=this.subs.currentValue[n];if(i&&i.state&&i.state.txId){this.sendResync(i,i.state),i.entities&&r&&r({type:Ee.LoadFromStorage,data:i.entities.map(s=>s.entity)});return}this.subs.set(s=>(s[n]={query:e,hash:n},s)),this.sendStart(e)})}flushPending(){return Ar(this,void 0,void 0,function*(){yield this.subs.waitForLoaded();for(const e of Object.keys(this.callbacks)){const n=this.subs.currentValue[e];n?yield this.initSubscription(n.query,n.hash):this.log.error("Missing sub for hash in flushPending",e)}})}onStartSyncOk(e){const n=e["subscription-id"],r=e.q,i=N(r);this.idToHash[n]=i,this.subs.set(s=>{const o=s[i];return o?(o.state={subscriptionId:n,token:e.token},s):(this.log.error("Missing sub for hash",i,"subscription-id",n,"query",r),s)})}notifyCbs(e,n){for(const r of this.callbacks[e]||[])r(n)}onSyncLoadBatch(e){const n=e["subscription-id"],r=e["join-rows"],i=this.idToHash[n];if(!i){this.log.error("Missing hash for subscription",e);return}const s=[],u=this.subs.set(c=>{var d;const a=c[i];if(!a)return this.log.error("Missing sub for hash",i,e),c;const f=(d=a.entities)!==null&&d!==void 0?d:[];a.entities=f;for(const h of r){const p=this.createStore(h),y=qt(a,p);f.push({store:p,entity:y}),s.push(y)}return c})[i];u.entities&&this.notifyCbs(i,{type:Ee.InitialSyncBatch,data:u.entities.map(c=>c.entity),batch:s})}onSyncInitFinish(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(i=>{const s=i[r];if(!s)return this.log.error("Missing sub for hash",r,e),i;const o=s.state;return o?(o.txId=e["tx-id"],i):(this.log.error("Sub never set init, missing result",s,e),i)})}onSyncUpdateTriples(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(i=>{var s;const o=i[r];if(!o)return this.log.error("Missing sub for hash",r,e),i;const u=o.state;if(!u)return this.log.error("Missing state for sub",o,e),i;for(const c of e.txes){if(u.txId>=c["tx-id"])continue;u.txId=c["tx-id"];const d=[],a={};for(const _ of c.changes){const T=(s=a[_.triple[0]])!==null&&s!==void 0?s:[];a[_.triple[0]]=T,T.push(_)}const f=o.entities||[];o.entities=f;const h=[];e:for(const[_,T]of Object.entries(a))for(const[g,S]of Object.entries(f))if(xi(S.store,_)){Cr(S.store,T);const m=qt(o,S.store),D=Qo(S.store,T)[_];for(const[O,{oldValue:R,newValue:F}]of Object.entries(D||{}))R===F&&delete D[O];m?(h.push({oldEntity:S.entity,newEntity:m,changedFields:D||{}}),S.entity=m):d.push(g),delete a[_];continue e}const p=[];for(const[_,T]of Object.entries(a)){const g=this.createStore([]);Cr(g,T);const S=qt(o,g);if(!S){this.log.error("No entity found after applying change",{sub:o,changes:T,store:g});continue}f.push({store:g,entity:S}),p.push(S)}const y=[];for(const _ of d.sort().reverse())y.push(f[_].entity),f.splice(_,1);this.notifyCbs(r,{type:Ee.SyncTransaction,data:f.map(_=>_.entity),added:p,removed:y,updated:h})}return i})}clearSubscriptionData(e){const n=this.idToHash[e];if(n){delete this.idToHash[e];const r=this.subs.currentValue[n];if(r.state&&this.sendRemove(r.state),this.subs.set(i=>(delete i[n],i)),r)return r}}onStartSyncError(e){const n=N(e["original-event"].q),r={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa.",status:e.status,type:e.type,hint:e.hint};this.notifyCbs(n,{type:Ee.Error,data:[],error:r})}onResyncError(e){const n=e["original-event"]["subscription-id"],r=this.clearSubscriptionData(n);r&&this.initSubscription(r.query,r.hash)}}var $=function(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function u(a){try{d(r.next(a))}catch(f){o(f)}}function c(a){try{d(r.throw(a))}catch(f){o(f)}}function d(a){a.done?s(a.value):i(a.value).then(u,c)}d((r=r.apply(t,e||[])).next())})},Ho=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n};const ae={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Yo=3e4,Jo=3e4,Zo=200,Xo={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},Bt="_instant_oauth_redirect",Qt="currentUser";function eu({transportType:t,appId:e,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new Er(`${r}?app_id=${e}`);switch(t){case"ws":return new Er(`${r}?app_id=${e}`);case"sse":return new zo(i,`${n}/runtime/sse?app_id=${e}`);default:throw new Error("Unknown transport type "+t)}}function tu(){return typeof window<"u"||typeof chrome<"u"}const kr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function nu(t,e){var n;const r=typeof t=="string"?JSON.parse(t):t;for(const i in r){const s=r[i];if(!((n=s==null?void 0:s.result)===null||n===void 0)&&n.store){const o=s.result.store;s.result.store=In(Object.assign(Object.assign({},o),{useDateObjects:e}))}}return r}function ru(t){var e;const n={};for(const r in t){const i=t[r],s=Object.assign({},i);!((e=i.result)===null||e===void 0)&&e.store&&(s.result=Object.assign(Object.assign({},i.result),{store:jn(i.result.store)})),n[r]=s}return n}function jr(t){return[...t].sort((e,n)=>{const[r,i]=e,[s,o]=n,u=i.order||0,c=o.order||0;return u==c?r<s?-1:r>s?1:0:u-c})}class iu{constructor(e,n=nr,r=rr,i,s){var o,u,c;if(this._isOnline=!0,this._isShutdown=!1,this.status=ae.CONNECTING,this.queryCbs={},this.queryOnceDfds={},this.authCbs=[],this.attrsCbs=[],this.mutationErrorCbs=[],this.connectionStatusCbs=[],this.mutationDeferredStore=new Map,this._reconnectTimeoutId=null,this._reconnectTimeoutMs=0,this._transportType="ws",this._wsOk=null,this._localIdPromises={},this._errorMessage=null,this._oauthCallbackResponse=null,this._linkIndex=null,this._rooms={},this._roomsPendingLeave={},this._presence={},this._broadcastQueue=[],this._broadcastSubs={},this._currentUserCached={isLoading:!0,error:void 0,user:void 0},this._beforeUnloadCbs=[],this._dataForQueryCache={},this._inFlightMutationEventIds=new Set,this._onMergeQuerySubs=(d,a)=>{const f=d||{},h=Object.assign({},a);Object.entries(a).forEach(([y,_])=>{var T;const g=(T=f==null?void 0:f[y])===null||T===void 0?void 0:T.result,S=_.result;g&&!S&&(h[y].result=g)}),Object.keys(f).filter(y=>!a[y]).sort((y,_)=>{var T,g;const S=((T=f[y])===null||T===void 0?void 0:T.lastAccessed)||0;return(((g=f[_])===null||g===void 0?void 0:g.lastAccessed)||0)-S}).slice(0,this.queryCacheLimit).forEach(y=>{h[y]=f[y]}),this.querySubs.set(y=>h),this.loadedNotifyAll()},this._onMergePendingMutations=(d,a)=>{const f=new Map([...d.entries(),...a.entries()]);this.pendingMutations.set(p=>f),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,d).forEach(([p,y])=>{!a.has(p)&&!y["tx-id"]&&this._sendMutation(p,y)})},this.getPreviousResult=d=>{const a=N(d);return this.dataForQuery(a)},this.notifyOne=d=>{var a,f;const h=(a=this.queryCbs[d])!==null&&a!==void 0?a:[],p=(f=this._dataForQueryCache[d])===null||f===void 0?void 0:f.data,y=this.dataForQuery(d);y&&(Ge(y,p)||h.forEach(_=>_.cb(y)))},this.notifyOneQueryOnce=d=>{var a;const f=(a=this.queryOnceDfds[d])!==null&&a!==void 0?a:[],h=this.dataForQuery(d);f.forEach(p=>{this._completeQueryOnce(p.q,d,p.dfd),p.dfd.resolve(h)})},this.notifyQueryError=(d,a)=>{(this.queryCbs[d]||[]).forEach(h=>h.cb({error:a}))},this.pushTx=d=>{this.config.disableValidation||Wo(d,this.config.schema);try{const a=bo({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(f=>{var h;return(h=f==null?void 0:f.result)===null||h===void 0?void 0:h.store}),useDateObjects:this.config.useDateObjects},d);return this.pushOps(a)}catch(a){return this.pushOps([],a)}},this.pushOps=(d,a)=>{const f=L(),h=[...this.pendingMutations.currentValue.values()],p=Math.max(0,...h.map(T=>T.order||0))+1,y={op:"transact","tx-steps":d,created:Date.now(),error:a,order:p};this.pendingMutations.set(T=>(T.set(f,y),T));const _=new ar;return this.mutationDeferredStore.set(f,_),this._sendMutation(f,y),this.notifyAll(),_.promise},this._transportOnOpen=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][open]",a.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(ae.OPENED),this.getCurrentUser().then(f=>{var h;this._trySend(L(),{op:"init","app-id":this.config.appId,"refresh-token":(h=f.user)===null||h===void 0?void 0:h.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(f=>{this._log.error("[socket][error]",a.id,f)})},this._transportOnMessage=d=>{const a=d.target,f=d.message;if(this._transport!==a){this._log.info("[socket][message]",a.id,f,"skip; this is no longer the current transport");return}!this._wsOk&&a.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(a.id,d.message)},this._transportOnError=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][error]",a.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",a.id,d)},this._scheduleReconnect=()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)},this._transportOnClose=d=>{const a=d.target;if(this._transport!==a){this._log.info("[socket][close]",a.id,"skip; this is no longer the current transport");return}this._setStatus(ae.CLOSED);for(const f of Object.values(this._rooms))f.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",a.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",a.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()},this._EventSource=s,this.config=Object.assign(Object.assign({},Xo),e),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._pendingTxCleanupTimeout=(u=this.config.pendingTxCleanupTimeout)!==null&&u!==void 0?u:Jo,this._pendingMutationCleanupThreshold=(c=this.config.pendingMutationCleanupThreshold)!==null&&c!==void 0?c:Zo,this._log=Mo(e.verbose||Wt||sr,()=>this._reactorStats()),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":lr}),this.config.schema&&(this._linkIndex=fr(this.config.schema)),!!tu()){if(!e.appId)throw new Error("Instant must be initialized with an appId.");if(!we(e.appId))throw new Error(`Instant must be initialized with a valid appId. \`${e.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",d=>$(this,void 0,void 0,function*(){var a;try{if(((a=d.data)===null||a===void 0?void 0:a.type)==="auth"){const f=yield this.getCurrentUser();this.updateUser(f.user)}}catch(f){this._log.error("[error] handle broadcast channel",f)}}))),this._initStorage(n),this._syncTable=new Go(this._trySendAuthed.bind(this),this._persister,{useDateObjects:this.config.useDateObjects},this._log,d=>Ye(this.attrs,d,this.config.enableCardinalityInference,this._linkIndex,this.config.useDateObjects)),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(d=>{this._isOnline=d,this._startSocket(),r.listen(a=>{a!==this._isOnline&&(this._log.info("[network] online =",a),this._isOnline=a,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",ae.CLOSED),this._setStatus(ae.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(e){this.config=Object.assign(Object.assign({},this.config),{schema:e,cardinalityInference:!!e}),this._linkIndex=e?fr(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(e){this._persister=new e(`instant_${this.config.appId}_5`),this.querySubs=new zt(this._persister,"querySubs",{},this._onMergeQuerySubs,ru,n=>nu(n,this.config.useDateObjects)),this.pendingMutations=new zt(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const e of this._beforeUnloadCbs)e();this._syncTable.beforeUnload()}_finishTransaction(e,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=e!=="error"&&e!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:e,eventId:n},r)),!!i)if(s)i.resolve({status:e,eventId:n});else if(r.type){const{status:o}=r,u=Ho(r,["status"]);i.reject(new nt({body:u,status:o}))}else i.reject(new me(r.message,r.hint))}_setStatus(e,n){this.status=e,this._errorMessage=n,this.notifyConnectionStatusSubs(e)}_flushEnqueuedRoomData(e){var n,r;const i=(r=(n=this._presence[e])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[e];if(this._broadcastQueue[e]=[],i&&this._trySetPresence(e,i),s)for(const o of s){const{topic:u,roomType:c,data:d}=o;this._tryBroadcast(e,c,u,d)}}_handleReceive(e,n){var r,i,s,o,u,c;const d=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(kr[n.op]||this._log.info("[receive]",e,n.op,n),n.op){case"init-ok":{this._setStatus(ae.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const h of Object.keys(this._rooms)){const p=(i=(r=this._presence[h])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(h,p)}break}case"add-query-exists":{this.notifyOneQueryOnce(N(n.q));break}case"add-query-ok":{const{q:h,result:p}=n,y=N(h),_=(o=(s=p==null?void 0:p[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],T=(c=(u=p==null?void 0:p[0])===null||u===void 0?void 0:u.data)===null||c===void 0?void 0:c.aggregate,g=dr(p),S=Ye(this.attrs,g,d,this._linkIndex,this.config.useDateObjects);this.querySubs.set(m=>(m[y].result={store:S,pageInfo:_,aggregate:T,processedTxId:n["processed-tx-id"]},m)),this._cleanupPendingMutationsQueries(),this.notifyOne(y),this.notifyOneQueryOnce(y),this._cleanupPendingMutationsTimeout();break}case"start-sync-ok":{this._syncTable.onStartSyncOk(n);break}case"sync-load-batch":{this._syncTable.onSyncLoadBatch(n);break}case"sync-init-finish":{this._syncTable.onSyncInitFinish(n);break}case"sync-update-triples":{this._syncTable.onSyncUpdateTriples(n);break}case"refresh-ok":{const{computations:h,attrs:p}=n,y=n["processed-tx-id"];p&&this._setAttrs(p),this._cleanupPendingMutationsTimeout();const _=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,y);_!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>_);const T=jr(_.entries()),g=h.map(S=>{var m,D,O,R;const F=S["instaql-query"],K=S["instaql-result"],Ne=N(F),it=dr(K),Jt=Ye(this.attrs,it,d,this._linkIndex,this.config.useDateObjects),Zt=this._applyOptimisticUpdates(Jt,T,y),st=(D=(m=K==null?void 0:K[0])===null||m===void 0?void 0:m.data)===null||D===void 0?void 0:D["page-info"],ie=(R=(O=K==null?void 0:K[0])===null||O===void 0?void 0:O.data)===null||R===void 0?void 0:R.aggregate;return{hash:Ne,store:Zt,pageInfo:st,aggregate:ie}});g.forEach(({hash:S,store:m,pageInfo:D,aggregate:O})=>{this.querySubs.set(R=>(R[S].result={store:m,pageInfo:D,aggregate:O,processedTxId:y},R))}),this._cleanupPendingMutationsQueries(),g.forEach(({hash:S})=>{this.notifyOne(S)});break}case"transact-ok":{const{"client-event-id":h,"tx-id":p}=n;this._inFlightMutationEventIds.delete(h);const _=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(h);if(!_)break;this.pendingMutations.set(g=>(g.set(h,Object.assign(Object.assign({},g.get(h)),{"tx-id":p,confirmed:Date.now()})),g));const T=_["tx-steps"].filter(([g,...S])=>g==="add-attr").map(([g,S])=>S).concat(Object.values(this.attrs));this._setAttrs(T),this._finishTransaction("synced",h),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const h=n["room-id"];this._trySetRoomConnected(h,!0),this._patchPresencePeers(h,n.edits),this._notifyPresenceSubs(h);break}case"refresh-presence":{const h=n["room-id"];this._trySetRoomConnected(h,!0),this._setPresencePeers(h,n.data),this._notifyPresenceSubs(h);break}case"server-broadcast":{const h=n["room-id"],p=n.topic;this._trySetRoomConnected(h,!0),this._notifyBroadcastSubs(h,p,n);break}case"join-room-ok":{const h=n["room-id"];if(!this._rooms[h]){this._roomsPendingLeave[h]&&(this._tryLeaveRoom(h),delete this._roomsPendingLeave[h]);break}this._trySetRoomConnected(h,!0),this._flushEnqueuedRoomData(h);break}case"leave-room-ok":{const h=n["room-id"];this._trySetRoomConnected(h,!1);break}case"join-room-error":const a=n["room-id"],f=this._rooms[a];f&&(f.error=n.error),this._notifyPresenceSubs(a);break;case"error":this._handleReceiveError(n);break;default:this._log.info("Uknown op",n.op,n);break}}_handleMutationError(e,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(e!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(e,n,r)}}_handleReceiveError(e){var n,r,i,s,o,u,c;console.log("error",e);const d=e["client-event-id"];this._inFlightMutationEventIds.delete(d);const a=this.pendingMutations.currentValue.get(d),f={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(e.hint&&(f.hint=e.hint),a){this._handleMutationError("error",d,e);return}if(!((n=e["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=e["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const y=(i=e["original-event"])===null||i===void 0?void 0:i.q,_=N(y);this.notifyQueryError(N(y),f),this.notifyQueryOnceError(y,_,d,f);return}if(((s=e["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(e.type==="record-not-found"&&((o=e.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(ae.ERRORED,f),this.notifyAll();return}if(((u=e["original-event"])===null||u===void 0?void 0:u.op)==="resync-table"){this._syncTable.onResyncError(e);return}if(((c=e["original-event"])===null||c===void 0?void 0:c.op)==="start-sync"){this._syncTable.onStartSyncError(e);return}const p=Object.assign({},e);delete p.message,delete p.hint,console.error(e.message,p),e.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
31
31
|
`,e.hint)}notifyQueryOnceError(e,n,r,i){var s;const o=(s=this.queryOnceDfds[n])===null||s===void 0?void 0:s.find(u=>u.eventId===r);o&&(o.dfd.reject(i),this._completeQueryOnce(e,n,o.dfd))}_setAttrs(e){this.attrs=e.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(e,n){const r=L();return this.querySubs.set(i=>(i[n]=i[n]||{q:e,result:null,eventId:r},i[n].lastAccessed=Date.now(),i)),this._trySendAuthed(r,{op:"add-query",q:e}),r}subscribeTable(e,n){return this._syncTable.subscribe(e,n)}subscribeQuery(e,n,r){var i;this.config.disableValidation||_r(e,this.config.schema),r&&"ruleParams"in r&&(e=Object.assign({$$ruleParams:r.ruleParams},e));const s=N(e),o=this.getPreviousResult(e);return o&&n(o),this.queryCbs[s]=(i=this.queryCbs[s])!==null&&i!==void 0?i:[],this.queryCbs[s].push({q:e,cb:n}),this._startQuerySub(e,s),()=>{this._unsubQuery(e,s,n)}}queryOnce(e,n){var r;this.config.disableValidation||_r(e,this.config.schema),n&&"ruleParams"in n&&(e=Object.assign({$$ruleParams:n.ruleParams},e));const i=new ar;if(!this._isOnline)return i.reject(new Error("We can't run `queryOnce`, because the device is offline.")),i.promise;if(!this.querySubs)return i.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.instantdb.com/docs/backend#query")),i.promise;const s=N(e),o=this._startQuerySub(e,s);return this.queryOnceDfds[s]=(r=this.queryOnceDfds[s])!==null&&r!==void 0?r:[],this.queryOnceDfds[s].push({q:e,dfd:i,eventId:o}),setTimeout(()=>i.reject(new Error("Query timed out")),Yo),i.promise}_completeQueryOnce(e,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(i=>i.dfd!==r),this._cleanupQuery(e,n))}_unsubQuery(e,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(i=>i.cb!==r),this._cleanupQuery(e,n))}_cleanupQuery(e,n){var r,i;!((r=this.queryCbs[n])===null||r===void 0)&&r.length||!((i=this.queryOnceDfds[n])===null||i===void 0)&&i.length||(delete this.queryCbs[n],delete this.queryOnceDfds[n],this._trySendAuthed(L(),{op:"remove-query",q:e}))}_rewriteMutations(e,n,r){if(!e)return n;const i=a=>{const[f,h,p]=a["forward-identity"];return W(e,h,p)},s=a=>{const[f,h,p]=a["forward-identity"];return he(e,h,p)},o={attrIdMap:{},refSwapAttrIds:new Set};let u=!1;const c=(a,f)=>{const h=[];for(const p of a){const[y]=p;if(y==="add-attr"){const[T,g]=p,S=i(g);if(S&&g.id!==S.id){o.attrIdMap[g.id]=S.id,u=!0;continue}if(g["value-type"]==="ref"){const m=s(g);if(m){o.attrIdMap[g.id]=m.id,o.refSwapAttrIds.add(g.id),u=!0;continue}}}if(r&&f&&r>=f&&y==="add-attr"||y==="update-attr"||y==="delete-attr"){u=!0;continue}const _=u?qs(o,p):p;h.push(_)}return u?h:a},d=new Map;for(const[a,f]of n.entries())d.set(a,Object.assign(Object.assign({},f),{"tx-steps":c(f["tx-steps"],f["tx-id"])}));return u?d:n}_rewriteMutationsSorted(e,n){return jr(this._rewriteMutations(e,n).entries())}optimisticAttrs(){var e;const n=[...this.pendingMutations.currentValue.values()].flatMap(u=>u["tx-steps"]),r=new Set(n.filter(([u,c])=>u==="delete-attr").map(([u,c])=>c)),i=[];for(const[u,c]of n)if(u==="add-attr")i.push(c);else if(u==="update-attr"&&c.id&&(!((e=this.attrs)===null||e===void 0)&&e[c.id])){const d=Object.assign(Object.assign({},this.attrs[c.id]),c);i.push(d)}const s=[...Object.values(this.attrs||{}),...i].filter(u=>!r.has(u.id));return Object.fromEntries(s.map(u=>[u.id,u]))}dataForQuery(e){const n=this._errorMessage;if(n)return{error:n};if(!this.querySubs||!this.pendingMutations)return;const r=this.querySubs.version(),i=this.querySubs.currentValue,s=this.pendingMutations.version(),o=this.pendingMutations.currentValue,{q:u,result:c}=i[e]||{};if(!c)return;const d=this._dataForQueryCache[e];if(d&&r===d.querySubVersion&&s===d.pendingMutationsVersion)return d.data;const{store:a,pageInfo:f,aggregate:h,processedTxId:p}=c,y=this._rewriteMutationsSorted(a.attrs,o),_=this._applyOptimisticUpdates(a,y,p),T=Yn({store:_,pageInfo:f,aggregate:h},u);return this._dataForQueryCache[e]={querySubVersion:r,pendingMutationsVersion:s,data:T},T}_applyOptimisticUpdates(e,n,r){for(const[i,s]of n)(!s["tx-id"]||r&&s["tx-id"]>r)&&(e=Qi(e,s["tx-steps"]));return e}notifyAll(){Object.keys(this.queryCbs).forEach(e=>{this.notifyOne(e)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var e;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(e=this._transport)===null||e===void 0||e.close()}_sendMutation(e,n){if(n.error){this._handleMutationError("error",e,{message:n.error.message});return}if(this.status!==ae.AUTHENTICATED){this._finishTransaction("enqueued",e);return}const r=Math.max(6e3,Math.min(this._inFlightMutationEventIds.size+1,this.pendingMutations.currentValue.size+1)*6e3);this._isOnline?(this._trySend(e,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",e,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",e)}_flushPendingMessages(){Object.keys(this.queryCbs).map(i=>this.querySubs.currentValue[i]).filter(i=>i).forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),Object.values(this.queryOnceDfds).flat().forEach(({eventId:i,q:s})=>{this._trySendAuthed(i,{op:"add-query",q:s})}),this._rewriteMutationsSorted(this.attrs,this.pendingMutations.currentValue).forEach(([i,s])=>{s["tx-id"]||this._sendMutation(i,s)}),this._syncTable.flushPending()}_cleanupPendingMutationsQueries(){let e=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(e=Math.min(e,n==null?void 0:n.processedTxId));this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i["tx-id"]&&i["tx-id"]<=e&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){if(this.pendingMutations.currentValue.size<this._pendingMutationCleanupThreshold)return;const e=Date.now();this.pendingMutations.set(n=>{for(const[r,i]of Array.from(n.entries()))i.confirmed&&i.confirmed+this._pendingTxCleanupTimeout<e&&n.delete(r);return n})}_trySendAuthed(...e){this.status===ae.AUTHENTICATED&&this._trySend(...e)}_trySend(e,n,r){if(this._transport.isOpen()){switch(kr[n.op]||this._log.info("[send]",this._transport.id,n.op,n),n.op){case"transact":{this._inFlightMutationEventIds.add(e);break}case"init":this._inFlightMutationEventIds.clear()}this._transport.send(Object.assign({"client-event-id":e},n))}}_startSocket(){if(this._wsOk=null,this._isShutdown){this._log.info("[socket][start]",this.config.appId,"Reactor has been shut down and will not start a new socket");return}if(this._transport&&this._transport.isConnecting()){this._log.info("[socket][start]",this._transport.id,"maintained as current transport, we were still in a connecting state");return}const e=this._transport;this._transport=eu({transportType:this._transportType,appId:this.config.appId,apiURI:this.config.apiURI,wsURI:this.config.websocketURI,EventSourceImpl:this._EventSource}),this._transport.onopen=this._transportOnOpen,this._transport.onmessage=this._transportOnMessage,this._transport.onclose=this._transportOnClose,this._transport.onerror=this._transportOnError,this._log.info("[socket][start]",this._transport.id),e!=null&&e.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",e.id),e.close())}getLocalId(e){return $(this,void 0,void 0,function*(){const n=`localToken_${e}`,r=yield this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const i=L();return this._localIdPromises[n]=this._persister.setItem(n,i).then(()=>i),this._localIdPromises[n]})}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const e=new URL(window.location.href);if(e.searchParams.get(Bt)){const n=e.toString();e.searchParams.delete(Bt),e.searchParams.delete("code"),e.searchParams.delete("error");const r=e.pathname+(e.searchParams.size?"?"+e.searchParams:"")+e.hash;if(history.replaceState(history.state,"",r),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let i=!1;const s=o=>{var u;i||(i=!0,navigation.removeEventListener("navigate",s),!o.userInitiated&&o.navigationType==="replace"&&((u=o.destination)===null||u===void 0?void 0:u.url)===n&&history.replaceState(history.state,"",r))};navigation.addEventListener("navigate",s)}}}_oauthLoginInit(){return $(this,void 0,void 0,function*(){var e,n,r,i;if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const s=new URLSearchParams(window.location.search);if(!s.get(Bt))return null;const o=s.get("error");if(o)return this._replaceUrlAfterOAuth(),{error:{message:o}};const u=s.get("code");if(!u)return null;this._replaceUrlAfterOAuth();try{const c=yield this._getCurrentUser(),d=(c==null?void 0:c.type)==="guest",{user:a}=yield ir({apiURI:this.config.apiURI,appId:this.config.appId,code:u,refreshToken:d?c.refresh_token:void 0});return this.setCurrentUser(a),null}catch(c){return((e=c==null?void 0:c.body)===null||e===void 0?void 0:e.type)==="record-not-found"&&((r=(n=c==null?void 0:c.body)===null||n===void 0?void 0:n.hint)===null||r===void 0?void 0:r["record-type"])==="app-oauth-code"&&(yield this._hasCurrentUser())?null:{error:{message:((i=c==null?void 0:c.body)===null||i===void 0?void 0:i.message)||"Error logging in."}}}})}_waitForOAuthCallbackResponse(){return $(this,void 0,void 0,function*(){return yield this._oauthCallbackResponse})}__subscribeMutationErrors(e){return this.mutationErrorCbs.push(e),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==e)}}subscribeAuth(e){this.authCbs.push(e);const n=this._currentUserCached;n.isLoading||e(this._currentUserCached);let r=!1;return this.getCurrentUser().then(i=>{r||Ge(i,n)||e(i)}),()=>{r=!0,this.authCbs=this.authCbs.filter(i=>i!==e)}}getAuth(){return $(this,void 0,void 0,function*(){const{user:e,error:n}=yield this.getCurrentUser();if(n)throw new me("Could not get current user: "+n.message);return e})}subscribeConnectionStatus(e){return this.connectionStatusCbs.push(e),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==e)}}subscribeAttrs(e){return this.attrsCbs.push(e),this.attrs&&e(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==e)}}notifyAuthSubs(e){this.authCbs.forEach(n=>n(e))}notifyMutationErrorSubs(e){this.mutationErrorCbs.forEach(n=>n(e))}notifyAttrsSubs(){if(!this.attrs)return;const e=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(e))}notifyConnectionStatusSubs(e){this.connectionStatusCbs.forEach(n=>n(e))}setCurrentUser(e){return $(this,void 0,void 0,function*(){yield this._persister.setItem(Qt,e)})}getCurrentUserCached(){return this._currentUserCached}_getCurrentUser(){return $(this,void 0,void 0,function*(){const e=yield this._persister.getItem(Qt);return typeof e=="string"?JSON.parse(e):e})}getCurrentUser(){return $(this,void 0,void 0,function*(){const e=yield this._waitForOAuthCallbackResponse();if(e!=null&&e.error){const i={error:e.error,user:void 0};return this._currentUserCached=Object.assign({isLoading:!1},i),i}const r={user:yield this._getCurrentUser(),error:void 0};return this._currentUserCached=Object.assign({isLoading:!1},r),r})}_hasCurrentUser(){return $(this,void 0,void 0,function*(){const e=yield this._persister.getItem(Qt);return JSON.parse(e)!=null})}changeCurrentUser(e){return $(this,void 0,void 0,function*(){var n;const{user:r}=yield this.getCurrentUser();if(!Ge(r,e)){yield this.setCurrentUser(e),this.updateUser(e);try{(n=this._broadcastChannel)===null||n===void 0||n.postMessage({type:"auth"})}catch(i){console.error("Error posting message to broadcast channel",i)}}})}updateUser(e){const n={error:void 0,user:e};this._currentUserCached=Object.assign({isLoading:!1},n),this._dataForQueryCache={},this.querySubs.set(r=>(Object.keys(r).forEach(i=>{delete r[i].result}),r)),this._reconnectTimeoutMs=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:e}){return To({apiURI:this.config.apiURI,appId:this.config.appId,email:e})}signInWithMagicCode(e){return $(this,arguments,void 0,function*({email:n,code:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield wo({apiURI:this.config.apiURI,appId:this.config.appId,email:n,code:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}signInWithCustomToken(e){return $(this,void 0,void 0,function*(){const n=yield So({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:e});return yield this.changeCurrentUser(n.user),n})}signInAsGuest(){return $(this,void 0,void 0,function*(){const e=yield mo({apiURI:this.config.apiURI,appId:this.config.appId});return yield this.changeCurrentUser(e.user),e})}potentiallyInvalidateToken(e,n){var r;const i=(r=e==null?void 0:e.user)===null||r===void 0?void 0:r.refresh_token;if(!i)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}Oo({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:i}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}signOut(e){return $(this,void 0,void 0,function*(){const n=yield this.getCurrentUser();this.potentiallyInvalidateToken(n,e),yield this.changeCurrentUser(null)})}createAuthorizationURL({clientName:e,redirectURL:n}){const{apiURI:r,appId:i}=this.config;return`${r}/runtime/oauth/start?app_id=${i}&client_name=${e}&redirect_uri=${n}`}exchangeCodeForToken(e){return $(this,arguments,void 0,function*({code:n,codeVerifier:r}){var i;const s=yield this.getCurrentUser(),o=((i=s==null?void 0:s.user)===null||i===void 0?void 0:i.type)==="guest",u=yield ir({apiURI:this.config.apiURI,appId:this.config.appId,code:n,codeVerifier:r,refreshToken:o?s.user.refresh_token:void 0});return yield this.changeCurrentUser(u.user),u})}issuerURI(){const{apiURI:e,appId:n}=this.config;return`${e}/runtime/${n}`}signInWithIdToken(e){return $(this,arguments,void 0,function*({idToken:n,clientName:r,nonce:i}){var s;const o=yield this.getCurrentUser(),u=(s=o==null?void 0:o.user)===null||s===void 0?void 0:s.refresh_token,c=yield vo({apiURI:this.config.apiURI,appId:this.config.appId,idToken:n,clientName:r,nonce:i,refreshToken:u});return yield this.changeCurrentUser(c.user),c})}joinRoom(e,n){let r=!1;this._rooms[e]||(r=!0,this._rooms[e]={isConnected:!1,error:void 0}),this._presence[e]=this._presence[e]||{};const i=this._presence[e].result;return n&&!i&&(this._presence[e].result=this._presence[e].result||{},this._presence[e].result.user=n,this._notifyPresenceSubs(e)),r&&this._tryJoinRoom(e,n),()=>{this._cleanupRoom(e)}}_cleanupRoom(e){var n,r,i,s;if(!(!((r=(n=this._presence[e])===null||n===void 0?void 0:n.handlers)===null||r===void 0)&&r.length)&&!Object.keys((i=this._broadcastSubs[e])!==null&&i!==void 0?i:{}).length){const o=(s=this._rooms[e])===null||s===void 0?void 0:s.isConnected;delete this._rooms[e],delete this._presence[e],delete this._broadcastSubs[e],o?this._tryLeaveRoom(e):this._roomsPendingLeave[e]=!0}}getPresence(e,n,r={}){const i=this._rooms[n],s=this._presence[n];return!i||!s||!s.result?null:Object.assign(Object.assign({},Io(s.result,r,this._sessionId)),{isLoading:!i.isConnected,error:i.error})}publishPresence(e,n,r){const i=this._rooms[n],s=this._presence[n];if(!i||!s)return;s.result=s.result||{};const o=Object.assign(Object.assign({},s.result.user),r);s.result.user=o,i.isConnected&&(this._trySetPresence(n,o),this._notifyPresenceSubs(n))}_trySetPresence(e,n){this._trySendAuthed(L(),{op:"set-presence","room-id":e,data:n})}_tryJoinRoom(e,n){this._trySendAuthed(L(),{op:"join-room","room-id":e,data:n}),delete this._roomsPendingLeave[e]}_tryLeaveRoom(e){this._trySendAuthed(L(),{op:"leave-room","room-id":e})}_trySetRoomConnected(e,n){const r=this._rooms[e];r&&(r.isConnected=n)}subscribePresence(e,n,r,i){const s=this.joinRoom(n,r.initialPresence||r.initialData),o=Object.assign(Object.assign({},r),{roomId:n,cb:i,prev:null});return this._presence[n]=this._presence[n]||{},this._presence[n].handlers=this._presence[n].handlers||[],this._presence[n].handlers.push(o),this._notifyPresenceSub(n,o),()=>{var u,c,d;this._presence[n].handlers=(d=(c=(u=this._presence[n])===null||u===void 0?void 0:u.handlers)===null||c===void 0?void 0:c.filter(a=>a!==o))!==null&&d!==void 0?d:[],s()}}_notifyPresenceSubs(e){var n,r;(r=(n=this._presence[e])===null||n===void 0?void 0:n.handlers)===null||r===void 0||r.forEach(i=>{this._notifyPresenceSub(e,i)})}_notifyPresenceSub(e,n){const r=this.getPresence("",e,n);r&&(n.prev&&!Po(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(e,n){var r,i,s;const o=((i=(r=this._presence[e])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.peers)||{};let u=Object.fromEntries(Object.entries(o).map(([d,a])=>[d,{data:a}]));(s=this._presence[e])===null||s===void 0||s.result;const c=Ot(u,d=>{for(let[a,f,h]of n)switch(f){case"+":bi(d,a,h);break;case"r":On(d,a,h);break;case"-":En(d,a);break}delete d[this._sessionId]});this._setPresencePeers(e,c)}_setPresencePeers(e,n){const r=Object.assign({},n);delete r[this._sessionId];const i=Object.fromEntries(Object.entries(r).map(([s,o])=>[s,o.data]));this._presence=Ot(this._presence,s=>{On(s,[e,"result","peers"],i)})}publishTopic({roomType:e,roomId:n,topic:r,data:i}){var s;const o=this._rooms[n];if(o){if(!o.isConnected){this._broadcastQueue[n]=(s=this._broadcastQueue[n])!==null&&s!==void 0?s:[],this._broadcastQueue[n].push({topic:r,roomType:e,data:i});return}this._tryBroadcast(n,e,r,i)}}_tryBroadcast(e,n,r,i){this._trySendAuthed(L(),{op:"client-broadcast","room-id":e,roomType:n,topic:r,data:i})}subscribeTopic(e,n,r){const i=this.joinRoom(e);return this._broadcastSubs[e]=this._broadcastSubs[e]||{},this._broadcastSubs[e][n]=this._broadcastSubs[e][n]||[],this._broadcastSubs[e][n].push(r),this._presence[e]=this._presence[e]||{},()=>{this._broadcastSubs[e][n]=this._broadcastSubs[e][n].filter(s=>s!==r),this._broadcastSubs[e][n].length||delete this._broadcastSubs[e][n],i()}}_notifyBroadcastSubs(e,n,r){var i,s,o;(o=(s=(i=this._broadcastSubs)===null||i===void 0?void 0:i[e])===null||s===void 0?void 0:s[n])===null||o===void 0||o.forEach(u=>{var c,d,a,f,h,p;const y=(c=r.data)===null||c===void 0?void 0:c.data,_=r.data["peer-id"]===this._sessionId?(a=(d=this._presence[e])===null||d===void 0?void 0:d.result)===null||a===void 0?void 0:a.user:(p=(h=(f=this._presence[e])===null||f===void 0?void 0:f.result)===null||h===void 0?void 0:h.peers)===null||p===void 0?void 0:p[r.data["peer-id"]];return u(y,_)})}uploadFile(e,n,r){return $(this,void 0,void 0,function*(){var i;const s=yield this.getCurrentUser(),o=(i=s==null?void 0:s.user)===null||i===void 0?void 0:i.refresh_token;return Eo(Object.assign(Object.assign({},r),{apiURI:this.config.apiURI,appId:this.config.appId,path:e,file:n,refreshToken:o}))})}deleteFile(e){return $(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield Ao({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:i})})}upload(e,n){return $(this,void 0,void 0,function*(){var r;const i=yield this.getCurrentUser(),s=(r=i==null?void 0:i.user)===null||r===void 0?void 0:r.refresh_token,o=e||n.name,u=yield Co({apiURI:this.config.apiURI,appId:this.config.appId,fileName:o,refreshToken:s});return yield ko(u,n)})}getDownloadUrl(e){return $(this,void 0,void 0,function*(){var n;const r=yield this.getCurrentUser(),i=(n=r==null?void 0:r.user)===null||n===void 0?void 0:n.refresh_token;return yield jo({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:i})})}}let rt;function su(t,e){rt==null||rt.dispose();const n=fu(e),r=au(e,u),i=uu(ou(t));function s(a){var f;a.source===i.element.contentWindow&&((f=a.data)===null||f===void 0?void 0:f.type)==="close"&&n.isVisible()&&u()}function o(a){const f=a.shiftKey&&a.ctrlKey&&a.key==="0",h=a.key==="Escape"||a.key==="Esc";(f||h&&n.isVisible())&&u()}function u(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(i.element)||n.element.appendChild(i.element))}function c(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",s)}function d(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",s),rt={dispose:c}}return d()}function ou(t){return`${Wt||or?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${t}`}function uu(t){const e=document.createElement("iframe");return e.src=t,e.className="instant-devtool-iframe",Object.assign(e.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:e}}function au(t,e){const n=`
|
|
32
32
|
<svg width="32" height="32" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
33
33
|
<rect width="512" height="512" fill="black"/>
|
|
34
34
|
<rect x="97.0973" y="91.3297" width="140" height="330" fill="white"/>
|
|
35
35
|
</svg>
|
|
36
|
-
`,r=document.createElement("button");return r.innerHTML=n,r.className="instant-devtool-toggler",Object.assign(r.style,Object.assign(Object.assign({position:"fixed"},cu(t.position)),{height:"32px",width:"32px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"9010",padding:"0",margin:"0",border:"none",cursor:"pointer"})),r.addEventListener("click",e),{element:r}}function cu(t){switch(t){case"bottom-left":return{bottom:"24px",left:"24px"};case"bottom-right":return{bottom:"24px",right:"24px"};case"top-right":return{top:"24px",right:"24px"};case"top-left":return{top:"24px",left:"24px"}}}function du(t){switch(t){case"bottom-left":return{bottom:"24px",right:"24px",left:"60px",top:"72px"};case"bottom-right":return{bottom:"24px",left:"24px",right:"60px",top:"72px"};case"top-right":return{top:"24px",left:"24px",right:"60px",bottom:"72px"};case"top-left":return{top:"24px",right:"24px",left:"60px",bottom:"72px"}}}function fu(t){const e=document.createElement("div");Object.assign(e.style,Object.assign(Object.assign({position:"fixed"},du(t.position)),{display:"block",borderRadius:"4px",border:"1px #ccc solid",boxShadow:"0px 0px 8px #00000044",backgroundColor:"#eee",zIndex:"999990"})),e.style.display="none",e.className="instant-devtool-container";function n(){return e.style.display!=="none"}return{element:e,isVisible:n}}const lu={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"};function hu(){var t;return globalThis.__instantDbSchemaHashStore=(t=globalThis.__instantDbSchemaHashStore)!==null&&t!==void 0?t:new WeakMap,globalThis.__instantDbSchemaHashStore}function pu(){var t;return globalThis.__instantDbStore=(t=globalThis.__instantDbStore)!==null&&t!==void 0?t:{},globalThis.__instantDbStore}function Gt(t){const e=t.__adminToken;return t.appId+"_"+(t.websocketURI||"default_ws_uri")+"_"+(t.apiURI||"default_api_uri")+"_"+(e||"client_only")+"_"+t.useDateObjects}const Ht=pu(),Yt=hu();class yu{constructor(e){this.db=e,this.sendMagicCode=n=>this.db.sendMagicCode(n),this.signInWithMagicCode=n=>this.db.signInWithMagicCode(n),this.signInWithToken=n=>this.db.signInWithCustomToken(n),this.signInAsGuest=()=>this.db.signInAsGuest(),this.createAuthorizationURL=n=>this.db.createAuthorizationURL(n),this.signInWithIdToken=n=>this.db.signInWithIdToken(n),this.exchangeOAuthCode=n=>this.db.exchangeCodeForToken(n),this.issuerURI=()=>this.db.issuerURI(),this.signOut=(n={invalidateToken:!0})=>this.db.signOut(n)}}class bu{constructor(e){this.db=e,this.uploadFile=(n,r,i={})=>this.db.uploadFile(n,r,i),this.delete=n=>this.db.deleteFile(n),this.upload=(n,r)=>this.db.upload(n,r),this.put=this.upload,this.getDownloadUrl=n=>this.db.getDownloadUrl(n)}}function _u(t){return JSON.parse(JSON.stringify(t))}class gu{constructor(e){this.tx=Ut(),this._reactor=e,this.auth=new yu(this._reactor),this.storage=new bu(this._reactor)}transact(e){return this._reactor.pushTx(e)}getLocalId(e){return this._reactor.getLocalId(e)}subscribeQuery(e,n,r){return this._reactor.subscribeQuery(e,n,r)}subscribeAuth(e){return this._reactor.subscribeAuth(e)}getAuth(){return this._reactor.getAuth()}subscribeConnectionStatus(e){return this._reactor.subscribeConnectionStatus(e)}joinRoom(e="_defaultRoomType",n="_defaultRoomId",r){return{leaveRoom:this._reactor.joinRoom(n,r==null?void 0:r.initialPresence),subscribeTopic:(s,o)=>this._reactor.subscribeTopic(n,s,o),subscribePresence:(s,o)=>this._reactor.subscribePresence(e,n,s,o),publishTopic:(s,o)=>this._reactor.publishTopic({roomType:e,roomId:n,topic:s,data:o}),publishPresence:s=>this._reactor.publishPresence(e,n,s),getPresence:s=>this._reactor.getPresence(e,n,s)}}shutdown(){delete Ht[Gt(this._reactor.config)],this._reactor.shutdown()}queryOnce(e,n){return this._reactor.queryOnce(e,n)}}function Ir(t){if(!t)return"0";if(Yt.get(t))return Yt.get(t);const e=N(t);return Yt.set(t,e),e}function Tu(t,e){return Ir(t._reactor.config.schema)!==Ir(e)}function wu(t,e,n,r,i){const s=Ht[Gt(t)];if(s)return Tu(s,t.schema)&&s._reactor.updateSchema(t.schema),s;const o=new iu(Object.assign(Object.assign(Object.assign({},lu),t),{cardinalityInference:!!t.schema}),e||nr,n||rr,Object.assign(Object.assign({},r||{}),{"@instantdb/core":lr}),i),u=new gu(o);return Ht[Gt(t)]=u,Su(t.appId,t.devtool),u}function Su(t,e){if(typeof window>"u"||typeof window.location>"u"||typeof document>"u"||typeof e=="boolean"&&!e)return;const n=Object.assign({position:"bottom-right",allowedHosts:["localhost"]},typeof e=="object"?e:{});n.allowedHosts.includes(window.location.hostname)&&su(t,n)}const mu={isLoading:!0,data:void 0,pageInfo:void 0,error:void 0};function Pr(t){return{isLoading:!t,data:void 0,pageInfo:void 0,error:void 0,...t||{}}}function vu(t,e,n){e&&n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=e?_u(e):null,i=N(r),s=k.useRef(Pr(t._reactor.getPreviousResult(r))),o=k.useCallback(c=>(s.current=Pr(t._reactor.getPreviousResult(r)),r?t.subscribeQuery(r,a=>{s.current={isLoading:!a,data:void 0,pageInfo:void 0,error:void 0,...a},c()}):()=>{}),[i]);return{state:k.useSyncExternalStore(o,()=>s.current,()=>mu),query:r}}function Ou(){const t=k.useRef(null);k.useEffect(()=>{n()},[]);function e(r,i){clearTimeout(t.current),t.current=setTimeout(i,r)}function n(){clearTimeout(t.current)}return{set:e,clear:n}}const Eu=1e3;function Au(t,e,n){k.useEffect(()=>t.core._reactor.subscribeTopic(t.id,e,(i,s)=>{n(i,s)}),[t.id,e])}function Cu(t,e){return k.useEffect(()=>t.core._reactor.joinRoom(t.id),[t.id]),k.useCallback(r=>{t.core._reactor.publishTopic({roomType:t.type,roomId:t.id,topic:e,data:r})},[t.id,e])}function ku(t,e={}){var o,u;const[n,r]=k.useState(()=>t.core._reactor.getPresence(t.type,t.id,e)??{peers:{},isLoading:!0});k.useEffect(()=>t.core._reactor.subscribePresence(t.type,t.id,e,d=>{r(d)}),[t.id,e.user,(o=e.peers)==null?void 0:o.join(),(u=e.keys)==null?void 0:u.join()]);const i=k.useCallback(c=>{t.core._reactor.publishPresence(t.type,t.id,c)},[t.type,t.id]);return k.useMemo(()=>({...n,publishPresence:i}),[n,i])}function ju(t,e,n){k.useEffect(()=>t.core._reactor.joinRoom(t.id,e),[t.id]),k.useEffect(()=>t.core._reactor.publishPresence(t.type,t.id,e),[t.type,t.id,n??JSON.stringify(e)])}function Iu(t,e,n={}){const r=Ou(),i=pe.usePresence(t,{keys:[e]}),s=k.useMemo(()=>{const a=t._core._reactor.getPresence(t.type,t.id);return n!=null&&n.writeOnly?[]:Object.values((a==null?void 0:a.peers)??{}).filter(f=>f[e]===!0)},[n==null?void 0:n.writeOnly,i]),o=k.useCallback(a=>{t.core._reactor.publishPresence(t.type,t.id,{[e]:a}),a&&((n==null?void 0:n.timeout)===null||(n==null?void 0:n.timeout)===0||r.set((n==null?void 0:n.timeout)??Eu,()=>{t.core._reactor.publishPresence(t.type,t.id,{[e]:null})}))},[t.type,t.id,e,n==null?void 0:n.timeout,r]),u=k.useCallback(a=>{const h=!((n==null?void 0:n.stopOnEnter)&&a.key==="Enter");o(h)},[n.stopOnEnter,o]),c=k.useCallback(()=>{o(!1)},[o]),d=k.useMemo(()=>({onKeyDown:u,onBlur:c}),[u,c]);return{active:s,setActive:o,inputProps:d}}const pe={useTopicEffect:Au,usePublishTopic:Cu,usePresence:ku,useSyncPresence:ju,useTypingIndicator:Iu};class Pu{constructor(e,n,r){this.useTopicEffect=(i,s)=>{pe.useTopicEffect(this,i,s)},this.usePublishTopic=i=>pe.usePublishTopic(this,i),this.usePresence=(i={})=>pe.usePresence(this,i),this.useSyncPresence=(i,s)=>pe.useSyncPresence(this,i,s),this.useTypingIndicator=(i,s={})=>pe.useTypingIndicator(this,i,s),this.core=e,this._core=this.core,this.type=n,this.id=r}}const Ru={isLoading:!0,user:void 0,error:void 0};class Mu{constructor(e,n){this.tx=Ut(),this.getLocalId=r=>this.core.getLocalId(r),this.useLocalId=r=>{const[i,s]=k.useState(null);return k.useEffect(()=>{(async()=>{const u=await this.getLocalId(r);s(u)})()},[r]),i},this.rooms=pe,this.transact=r=>this.core.transact(r),this.useQuery=(r,i)=>vu(this.core,r,i).state,this.useAuth=()=>{const r=k.useRef(this.core._reactor._currentUserCached),i=k.useCallback(o=>this.core.subscribeAuth(c=>{r.current={isLoading:!1,...c},o()}),[]);return k.useSyncExternalStore(i,()=>r.current,()=>Ru)},this.useUser=()=>{const{user:r}=this.useAuth();if(!r)throw new me("useUser must be used within an auth-protected route");return r},this.useConnectionStatus=()=>{const r=k.useRef(this.core._reactor.status),i=k.useCallback(o=>this.core.subscribeConnectionStatus(c=>{c!==r.current&&(r.current=c,o())}),[]);return k.useSyncExternalStore(i,()=>r.current,()=>"connecting")},this.queryOnce=(r,i)=>this.core.queryOnce(r,i),this.SignedIn=({children:r})=>{const i=this.useAuth();return i.isLoading||i.error||!i.user?null:ze.jsx(ze.Fragment,{children:r})},this.SignedOut=({children:r})=>{const i=this.useAuth();return i.isLoading||i.error||i.user?null:ze.jsx(ze.Fragment,{children:r})},this.core=wu(e,this.constructor.Storage,this.constructor.NetworkListener,n,this.constructor.EventSourceImpl),this._core=this.core,this.auth=this.core.auth,this.storage=this.core.storage}room(e="_defaultRoomType",n="_defaultRoomId"){return new Pu(this.core,e,n)}getAuth(){return this.core.getAuth()}}ce.InstantReactAbstractDatabase=Mu,Object.defineProperty(ce,Symbol.toStringTag,{value:"Module"})});
|
|
36
|
+
`,r=document.createElement("button");return r.innerHTML=n,r.className="instant-devtool-toggler",Object.assign(r.style,Object.assign(Object.assign({position:"fixed"},cu(t.position)),{height:"32px",width:"32px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"9010",padding:"0",margin:"0",border:"none",cursor:"pointer"})),r.addEventListener("click",e),{element:r}}function cu(t){switch(t){case"bottom-left":return{bottom:"24px",left:"24px"};case"bottom-right":return{bottom:"24px",right:"24px"};case"top-right":return{top:"24px",right:"24px"};case"top-left":return{top:"24px",left:"24px"}}}function du(t){switch(t){case"bottom-left":return{bottom:"24px",right:"24px",left:"60px",top:"72px"};case"bottom-right":return{bottom:"24px",left:"24px",right:"60px",top:"72px"};case"top-right":return{top:"24px",left:"24px",right:"60px",bottom:"72px"};case"top-left":return{top:"24px",right:"24px",left:"60px",bottom:"72px"}}}function fu(t){const e=document.createElement("div");Object.assign(e.style,Object.assign(Object.assign({position:"fixed"},du(t.position)),{display:"block",borderRadius:"4px",border:"1px #ccc solid",boxShadow:"0px 0px 8px #00000044",backgroundColor:"#eee",zIndex:"999990"})),e.style.display="none",e.className="instant-devtool-container";function n(){return e.style.display!=="none"}return{element:e,isVisible:n}}const lu={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"};function hu(){var t;return globalThis.__instantDbSchemaHashStore=(t=globalThis.__instantDbSchemaHashStore)!==null&&t!==void 0?t:new WeakMap,globalThis.__instantDbSchemaHashStore}function pu(){var t;return globalThis.__instantDbStore=(t=globalThis.__instantDbStore)!==null&&t!==void 0?t:{},globalThis.__instantDbStore}function Gt(t){const e=t.__adminToken;return t.appId+"_"+(t.websocketURI||"default_ws_uri")+"_"+(t.apiURI||"default_api_uri")+"_"+(e||"client_only")+"_"+t.useDateObjects}const Ht=pu(),Yt=hu();class yu{constructor(e){this.db=e,this.sendMagicCode=n=>this.db.sendMagicCode(n),this.signInWithMagicCode=n=>this.db.signInWithMagicCode(n),this.signInWithToken=n=>this.db.signInWithCustomToken(n),this.signInAsGuest=()=>this.db.signInAsGuest(),this.createAuthorizationURL=n=>this.db.createAuthorizationURL(n),this.signInWithIdToken=n=>this.db.signInWithIdToken(n),this.exchangeOAuthCode=n=>this.db.exchangeCodeForToken(n),this.issuerURI=()=>this.db.issuerURI(),this.signOut=(n={invalidateToken:!0})=>this.db.signOut(n)}}class bu{constructor(e){this.db=e,this.uploadFile=(n,r,i={})=>this.db.uploadFile(n,r,i),this.delete=n=>this.db.deleteFile(n),this.upload=(n,r)=>this.db.upload(n,r),this.put=this.upload,this.getDownloadUrl=n=>this.db.getDownloadUrl(n)}}function _u(t){return JSON.parse(JSON.stringify(t))}class gu{constructor(e){this.tx=Ut(),this._reactor=e,this.auth=new yu(this._reactor),this.storage=new bu(this._reactor)}transact(e){return this._reactor.pushTx(e)}getLocalId(e){return this._reactor.getLocalId(e)}subscribeQuery(e,n,r){return this._reactor.subscribeQuery(e,n,r)}subscribeAuth(e){return this._reactor.subscribeAuth(e)}getAuth(){return this._reactor.getAuth()}subscribeConnectionStatus(e){return this._reactor.subscribeConnectionStatus(e)}joinRoom(e="_defaultRoomType",n="_defaultRoomId",r){return{leaveRoom:this._reactor.joinRoom(n,r==null?void 0:r.initialPresence),subscribeTopic:(s,o)=>this._reactor.subscribeTopic(n,s,o),subscribePresence:(s,o)=>this._reactor.subscribePresence(e,n,s,o),publishTopic:(s,o)=>this._reactor.publishTopic({roomType:e,roomId:n,topic:s,data:o}),publishPresence:s=>this._reactor.publishPresence(e,n,s),getPresence:s=>this._reactor.getPresence(e,n,s)}}shutdown(){delete Ht[Gt(this._reactor.config)],this._reactor.shutdown()}queryOnce(e,n){return this._reactor.queryOnce(e,n)}_syncTableExperimental(e,n){return this._reactor.subscribeTable(e,n)}}function Ir(t){if(!t)return"0";if(Yt.get(t))return Yt.get(t);const e=N(t);return Yt.set(t,e),e}function Tu(t,e){return Ir(t._reactor.config.schema)!==Ir(e)}function wu(t,e,n,r,i){const s=Ht[Gt(t)];if(s)return Tu(s,t.schema)&&s._reactor.updateSchema(t.schema),s;const o=new iu(Object.assign(Object.assign(Object.assign({},lu),t),{cardinalityInference:!!t.schema}),e||nr,n||rr,Object.assign(Object.assign({},r||{}),{"@instantdb/core":lr}),i),u=new gu(o);return Ht[Gt(t)]=u,Su(t.appId,t.devtool),u}function Su(t,e){if(typeof window>"u"||typeof window.location>"u"||typeof document>"u"||typeof e=="boolean"&&!e)return;const n=Object.assign({position:"bottom-right",allowedHosts:["localhost"]},typeof e=="object"?e:{});n.allowedHosts.includes(window.location.hostname)&&su(t,n)}const mu={isLoading:!0,data:void 0,pageInfo:void 0,error:void 0};function Pr(t){return{isLoading:!t,data:void 0,pageInfo:void 0,error:void 0,...t||{}}}function vu(t,e,n){e&&n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=e?_u(e):null,i=N(r),s=k.useRef(Pr(t._reactor.getPreviousResult(r))),o=k.useCallback(c=>(s.current=Pr(t._reactor.getPreviousResult(r)),r?t.subscribeQuery(r,a=>{s.current={isLoading:!a,data:void 0,pageInfo:void 0,error:void 0,...a},c()}):()=>{}),[i]);return{state:k.useSyncExternalStore(o,()=>s.current,()=>mu),query:r}}function Ou(){const t=k.useRef(null);k.useEffect(()=>{n()},[]);function e(r,i){clearTimeout(t.current),t.current=setTimeout(i,r)}function n(){clearTimeout(t.current)}return{set:e,clear:n}}const Eu=1e3;function Au(t,e,n){k.useEffect(()=>t.core._reactor.subscribeTopic(t.id,e,(i,s)=>{n(i,s)}),[t.id,e])}function Cu(t,e){return k.useEffect(()=>t.core._reactor.joinRoom(t.id),[t.id]),k.useCallback(r=>{t.core._reactor.publishTopic({roomType:t.type,roomId:t.id,topic:e,data:r})},[t.id,e])}function ku(t,e={}){var o,u;const[n,r]=k.useState(()=>t.core._reactor.getPresence(t.type,t.id,e)??{peers:{},isLoading:!0});k.useEffect(()=>t.core._reactor.subscribePresence(t.type,t.id,e,d=>{r(d)}),[t.id,e.user,(o=e.peers)==null?void 0:o.join(),(u=e.keys)==null?void 0:u.join()]);const i=k.useCallback(c=>{t.core._reactor.publishPresence(t.type,t.id,c)},[t.type,t.id]);return k.useMemo(()=>({...n,publishPresence:i}),[n,i])}function ju(t,e,n){k.useEffect(()=>t.core._reactor.joinRoom(t.id,e),[t.id]),k.useEffect(()=>t.core._reactor.publishPresence(t.type,t.id,e),[t.type,t.id,n??JSON.stringify(e)])}function Iu(t,e,n={}){const r=Ou(),i=pe.usePresence(t,{keys:[e]}),s=k.useMemo(()=>{const a=t._core._reactor.getPresence(t.type,t.id);return n!=null&&n.writeOnly?[]:Object.values((a==null?void 0:a.peers)??{}).filter(f=>f[e]===!0)},[n==null?void 0:n.writeOnly,i]),o=k.useCallback(a=>{t.core._reactor.publishPresence(t.type,t.id,{[e]:a}),a&&((n==null?void 0:n.timeout)===null||(n==null?void 0:n.timeout)===0||r.set((n==null?void 0:n.timeout)??Eu,()=>{t.core._reactor.publishPresence(t.type,t.id,{[e]:null})}))},[t.type,t.id,e,n==null?void 0:n.timeout,r]),u=k.useCallback(a=>{const h=!((n==null?void 0:n.stopOnEnter)&&a.key==="Enter");o(h)},[n.stopOnEnter,o]),c=k.useCallback(()=>{o(!1)},[o]),d=k.useMemo(()=>({onKeyDown:u,onBlur:c}),[u,c]);return{active:s,setActive:o,inputProps:d}}const pe={useTopicEffect:Au,usePublishTopic:Cu,usePresence:ku,useSyncPresence:ju,useTypingIndicator:Iu};class Pu{constructor(e,n,r){this.useTopicEffect=(i,s)=>{pe.useTopicEffect(this,i,s)},this.usePublishTopic=i=>pe.usePublishTopic(this,i),this.usePresence=(i={})=>pe.usePresence(this,i),this.useSyncPresence=(i,s)=>pe.useSyncPresence(this,i,s),this.useTypingIndicator=(i,s={})=>pe.useTypingIndicator(this,i,s),this.core=e,this._core=this.core,this.type=n,this.id=r}}const Ru={isLoading:!0,user:void 0,error:void 0};class Mu{constructor(e,n){this.tx=Ut(),this.getLocalId=r=>this.core.getLocalId(r),this.useLocalId=r=>{const[i,s]=k.useState(null);return k.useEffect(()=>{(async()=>{const u=await this.getLocalId(r);s(u)})()},[r]),i},this.rooms=pe,this.transact=r=>this.core.transact(r),this.useQuery=(r,i)=>vu(this.core,r,i).state,this.useAuth=()=>{const r=k.useRef(this.core._reactor._currentUserCached),i=k.useCallback(o=>this.core.subscribeAuth(c=>{r.current={isLoading:!1,...c},o()}),[]);return k.useSyncExternalStore(i,()=>r.current,()=>Ru)},this.useUser=()=>{const{user:r}=this.useAuth();if(!r)throw new me("useUser must be used within an auth-protected route");return r},this.useConnectionStatus=()=>{const r=k.useRef(this.core._reactor.status),i=k.useCallback(o=>this.core.subscribeConnectionStatus(c=>{c!==r.current&&(r.current=c,o())}),[]);return k.useSyncExternalStore(i,()=>r.current,()=>"connecting")},this.queryOnce=(r,i)=>this.core.queryOnce(r,i),this.SignedIn=({children:r})=>{const i=this.useAuth();return i.isLoading||i.error||!i.user?null:ze.jsx(ze.Fragment,{children:r})},this.SignedOut=({children:r})=>{const i=this.useAuth();return i.isLoading||i.error||i.user?null:ze.jsx(ze.Fragment,{children:r})},this.core=wu(e,this.constructor.Storage,this.constructor.NetworkListener,n,this.constructor.EventSourceImpl),this._core=this.core,this.auth=this.core.auth,this.storage=this.core.storage}room(e="_defaultRoomType",n="_defaultRoomId"){return new Pu(this.core,e,n)}getAuth(){return this.core.getAuth()}}ce.InstantReactAbstractDatabase=Mu,Object.defineProperty(ce,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@instantdb/react-common",
|
|
3
|
-
"version": "v0.22.47-experimental.sync-table.
|
|
3
|
+
"version": "v0.22.47-experimental.sync-table.19174988015.1",
|
|
4
4
|
"description": "Instant DB shared components for React and React Native",
|
|
5
5
|
"homepage": "https://github.com/instantdb/instant/tree/main/client/packages/react-common",
|
|
6
6
|
"repository": {
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"react": ">=16"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@instantdb/core": "v0.22.47-experimental.sync-table.
|
|
57
|
-
"@instantdb/version": "v0.22.47-experimental.sync-table.
|
|
56
|
+
"@instantdb/core": "v0.22.47-experimental.sync-table.19174988015.1",
|
|
57
|
+
"@instantdb/version": "v0.22.47-experimental.sync-table.19174988015.1"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"test": "vitest",
|