@instantdb/react-common 0.22.29 → 0.22.30-experimental.adtk6.18724548131.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
|
@@ -3825,7 +3825,7 @@ function nr(e) {
|
|
|
3825
3825
|
}, t;
|
|
3826
3826
|
}, {});
|
|
3827
3827
|
}
|
|
3828
|
-
const Br = "v0.22.
|
|
3828
|
+
const Br = "v0.22.30-experimental.adtk6.18724548131.1";
|
|
3829
3829
|
function au(e) {
|
|
3830
3830
|
return {
|
|
3831
3831
|
info: e ? console.info.bind(console) : () => {
|
|
@@ -5297,7 +5297,7 @@ class ju {
|
|
|
5297
5297
|
}
|
|
5298
5298
|
// TODO: look into typing again
|
|
5299
5299
|
subscribePresence(t, n, r, i) {
|
|
5300
|
-
const s = this.joinRoom(n, r.
|
|
5300
|
+
const s = this.joinRoom(n, r.initialData), o = Object.assign(Object.assign({}, r), { roomId: n, cb: i, prev: null });
|
|
5301
5301
|
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), () => {
|
|
5302
5302
|
var u, a, c;
|
|
5303
5303
|
this._presence[n].handlers = (c = (a = (u = this._presence[n]) === null || u === void 0 ? void 0 : u.handlers) === null || a === void 0 ? void 0 : a.filter((d) => d !== o)) !== null && c !== void 0 ? c : [], s();
|
|
@@ -27,8 +27,8 @@ Check the top-level render call using <`+_+">.")}return y}}function zr(f,y){{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} />`,pn,ve,Gu,ve),Br[ve+pn]=!0}}return f===i?Ku($):Wu($),$}}function zu(f,y,_){return Qr(f,y,_,!0)}function qu(f,y,_){return Qr(f,y,_,!1)}var Bu=qu,Qu=zu;$e.Fragment=i,$e.jsx=Bu,$e.jsxs=Qu}(),$e}var Hr={};Hr.NODE_ENV==="production"?Tt.exports=Gr():Tt.exports=Yr();var Ze=Tt.exports;function B(e){if(typeof e=="number")return(Math.abs(e*2654435761)>>>0).toString(16);if(typeof e=="boolean")return e?"1":"0";if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string"){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t=t>>>0;return t.toString(16)}if(Array.isArray(e)){let t=2166136261;for(let n=0;n<e.length;n++){t^=(n+1)*2654435761;const r=B(e[n]);for(let i=0;i<r.length;i++)t^=r.charCodeAt(i),t*=16777619,t=t>>>0}return t.toString(16)}if(typeof e=="object"){let t=2166136261;const n=Object.keys(e).sort();for(let r=0;r<n.length;r++){const i=n[r],s=B(i);t^=parseInt(s,16),t*=16777619,t=t>>>0;const o=B(e[i]);t^=parseInt(o,16),t*=16777619,t=t>>>0}return t.toString(16)}return B(String(e))}const M={Remove:"remove",Replace:"replace",Add:"add"},_n=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Jr=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Xe=Symbol.iterator,J={mutable:"mutable",immutable:"immutable"},wt={};function Ue(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function gn(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,t);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function mt(e){return Object.getPrototypeOf(e)===Set.prototype}function St(e){return Object.getPrototypeOf(e)===Map.prototype}function Z(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function ge(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[_n]}function vt(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ne(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,J))===J.immutable||typeof n=="function")}function Tn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,r=E(ae(n,e.key));if(r!==null&&(r==null?void 0:r.original)!==e.original)return null;const i=e.parent.type===3,s=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>s||Ue(n,s)))return null;t.push(s)}if(e.parent)return Tn(e.parent,t);t.reverse();try{Zr(e.copy,t)}catch{return null}return t}function Te(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function ae(e,t){return Te(e)===2?e.get(t):e[t]}function Le(e,t,n){Te(e)===2?e.set(t,n):e[t]=n}function Ot(e,t){const n=E(e);return(n?Z(n):e)[t]}function ce(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Et(e){if(e)for(;e.finalities.revoke.length>0;)e.finalities.revoke.pop()()}function we(e,t){return t?e:[""].concat(e).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Zr(e,t){for(let n=0;n<t.length-1;n+=1){const r=t[n];if(e=ae(Te(e)===3?Array.from(e):e,r),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Xr(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(e,n);if(r.enumerable&&r.configurable&&r.writable){t[n]=e[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:e[n]}),Reflect.defineProperty(t,n,r)}),t}const ei=Object.prototype.propertyIsEnumerable;function wn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!St(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,J),n!==void 0)&&n!==J.mutable){if(n===J.immutable)return Xr(e);if(typeof n=="function"){if(t.enablePatches||t.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 e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const r={};return Object.keys(e).forEach(i=>{r[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{ei.call(e,i)&&(r[i]=e[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function W(e){e.copy||(e.copy=wn(e.original,e.options))}function Fe(e){if(!ne(e))return vt(e);if(Array.isArray(e))return e.map(Fe);if(e instanceof Map){const n=Array.from(e.entries()).map(([r,i])=>[r,Fe(i)]);if(!St(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Fe);if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Fe(e[n]);return t}function et(e){return ge(e)?Fe(e):e}function se(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&se(e.parent))}function mn(){throw new Error("Cannot modify frozen object")}function Oe(e,t,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(e)?n.get(e):e;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((a,c)=>{if(typeof a=="symbol")return`[${a.toString()}]`;const d=r[c];return typeof a=="object"&&(d instanceof Map||d instanceof Set)?Array.from(d.keys()).indexOf(a):a}).join("/")}`);r.push(o),i.push(t)}else r.push(o)}if(Object.isFrozen(e)||ge(e)){r.pop(),i.pop();return}switch(Te(e)){case 2:for(const[u,a]of e)Oe(u,u,n,r,i),Oe(a,u,n,r,i);e.set=e.clear=e.delete=mn;break;case 3:for(const u of e)Oe(u,u,n,r,i);e.add=e.clear=e.delete=mn;break;case 1:Object.freeze(e);let o=0;for(const u of e)Oe(u,o,n,r,i),o+=1;break;default:Object.freeze(e),Object.keys(e).forEach(u=>{const a=e[u];Oe(a,u,n,r,i)})}r.pop(),i.pop()}function At(e,t){const n=Te(e);if(n===0)Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)});else if(n===1){let r=0;for(const i of e)t(r,i,e),r+=1}else e.forEach((r,i)=>t(i,r,e))}function Sn(e,t,n){if(ge(e)||!ne(e,n)||t.has(e)||Object.isFrozen(e))return;const r=e instanceof Set,i=r?new Map:void 0;if(t.add(e),At(e,(s,o)=>{var u;if(ge(o)){const a=E(o);W(a);const c=!((u=a.assignedMap)===null||u===void 0)&&u.size||a.operated?a.copy:a.original;Le(r?i:e,s,c)}else Sn(o,t,n)}),i){const s=e,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ti(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Sn(ae(n,t),e.finalities.handledSet,e.options)}function Ct(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(vt(t))}))}function jt(e,t,n,r){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&r){const s=Tn(e);s&&t(e,s,n,r)}e.finalized=!0}}function kt(e,t,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const a=e.type===3?e.setMap:e.copy;if(ce(ae(a,t),n)){let c=i.original;i.copy&&(c=i.copy),Ct(e),jt(e,r,s,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(u=e.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,e.options.updatedValues.set(c,i.original)),Le(a,t,c)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ne(n,e.options)&&e.finalities.draft.push(()=>{const s=e.type===3?e.setMap:e.copy;ce(ae(s,t),n)&&ti(e,t)})}function ni(e,t,n,r,i){let{original:s,assignedMap:o,options:u}=e,a=e.copy;a.length<s.length&&([s,a]=[a,s],[n,r]=[r,n]);for(let c=0;c<s.length;c+=1)if(o.get(c.toString())&&a[c]!==s[c]){const d=t.concat([c]),l=we(d,i);n.push({op:M.Replace,path:l,value:et(a[c])}),r.push({op:M.Replace,path:l,value:et(s[c])})}for(let c=s.length;c<a.length;c+=1){const d=t.concat([c]),l=we(d,i);n.push({op:M.Add,path:l,value:et(a[c])})}if(s.length<a.length){const{arrayLengthAssignment:c=!0}=u.enablePatches;if(c){const d=t.concat(["length"]),l=we(d,i);r.push({op:M.Replace,path:l,value:s.length})}else for(let d=a.length;s.length<d;d-=1){const l=t.concat([d-1]),h=we(l,i);r.push({op:M.Remove,path:h})}}}function ri({original:e,copy:t,assignedMap:n},r,i,s,o){n.forEach((u,a)=>{const c=ae(e,a),d=et(ae(t,a)),l=u?Ue(e,a)?M.Replace:M.Add:M.Remove;if(ce(c,d)&&l===M.Replace)return;const h=r.concat(a),p=we(h,o);i.push(l===M.Remove?{op:l,path:p}:{op:l,path:p,value:d}),s.push(l===M.Add?{op:M.Remove,path:p}:l===M.Remove?{op:M.Add,path:p,value:c}:{op:M.Replace,path:p,value:c})})}function ii({original:e,copy:t},n,r,i,s){let o=0;e.forEach(u=>{if(!t.has(u)){const a=n.concat([o]),c=we(a,s);r.push({op:M.Remove,path:c,value:u}),i.unshift({op:M.Add,path:c,value:u})}o+=1}),o=0,t.forEach(u=>{if(!e.has(u)){const a=n.concat([o]),c=we(a,s);r.push({op:M.Add,path:c,value:u}),i.unshift({op:M.Remove,path:c,value:u})}o+=1})}function Ne(e,t,n,r){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ri(e,t,n,r,i);case 1:return ni(e,t,n,r,i);case 3:return ii(e,t,n,r,i)}}const tt=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ne(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},Pt={get size(){return Z(E(this)).size},has(e){return Z(E(this)).has(e)},set(e,t){const n=E(this),r=Z(n);return(!r.has(e)||!ce(r.get(e),t))&&(W(n),se(n),n.assignedMap.set(e,!0),n.copy.set(e,t),kt(n,e,t,Ne)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return W(t),se(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){W(e),se(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);Z(n).forEach((r,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const r=E(this),i=Z(r).get(e),s=((n=(t=r.options).mark)===null||n===void 0?void 0:n.call(t,i,J))===J.mutable;if(r.options.strict&&tt(i,r.options,s),s||r.finalized||!ne(i,r.options)||i!==r.original.get(e))return i;const o=wt.createDraft({original:i,parentDraft:r,key:e,finalities:r.finalities,options:r.options});return W(r),r.copy.set(e,o),o},keys(){return Z(E(this)).keys()},values(){const e=this.keys();return{[Xe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Xe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Xe](){return this.entries()}},si=Reflect.ownKeys(Pt),vn=(e,t,{isValuesIterator:n})=>()=>{var r,i;const s=t.next();if(s.done)return s;const o=s.value;let u=e.setMap.get(o);const a=E(u),c=((i=(r=e.options).mark)===null||i===void 0?void 0:i.call(r,u,J))===J.mutable;if(e.options.strict&&tt(o,e.options,c),!c&&!a&&ne(o,e.options)&&!e.finalized&&e.original.has(o)){const d=wt.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,d),u=d}else a&&(u=a.proxy);return{done:!1,value:n?u:[u,u]}},nt={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;W(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(W(t),se(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),kt(t,e,e,Ne)),this},delete(e){if(!this.has(e))return!1;const t=E(this);W(t),se(t);const n=E(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=E(this);W(e),se(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);W(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:vn(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);W(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:vn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Xe](){return this.values()},forEach(e,t){const n=this.values();let r=n.next();for(;!r.done;)e.call(t,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(nt,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const oi=Reflect.ownKeys(nt),On=new WeakSet,En={get(e,t,n){var r,i;const s=(r=e.copy)===null||r===void 0?void 0:r[t];if(s&&On.has(s))return s;if(t===_n)return e;let o;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(c,J),o===J.mutable)return e.options.strict&&tt(c,e.options,!0),c}const u=Z(e);if(u instanceof Map&&si.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Pt,"size").get.call(e.proxy);const c=Pt[t];if(c)return c.bind(e.proxy)}if(u instanceof Set&&oi.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(nt,"size").get.call(e.proxy);const c=nt[t];if(c)return c.bind(e.proxy)}if(!Ue(u,t)){const c=gn(u,t);return c?"value"in c?c.value:(i=c.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const a=u[t];if(e.options.strict&&tt(a,e.options),e.finalized||!ne(a,e.options))return a;if(a===Ot(e.original,t)){if(W(e),e.copy[t]=It({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return W(c),se(c),c.copy}return e.copy[t]}return a},set(e,t,n){var r;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const s=gn(Z(e),t);if(s!=null&&s.set)return s.set.call(e.proxy,n),!0;const o=Ot(Z(e),t),u=E(o);return u&&ce(u.original,n)?(e.copy[t]=n,e.assignedMap=(r=e.assignedMap)!==null&&r!==void 0?r:new Map,e.assignedMap.set(t,!1),!0):(ce(n,o)&&(n!==void 0||Ue(e.original,t))||(W(e),se(e),Ue(e.original,t)&&ce(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,kt(e,t,n,Ne)),!0)},has(e,t){return t in Z(e)},ownKeys(e){return Reflect.ownKeys(Z(e))},getOwnPropertyDescriptor(e,t){const n=Z(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?En.set.call(this,e,t,void 0,e.proxy):(Ot(e.original,t)!==void 0||t in e.original?(W(e),se(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function It(e){const{original:t,parentDraft:n,key:r,finalities:i,options:s}=e,o=Te(t),u={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(t.entries()):void 0};(r||"key"in e)&&(u.key=r);const{proxy:a,revoke:c}=Proxy.revocable(o===1?Object.assign([],u):u,En);if(i.revoke.push(c),On.add(a),u.proxy=a,n){const d=n;d.finalities.draft.push((l,h)=>{var p,b;const g=E(a);let w=d.type===3?d.setMap:d.copy;const T=ae(w,r),v=E(T);if(v){let S=v.original;v.operated&&(S=vt(T)),Ct(v),jt(v,Ne,l,h),d.options.enableAutoFreeze&&(d.options.updatedValues=(p=d.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,d.options.updatedValues.set(S,v.original)),Le(w,r,S)}(b=g.callbacks)===null||b===void 0||b.forEach(S=>{S(l,h)})})}else{const d=E(a);d.finalities.draft.push((l,h)=>{Ct(d),jt(d,Ne,l,h)})}return a}wt.createDraft=It;function ui(e,t,n,r,i){var s;const o=E(e),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:e,a=!!t.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const c=a?t[0]:o?o.operated?o.copy:o.original:e;return o&&Et(o),i&&Oe(c,c,o==null?void 0:o.options.updatedValues),[c,n&&a?[{op:M.Replace,path:[],value:t[0]}]:n,r&&a?[{op:M.Replace,path:[],value:u}]:r]}function ai(e,t){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;t.enablePatches&&(i=[],s=[]);const u=((n=t.mark)===null||n===void 0?void 0:n.call(t,e,J))===J.mutable||!ne(e,t)?e:It({original:e,parentDraft:null,finalities:r,options:t});return[u,(a=[])=>{const[c,d,l]=ui(u,a,i,s,t.enableAutoFreeze);return t.enablePatches?[c,d,l]:c}]}function Rt(e){const{rootDraft:t,value:n,useRawReturn:r=!1,isRoot:i=!0}=e;At(n,(s,o,u)=>{const a=E(o);if(a&&t&&a.finalities===t.finalities){e.isContainDraft=!0;const c=a.original;if(u instanceof Set){const d=Array.from(u);u.clear(),d.forEach(l=>u.add(s===l?c:l))}else Le(u,s,c)}else typeof o=="object"&&o!==null&&(e.value=o,e.isRoot=!1,Rt(e))}),i&&(e.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 An(e){var t;const n=E(e);if(!ne(e,n==null?void 0:n.options))return e;const r=Te(e);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?St(e)?new Map(e):new(Object.getPrototypeOf(e)).constructor(e):r===3?Array.from(n.setMap.values()):wn(e,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=e;if(At(i,(o,u)=>{if(n&&ce(ae(n.original,o),u))return;const a=An(u);a!==u&&(i===e&&s(),Le(i,o,a))}),r===3){const o=(t=n==null?void 0:n.original)!==null&&t!==void 0?t:i;return mt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function Cn(e){if(!ge(e))throw new Error(`current() is only used for Draft, parameter: ${e}`);return An(e)}const Mt=(e=>function t(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...L){return t(O,U=>n.call(this,U,...L),r)};const a=n,c=r;let d=i;if(typeof r!="function"&&(d=r),d!==void 0&&Object.prototype.toString.call(d)!=="[object Object]")throw new Error(`Invalid options: ${d}, 'options' should be an object.`);d=Object.assign(Object.assign({},e),d);const l=ge(a)?Cn(a):a,h=Array.isArray(d.mark)?(O,L)=>{for(const U of d.mark){if(typeof U!="function")throw new Error(`Invalid mark: ${U}, 'mark' should be a function.`);const le=U(O,L);if(le)return le}}:d.mark,p=(s=d.enablePatches)!==null&&s!==void 0?s:!1,b=(o=d.strict)!==null&&o!==void 0?o:!1,w={enableAutoFreeze:(u=d.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:b,enablePatches:p};if(!ne(l,w)&&typeof l=="object"&&l!==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[T,v]=ai(l,w);if(typeof r!="function"){if(!ne(l,w))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[T,v]}let S;try{S=c(T)}catch(O){throw Et(E(T)),O}const K=O=>{const L=E(T);if(!ge(O)){if(O!==void 0&&!ce(O,T)&&(L!=null&&L.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 le=O==null?void 0:O[Jr];if(le){const ht=le[0];return w.strict&&typeof O=="object"&&O!==null&&Rt({rootDraft:L,value:O,useRawReturn:!0}),v([ht])}if(O!==void 0)return typeof O=="object"&&O!==null&&Rt({rootDraft:L,value:O}),v([O])}if(O===T||O===void 0)return v([]);const U=E(O);if(w===U.options){if(U.operated)throw new Error("Cannot return a modified child draft.");return v([Cn(O)])}return v([O])};return S instanceof Promise?S.then(K,O=>{throw Et(E(T)),O}):K(S)})();Object.prototype.constructor.toString();function jn(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&Object.keys(e).every(i=>t.hasOwnProperty(i))}function kn(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>t.hasOwnProperty(n)&&e[n]===t[n])}function rt(e,t){return typeof e!="object"||typeof t!="object"||e===null||t===null?e===t:jn(e,t)?Object.keys(e).every(n=>rt(e[n],t[n])):!1}function Dt(e){if(!Ve(e))return e;const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Pn(e,t){if(!Ve(e)||!Ve(t))return t;const n=Object.assign({},e);for(const r of Object.keys(t)){if(t[r]===void 0)continue;if(t[r]===null){delete n[r];continue}const i=Ve(e[r])&&Ve(t[r]);n[r]=i?Pn(e[r],t[r]):t[r]}return n}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ci(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let s=0;s<t.length-1;s++){const o=t[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof t[s+1]=="number"?[]:{}),r=r[o]}const i=t[t.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function In(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let i=0;i<t.length-1;i++){const s=t[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof t[i+1]=="number"?[]:{}),r=r[s]}r[t[t.length-1]]=n}function Rn(e,t){if(!e||t.length===0)return;const[n,...r]=t;if(n in e){if(r.length===0){Array.isArray(e)?e.splice(n,1):delete e[n];return}Rn(e[n],r),di(e[n])&&delete e[n]}}function di(e){return e&&Object.keys(e).length===0}const Mn=/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$/,fi={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 li(e){return new Date(e)}function hi(e){return new Date(e+"Z")}const pi=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function yi(e){const t=e.match(pi);if(!t)return null;const[n,r,i,s]=t;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 bi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function _i(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function gi(e){return new Date(e)}function Ti(e){const t=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!e.match(t))throw new Error(`Unable to parse \`${e}\` as a date.`);const r=new Date(e+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function wi(e){const t=/^(.+T.+)([+-])(\d{2})$/,n=e.match(t);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function mi(e){const[t,n]=e.split(", "),[r,i,s]=t.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: ${e}`);let[,u,a,c,d]=o;return u=Number(u),a=Number(a),c=Number(c),d==="PM"&&u!==12?u+=12:d==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,a,c))}function Si(e){switch(e){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function vi(e){const t=e.match(Mn);if(!t)return null;const[n]=t,r=fi[n],i=new Date(e.replace(Mn,"Z"));return new Date(i.getTime()-r*1e3)}const Oi=[yi,_i,Ti,mi,gi,hi,wi,bi,li,Si,vi];function Ei(e,t){try{const n=e(t);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function xt(e){for(const t of Oi){const n=Ei(t,e);if(n)return n}return null}function Ai(e){try{const t=JSON.parse(e);return typeof t=="string"?xt(t):null}catch{return null}}function it(e){if(e!==void 0){if(e===null)return null;if(e instanceof Date)return e;if(typeof e=="string"){const t=xt(e)||Ai(e)||xt(e.trim());if(!t)throw new Error(`Unable to parse \`${e}\` as a date.`);return t}else if(typeof e=="number")return new Date(e);throw new Error(`Invalid date value \`${e}\`. Expected a date, number, or string, got type ${typeof e}.`)}}function Ci(e){return e.cardinality==="one"}function $t(e){return e["value-type"]==="ref"}function Ut(e){return e["value-type"]==="blob"}function Ee(e,t){return e[t]}function st(e,t){return t.reduce((n,r)=>n&&n.get(r),e)}function re(e,t){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.delete(t[0]);return}const[n,...r]=t;e.has(n)&&re(e.get(n),r)}function Q(e,t,n){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.set(t[0],n);return}const[r,...i]=t;let s=e.get(r);s||(s=new Map,e.set(r,s)),Q(s,i,n)}function Dn(e,t,n){const r=new Map,i=new Map,s=new Map;for(const o of t){let[u,a,c,d]=o;const l=Ee(e,a);if(!l){console.warn("no such attr",u,e);continue}l["checked-data-type"]==="date"&&n&&(c=it(c),o[2]=c),$t(l)&&Q(s,[c,a,u],o),Q(r,[u,a,c],o),Q(i,[a,u,c],o)}return{eav:r,aev:i,vae:s}}function xn(e){const t=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(e)){const o=s["forward-identity"],[u,a,c]=o,d=s["reverse-identity"];if(Q(r,[a,c],s),Ut(s)&&Q(t,[a,c],s),s["primary?"]&&Q(n,[a],s),d){const[l,h,p]=d;Q(i,[h,p],s)}}return{blobAttrs:t,primaryKeys:n,forwardIdents:r,revIdents:i}}function ji(e){return{__type:e.__type,attrs:e.attrs,triples:G(e.eav,3),cardinalityInference:e.cardinalityInference,linkIndex:e.linkIndex,useDateObjects:e.useDateObjects}}function ki(e){return Ft(e.attrs,e.triples,e.cardinalityInference,e.linkIndex,e.useDateObjects)}function Lt(e){e.attrIndexes=xn(e.attrs)}function Ft(e,t,n,r,i){const s=Dn(e,t,i);return s.useDateObjects=i,s.attrs=e,s.attrIndexes=xn(e),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function We(e,t){var n,r;let i;if(Array.isArray(t[0])){const[o,u]=t[0],a=e.aev.get(o);if(!a)return null;i=(n=G(a,2).find(d=>d[2]===u))===null||n===void 0?void 0:n[0]}else i=t[0];if(!i)return null;const s=t[2];if(Array.isArray(s)&&s.length===2&&e.aev.get(s[0])){const[o,u]=s,a=e.aev.get(o);if(!a)return null;const d=(r=G(a,2).find(g=>g[2]===u))===null||r===void 0?void 0:r[0];if(!d)return null;const[l,h,p,...b]=t;return[i,h,d,...b]}else{const[o,...u]=t;return[i,...u]}}function Pi(e,t){const n=We(e,t);if(!n)return;const[r,i,s]=n,o=Ee(e.attrs,i);o&&(re(e.eav,[r,i,s]),re(e.aev,[i,r,s]),$t(o)&&re(e.vae,[s,i,r]))}let Ii=0;function $n(e,t,n){const[r,i,s]=n;let o;const u=st(e.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+Ii++}function Ri(e,t){var n;const r=We(e,t);if(!r)return;let[i,s,o]=r;const u=Ee(e.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&e.useDateObjects&&(o=it(o));const a=st(e.eav,[i,s,o]),c=(n=a==null?void 0:a[3])!==null&&n!==void 0?n:$n(e,u,r),d=[i,s,o,c];Ci(u)?(Q(e.eav,[i,s],new Map([[o,d]])),Q(e.aev,[s,i],new Map([[o,d]]))):(Q(e.eav,[i,s,o],d),Q(e.aev,[s,i,o],d)),$t(u)&&Q(e.vae,[o,s,i],d)}function Mi(e,t){var n;const r=We(e,t);if(!r)return;const[i,s,o]=r,u=Ee(e.attrs,s);if(!u)return;if(!Ut(u))throw new Error("merge operation is not supported for links");const a=st(e.eav,[i,s]);if(!a)return;const c=(n=a.values().next())===null||n===void 0?void 0:n.value;if(!c)return;const d=c[2],l=Pn(d,o),h=[i,s,l,$n(e,u,c)];Q(e.eav,[i,s],new Map([[l,h]]))}function Nt(e,t){var n,r;const[i,s]=t,o=We(e,[i]);if(!o)return;const[u]=o,a=e.eav.get(u);if(a){for(const d of a.keys()){const l=e.attrs[d];l&&l["on-delete-reverse"]==="cascade"&&G(a.get(d),1).forEach(([h,p,b])=>{var g;return Nt(e,[b,(g=l["reverse-identity"])===null||g===void 0?void 0:g[1]])}),(!s||!l||((n=l["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(re(e.aev,[d,u]),re(e.eav,[u,d]))}a.size===0&&re(e.eav,[u])}const c=e.vae.get(u)&&G(e.vae.get(u),2);c&&c.forEach(d=>{var l,h,p;const[b,g,w]=d,T=e.attrs[g];(!s||!T||((l=T["reverse-identity"])===null||l===void 0?void 0:l[1])===s)&&(re(e.eav,[b,g,w]),re(e.aev,[g,b,w]),re(e.vae,[w,g,b])),T&&T["on-delete"]==="cascade"&&((h=T["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&Nt(e,[b,(p=T["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=e.vae.get(u))===null||r===void 0?void 0:r.size)===0&&re(e.vae,[u])}function Un(e,t){const n=Dn(e.attrs,t,e.useDateObjects);Object.keys(n).forEach(r=>{e[r]=n[r]})}function Di(e,[t]){e.attrs[t.id]=t,Lt(e)}function Ln(e){return G(e.eav,3)}function xi(e,[t]){if(!e.attrs[t])return;const n=Ln(e).filter(([r,i])=>i!==t);delete e.attrs[t],Lt(e),Un(e,n)}function $i(e,[t]){const n=e.attrs[t.id];n&&(e.attrs[t.id]=Object.assign(Object.assign({},n),t),Lt(e),Un(e,Ln(e)))}function Ui(e,t){const[n,...r]=t;switch(n){case"add-triple":Ri(e,r);break;case"deep-merge-triple":Mi(e,r);break;case"retract-triple":Pi(e,r);break;case"delete-entity":Nt(e,r);break;case"add-attr":Di(e,r);break;case"delete-attr":xi(e,r);break;case"update-attr":$i(e,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function G(e,t,n=[]){if(!e||t===0)return n;if(t===1){for(const r of e.values())n.push(r);return n}for(const r of e.values())G(r,t-1,n);return n}function ot(e,t,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of t.keys())n.$not!==u&&s.push(t.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:a,reverse:c}=n.$isNull;if(c)for(const d of t.keys()){const l=e.vae.get(d),h=!l||((r=l.get(u))===null||r===void 0?void 0:r.get(null))||!l.get(u);(a?h:!h)&&s.push(t.get(d))}else{const d=e.aev.get(u);for(const l of t.keys()){const h=!d||((i=d.get(l))===null||i===void 0?void 0:i.get(null))||!d.get(l);(a?h:!h)&&s.push(t.get(l))}}return s}if(n!=null&&n.$comparator)return G(t,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const a=t.get(u);a&&s.push(a)}return s}function Li(e,t,n){let r="";return e!==void 0&&(r+="e"),t!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Fi(e,[t,n,r]){var i,s;switch(Li(t,n,r)){case"e":{const u=e.eav.get(t);return G(u,2)}case"ea":{const u=(i=e.eav.get(t))===null||i===void 0?void 0:i.get(n);return G(u,1)}case"eav":{const u=(s=e.eav.get(t))===null||s===void 0?void 0:s.get(n);return u?ot(e,u,r):[]}case"ev":{const u=e.eav.get(t);if(!u)return[];const a=[];for(const c of u.values())a.push(...ot(e,c,r));return a}case"a":{const u=e.aev.get(n);return G(u,2)}case"av":{const u=e.aev.get(n);if(!u)return[];const a=[];for(const c of u.values())a.push(...ot(e,c,r));return a}case"v":{const u=[];for(const a of e.eav.values())for(const c of a.values())u.push(...ot(e,c,r));return u}default:return G(e.eav,3)}}function Ni(e,t,n){var r;const i={};for(const[s,o]of t.entries()){const u=(r=e.eav.get(n))===null||r===void 0?void 0:r.get(o.id),a=G(u,1);for(const c of a)i[s]=c[2]}return i}function Ae(e,t,n){var r;return(r=e.attrIndexes.forwardIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Fn(e,t,n){var r;return(r=e.attrIndexes.revIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Vi(e,t){return e.attrIndexes.blobAttrs.get(t)}function Nn(e,t){var n;const r=e.attrIndexes.primaryKeys.get(t);return r||((n=e.attrIndexes.forwardIdents.get(t))===null||n===void 0?void 0:n.get("id"))}function Wi(e,t){const n=We(e,t);if(!n)return;const[r,i,s]=n;if(Ee(e.attrs,i))return st(e.eav,[r,i])}function Ki(e,t){const n=t.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const a=u==null?void 0:u.mode;if(a!=="create"&&a!=="update")return!0;let c=!1;const d=Ee(e.attrs,s);if(d){const l=Nn(e,d["forward-identity"][1]);c=!!Wi(e,[i,l.id,i])}return!(a==="create"&&c||a==="update"&&!c)});return Mt(e,r=>{n.forEach(i=>{Ui(r,i)})})}function zi(e){return typeof e=="string"&&e.startsWith("?")}function qi(e,t,n){if(n.hasOwnProperty(e)){const r=n[e];return Wn(r,t,n)}return Object.assign(Object.assign({},n),{[e]:t})}function Vn(e,t,n){return e===t?n:null}function Bi(e){switch(typeof e){case"string":return e.startsWith("?")?qi:Vn;default:return Vn}}const Qi=["in","$in","$not","$isNull","$comparator"];function Gi(e){for(const t of Qi)if(e.hasOwnProperty(t))return!0;return!1}function Wn(e,t,n){return n?typeof e=="object"?Gi(e)?n:null:Bi(e)(e,t,n):null}function Yi(e,t,n){return e.reduce((r,i,s)=>{const o=t[s];return Wn(i,o,r)},n)}function Hi(e,t,n){return Xi(e,t,n).map(r=>Yi(t,r,n)).filter(r=>r)}function Ji(e,t,n){return t.or?t.or.patterns.flatMap(r=>Vt(e,r,n)):t.and?t.and.patterns.reduce((r,i)=>Vt(e,i,r),n):n.flatMap(r=>Hi(e,t,r))}function Vt(e,t,n=[{}]){return t.reduce((r,i)=>Ji(e,i,r),n)}function Wt(e,t){return Array.isArray(t)?t.map(n=>Wt(e,n)):zi(t)?e[t]:t}function Zi(e,{find:t,where:n}){return Vt(e,n).map(i=>Wt(i,t))}function Xi(e,t,n){return Fi(e,Wt(n,t))}const es=/^(?:[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 Ce(e){return typeof e=="string"&&es.test(e)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function ts(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}let Kt;const ns=new Uint8Array(16);function rs(){if(!Kt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kt=crypto.getRandomValues.bind(crypto)}return Kt(ns)}const Kn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function is(e,t,n){var i;if(Kn.randomUUID&&!e)return Kn.randomUUID();e=e||{};const r=e.random??((i=e.rng)==null?void 0:i.call(e))??rs();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,ts(r)}function zn(e){const t=e.replace(/-/g,""),n=[];for(let r=0;r<t.length;r+=2)n.push(parseInt(t.substring(r,r+2),16));return n}function ss(e,t){for(let n=0;n<e.length;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function os(e,t){return ss(zn(e),zn(t))}function V(){return is()}function us(e,t){return e.localeCompare(t)}function as(){let e=us;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}const cs=as();let ds=0;function Ke(e){return ut(`_${e}`,ds++)}function ut(e,t){return`?${e}-${t}`}class je extends Error{constructor(t){super(t),this.name="AttrNotFoundError"}}function fs(e,t){const n=Nn(e,t);if(!n)throw new je(`Could not find id attr for ${t}`);return n}function qn(e,t,n,r){return[ls(e,t,n,r)]}function ls(e,t,n,r){return[e(n,r),fs(t,n).id,e(n,r),e("time",r)]}function hs(e,t,n){return e.map(r=>r===t?n:r)}function Bn(e,t,n,r,i){const s=Ae(t,n,i),o=Fn(t,n,i),u=s||o;if(!u)throw new je(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[a,c]=u["forward-identity"],[d,l]=u["reverse-identity"],h=r+1,p=s?[e(c,r),u.id,e(l,h),Ke("time")]:[e(c,h),u.id,e(l,r),Ke("time")];return[s?l:c,h,p,u,!!s]}function Qn(e,t){if(typeof t!="string")return function(o){return!1};const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,e?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function ps(e,t){if(typeof t!="object"||t.hasOwnProperty("$in")||t.hasOwnProperty("in"))return t;const n=e["checked-data-type"]==="date";if(t.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(t.$gt)}:function(i){return i[2]>t.$gt}};if(t.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(t.$gte)}:function(i){return i[2]>=t.$gte}};if(t.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(t.$lt)}:function(i){return i[2]<t.$lt}};if(t.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(t.$lte)}:function(i){return i[2]<=t.$lte}};if(t.hasOwnProperty("$like")){const r=Qn(!0,t.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(t.hasOwnProperty("$ilike")){const r=Qn(!1,t.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return t}function ys(e,t,n,r,i,s){const o=Ae(t,n,i),u=Fn(t,n,i),a=o||u;if(!a)throw new je(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const c=Ae(t,n,"id");if(!c)throw new je(`No attr for etype = ${n} label = id`);return[e(n,r),c.id,{$isNull:{attrId:a.id,isNull:s.$isNull,reverse:!o}},Ke("time")]}return o?[e(n,r),a.id,ps(a,s),Ke("time")]:[s,a.id,e(n,r),Ke("time")]}function bs(e,t,n,r,i){const[s,o,u]=i.reduce((a,c)=>{const[d,l,h]=a,[p,b,g]=Bn(e,t,d,l,c);return[p,b,[...h,g]]},[n,r,[]]);return[s,o,u]}function zt(e,t,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[a,c,d]=bs(e,t,n,r,o),l=ys(e,t,a,c,u,s);return d.concat([l])}function _s(e,t){return t?[t].concat(e):e}function gs([e,t]){return e==="or"&&Array.isArray(t)}function Ts([e,t]){return e==="and"&&Array.isArray(t)}function ws(e,t,n){return(r,i)=>{const s=e(r,i);return t==s?s:`${s}-${n}`}}function Gn(e,t,n,r,i,s){const o=e(r,i),u=s.map((a,c)=>{const d=ws(e,o,c);return Hn(d,n,r,i,a)});return{[t]:{patterns:u,joinSym:o}}}function ms(e){const t=[];for(let n=1;n<=e.length;n++)t.push(e.slice(0,n));return t}function Yn(e,t,n,r,i){return ms(i).map(s=>zt(e,t,n,r,s,{$isNull:!0}))}function Hn(e,t,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(gs([s,o]))return Gn(e,"or",t,n,r,o);if(Ts([s,o]))return Gn(e,"and",t,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 a=zt(e,t,n,r,u,o),c=Yn(e,t,n,r,u);return[{or:{patterns:[a,...c],joinSym:e(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Yn(e,t,n,r,u),joinSym:e(n,r)}}]:zt(e,t,n,r,u,o)})}function Ss(e,t,n,r){const i=ut;return r?Hn(i,e,t,n,r).concat(qn(i,e,t,n)):qn(i,e,t,n)}function vs(e,t,n){return[e(t,n),e("time",n)]}function Os(e,t,n,r,i,s){const[o,u,a,c,d]=Bn(e,t,n,r,i),l=hs(a,e(n,r),s);return[o,u,l,c,d]}function Es(e,t,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([a,c]){return o.map(function(h){var p,b,g;const w=!!(t.cardinalityInference&&(!((g=(b=(p=t.linkIndex)===null||p===void 0?void 0:p[n])===null||b===void 0?void 0:b[h])===null||g===void 0)&&g.isSingular));try{const[T,v,S]=Os(e,t,n,r,h,a),K=Zn(t,{etype:T,level:v,form:i[h],join:S}),O=w?K[0]:K;return{[h]:O}}catch(T){if(T instanceof je)return{[h]:w?void 0:[]};throw T}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},c)}):Object.values(s)}function As(e,t,n){return n==="string"?cs(e,t):e>t?1:-1}function at([e,t],[n,r],i){return t===r||t==null&&r==null?os(e,n):r==null?1:t==null?-1:As(t,r,i)}function qt(e){return e==null?e:new Date(e).getTime()}function Cs(e,t,n,r){var i;const[s,o,u,a]=e,c=n==="desc"?1:-1;if(((i=t["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return at(r,[s,a],null)===c;const[d,l]=r,h=t["checked-data-type"],p=h==="date"?qt(l):l,b=h==="date"?qt(u):u;return at([d,p],[s,b],h)===c}function js(e,t){const n=t[1];return e.attrs[n]}function ks(e,t,n){const r=Object.keys(n)[0];return Ae(e,t,r)}function Ps(e,t,n,r){if(n)return js(e,n);if(r)return ks(e,t,r)}function Is(e,t,n){var r,i;if(!Array.isArray(n.fields))return Vi(e,t);const s=new Map;for(const o of n.fields){const u=Ae(e,t,o),a=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];a&&Ut(u)&&s.set(a,u)}if(!s.has("id")){const o=Ae(e,t,"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 Rs(e,{etype:t,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,a=Jn(i),c=Ms(i);let d=Zi(e,r);const l=n==null?void 0:n["start-cursor"],h=Ps(e,t,l,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const g=h["checked-data-type"]==="date",w=h.id;d=d.map(([T])=>{var v,S,K,O,L;let U=(L=(O=(K=(S=(v=e.eav.get(T))===null||v===void 0?void 0:v.get(w))===null||S===void 0?void 0:S.values())===null||K===void 0?void 0:K.next())===null||O===void 0?void 0:O.value)===null||L===void 0?void 0:L[2];return g&&(U=qt(U)),[T,U]})}d.sort(c==="asc"?function(w,T){return at(w,T,h==null?void 0:h["checked-data-type"])}:function(w,T){return at(T,w,h==null?void 0:h["checked-data-type"])});let p={};const b=Is(e,t,r);for(const g of d){const[w]=g;if(p[w]||!a&&l&&h&&Cs(l,h,c,g))continue;const T=Ni(e,b,w);T&&(p[w]=T)}return p}function Ms(e){var t;const n=(t=e.$)===null||t===void 0?void 0:t.order;return n&&n[Object.keys(n)[0]]||"asc"}function Jn(e){var t,n,r;const i=(t=e.$)===null||t===void 0?void 0:t.offset,s=(n=e.$)===null||n===void 0?void 0:n.before,o=(r=e.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Ds(e,{etype:t,level:n,form:r,join:i,pageInfo:s}){var o,u,a,c,d;if(!Jn(r)&&(!s||!s["start-cursor"]))return[];const l=_s(Ss(e,t,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=vs(ut,t,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,b=Rs(e,{etype:t,pageInfo:s,form:r,dq:{where:l,find:h,fields:p}}),g=((a=r.$)===null||a===void 0?void 0:a.limit)||((c=r.$)===null||c===void 0?void 0:c.first)||((d=r.$)===null||d===void 0?void 0:d.last);if(g!=null){const w=Object.entries(b);return w.length<=g?b:Object.fromEntries(w.slice(0,g))}return b}function xs(e,t){try{return Ds(e,t)}catch(n){if(n instanceof je)return{};throw n}}function Zn(e,t){const n=xs(e,t);return Es(ut,e,t,n)}function $s(e){const t={};for(const[n,r]of Object.entries(e))t[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return t}function Us({store:e,pageInfo:t,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,a){return n!=null&&n[a]||a==="$$ruleParams"||(u[a]=Zn(e,{etype:a,form:r[a],level:0,pageInfo:t==null?void 0:t[a]})),u},{})};return t&&(s.pageInfo=$s(t)),n&&(s.aggregate=n),s}function Ls(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Fs=Ls();function Bt(e,t,n){const r={__etype:e,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return e;if(Fs.has(s))return(o,u)=>Bt(e,t,[...n,u?[s,e,t,o,u]:[s,e,t,o]])}})}function ct(e){return e.startsWith("lookup__")}function Xn(e){const[t,n,...r]=e.split("__");return[n,JSON.parse(r.join("__"))]}function Ns(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const r=n;return ct(r)?Bt(e,Xn(r),[]):Bt(e,r,[])}})}function Qt(){return new Proxy({},{get(e,t){return Ns(t)}})}Qt();function Vs(e){return e.__ops}function Ws(e,t){const{attrIdMap:n,refSwapAttrIds:r}=e,i=[];for(const o of t){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[a,c]=o;i.push([n[a],c])}else i.push(o)}const[s]=t;if((s==="add-triple"||s==="retract-triple")&&r.has(t[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function N(e,t,n){return Object.values(e).find(r=>{const[i,s,o]=r["forward-identity"];return s===t&&o===n})}function me(e,t,n){return Object.values(e).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===t&&u===n})}function Ks(e){if(Array.isArray(e))return e;const t=Object.entries(e);if(t.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return t[0]}function Gt(e,t,n){return n.indexOf(".")!==-1&&!N(e,t,n)}function Yt(e){const[t,n,...r]=e.split(".");if(r.length>0||n!=="id")throw new Error(`${e} is not a valid lookup attribute.`);return t}function zs(e,t,n){if(!Gt(e,t,n))return N(e,t,n);const r=Yt(n),i=N(e,t,r)||me(e,t,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Ht(e){return typeof e=="string"&&!ct(e)?null:typeof e=="string"&&ct(e)?Xn(e):Ks(e)}function Y(e,t,n){const r=Ht(n);if(r===null)return n;const[i,s]=r,o=zs(e,t,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function er(e,t,n,r){const i=Y(e,t,n);return Array.isArray(i)?[["add-triple",i,N(e,t,"id").id,i]].concat(r):r}function qs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),c=me(e,t,s);return u.map(d=>a?["add-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],d)]:["add-triple",Y(e,c["forward-identity"][1],d),c.id,Y(e,t,n)])});return er(e,t,n,i)}function Bs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),c=me(e,t,s);return u.map(d=>a?["retract-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],d)]:["retract-triple",Y(e,c["forward-identity"][1],d),c.id,Y(e,t,n)])});return er(e,t,n,i)}function Qs(e,t,n){if(Array.isArray(n)){const[r,i]=n;for(const s of e||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,a,c]of G(o,2))if(c===i)return!0}}}else for(const r of e||[]){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]==t)return!0}}return!1}function tr({stores:e,attrs:t},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Qs(e,n,r)?{mode:"update"}:null}function Gs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s);return[["id",c]].concat(Object.entries(a)).map(([l,h])=>{const p=N(r,i,l);return p["checked-data-type"]==="date"&&e.useDateObjects&&(h=it(h)),["add-triple",c,p.id,h,{mode:"create"}]})}function Ys(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s),d=tr(e,[i,c,o,u]);return[["id",c]].concat(Object.entries(a)).map(([h,p])=>{const b=N(r,i,h);return b["checked-data-type"]==="date"&&e.useDateObjects&&(p=it(p)),["add-triple",c,b.id,p,...d?[d]:[]]})}function Hs({attrs:e},[t,n]){return[["delete-entity",Y(e,t,n),t]]}function Js(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s),d=tr(e,[i,c,o,u]),l=Object.entries(a).map(([p,b])=>{const g=N(r,i,p);return["deep-merge-triple",c,g.id,b,...d?[d]:[]]});return[["add-triple",c,N(r,i,"id").id,c,...d?[d]:[]]].concat(l)}function Zs({attrs:e},[t,n,r]){return[["rule-params",Y(e,t,n),t,r]]}function Xs(e){const[t,n,r,i,s]=e;if(!i)return e;const o=Object.assign({},i);return delete o.id,[t,n,r,o,...s?[s]:[]]}function eo(e,t){const[n,...r]=Xs(t);switch(n){case"merge":return Js(e,r);case"create":return Gs(e,r);case"update":return Ys(e,r);case"link":return qs(e,r);case"unlink":return Bs(e,r);case"delete":return Hs(e,r);case"ruleParams":return Zs(e,r);default:throw new Error(`unsupported action ${n}`)}}function to(e){switch(e){case"string":case"date":case"boolean":case"number":return e;default:return}}function no(e,t,n){var r,i;const s=(i=(r=e.entities[t])===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(`${t}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,a=to(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":a}}function dt(e,t,n,r){const i=e?no(e,t,n):null,s=V(),u=[V(),t,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 ro(e,t,n){return Object.values(e.links).find(i=>i.forward.on===t&&i.forward.label===n||i.reverse.on===t&&i.reverse.label===n)}function io(e,t,n){const r=ro(e,t,n);if(!r)throw new Error(`Couldn't find the link ${t}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[V(),i.on,i.label],"reverse-identity":[V(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function nr(e,t,n,r){const i=e?io(e,t,n):null,s=V(),o=[V(),t,n],u=[V(),n,t];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 so=new Set(["create","update","merge","link","unlink"]),oo=new Set(["link","unlink"]),uo=new Set(["create","update","merge"]),ao=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Jt={"unique?":!0,"index?":!0},co=Object.assign(Object.assign({},Jt),{cardinality:"one"});function fo(e){const t=[],[n,r,i,s]=e;if(!ao.has(n))return t;const o=Ht(i);if(o&&t.push({etype:r,lookupPair:o}),n==="link")for(const[u,a]of Object.entries(s)){const c=Array.isArray(a)?a:[a];for(const d of c){const l=Ht(d);l&&t.push({etype:r,lookupPair:l,linkLabel:u})}}return t}function lo({attrs:e,schema:t},n){var r,i;const[s,o,u]=[new Set,Object.assign({},e),[]];function a(l){o[l.id]=l,u.push(["add-attr",l]),s.add(l.id)}function c(l){l!=null&&l.isUnsynced&&!s.has(l.id)&&(u.push(["add-attr",l]),s.add(l.id))}function d(l,h){const p=N(o,l,h),b=me(o,l,h);c(p),c(b),!p&&!b&&a(nr(t,l,h,co))}for(const l of n)for(const{etype:h,lookupPair:p,linkLabel:b}of fo(l)){const g=p[0];if(b){d(h,b);const w=N(o,h,b),T=me(o,h,b);c(w),c(T);const v=((r=w==null?void 0:w["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=T==null?void 0:T["forward-identity"])===null||i===void 0?void 0:i[1])||b;if(Gt(o,v,g))d(v,Yt(g));else{const S=N(o,v,g);S||a(dt(t,v,g,Jt)),c(S)}}else if(Gt(o,h,g))d(h,Yt(g));else{const w=N(o,h,g);w||a(dt(t,h,g,Jt)),c(w)}}for(const l of n){const[h,p,b,g]=l;if(so.has(h)){const w=N(o,p,"id");c(w),w||a(dt(t,p,"id",{"unique?":!0}));for(const T of Object.keys(g)){const v=N(o,p,T);if(c(v),uo.has(h)&&(v||a(dt(t,p,T,T==="id"?{"unique?":!0}:null))),oo.has(h)){const S=me(o,p,T);!v&&!S&&a(nr(t,p,T)),c(S)}}}}return[o,u]}function ho(e,t){const r=(Array.isArray(t)?t:[t]).flatMap(a=>Vs(a)),[i,s]=lo(e,r),o=Object.assign(Object.assign({},e),{attrs:i}),u=r.flatMap(a=>eo(o,a));return[...s,...u]}var rr=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class ir{constructor(t){this.dbName=t,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;t(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(t){return rr(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(t);u.onerror=a=>{i(a)},u.onsuccess=a=>{u.result?r(u.result):r(null)}})})}setItem(t,n){return rr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const a=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,t);a.onerror=c=>{s(c)},a.onsuccess=c=>{i()}})})}}var po=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class sr{static getIsOnline(){return po(this,void 0,void 0,function*(){return navigator.onLine})}static listen(t){const n=()=>{t(!0)},r=()=>{t(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class ke extends Error{constructor(t,n){super(t),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,ke),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var yo=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class ft extends ke{constructor(t){var n;const r=((n=t.body)===null||n===void 0?void 0:n.message)||`API Error (${t.status})`;super(r,t.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,ft),this.name="InstantAPIError",this.status=t.status,this.body=t.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function ie(e,t){return yo(this,void 0,void 0,function*(){const n=yield fetch(e,t),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new ft({status:n.status,body:r}))})}var Pe=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function bo({apiURI:e,appId:t,email:n}){return ie(`${e}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":t,email:n})})}function _o(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,email:r,code:i,refreshToken:s}){return yield ie(`${t}/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 go(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield ie(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function To(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n}){return yield ie(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function or(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield ie(`${t}/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 wo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield ie(`${t}/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 mo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield ie(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var ze=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function So(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const a={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(a["content-disposition"]=u),yield ie(`${t}/storage/upload`,{method:"PUT",headers:a,body:i})})}function vo(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield ie(`${t}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function Oo(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield ie(`${t}/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 Eo(e,t){return ze(this,void 0,void 0,function*(){return(yield fetch(e,{method:"PUT",body:t,headers:{"Content-Type":t.type}})).ok})}function Ao(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield ie(`${t}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Zt=!1,ur=!1,ar=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Zt=!!window.localStorage.getItem("devBackend"),ur=!!window.localStorage.getItem("__instantLogging"),ar=!!window.localStorage.getItem("__devtoolLocalDash"));function cr(e,t){if(!t)return e;const n={};return t.forEach(r=>{n[r]=e[r]}),n}function Co(e,t,n){var r,i;const s={peers:{}};if(t&&"user"in t?t.user:!0){const u=cr((r=e.user)!==null&&r!==void 0?r:{},t==null?void 0:t.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=e.peers)!==null&&i!==void 0?i:{})){const a=(t==null?void 0:t.peers)===void 0,c=Array.isArray(t==null?void 0:t.peers)&&(t==null?void 0:t.peers.includes(u));if(a||c){const d=cr(e.peers[u],t==null?void 0:t.keys);s.peers[u]=Object.assign(Object.assign({},d),{peerId:u})}}return s}function jo(e,t){if(e.isLoading!==t.isLoading||e.error!==t.error||(e.user||t.user)&&(!e.user||!t.user||!kn(e.user,t.user))||!jn(e.peers,t.peers))return!0;for(const r of Object.keys(e.peers))if(!kn(e.peers[r],t.peers[r]))return!0;return!1}class dr{constructor(){this.promise=new Promise((t,n)=>{this._resolve=t,this._reject=n})}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}var qe=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function ko(e,t){typeof requestIdleCallback>"u"?e():requestIdleCallback(e,{timeout:t})}class fr{constructor(t,n,r,i,s=c=>c,o=c=>c,u=100,a=1e3){this._subs=[],this._nextSave=null,this._persister=t,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=a,this._load()}_getFromStorage(){return qe(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(t){return console.error(`Unable to read from storage for key=${this._key}`,t),null}})}_load(){return qe(this,void 0,void 0,function*(){const t=yield this._getFromStorage();this._isLoading=!1,this._onMerge(t,this.currentValue);for(const n of this._loadedCbs)n()})}waitForLoaded(){return qe(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 qe(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 t of this._pendingSaveCbs)t();this._pendingSaveCbs.length=0}flush(){return qe(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(t){if(this._nextSave){t&&this._pendingSaveCbs.push(t);return}this._nextSave=setTimeout(()=>{ko(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(t,n){this._version++,this.currentValue=t(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue)}subscribe(t){return this._subs.push(t),t(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==t)}}}function lr(e,t=[]){e.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)t.push(u);lr(n["child-nodes"],t)})}function hr(e){const t=[];return lr(e,t),t}function pr(e){return Object.values(e.links).reduce((t,n)=>{var r,i,s,o;return(r=t[s=n.forward.on])!==null&&r!==void 0||(t[s]={}),t[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=t[o=n.reverse.on])!==null&&i!==void 0||(t[o]={}),t[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},t},{})}const yr="v0.22.29";function Po(e){return{info:e?console.info.bind(console):()=>{},debug:e?console.debug.bind(console):()=>{},error:e?console.error.bind(console):()=>{}}}class de{constructor(t,n,r,i={indexed:!1,unique:!1}){this.valueType=t,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new de(this.valueType,!1,this.isIndexed,this.config)}optional(){return new de(this.valueType,!1,this.isIndexed,this.config)}unique(){return new de(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new de(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class R extends Error{constructor(t,n){const r=n?`At path '${n}': ${t}`:t;super(r),this.name="QueryValidationError"}}const br=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Io=e=>e.valueType||"unknown",_r=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Ro=(e,t,n,r,i,s,o)=>{const u=s.valueType==="json",a=(c,d,l)=>{if(!_r(l,d,u))throw new R(`Invalid value for operator '${c}' on attribute '${r}' in entity '${i}'. Expected ${d}, but received: ${typeof l}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new R(`Operator '${e}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof t}`,o);for(const c of t)a(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":a(e,n,t);break;case"$like":case"$ilike":if(a(e,"string",t),e==="$ilike"&&!s.isIndexed)throw new R(`Operator '${e}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":a(e,"boolean",t);break;default:throw new R(`Unknown operator '${e}' for attribute '${r}' in entity '${i}'`,o)}},Ie=(e,t,n,r,i)=>{const s=Io(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const a=e;for(const[c,d]of Object.entries(a))Ro(c,d,s,t,r,n,`${i}.${c}`)}else if(!_r(e,s,o))throw new R(`Invalid value for attribute '${t}' in entity '${r}'. Expected ${s}, but received: ${typeof e}`,i)},Mo=(e,t,n,r,i)=>{const s=e.split(".");if(s.length<2)throw new R(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let d=0;d<s.length-1;d++){const l=s[d],h=r.entities[o];if(!h)throw new R(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const p=h.links[l];if(!p){const b=Object.keys(h.links);throw new R(`Link '${l}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${b.length>0?b.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],a=r.entities[o];if(!a)throw new R(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(u==="id"){if(typeof t=="string"&&!Ce(t))throw new R(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ie(t,e,new de("string",!1,!0),n,i);return}const c=a.attrs[u];if(Object.keys(a.links).includes(u)){if(typeof t=="string"&&!Ce(t))throw new R(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ie(t,e,new de("string",!1,!0),n,i);return}if(!c){const d=Object.keys(a.attrs);throw new R(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,i)}Ie(t,e,c,n,i)},gr=(e,t,n,r)=>{for(const[i,s]of Object.entries(e)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const c of s)typeof c=="object"&&c!==null&&gr(c,t,n,`${r}.${i}[${c}]`);continue}if(i==="id"){Ie(s,"id",new de("string",!1,!0),t,`${r}.id`);continue}if(i.includes(".")){Mo(i,s,t,n,`${r}.${i}`);continue}const o=n.entities[t];if(!o)continue;const u=o.attrs[i],a=o.links[i];if(!u&&!a){const c=Object.keys(o.attrs),d=Object.keys(o.links);throw new R(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${r}.${i}`)}if(u)Ie(s,i,u,t,`${r}.${i}`);else if(a){if(typeof s=="string"&&!Ce(s))throw new R(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const c=new de("string",!1,!0);Ie(s,i,c,t,`${r}.${i}`)}}},Do=(e,t,n,r,i=0)=>{for(const o of Object.keys(e))if(!br.includes(o))throw new R(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${br.join(", ")}. Found: ${o}`,r);const s=["limit","offset","before","after","first","last"];for(const o of s)if(e[o]!==void 0&&i>0)throw new R(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new R(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,r?`${r}.where`:void 0);gr(e.where,t,n,r?`${r}.where`:"where")}},Tr=(e,t,n,r,i=0)=>{var s;if(!e||typeof e!="object")throw new R(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,r);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const a=Object.keys(n.entities[t].links);throw new R(`Link '${o}' does not exist on entity '${t}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${o}`)}const u=e[o];if(typeof u=="object"&&u!==null){const a=(s=n==null?void 0:n.entities[t].links[o])===null||s===void 0?void 0:s.entityName;a&&Tr(u,a,n,`${r}.${o}`,i+1)}}else{const u=e[o];if(typeof u!="object"||u===null)throw new R(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof u}`,`${r}.$`);Do(u,t,n,`${r}.$`,i)}},wr=(e,t)=>{if(typeof e!="object"||e===null)throw new R(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new R(`Query must be an object, but received: ${typeof e}`);const n=e;for(const r of Object.keys(n)){if(Array.isArray(e[r]))throw new R(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new R(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(t&&!t.entities[r]){const i=Object.keys(t.entities);throw new R(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}Tr(n[r],r,t,r,0)}}},mr=e=>typeof e!="string"?!1:ct(e)?!0:Ce(e);class ee extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const Sr=e=>e.length>0?e.join(", "):"none",xo=(e,t)=>new ee(`Entity '${e}' does not exist in schema. Available entities: ${Sr(t)}`),vr={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},$o=(e,t)=>{var n,r;return e==null?!0:(r=(n=vr[t.valueType])===null||n===void 0?void 0:n.call(vr,e))!==null&&r!==void 0?r:!1},Or=(e,t)=>{const n=t.entities[e];if(!n)throw xo(e,Object.keys(t.entities));return n},Xt=(e,t,n)=>{const r=Or(e,n);if(typeof t!="object"||t===null)throw new ee(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(i==="id")continue;const o=r.attrs[i];if(o&&!$o(s,o))throw new ee(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof s}`)}},Er=(e,t,n)=>{const r=Or(e,n);if(typeof t!="object"||t===null)throw new ee(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(!r.links[i]){const u=Object.keys(r.links);throw new ee(`Link '${i}' does not exist on entity '${e}'. Available links: ${Sr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!mr(u))throw new ee(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!mr(s))throw new ee(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${s}`)}}},Uo={create:Xt,update:Xt,merge:Xt,link:Er,unlink:Er,delete:()=>{}},Lo=(e,t)=>{if(!t)return;const[n,r,i,s]=e;if(!Array.isArray(i)&&!Ce(i))throw new ee(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new ee(`Entity name must be a string, but received: ${typeof r}`);const o=Uo[n];o&&s!==void 0&&o(r,s,t)},Fo=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const r of n){if(!r||typeof r!="object")throw new ee(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ee(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new ee(`Transaction operation must be an array, but received: ${typeof i}`);Lo(i,t)}}};var Ar=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};let Cr=0;class jr{constructor(t){this.type="ws",this.id=`${this.type}_${Cr++}`,this.conn=new WebSocket(t),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(t){return this.conn.send(JSON.stringify(t))}}class No{constructor(t,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Cr++}`,this.url=n,this.ES=t,this.conn=new t(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(t){return Ar(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:t})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return Ar(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(t){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(t),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 x=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})},Vo=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const fe={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Wo=3e4,Ko=3e4,zo={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},en="_instant_oauth_redirect",tn="currentUser";function qo({transportType:e,appId:t,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new jr(`${r}?app_id=${t}`);switch(e){case"ws":return new jr(`${r}?app_id=${t}`);case"sse":return new No(i,`${n}/runtime/sse?app_id=${t}`);default:throw new Error("Unknown transport type "+e)}}function Bo(){return typeof window<"u"||typeof chrome<"u"}const kr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Qo(e,t){var n;const r=typeof e=="string"?JSON.parse(e):e;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=ki(Object.assign(Object.assign({},o),{useDateObjects:t}))}}return r}function Go(e){var t;const n={};for(const r in e){const i=e[r],s=Object.assign({},i);!((t=i.result)===null||t===void 0)&&t.store&&(s.result=Object.assign(Object.assign({},i.result),{store:ji(i.result.store)})),n[r]=s}return n}function Pr(e){return[...e].sort((t,n)=>{const[r,i]=t,[s,o]=n,u=i.order||0,a=o.order||0;return u==a?r<s?-1:r>s?1:0:u-a})}class Yo{constructor(t,n=ir,r=sr,i,s){var o;if(this._isOnline=!0,this._isShutdown=!1,this.status=fe.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._onMergeQuerySubs=(u,a)=>{const c=u||{},d=Object.assign({},a);Object.entries(a).forEach(([h,p])=>{var b;const g=(b=c==null?void 0:c[h])===null||b===void 0?void 0:b.result,w=p.result;g&&!w&&(d[h].result=g)}),Object.keys(c).filter(h=>!a[h]).sort((h,p)=>{var b,g;const w=((b=c[h])===null||b===void 0?void 0:b.lastAccessed)||0;return(((g=c[p])===null||g===void 0?void 0:g.lastAccessed)||0)-w}).slice(0,this.queryCacheLimit).forEach(h=>{d[h]=c[h]}),this.querySubs.set(h=>d),this.loadedNotifyAll()},this._onMergePendingMutations=(u,a)=>{const c=new Map([...u.entries(),...a.entries()]);this.pendingMutations.set(l=>c),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,u).forEach(([l,h])=>{!a.has(l)&&!h["tx-id"]&&this._sendMutation(l,h)})},this.getPreviousResult=u=>{const a=B(u);return this.dataForQuery(a)},this.notifyOne=u=>{var a,c;const d=(a=this.queryCbs[u])!==null&&a!==void 0?a:[],l=(c=this._dataForQueryCache[u])===null||c===void 0?void 0:c.data,h=this.dataForQuery(u);h&&(rt(h,l)||d.forEach(p=>p.cb(h)))},this.notifyOneQueryOnce=u=>{var a;const c=(a=this.queryOnceDfds[u])!==null&&a!==void 0?a:[],d=this.dataForQuery(u);c.forEach(l=>{this._completeQueryOnce(l.q,u,l.dfd),l.dfd.resolve(d)})},this.notifyQueryError=(u,a)=>{(this.queryCbs[u]||[]).forEach(d=>d.cb({error:a}))},this.pushTx=u=>{this.config.disableValidation||Fo(u,this.config.schema);try{const a=ho({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(c=>{var d;return(d=c==null?void 0:c.result)===null||d===void 0?void 0:d.store}),useDateObjects:this.config.useDateObjects},u);return this.pushOps(a)}catch(a){return this.pushOps([],a)}},this.pushOps=(u,a)=>{const c=V(),d=[...this.pendingMutations.currentValue.values()],l=Math.max(0,...d.map(b=>b.order||0))+1,h={op:"transact","tx-steps":u,created:Date.now(),error:a,order:l};this.pendingMutations.set(b=>(b.set(c,h),b));const p=new dr;return this.mutationDeferredStore.set(c,p),this._sendMutation(c,h),this.notifyAll(),p.promise},this._transportOnOpen=u=>{const a=u.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(fe.OPENED),this.getCurrentUser().then(c=>{var d;this._trySend(V(),{op:"init","app-id":this.config.appId,"refresh-token":(d=c.user)===null||d===void 0?void 0:d.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(c=>{this._log.error("[socket][error]",a.id,c)})},this._transportOnMessage=u=>{const a=u.target,c=u.message;if(this._transport!==a){this._log.info("[socket][message]",a.id,c,"skip; this is no longer the current transport");return}!this._wsOk&&a.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(a.id,u.message)},this._transportOnError=u=>{const a=u.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,u)},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=u=>{const a=u.target;if(this._transport!==a){this._log.info("[socket][close]",a.id,"skip; this is no longer the current transport");return}this._setStatus(fe.CLOSED);for(const c of Object.values(this._rooms))c.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({},zo),t),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._log=Po(t.verbose||Zt||ur),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":yr}),this.config.schema&&(this._linkIndex=pr(this.config.schema)),!!Bo()){if(!t.appId)throw new Error("Instant must be initialized with an appId.");if(!Ce(t.appId))throw new Error(`Instant must be initialized with a valid appId. \`${t.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",u=>x(this,void 0,void 0,function*(){var a;try{if(((a=u.data)===null||a===void 0?void 0:a.type)==="auth"){const c=yield this.getCurrentUser();this.updateUser(c.user)}}catch(c){this._log.error("[error] handle broadcast channel",c)}}))),this._initStorage(n),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(u=>{this._isOnline=u,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",fe.CLOSED),this._setStatus(fe.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(t){this.config=Object.assign(Object.assign({},this.config),{schema:t,cardinalityInference:!!t}),this._linkIndex=t?pr(this.config.schema):null}_initStorage(t){this._persister=new t(`instant_${this.config.appId}_5`),this.querySubs=new fr(this._persister,"querySubs",{},this._onMergeQuerySubs,Go,n=>Qo(n,this.config.useDateObjects)),this.pendingMutations=new fr(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 t of this._beforeUnloadCbs)t()}_finishTransaction(t,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=t!=="error"&&t!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:t,eventId:n},r)),!!i)if(s)i.resolve({status:t,eventId:n});else if(r.type){const{status:o}=r,u=Vo(r,["status"]);i.reject(new ft({body:u,status:o}))}else i.reject(new ke(r.message,r.hint))}_setStatus(t,n){this.status=t,this._errorMessage=n,this.notifyConnectionStatusSubs(t)}_flushEnqueuedRoomData(t){var n,r;const i=(r=(n=this._presence[t])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[t];if(this._broadcastQueue[t]=[],i&&this._trySetPresence(t,i),s)for(const o of s){const{topic:u,roomType:a,data:c}=o;this._tryBroadcast(t,a,u,c)}}_handleReceive(t,n){var r,i,s,o,u,a;const c=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(kr[n.op]||this._log.info("[receive]",t,n.op,n),n.op){case"init-ok":this._setStatus(fe.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const P of Object.keys(this._rooms)){const X=(i=(r=this._presence[P])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(P,X)}break;case"add-query-exists":this.notifyOneQueryOnce(B(n.q));break;case"add-query-ok":const{q:d,result:l}=n,h=B(d),p=(o=(s=l==null?void 0:l[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],b=(a=(u=l==null?void 0:l[0])===null||u===void 0?void 0:u.data)===null||a===void 0?void 0:a.aggregate,g=hr(l),w=Ft(this.attrs,g,c,this._linkIndex,this.config.useDateObjects);this.querySubs.set(P=>(P[h].result={store:w,pageInfo:p,aggregate:b,processedTxId:n["processed-tx-id"]},P)),this._cleanupPendingMutationsQueries(),this.notifyOne(h),this.notifyOneQueryOnce(h),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:T,attrs:v}=n,S=n["processed-tx-id"];v&&this._setAttrs(v),this._cleanupPendingMutationsTimeout();const K=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,S);K!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>K);const O=Pr(K.entries()),L=T.map(P=>{var X,ye,be,he;const yt=P["instaql-query"],ue=P["instaql-result"],an=B(yt),cn=hr(ue),Ge=Ft(this.attrs,cn,c,this._linkIndex,this.config.useDateObjects),Ye=this._applyOptimisticUpdates(Ge,O,S),Re=(ye=(X=ue==null?void 0:ue[0])===null||X===void 0?void 0:X.data)===null||ye===void 0?void 0:ye["page-info"],He=(he=(be=ue==null?void 0:ue[0])===null||be===void 0?void 0:be.data)===null||he===void 0?void 0:he.aggregate;return{hash:an,store:Ye,pageInfo:Re,aggregate:He}});L.forEach(({hash:P,store:X,pageInfo:ye,aggregate:be})=>{this.querySubs.set(he=>(he[P].result={store:X,pageInfo:ye,aggregate:be,processedTxId:S},he))}),this._cleanupPendingMutationsQueries(),L.forEach(({hash:P})=>{this.notifyOne(P)});break;case"transact-ok":const{"client-event-id":U,"tx-id":le}=n,Be=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(U);if(!Be)break;this.pendingMutations.set(P=>(P.set(U,Object.assign(Object.assign({},P.get(U)),{"tx-id":le,confirmed:Date.now()})),P)),this._cleanupPendingMutationsTimeout();const on=Be["tx-steps"].filter(([P,...X])=>P==="add-attr").map(([P,X])=>X).concat(Object.values(this.attrs));this._setAttrs(on),this._finishTransaction("synced",U);break;case"patch-presence":{const P=n["room-id"];this._patchPresencePeers(P,n.edits),this._notifyPresenceSubs(P);break}case"refresh-presence":{const P=n["room-id"];this._setPresencePeers(P,n.data),this._notifyPresenceSubs(P);break}case"server-broadcast":const un=n["room-id"],pt=n.topic;this._notifyBroadcastSubs(un,pt,n);break;case"join-room-ok":const z=n["room-id"],oe=this._rooms[z];if(!oe){this._roomsPendingLeave[z]&&(this._tryLeaveRoom(z),delete this._roomsPendingLeave[z]);break}oe.isConnected=!0,this._notifyPresenceSubs(z),this._flushEnqueuedRoomData(z);break;case"join-room-error":const pe=n["room-id"],Qe=this._rooms[pe];Qe&&(Qe.error=n.error),this._notifyPresenceSubs(pe);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(t,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(t!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o));const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(t,n,r)}}_handleReceiveError(t){var n,r,i,s,o;console.log("error",t);const u=t["client-event-id"],a=this.pendingMutations.currentValue.get(u),c={message:t.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(t.hint&&(c.hint=t.hint),a){this._handleMutationError("error",u,t);return}if(!((n=t["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=t["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const h=(i=t["original-event"])===null||i===void 0?void 0:i.q,p=B(h);this.notifyQueryError(B(h),c),this.notifyQueryOnceError(h,p,u,c);return}if(((s=t["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(t.type==="record-not-found"&&((o=t.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(fe.ERRORED,c),this.notifyAll();return}const l=Object.assign({},t);delete l.message,delete l.hint,console.error(t.message,l),t.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
31
|
-
`,t.hint)}notifyQueryOnceError(t,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(t,n,o.dfd))}_setAttrs(t){this.attrs=t.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(t,n){const r=V();return this.querySubs.set(i=>(i[n]=i[n]||{q:t,result:null,eventId:r},i[n].lastAccessed=Date.now(),i)),this._trySendAuthed(r,{op:"add-query",q:t}),r}subscribeQuery(t,n,r){var i;this.config.disableValidation||wr(t,this.config.schema),r&&"ruleParams"in r&&(t=Object.assign({$$ruleParams:r.ruleParams},t));const s=B(t),o=this.getPreviousResult(t);return o&&n(o),this.queryCbs[s]=(i=this.queryCbs[s])!==null&&i!==void 0?i:[],this.queryCbs[s].push({q:t,cb:n}),this._startQuerySub(t,s),()=>{this._unsubQuery(t,s,n)}}queryOnce(t,n){var r;this.config.disableValidation||wr(t,this.config.schema),n&&"ruleParams"in n&&(t=Object.assign({$$ruleParams:n.ruleParams},t));const i=new dr;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=B(t),o=this._startQuerySub(t,s);return this.queryOnceDfds[s]=(r=this.queryOnceDfds[s])!==null&&r!==void 0?r:[],this.queryOnceDfds[s].push({q:t,dfd:i,eventId:o}),setTimeout(()=>i.reject(new Error("Query timed out")),Wo),i.promise}_completeQueryOnce(t,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(i=>i.dfd!==r),this._cleanupQuery(t,n))}_unsubQuery(t,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(i=>i.cb!==r),this._cleanupQuery(t,n))}_cleanupQuery(t,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(V(),{op:"remove-query",q:t}))}_rewriteMutations(t,n,r){if(!t)return n;const i=d=>{const[l,h,p]=d["forward-identity"];return N(t,h,p)},s=d=>{const[l,h,p]=d["forward-identity"];return me(t,h,p)},o={attrIdMap:{},refSwapAttrIds:new Set};let u=!1;const a=(d,l)=>{const h=[];for(const p of d){const[b]=p;if(b==="add-attr"){const[w,T]=p,v=i(T);if(v&&T.id!==v.id){o.attrIdMap[T.id]=v.id,u=!0;continue}if(T["value-type"]==="ref"){const S=s(T);if(S){o.attrIdMap[T.id]=S.id,o.refSwapAttrIds.add(T.id),u=!0;continue}}}if(r&&l&&r>=l&&b==="add-attr"||b==="update-attr"||b==="delete-attr"){u=!0;continue}const g=u?Ws(o,p):p;h.push(g)}return u?h:d},c=new Map;for(const[d,l]of n.entries())c.set(d,Object.assign(Object.assign({},l),{"tx-steps":a(l["tx-steps"],l["tx-id"])}));return u?c:n}_rewriteMutationsSorted(t,n){return Pr(this._rewriteMutations(t,n).entries())}optimisticAttrs(){var t;const n=[...this.pendingMutations.currentValue.values()].flatMap(u=>u["tx-steps"]),r=new Set(n.filter(([u,a])=>u==="delete-attr").map(([u,a])=>a)),i=[];for(const[u,a]of n)if(u==="add-attr")i.push(a);else if(u==="update-attr"&&a.id&&(!((t=this.attrs)===null||t===void 0)&&t[a.id])){const c=Object.assign(Object.assign({},this.attrs[a.id]),a);i.push(c)}const s=[...Object.values(this.attrs||{}),...i].filter(u=>!r.has(u.id));return Object.fromEntries(s.map(u=>[u.id,u]))}dataForQuery(t){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:a}=i[t]||{};if(!a)return;const c=this._dataForQueryCache[t];if(c&&r===c.querySubVersion&&s===c.pendingMutationsVersion)return c.data;const{store:d,pageInfo:l,aggregate:h,processedTxId:p}=a,b=this._rewriteMutationsSorted(d.attrs,o),g=this._applyOptimisticUpdates(d,b,p),w=Us({store:g,pageInfo:l,aggregate:h},u);return this._dataForQueryCache[t]={querySubVersion:r,pendingMutationsVersion:s,data:w},w}_applyOptimisticUpdates(t,n,r){for(const[i,s]of n)(!s["tx-id"]||r&&s["tx-id"]>r)&&(t=Ki(t,s["tx-steps"]));return t}notifyAll(){Object.keys(this.queryCbs).forEach(t=>{this.notifyOne(t)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var t;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(t=this._transport)===null||t===void 0||t.close()}_sendMutation(t,n){if(n.error){this._handleMutationError("error",t,{message:n.error.message});return}if(this.status!==fe.AUTHENTICATED){this._finishTransaction("enqueued",t);return}const r=Math.max(5e3,this.pendingMutations.currentValue.size*5e3);this._isOnline?(this._trySend(t,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",t,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",t)}_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)})}_cleanupPendingMutationsQueries(){let t=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(t=Math.min(t,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"]<=t&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){const t=Date.now();this.pendingMutations.currentValue.size<200||this.pendingMutations.set(n=>{let r=!1,i=!1;for(const[s,o]of Array.from(n.entries()))o.confirmed||(i=!0),o.confirmed&&o.confirmed+Ko<t&&(n.delete(s),r=!0);if(r&&i)for(const[s,o]of Array.from(n.entries()))o.confirmed||n.delete(s);return n})}_trySendAuthed(...t){this.status===fe.AUTHENTICATED&&this._trySend(...t)}_trySend(t,n,r){this._transport.isOpen()&&(kr[n.op]||this._log.info("[send]",this._transport.id,n.op,n),this._transport.send(Object.assign({"client-event-id":t},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 t=this._transport;this._transport=qo({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),t!=null&&t.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",t.id),t.close())}getLocalId(t){return x(this,void 0,void 0,function*(){const n=`localToken_${t}`,r=yield this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const i=V();return this._localIdPromises[n]=this._persister.setItem(n,i).then(()=>i),this._localIdPromises[n]})}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const t=new URL(window.location.href);if(t.searchParams.get(en)){const n=t.toString();t.searchParams.delete(en),t.searchParams.delete("code"),t.searchParams.delete("error");const r=t.pathname+(t.searchParams.size?"?"+t.searchParams:"")+t.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 x(this,void 0,void 0,function*(){var t,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(en))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 a=yield this._getCurrentUser(),c=(a==null?void 0:a.type)==="guest",{user:d}=yield or({apiURI:this.config.apiURI,appId:this.config.appId,code:u,refreshToken:c?a.refresh_token:void 0});return this.setCurrentUser(d),null}catch(a){return((t=a==null?void 0:a.body)===null||t===void 0?void 0:t.type)==="record-not-found"&&((r=(n=a==null?void 0:a.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=a==null?void 0:a.body)===null||i===void 0?void 0:i.message)||"Error logging in."}}}})}_waitForOAuthCallbackResponse(){return x(this,void 0,void 0,function*(){return yield this._oauthCallbackResponse})}__subscribeMutationErrors(t){return this.mutationErrorCbs.push(t),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==t)}}subscribeAuth(t){this.authCbs.push(t);const n=this._currentUserCached;n.isLoading||t(this._currentUserCached);let r=!1;return this.getCurrentUser().then(i=>{r||rt(i,n)||t(i)}),()=>{r=!0,this.authCbs=this.authCbs.filter(i=>i!==t)}}getAuth(){return x(this,void 0,void 0,function*(){const{user:t,error:n}=yield this.getCurrentUser();if(n)throw new ke("Could not get current user: "+n.message);return t})}subscribeConnectionStatus(t){return this.connectionStatusCbs.push(t),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==t)}}subscribeAttrs(t){return this.attrsCbs.push(t),this.attrs&&t(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==t)}}notifyAuthSubs(t){this.authCbs.forEach(n=>n(t))}notifyMutationErrorSubs(t){this.mutationErrorCbs.forEach(n=>n(t))}notifyAttrsSubs(){if(!this.attrs)return;const t=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(t))}notifyConnectionStatusSubs(t){this.connectionStatusCbs.forEach(n=>n(t))}setCurrentUser(t){return x(this,void 0,void 0,function*(){yield this._persister.setItem(tn,t)})}getCurrentUserCached(){return this._currentUserCached}_getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(tn);return typeof t=="string"?JSON.parse(t):t})}getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._waitForOAuthCallbackResponse();if(t!=null&&t.error){const i={error:t.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 x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(tn);return JSON.parse(t)!=null})}changeCurrentUser(t){return x(this,void 0,void 0,function*(){var n;const{user:r}=yield this.getCurrentUser();if(!rt(r,t)){yield this.setCurrentUser(t),this.updateUser(t);try{(n=this._broadcastChannel)===null||n===void 0||n.postMessage({type:"auth"})}catch(i){console.error("Error posting message to broadcast channel",i)}}})}updateUser(t){const n={error:void 0,user:t};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:t}){return bo({apiURI:this.config.apiURI,appId:this.config.appId,email:t})}signInWithMagicCode(t){return x(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 _o({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(t){return x(this,void 0,void 0,function*(){const n=yield go({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:t});return yield this.changeCurrentUser(n.user),n})}signInAsGuest(){return x(this,void 0,void 0,function*(){const t=yield To({apiURI:this.config.apiURI,appId:this.config.appId});return yield this.changeCurrentUser(t.user),t})}potentiallyInvalidateToken(t,n){var r;const i=(r=t==null?void 0:t.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}mo({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:i}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}signOut(t){return x(this,void 0,void 0,function*(){const n=yield this.getCurrentUser();this.potentiallyInvalidateToken(n,t),yield this.changeCurrentUser(null)})}createAuthorizationURL({clientName:t,redirectURL:n}){const{apiURI:r,appId:i}=this.config;return`${r}/runtime/oauth/start?app_id=${i}&client_name=${t}&redirect_uri=${n}`}exchangeCodeForToken(t){return x(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 or({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:t,appId:n}=this.config;return`${t}/runtime/${n}`}signInWithIdToken(t){return x(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,a=yield wo({apiURI:this.config.apiURI,appId:this.config.appId,idToken:n,clientName:r,nonce:i,refreshToken:u});return yield this.changeCurrentUser(a.user),a})}joinRoom(t,n){return this._rooms[t]||(this._rooms[t]={isConnected:!1,error:void 0}),this._presence[t]=this._presence[t]||{},n&&(this._presence[t].result=this._presence[t].result||{},this._presence[t].result.user=n,this._notifyPresenceSubs(t)),this._tryJoinRoom(t,n),()=>{this._cleanupRoom(t)}}_cleanupRoom(t){var n,r,i,s;if(!(!((r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0)&&r.length)&&!Object.keys((i=this._broadcastSubs[t])!==null&&i!==void 0?i:{}).length){const o=(s=this._rooms[t])===null||s===void 0?void 0:s.isConnected;delete this._rooms[t],delete this._presence[t],delete this._broadcastSubs[t],o?this._tryLeaveRoom(t):this._roomsPendingLeave[t]=!0}}getPresence(t,n,r={}){const i=this._rooms[n],s=this._presence[n];return!i||!s||!s.result?null:Object.assign(Object.assign({},Co(s.result,r,this._sessionId)),{isLoading:!i.isConnected,error:i.error})}publishPresence(t,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(t,n){this._trySendAuthed(V(),{op:"set-presence","room-id":t,data:n})}_tryJoinRoom(t,n){this._trySendAuthed(V(),{op:"join-room","room-id":t,data:n}),delete this._roomsPendingLeave[t]}_tryLeaveRoom(t){this._trySendAuthed(V(),{op:"leave-room","room-id":t})}subscribePresence(t,n,r,i){const s=this.joinRoom(n,r.data),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,a,c;this._presence[n].handlers=(c=(a=(u=this._presence[n])===null||u===void 0?void 0:u.handlers)===null||a===void 0?void 0:a.filter(d=>d!==o))!==null&&c!==void 0?c:[],s()}}_notifyPresenceSubs(t){var n,r;(r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0||r.forEach(i=>{this._notifyPresenceSub(t,i)})}_notifyPresenceSub(t,n){const r=this.getPresence("",t,n);r&&(n.prev&&!jo(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(t,n){var r,i,s;const o=((i=(r=this._presence[t])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.peers)||{};let u=Object.fromEntries(Object.entries(o).map(([c,d])=>[c,{data:d}]));(s=this._presence[t])===null||s===void 0||s.result;const a=Mt(u,c=>{for(let[d,l,h]of n)switch(l){case"+":ci(c,d,h);break;case"r":In(c,d,h);break;case"-":Rn(c,d);break}delete c[this._sessionId]});this._setPresencePeers(t,a)}_setPresencePeers(t,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=Mt(this._presence,s=>{In(s,[t,"result","peers"],i)})}publishTopic({roomType:t,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:t,data:i});return}this._tryBroadcast(n,t,r,i)}}_tryBroadcast(t,n,r,i){this._trySendAuthed(V(),{op:"client-broadcast","room-id":t,roomType:n,topic:r,data:i})}subscribeTopic(t,n,r){const i=this.joinRoom(t);return this._broadcastSubs[t]=this._broadcastSubs[t]||{},this._broadcastSubs[t][n]=this._broadcastSubs[t][n]||[],this._broadcastSubs[t][n].push(r),this._presence[t]=this._presence[t]||{},()=>{this._broadcastSubs[t][n]=this._broadcastSubs[t][n].filter(s=>s!==r),this._broadcastSubs[t][n].length||delete this._broadcastSubs[t][n],i()}}_notifyBroadcastSubs(t,n,r){var i,s,o;(o=(s=(i=this._broadcastSubs)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[n])===null||o===void 0||o.forEach(u=>{var a,c,d,l,h,p;const b=(a=r.data)===null||a===void 0?void 0:a.data,g=r.data["peer-id"]===this._sessionId?(d=(c=this._presence[t])===null||c===void 0?void 0:c.result)===null||d===void 0?void 0:d.user:(p=(h=(l=this._presence[t])===null||l===void 0?void 0:l.result)===null||h===void 0?void 0:h.peers)===null||p===void 0?void 0:p[r.data["peer-id"]];return u(b,g)})}uploadFile(t,n,r){return x(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 So(Object.assign(Object.assign({},r),{apiURI:this.config.apiURI,appId:this.config.appId,path:t,file:n,refreshToken:o}))})}deleteFile(t){return x(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 vo({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}upload(t,n){return x(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=t||n.name,u=yield Oo({apiURI:this.config.apiURI,appId:this.config.appId,fileName:o,refreshToken:s});return yield Eo(u,n)})}getDownloadUrl(t){return x(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:t,refreshToken:i})})}}let lt;function Ho(e,t){lt==null||lt.dispose();const n=nu(t),r=Xo(t,u),i=Zo(Jo(e));function s(d){var l;d.source===i.element.contentWindow&&((l=d.data)===null||l===void 0?void 0:l.type)==="close"&&n.isVisible()&&u()}function o(d){const l=d.shiftKey&&d.ctrlKey&&d.key==="0",h=d.key==="Escape"||d.key==="Esc";(l||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 a(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",s)}function c(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",s),lt={dispose:a}}return c()}function Jo(e){return`${Zt||ar?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${e}`}function Zo(e){const t=document.createElement("iframe");return t.src=e,t.className="instant-devtool-iframe",Object.assign(t.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:t}}function Xo(e,t){const n=`
|
|
30
|
+
<%s key={someKey} {...props} />`,pn,ve,Gu,ve),Br[ve+pn]=!0}}return f===i?Ku($):Wu($),$}}function zu(f,y,_){return Qr(f,y,_,!0)}function qu(f,y,_){return Qr(f,y,_,!1)}var Bu=qu,Qu=zu;$e.Fragment=i,$e.jsx=Bu,$e.jsxs=Qu}(),$e}var Hr={};Hr.NODE_ENV==="production"?Tt.exports=Gr():Tt.exports=Yr();var Ze=Tt.exports;function B(e){if(typeof e=="number")return(Math.abs(e*2654435761)>>>0).toString(16);if(typeof e=="boolean")return e?"1":"0";if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string"){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24),t=t>>>0;return t.toString(16)}if(Array.isArray(e)){let t=2166136261;for(let n=0;n<e.length;n++){t^=(n+1)*2654435761;const r=B(e[n]);for(let i=0;i<r.length;i++)t^=r.charCodeAt(i),t*=16777619,t=t>>>0}return t.toString(16)}if(typeof e=="object"){let t=2166136261;const n=Object.keys(e).sort();for(let r=0;r<n.length;r++){const i=n[r],s=B(i);t^=parseInt(s,16),t*=16777619,t=t>>>0;const o=B(e[i]);t^=parseInt(o,16),t*=16777619,t=t>>>0}return t.toString(16)}return B(String(e))}const M={Remove:"remove",Replace:"replace",Add:"add"},_n=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Jr=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Xe=Symbol.iterator,J={mutable:"mutable",immutable:"immutable"},wt={};function Ue(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function gn(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,t);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function mt(e){return Object.getPrototypeOf(e)===Set.prototype}function St(e){return Object.getPrototypeOf(e)===Map.prototype}function Z(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function ge(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[_n]}function vt(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ne(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,J))===J.immutable||typeof n=="function")}function Tn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,r=E(ae(n,e.key));if(r!==null&&(r==null?void 0:r.original)!==e.original)return null;const i=e.parent.type===3,s=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>s||Ue(n,s)))return null;t.push(s)}if(e.parent)return Tn(e.parent,t);t.reverse();try{Zr(e.copy,t)}catch{return null}return t}function Te(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function ae(e,t){return Te(e)===2?e.get(t):e[t]}function Le(e,t,n){Te(e)===2?e.set(t,n):e[t]=n}function Ot(e,t){const n=E(e);return(n?Z(n):e)[t]}function ce(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Et(e){if(e)for(;e.finalities.revoke.length>0;)e.finalities.revoke.pop()()}function we(e,t){return t?e:[""].concat(e).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Zr(e,t){for(let n=0;n<t.length-1;n+=1){const r=t[n];if(e=ae(Te(e)===3?Array.from(e):e,r),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Xr(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(e,n);if(r.enumerable&&r.configurable&&r.writable){t[n]=e[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:e[n]}),Reflect.defineProperty(t,n,r)}),t}const ei=Object.prototype.propertyIsEnumerable;function wn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!St(e)){const r=Object.getPrototypeOf(e).constructor;return new r(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,J),n!==void 0)&&n!==J.mutable){if(n===J.immutable)return Xr(e);if(typeof n=="function"){if(t.enablePatches||t.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 e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const r={};return Object.keys(e).forEach(i=>{r[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{ei.call(e,i)&&(r[i]=e[i])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function W(e){e.copy||(e.copy=wn(e.original,e.options))}function Fe(e){if(!ne(e))return vt(e);if(Array.isArray(e))return e.map(Fe);if(e instanceof Map){const n=Array.from(e.entries()).map(([r,i])=>[r,Fe(i)]);if(!St(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Fe);if(!mt(e)){const r=Object.getPrototypeOf(e).constructor;return new r(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Fe(e[n]);return t}function et(e){return ge(e)?Fe(e):e}function se(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&se(e.parent))}function mn(){throw new Error("Cannot modify frozen object")}function Oe(e,t,n,r,i){{n=n??new WeakMap,r=r??[],i=i??[];const o=n.has(e)?n.get(e):e;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((a,c)=>{if(typeof a=="symbol")return`[${a.toString()}]`;const d=r[c];return typeof a=="object"&&(d instanceof Map||d instanceof Set)?Array.from(d.keys()).indexOf(a):a}).join("/")}`);r.push(o),i.push(t)}else r.push(o)}if(Object.isFrozen(e)||ge(e)){r.pop(),i.pop();return}switch(Te(e)){case 2:for(const[u,a]of e)Oe(u,u,n,r,i),Oe(a,u,n,r,i);e.set=e.clear=e.delete=mn;break;case 3:for(const u of e)Oe(u,u,n,r,i);e.add=e.clear=e.delete=mn;break;case 1:Object.freeze(e);let o=0;for(const u of e)Oe(u,o,n,r,i),o+=1;break;default:Object.freeze(e),Object.keys(e).forEach(u=>{const a=e[u];Oe(a,u,n,r,i)})}r.pop(),i.pop()}function At(e,t){const n=Te(e);if(n===0)Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)});else if(n===1){let r=0;for(const i of e)t(r,i,e),r+=1}else e.forEach((r,i)=>t(i,r,e))}function Sn(e,t,n){if(ge(e)||!ne(e,n)||t.has(e)||Object.isFrozen(e))return;const r=e instanceof Set,i=r?new Map:void 0;if(t.add(e),At(e,(s,o)=>{var u;if(ge(o)){const a=E(o);W(a);const c=!((u=a.assignedMap)===null||u===void 0)&&u.size||a.operated?a.copy:a.original;Le(r?i:e,s,c)}else Sn(o,t,n)}),i){const s=e,o=Array.from(s);s.clear(),o.forEach(u=>{s.add(i.has(u)?i.get(u):u)})}}function ti(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Sn(ae(n,t),e.finalities.handledSet,e.options)}function Ct(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(vt(t))}))}function jt(e,t,n,r){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&r){const s=Tn(e);s&&t(e,s,n,r)}e.finalized=!0}}function kt(e,t,n,r){const i=E(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((s,o)=>{var u;const a=e.type===3?e.setMap:e.copy;if(ce(ae(a,t),n)){let c=i.original;i.copy&&(c=i.copy),Ct(e),jt(e,r,s,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(u=e.options.updatedValues)!==null&&u!==void 0?u:new WeakMap,e.options.updatedValues.set(c,i.original)),Le(a,t,c)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ne(n,e.options)&&e.finalities.draft.push(()=>{const s=e.type===3?e.setMap:e.copy;ce(ae(s,t),n)&&ti(e,t)})}function ni(e,t,n,r,i){let{original:s,assignedMap:o,options:u}=e,a=e.copy;a.length<s.length&&([s,a]=[a,s],[n,r]=[r,n]);for(let c=0;c<s.length;c+=1)if(o.get(c.toString())&&a[c]!==s[c]){const d=t.concat([c]),l=we(d,i);n.push({op:M.Replace,path:l,value:et(a[c])}),r.push({op:M.Replace,path:l,value:et(s[c])})}for(let c=s.length;c<a.length;c+=1){const d=t.concat([c]),l=we(d,i);n.push({op:M.Add,path:l,value:et(a[c])})}if(s.length<a.length){const{arrayLengthAssignment:c=!0}=u.enablePatches;if(c){const d=t.concat(["length"]),l=we(d,i);r.push({op:M.Replace,path:l,value:s.length})}else for(let d=a.length;s.length<d;d-=1){const l=t.concat([d-1]),h=we(l,i);r.push({op:M.Remove,path:h})}}}function ri({original:e,copy:t,assignedMap:n},r,i,s,o){n.forEach((u,a)=>{const c=ae(e,a),d=et(ae(t,a)),l=u?Ue(e,a)?M.Replace:M.Add:M.Remove;if(ce(c,d)&&l===M.Replace)return;const h=r.concat(a),p=we(h,o);i.push(l===M.Remove?{op:l,path:p}:{op:l,path:p,value:d}),s.push(l===M.Add?{op:M.Remove,path:p}:l===M.Remove?{op:M.Add,path:p,value:c}:{op:M.Replace,path:p,value:c})})}function ii({original:e,copy:t},n,r,i,s){let o=0;e.forEach(u=>{if(!t.has(u)){const a=n.concat([o]),c=we(a,s);r.push({op:M.Remove,path:c,value:u}),i.unshift({op:M.Add,path:c,value:u})}o+=1}),o=0,t.forEach(u=>{if(!e.has(u)){const a=n.concat([o]),c=we(a,s);r.push({op:M.Add,path:c,value:u}),i.unshift({op:M.Remove,path:c,value:u})}o+=1})}function Ne(e,t,n,r){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ri(e,t,n,r,i);case 1:return ni(e,t,n,r,i);case 3:return ii(e,t,n,r,i)}}const tt=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ne(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},Pt={get size(){return Z(E(this)).size},has(e){return Z(E(this)).has(e)},set(e,t){const n=E(this),r=Z(n);return(!r.has(e)||!ce(r.get(e),t))&&(W(n),se(n),n.assignedMap.set(e,!0),n.copy.set(e,t),kt(n,e,t,Ne)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return W(t),se(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){W(e),se(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);Z(n).forEach((r,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const r=E(this),i=Z(r).get(e),s=((n=(t=r.options).mark)===null||n===void 0?void 0:n.call(t,i,J))===J.mutable;if(r.options.strict&&tt(i,r.options,s),s||r.finalized||!ne(i,r.options)||i!==r.original.get(e))return i;const o=wt.createDraft({original:i,parentDraft:r,key:e,finalities:r.finalities,options:r.options});return W(r),r.copy.set(e,o),o},keys(){return Z(E(this)).keys()},values(){const e=this.keys();return{[Xe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Xe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Xe](){return this.entries()}},si=Reflect.ownKeys(Pt),vn=(e,t,{isValuesIterator:n})=>()=>{var r,i;const s=t.next();if(s.done)return s;const o=s.value;let u=e.setMap.get(o);const a=E(u),c=((i=(r=e.options).mark)===null||i===void 0?void 0:i.call(r,u,J))===J.mutable;if(e.options.strict&&tt(o,e.options,c),!c&&!a&&ne(o,e.options)&&!e.finalized&&e.original.has(o)){const d=wt.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,d),u=d}else a&&(u=a.proxy);return{done:!1,value:n?u:[u,u]}},nt={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;W(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(W(t),se(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),kt(t,e,e,Ne)),this},delete(e){if(!this.has(e))return!1;const t=E(this);W(t),se(t);const n=E(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=E(this);W(e),se(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);W(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:vn(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);W(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:vn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Xe](){return this.values()},forEach(e,t){const n=this.values();let r=n.next();for(;!r.done;)e.call(t,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(nt,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const oi=Reflect.ownKeys(nt),On=new WeakSet,En={get(e,t,n){var r,i;const s=(r=e.copy)===null||r===void 0?void 0:r[t];if(s&&On.has(s))return s;if(t===_n)return e;let o;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(c,J),o===J.mutable)return e.options.strict&&tt(c,e.options,!0),c}const u=Z(e);if(u instanceof Map&&si.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Pt,"size").get.call(e.proxy);const c=Pt[t];if(c)return c.bind(e.proxy)}if(u instanceof Set&&oi.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(nt,"size").get.call(e.proxy);const c=nt[t];if(c)return c.bind(e.proxy)}if(!Ue(u,t)){const c=gn(u,t);return c?"value"in c?c.value:(i=c.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const a=u[t];if(e.options.strict&&tt(a,e.options),e.finalized||!ne(a,e.options))return a;if(a===Ot(e.original,t)){if(W(e),e.copy[t]=It({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return W(c),se(c),c.copy}return e.copy[t]}return a},set(e,t,n){var r;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const s=gn(Z(e),t);if(s!=null&&s.set)return s.set.call(e.proxy,n),!0;const o=Ot(Z(e),t),u=E(o);return u&&ce(u.original,n)?(e.copy[t]=n,e.assignedMap=(r=e.assignedMap)!==null&&r!==void 0?r:new Map,e.assignedMap.set(t,!1),!0):(ce(n,o)&&(n!==void 0||Ue(e.original,t))||(W(e),se(e),Ue(e.original,t)&&ce(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,kt(e,t,n,Ne)),!0)},has(e,t){return t in Z(e)},ownKeys(e){return Reflect.ownKeys(Z(e))},getOwnPropertyDescriptor(e,t){const n=Z(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?En.set.call(this,e,t,void 0,e.proxy):(Ot(e.original,t)!==void 0||t in e.original?(W(e),se(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function It(e){const{original:t,parentDraft:n,key:r,finalities:i,options:s}=e,o=Te(t),u={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:s,setMap:o===3?new Map(t.entries()):void 0};(r||"key"in e)&&(u.key=r);const{proxy:a,revoke:c}=Proxy.revocable(o===1?Object.assign([],u):u,En);if(i.revoke.push(c),On.add(a),u.proxy=a,n){const d=n;d.finalities.draft.push((l,h)=>{var p,b;const g=E(a);let w=d.type===3?d.setMap:d.copy;const T=ae(w,r),v=E(T);if(v){let S=v.original;v.operated&&(S=vt(T)),Ct(v),jt(v,Ne,l,h),d.options.enableAutoFreeze&&(d.options.updatedValues=(p=d.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,d.options.updatedValues.set(S,v.original)),Le(w,r,S)}(b=g.callbacks)===null||b===void 0||b.forEach(S=>{S(l,h)})})}else{const d=E(a);d.finalities.draft.push((l,h)=>{Ct(d),jt(d,Ne,l,h)})}return a}wt.createDraft=It;function ui(e,t,n,r,i){var s;const o=E(e),u=(s=o==null?void 0:o.original)!==null&&s!==void 0?s:e,a=!!t.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const c=a?t[0]:o?o.operated?o.copy:o.original:e;return o&&Et(o),i&&Oe(c,c,o==null?void 0:o.options.updatedValues),[c,n&&a?[{op:M.Replace,path:[],value:t[0]}]:n,r&&a?[{op:M.Replace,path:[],value:u}]:r]}function ai(e,t){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let i,s;t.enablePatches&&(i=[],s=[]);const u=((n=t.mark)===null||n===void 0?void 0:n.call(t,e,J))===J.mutable||!ne(e,t)?e:It({original:e,parentDraft:null,finalities:r,options:t});return[u,(a=[])=>{const[c,d,l]=ui(u,a,i,s,t.enableAutoFreeze);return t.enablePatches?[c,d,l]:c}]}function Rt(e){const{rootDraft:t,value:n,useRawReturn:r=!1,isRoot:i=!0}=e;At(n,(s,o,u)=>{const a=E(o);if(a&&t&&a.finalities===t.finalities){e.isContainDraft=!0;const c=a.original;if(u instanceof Set){const d=Array.from(u);u.clear(),d.forEach(l=>u.add(s===l?c:l))}else Le(u,s,c)}else typeof o=="object"&&o!==null&&(e.value=o,e.isRoot=!1,Rt(e))}),i&&(e.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 An(e){var t;const n=E(e);if(!ne(e,n==null?void 0:n.options))return e;const r=Te(e);if(n&&!n.operated)return n.original;let i;function s(){i=r===2?St(e)?new Map(e):new(Object.getPrototypeOf(e)).constructor(e):r===3?Array.from(n.setMap.values()):wn(e,n==null?void 0:n.options)}if(n){n.finalized=!0;try{s()}finally{n.finalized=!1}}else i=e;if(At(i,(o,u)=>{if(n&&ce(ae(n.original,o),u))return;const a=An(u);a!==u&&(i===e&&s(),Le(i,o,a))}),r===3){const o=(t=n==null?void 0:n.original)!==null&&t!==void 0?t:i;return mt(o)?new Set(i):new(Object.getPrototypeOf(o)).constructor(i)}return i}function Cn(e){if(!ge(e))throw new Error(`current() is only used for Draft, parameter: ${e}`);return An(e)}const Mt=(e=>function t(n,r,i){var s,o,u;if(typeof n=="function"&&typeof r!="function")return function(O,...L){return t(O,U=>n.call(this,U,...L),r)};const a=n,c=r;let d=i;if(typeof r!="function"&&(d=r),d!==void 0&&Object.prototype.toString.call(d)!=="[object Object]")throw new Error(`Invalid options: ${d}, 'options' should be an object.`);d=Object.assign(Object.assign({},e),d);const l=ge(a)?Cn(a):a,h=Array.isArray(d.mark)?(O,L)=>{for(const U of d.mark){if(typeof U!="function")throw new Error(`Invalid mark: ${U}, 'mark' should be a function.`);const le=U(O,L);if(le)return le}}:d.mark,p=(s=d.enablePatches)!==null&&s!==void 0?s:!1,b=(o=d.strict)!==null&&o!==void 0?o:!1,w={enableAutoFreeze:(u=d.enableAutoFreeze)!==null&&u!==void 0?u:!1,mark:h,strict:b,enablePatches:p};if(!ne(l,w)&&typeof l=="object"&&l!==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[T,v]=ai(l,w);if(typeof r!="function"){if(!ne(l,w))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[T,v]}let S;try{S=c(T)}catch(O){throw Et(E(T)),O}const K=O=>{const L=E(T);if(!ge(O)){if(O!==void 0&&!ce(O,T)&&(L!=null&&L.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 le=O==null?void 0:O[Jr];if(le){const ht=le[0];return w.strict&&typeof O=="object"&&O!==null&&Rt({rootDraft:L,value:O,useRawReturn:!0}),v([ht])}if(O!==void 0)return typeof O=="object"&&O!==null&&Rt({rootDraft:L,value:O}),v([O])}if(O===T||O===void 0)return v([]);const U=E(O);if(w===U.options){if(U.operated)throw new Error("Cannot return a modified child draft.");return v([Cn(O)])}return v([O])};return S instanceof Promise?S.then(K,O=>{throw Et(E(T)),O}):K(S)})();Object.prototype.constructor.toString();function jn(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&Object.keys(e).every(i=>t.hasOwnProperty(i))}function kn(e,t){return Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>t.hasOwnProperty(n)&&e[n]===t[n])}function rt(e,t){return typeof e!="object"||typeof t!="object"||e===null||t===null?e===t:jn(e,t)?Object.keys(e).every(n=>rt(e[n],t[n])):!1}function Dt(e){if(!Ve(e))return e;const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Pn(e,t){if(!Ve(e)||!Ve(t))return t;const n=Object.assign({},e);for(const r of Object.keys(t)){if(t[r]===void 0)continue;if(t[r]===null){delete n[r];continue}const i=Ve(e[r])&&Ve(t[r]);n[r]=i?Pn(e[r],t[r]):t[r]}return n}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ci(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let s=0;s<t.length-1;s++){const o=t[s];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof t[s+1]=="number"?[]:{}),r=r[o]}const i=t[t.length-1];Array.isArray(r)&&typeof i=="number"?r.splice(i,0,n):r[i]=n}function In(e,t,n){if(!e||t.length===0)return;let r=e||{};for(let i=0;i<t.length-1;i++){const s=t[i];(!(s in r)||typeof r[s]!="object")&&(r[s]=typeof t[i+1]=="number"?[]:{}),r=r[s]}r[t[t.length-1]]=n}function Rn(e,t){if(!e||t.length===0)return;const[n,...r]=t;if(n in e){if(r.length===0){Array.isArray(e)?e.splice(n,1):delete e[n];return}Rn(e[n],r),di(e[n])&&delete e[n]}}function di(e){return e&&Object.keys(e).length===0}const Mn=/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$/,fi={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 li(e){return new Date(e)}function hi(e){return new Date(e+"Z")}const pi=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function yi(e){const t=e.match(pi);if(!t)return null;const[n,r,i,s]=t;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 bi(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function _i(e){const[t,n]=e.split(" ");return new Date(t+"T"+n+"Z")}function gi(e){return new Date(e)}function Ti(e){const t=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!e.match(t))throw new Error(`Unable to parse \`${e}\` as a date.`);const r=new Date(e+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function wi(e){const t=/^(.+T.+)([+-])(\d{2})$/,n=e.match(t);if(n){const[,r,i,s]=n,o=`${r}${i}${s}:00`;return new Date(o)}return null}function mi(e){const[t,n]=e.split(", "),[r,i,s]=t.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: ${e}`);let[,u,a,c,d]=o;return u=Number(u),a=Number(a),c=Number(c),d==="PM"&&u!==12?u+=12:d==="AM"&&u===12&&(u=0),new Date(Date.UTC(s,r-1,i,u,a,c))}function Si(e){switch(e){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function vi(e){const t=e.match(Mn);if(!t)return null;const[n]=t,r=fi[n],i=new Date(e.replace(Mn,"Z"));return new Date(i.getTime()-r*1e3)}const Oi=[yi,_i,Ti,mi,gi,hi,wi,bi,li,Si,vi];function Ei(e,t){try{const n=e(t);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function xt(e){for(const t of Oi){const n=Ei(t,e);if(n)return n}return null}function Ai(e){try{const t=JSON.parse(e);return typeof t=="string"?xt(t):null}catch{return null}}function it(e){if(e!==void 0){if(e===null)return null;if(e instanceof Date)return e;if(typeof e=="string"){const t=xt(e)||Ai(e)||xt(e.trim());if(!t)throw new Error(`Unable to parse \`${e}\` as a date.`);return t}else if(typeof e=="number")return new Date(e);throw new Error(`Invalid date value \`${e}\`. Expected a date, number, or string, got type ${typeof e}.`)}}function Ci(e){return e.cardinality==="one"}function $t(e){return e["value-type"]==="ref"}function Ut(e){return e["value-type"]==="blob"}function Ee(e,t){return e[t]}function st(e,t){return t.reduce((n,r)=>n&&n.get(r),e)}function re(e,t){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.delete(t[0]);return}const[n,...r]=t;e.has(n)&&re(e.get(n),r)}function Q(e,t,n){if(t.length===0)throw new Error("path must have at least one element");if(t.length===1){e.set(t[0],n);return}const[r,...i]=t;let s=e.get(r);s||(s=new Map,e.set(r,s)),Q(s,i,n)}function Dn(e,t,n){const r=new Map,i=new Map,s=new Map;for(const o of t){let[u,a,c,d]=o;const l=Ee(e,a);if(!l){console.warn("no such attr",u,e);continue}l["checked-data-type"]==="date"&&n&&(c=it(c),o[2]=c),$t(l)&&Q(s,[c,a,u],o),Q(r,[u,a,c],o),Q(i,[a,u,c],o)}return{eav:r,aev:i,vae:s}}function xn(e){const t=new Map,n=new Map,r=new Map,i=new Map;for(const s of Object.values(e)){const o=s["forward-identity"],[u,a,c]=o,d=s["reverse-identity"];if(Q(r,[a,c],s),Ut(s)&&Q(t,[a,c],s),s["primary?"]&&Q(n,[a],s),d){const[l,h,p]=d;Q(i,[h,p],s)}}return{blobAttrs:t,primaryKeys:n,forwardIdents:r,revIdents:i}}function ji(e){return{__type:e.__type,attrs:e.attrs,triples:G(e.eav,3),cardinalityInference:e.cardinalityInference,linkIndex:e.linkIndex,useDateObjects:e.useDateObjects}}function ki(e){return Ft(e.attrs,e.triples,e.cardinalityInference,e.linkIndex,e.useDateObjects)}function Lt(e){e.attrIndexes=xn(e.attrs)}function Ft(e,t,n,r,i){const s=Dn(e,t,i);return s.useDateObjects=i,s.attrs=e,s.attrIndexes=xn(e),s.cardinalityInference=n,s.linkIndex=r,s.__type="store",s}function We(e,t){var n,r;let i;if(Array.isArray(t[0])){const[o,u]=t[0],a=e.aev.get(o);if(!a)return null;i=(n=G(a,2).find(d=>d[2]===u))===null||n===void 0?void 0:n[0]}else i=t[0];if(!i)return null;const s=t[2];if(Array.isArray(s)&&s.length===2&&e.aev.get(s[0])){const[o,u]=s,a=e.aev.get(o);if(!a)return null;const d=(r=G(a,2).find(g=>g[2]===u))===null||r===void 0?void 0:r[0];if(!d)return null;const[l,h,p,...b]=t;return[i,h,d,...b]}else{const[o,...u]=t;return[i,...u]}}function Pi(e,t){const n=We(e,t);if(!n)return;const[r,i,s]=n,o=Ee(e.attrs,i);o&&(re(e.eav,[r,i,s]),re(e.aev,[i,r,s]),$t(o)&&re(e.vae,[s,i,r]))}let Ii=0;function $n(e,t,n){const[r,i,s]=n;let o;const u=st(e.ea,[r,i,s]);return u&&(o=u[3]),o||Date.now()*10+Ii++}function Ri(e,t){var n;const r=We(e,t);if(!r)return;let[i,s,o]=r;const u=Ee(e.attrs,s);if(!u)return;u["checked-data-type"]==="date"&&e.useDateObjects&&(o=it(o));const a=st(e.eav,[i,s,o]),c=(n=a==null?void 0:a[3])!==null&&n!==void 0?n:$n(e,u,r),d=[i,s,o,c];Ci(u)?(Q(e.eav,[i,s],new Map([[o,d]])),Q(e.aev,[s,i],new Map([[o,d]]))):(Q(e.eav,[i,s,o],d),Q(e.aev,[s,i,o],d)),$t(u)&&Q(e.vae,[o,s,i],d)}function Mi(e,t){var n;const r=We(e,t);if(!r)return;const[i,s,o]=r,u=Ee(e.attrs,s);if(!u)return;if(!Ut(u))throw new Error("merge operation is not supported for links");const a=st(e.eav,[i,s]);if(!a)return;const c=(n=a.values().next())===null||n===void 0?void 0:n.value;if(!c)return;const d=c[2],l=Pn(d,o),h=[i,s,l,$n(e,u,c)];Q(e.eav,[i,s],new Map([[l,h]]))}function Nt(e,t){var n,r;const[i,s]=t,o=We(e,[i]);if(!o)return;const[u]=o,a=e.eav.get(u);if(a){for(const d of a.keys()){const l=e.attrs[d];l&&l["on-delete-reverse"]==="cascade"&&G(a.get(d),1).forEach(([h,p,b])=>{var g;return Nt(e,[b,(g=l["reverse-identity"])===null||g===void 0?void 0:g[1]])}),(!s||!l||((n=l["forward-identity"])===null||n===void 0?void 0:n[1])===s)&&(re(e.aev,[d,u]),re(e.eav,[u,d]))}a.size===0&&re(e.eav,[u])}const c=e.vae.get(u)&&G(e.vae.get(u),2);c&&c.forEach(d=>{var l,h,p;const[b,g,w]=d,T=e.attrs[g];(!s||!T||((l=T["reverse-identity"])===null||l===void 0?void 0:l[1])===s)&&(re(e.eav,[b,g,w]),re(e.aev,[g,b,w]),re(e.vae,[w,g,b])),T&&T["on-delete"]==="cascade"&&((h=T["reverse-identity"])===null||h===void 0?void 0:h[1])===s&&Nt(e,[b,(p=T["forward-identity"])===null||p===void 0?void 0:p[1]])}),((r=e.vae.get(u))===null||r===void 0?void 0:r.size)===0&&re(e.vae,[u])}function Un(e,t){const n=Dn(e.attrs,t,e.useDateObjects);Object.keys(n).forEach(r=>{e[r]=n[r]})}function Di(e,[t]){e.attrs[t.id]=t,Lt(e)}function Ln(e){return G(e.eav,3)}function xi(e,[t]){if(!e.attrs[t])return;const n=Ln(e).filter(([r,i])=>i!==t);delete e.attrs[t],Lt(e),Un(e,n)}function $i(e,[t]){const n=e.attrs[t.id];n&&(e.attrs[t.id]=Object.assign(Object.assign({},n),t),Lt(e),Un(e,Ln(e)))}function Ui(e,t){const[n,...r]=t;switch(n){case"add-triple":Ri(e,r);break;case"deep-merge-triple":Mi(e,r);break;case"retract-triple":Pi(e,r);break;case"delete-entity":Nt(e,r);break;case"add-attr":Di(e,r);break;case"delete-attr":xi(e,r);break;case"update-attr":$i(e,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function G(e,t,n=[]){if(!e||t===0)return n;if(t===1){for(const r of e.values())n.push(r);return n}for(const r of e.values())G(r,t-1,n);return n}function ot(e,t,n){var r,i;const s=[];if(n!=null&&n.hasOwnProperty("$not")){for(const u of t.keys())n.$not!==u&&s.push(t.get(u));return s}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:u,isNull:a,reverse:c}=n.$isNull;if(c)for(const d of t.keys()){const l=e.vae.get(d),h=!l||((r=l.get(u))===null||r===void 0?void 0:r.get(null))||!l.get(u);(a?h:!h)&&s.push(t.get(d))}else{const d=e.aev.get(u);for(const l of t.keys()){const h=!d||((i=d.get(l))===null||i===void 0?void 0:i.get(null))||!d.get(l);(a?h:!h)&&s.push(t.get(l))}}return s}if(n!=null&&n.$comparator)return G(t,1).filter(n.$op);const o=n.in||n.$in||[n];for(const u of o){const a=t.get(u);a&&s.push(a)}return s}function Li(e,t,n){let r="";return e!==void 0&&(r+="e"),t!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Fi(e,[t,n,r]){var i,s;switch(Li(t,n,r)){case"e":{const u=e.eav.get(t);return G(u,2)}case"ea":{const u=(i=e.eav.get(t))===null||i===void 0?void 0:i.get(n);return G(u,1)}case"eav":{const u=(s=e.eav.get(t))===null||s===void 0?void 0:s.get(n);return u?ot(e,u,r):[]}case"ev":{const u=e.eav.get(t);if(!u)return[];const a=[];for(const c of u.values())a.push(...ot(e,c,r));return a}case"a":{const u=e.aev.get(n);return G(u,2)}case"av":{const u=e.aev.get(n);if(!u)return[];const a=[];for(const c of u.values())a.push(...ot(e,c,r));return a}case"v":{const u=[];for(const a of e.eav.values())for(const c of a.values())u.push(...ot(e,c,r));return u}default:return G(e.eav,3)}}function Ni(e,t,n){var r;const i={};for(const[s,o]of t.entries()){const u=(r=e.eav.get(n))===null||r===void 0?void 0:r.get(o.id),a=G(u,1);for(const c of a)i[s]=c[2]}return i}function Ae(e,t,n){var r;return(r=e.attrIndexes.forwardIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Fn(e,t,n){var r;return(r=e.attrIndexes.revIdents.get(t))===null||r===void 0?void 0:r.get(n)}function Vi(e,t){return e.attrIndexes.blobAttrs.get(t)}function Nn(e,t){var n;const r=e.attrIndexes.primaryKeys.get(t);return r||((n=e.attrIndexes.forwardIdents.get(t))===null||n===void 0?void 0:n.get("id"))}function Wi(e,t){const n=We(e,t);if(!n)return;const[r,i,s]=n;if(Ee(e.attrs,i))return st(e.eav,[r,i])}function Ki(e,t){const n=t.filter(([r,i,s,o,u])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const a=u==null?void 0:u.mode;if(a!=="create"&&a!=="update")return!0;let c=!1;const d=Ee(e.attrs,s);if(d){const l=Nn(e,d["forward-identity"][1]);c=!!Wi(e,[i,l.id,i])}return!(a==="create"&&c||a==="update"&&!c)});return Mt(e,r=>{n.forEach(i=>{Ui(r,i)})})}function zi(e){return typeof e=="string"&&e.startsWith("?")}function qi(e,t,n){if(n.hasOwnProperty(e)){const r=n[e];return Wn(r,t,n)}return Object.assign(Object.assign({},n),{[e]:t})}function Vn(e,t,n){return e===t?n:null}function Bi(e){switch(typeof e){case"string":return e.startsWith("?")?qi:Vn;default:return Vn}}const Qi=["in","$in","$not","$isNull","$comparator"];function Gi(e){for(const t of Qi)if(e.hasOwnProperty(t))return!0;return!1}function Wn(e,t,n){return n?typeof e=="object"?Gi(e)?n:null:Bi(e)(e,t,n):null}function Yi(e,t,n){return e.reduce((r,i,s)=>{const o=t[s];return Wn(i,o,r)},n)}function Hi(e,t,n){return Xi(e,t,n).map(r=>Yi(t,r,n)).filter(r=>r)}function Ji(e,t,n){return t.or?t.or.patterns.flatMap(r=>Vt(e,r,n)):t.and?t.and.patterns.reduce((r,i)=>Vt(e,i,r),n):n.flatMap(r=>Hi(e,t,r))}function Vt(e,t,n=[{}]){return t.reduce((r,i)=>Ji(e,i,r),n)}function Wt(e,t){return Array.isArray(t)?t.map(n=>Wt(e,n)):zi(t)?e[t]:t}function Zi(e,{find:t,where:n}){return Vt(e,n).map(i=>Wt(i,t))}function Xi(e,t,n){return Fi(e,Wt(n,t))}const es=/^(?:[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 Ce(e){return typeof e=="string"&&es.test(e)}const F=[];for(let e=0;e<256;++e)F.push((e+256).toString(16).slice(1));function ts(e,t=0){return(F[e[t+0]]+F[e[t+1]]+F[e[t+2]]+F[e[t+3]]+"-"+F[e[t+4]]+F[e[t+5]]+"-"+F[e[t+6]]+F[e[t+7]]+"-"+F[e[t+8]]+F[e[t+9]]+"-"+F[e[t+10]]+F[e[t+11]]+F[e[t+12]]+F[e[t+13]]+F[e[t+14]]+F[e[t+15]]).toLowerCase()}let Kt;const ns=new Uint8Array(16);function rs(){if(!Kt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Kt=crypto.getRandomValues.bind(crypto)}return Kt(ns)}const Kn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function is(e,t,n){var i;if(Kn.randomUUID&&!e)return Kn.randomUUID();e=e||{};const r=e.random??((i=e.rng)==null?void 0:i.call(e))??rs();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,ts(r)}function zn(e){const t=e.replace(/-/g,""),n=[];for(let r=0;r<t.length;r+=2)n.push(parseInt(t.substring(r,r+2),16));return n}function ss(e,t){for(let n=0;n<e.length;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function os(e,t){return ss(zn(e),zn(t))}function V(){return is()}function us(e,t){return e.localeCompare(t)}function as(){let e=us;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}const cs=as();let ds=0;function Ke(e){return ut(`_${e}`,ds++)}function ut(e,t){return`?${e}-${t}`}class je extends Error{constructor(t){super(t),this.name="AttrNotFoundError"}}function fs(e,t){const n=Nn(e,t);if(!n)throw new je(`Could not find id attr for ${t}`);return n}function qn(e,t,n,r){return[ls(e,t,n,r)]}function ls(e,t,n,r){return[e(n,r),fs(t,n).id,e(n,r),e("time",r)]}function hs(e,t,n){return e.map(r=>r===t?n:r)}function Bn(e,t,n,r,i){const s=Ae(t,n,i),o=Fn(t,n,i),u=s||o;if(!u)throw new je(`Could not find attr for ${[n,i]}`);if(u["value-type"]!=="ref")throw new Error(`Attr ${u.id} is not a ref`);const[a,c]=u["forward-identity"],[d,l]=u["reverse-identity"],h=r+1,p=s?[e(c,r),u.id,e(l,h),Ke("time")]:[e(c,h),u.id,e(l,r),Ke("time")];return[s?l:c,h,p,u,!!s]}function Qn(e,t){if(typeof t!="string")return function(o){return!1};const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),i=new RegExp(`^${r}$`,e?void 0:"i");return function(o){return typeof o!="string"?!1:i.test(o)}}function ps(e,t){if(typeof t!="object"||t.hasOwnProperty("$in")||t.hasOwnProperty("in"))return t;const n=e["checked-data-type"]==="date";if(t.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>new Date(t.$gt)}:function(i){return i[2]>t.$gt}};if(t.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])>=new Date(t.$gte)}:function(i){return i[2]>=t.$gte}};if(t.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<new Date(t.$lt)}:function(i){return i[2]<t.$lt}};if(t.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(i){return new Date(i[2])<=new Date(t.$lte)}:function(i){return i[2]<=t.$lte}};if(t.hasOwnProperty("$like")){const r=Qn(!0,t.$like);return{$comparator:!0,$op:function(s){return r(s[2])}}}if(t.hasOwnProperty("$ilike")){const r=Qn(!1,t.$ilike);return{$comparator:!0,$op:function(s){return r(s[2])}}}return t}function ys(e,t,n,r,i,s){const o=Ae(t,n,i),u=Fn(t,n,i),a=o||u;if(!a)throw new je(`No attr for etype = ${n} label = ${i}`);if(s!=null&&s.hasOwnProperty("$isNull")){const c=Ae(t,n,"id");if(!c)throw new je(`No attr for etype = ${n} label = id`);return[e(n,r),c.id,{$isNull:{attrId:a.id,isNull:s.$isNull,reverse:!o}},Ke("time")]}return o?[e(n,r),a.id,ps(a,s),Ke("time")]:[s,a.id,e(n,r),Ke("time")]}function bs(e,t,n,r,i){const[s,o,u]=i.reduce((a,c)=>{const[d,l,h]=a,[p,b,g]=Bn(e,t,d,l,c);return[p,b,[...h,g]]},[n,r,[]]);return[s,o,u]}function zt(e,t,n,r,i,s){const o=i.slice(0,i.length-1),u=i[i.length-1],[a,c,d]=bs(e,t,n,r,o),l=ys(e,t,a,c,u,s);return d.concat([l])}function _s(e,t){return t?[t].concat(e):e}function gs([e,t]){return e==="or"&&Array.isArray(t)}function Ts([e,t]){return e==="and"&&Array.isArray(t)}function ws(e,t,n){return(r,i)=>{const s=e(r,i);return t==s?s:`${s}-${n}`}}function Gn(e,t,n,r,i,s){const o=e(r,i),u=s.map((a,c)=>{const d=ws(e,o,c);return Hn(d,n,r,i,a)});return{[t]:{patterns:u,joinSym:o}}}function ms(e){const t=[];for(let n=1;n<=e.length;n++)t.push(e.slice(0,n));return t}function Yn(e,t,n,r,i){return ms(i).map(s=>zt(e,t,n,r,s,{$isNull:!0}))}function Hn(e,t,n,r,i){return Object.entries(i).flatMap(([s,o])=>{if(gs([s,o]))return Gn(e,"or",t,n,r,o);if(Ts([s,o]))return Gn(e,"and",t,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 a=zt(e,t,n,r,u,o),c=Yn(e,t,n,r,u);return[{or:{patterns:[a,...c],joinSym:e(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&u.length>1?[{or:{patterns:Yn(e,t,n,r,u),joinSym:e(n,r)}}]:zt(e,t,n,r,u,o)})}function Ss(e,t,n,r){const i=ut;return r?Hn(i,e,t,n,r).concat(qn(i,e,t,n)):qn(i,e,t,n)}function vs(e,t,n){return[e(t,n),e("time",n)]}function Os(e,t,n,r,i,s){const[o,u,a,c,d]=Bn(e,t,n,r,i),l=hs(a,e(n,r),s);return[o,u,l,c,d]}function Es(e,t,{etype:n,level:r,form:i},s){const o=Object.keys(i).filter(u=>u!=="$");return o.length?Object.entries(s).map(function([a,c]){return o.map(function(h){var p,b,g;const w=!!(t.cardinalityInference&&(!((g=(b=(p=t.linkIndex)===null||p===void 0?void 0:p[n])===null||b===void 0?void 0:b[h])===null||g===void 0)&&g.isSingular));try{const[T,v,S]=Os(e,t,n,r,h,a),K=Zn(t,{etype:T,level:v,form:i[h],join:S}),O=w?K[0]:K;return{[h]:O}}catch(T){if(T instanceof je)return{[h]:w?void 0:[]};throw T}}).reduce(function(h,p){return Object.assign(Object.assign({},h),p)},c)}):Object.values(s)}function As(e,t,n){return n==="string"?cs(e,t):e>t?1:-1}function at([e,t],[n,r],i){return t===r||t==null&&r==null?os(e,n):r==null?1:t==null?-1:As(t,r,i)}function qt(e){return e==null?e:new Date(e).getTime()}function Cs(e,t,n,r){var i;const[s,o,u,a]=e,c=n==="desc"?1:-1;if(((i=t["forward-identity"])===null||i===void 0?void 0:i[2])==="id")return at(r,[s,a],null)===c;const[d,l]=r,h=t["checked-data-type"],p=h==="date"?qt(l):l,b=h==="date"?qt(u):u;return at([d,p],[s,b],h)===c}function js(e,t){const n=t[1];return e.attrs[n]}function ks(e,t,n){const r=Object.keys(n)[0];return Ae(e,t,r)}function Ps(e,t,n,r){if(n)return js(e,n);if(r)return ks(e,t,r)}function Is(e,t,n){var r,i;if(!Array.isArray(n.fields))return Vi(e,t);const s=new Map;for(const o of n.fields){const u=Ae(e,t,o),a=(r=u==null?void 0:u["forward-identity"])===null||r===void 0?void 0:r[2];a&&Ut(u)&&s.set(a,u)}if(!s.has("id")){const o=Ae(e,t,"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 Rs(e,{etype:t,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,a=Jn(i),c=Ms(i);let d=Zi(e,r);const l=n==null?void 0:n["start-cursor"],h=Ps(e,t,l,u);if(h&&((o=h==null?void 0:h["forward-identity"])===null||o===void 0?void 0:o[2])!=="id"){const g=h["checked-data-type"]==="date",w=h.id;d=d.map(([T])=>{var v,S,K,O,L;let U=(L=(O=(K=(S=(v=e.eav.get(T))===null||v===void 0?void 0:v.get(w))===null||S===void 0?void 0:S.values())===null||K===void 0?void 0:K.next())===null||O===void 0?void 0:O.value)===null||L===void 0?void 0:L[2];return g&&(U=qt(U)),[T,U]})}d.sort(c==="asc"?function(w,T){return at(w,T,h==null?void 0:h["checked-data-type"])}:function(w,T){return at(T,w,h==null?void 0:h["checked-data-type"])});let p={};const b=Is(e,t,r);for(const g of d){const[w]=g;if(p[w]||!a&&l&&h&&Cs(l,h,c,g))continue;const T=Ni(e,b,w);T&&(p[w]=T)}return p}function Ms(e){var t;const n=(t=e.$)===null||t===void 0?void 0:t.order;return n&&n[Object.keys(n)[0]]||"asc"}function Jn(e){var t,n,r;const i=(t=e.$)===null||t===void 0?void 0:t.offset,s=(n=e.$)===null||n===void 0?void 0:n.before,o=(r=e.$)===null||r===void 0?void 0:r.after;return!i&&!s&&!o}function Ds(e,{etype:t,level:n,form:r,join:i,pageInfo:s}){var o,u,a,c,d;if(!Jn(r)&&(!s||!s["start-cursor"]))return[];const l=_s(Ss(e,t,n,(o=r.$)===null||o===void 0?void 0:o.where),i),h=vs(ut,t,n),p=(u=r.$)===null||u===void 0?void 0:u.fields,b=Rs(e,{etype:t,pageInfo:s,form:r,dq:{where:l,find:h,fields:p}}),g=((a=r.$)===null||a===void 0?void 0:a.limit)||((c=r.$)===null||c===void 0?void 0:c.first)||((d=r.$)===null||d===void 0?void 0:d.last);if(g!=null){const w=Object.entries(b);return w.length<=g?b:Object.fromEntries(w.slice(0,g))}return b}function xs(e,t){try{return Ds(e,t)}catch(n){if(n instanceof je)return{};throw n}}function Zn(e,t){const n=xs(e,t);return Es(ut,e,t,n)}function $s(e){const t={};for(const[n,r]of Object.entries(e))t[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return t}function Us({store:e,pageInfo:t,aggregate:n},r){const s={data:Object.keys(r).reduce(function(u,a){return n!=null&&n[a]||a==="$$ruleParams"||(u[a]=Zn(e,{etype:a,form:r[a],level:0,pageInfo:t==null?void 0:t[a]})),u},{})};return t&&(s.pageInfo=$s(t)),n&&(s.aggregate=n),s}function Ls(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Fs=Ls();function Bt(e,t,n){const r={__etype:e,__ops:n};return new Proxy(r,{get:(i,s)=>{if(s==="__ops")return n;if(s==="__etype")return e;if(Fs.has(s))return(o,u)=>Bt(e,t,[...n,u?[s,e,t,o,u]:[s,e,t,o]])}})}function ct(e){return e.startsWith("lookup__")}function Xn(e){const[t,n,...r]=e.split("__");return[n,JSON.parse(r.join("__"))]}function Ns(e){return new Proxy({__etype:e},{get(t,n){if(n==="__etype")return e;const r=n;return ct(r)?Bt(e,Xn(r),[]):Bt(e,r,[])}})}function Qt(){return new Proxy({},{get(e,t){return Ns(t)}})}Qt();function Vs(e){return e.__ops}function Ws(e,t){const{attrIdMap:n,refSwapAttrIds:r}=e,i=[];for(const o of t){const u=n[o];if(u)i.push(u);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[a,c]=o;i.push([n[a],c])}else i.push(o)}const[s]=t;if((s==="add-triple"||s==="retract-triple")&&r.has(t[2])){const o=i[1];i[1]=i[3],i[3]=o}return i}function N(e,t,n){return Object.values(e).find(r=>{const[i,s,o]=r["forward-identity"];return s===t&&o===n})}function me(e,t,n){return Object.values(e).find(r=>{const i=r["reverse-identity"];if(!i)return!1;const[s,o,u]=i;return o===t&&u===n})}function Ks(e){if(Array.isArray(e))return e;const t=Object.entries(e);if(t.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return t[0]}function Gt(e,t,n){return n.indexOf(".")!==-1&&!N(e,t,n)}function Yt(e){const[t,n,...r]=e.split(".");if(r.length>0||n!=="id")throw new Error(`${e} is not a valid lookup attribute.`);return t}function zs(e,t,n){if(!Gt(e,t,n))return N(e,t,n);const r=Yt(n),i=N(e,t,r)||me(e,t,r);if(i&&i["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return i}function Ht(e){return typeof e=="string"&&!ct(e)?null:typeof e=="string"&&ct(e)?Xn(e):Ks(e)}function Y(e,t,n){const r=Ht(n);if(r===null)return n;const[i,s]=r,o=zs(e,t,i);if(!o||!o["unique?"])throw new Error(`${i} is not a unique attribute.`);return[o.id,s]}function er(e,t,n,r){const i=Y(e,t,n);return Array.isArray(i)?[["add-triple",i,N(e,t,"id").id,i]].concat(r):r}function qs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),c=me(e,t,s);return u.map(d=>a?["add-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],d)]:["add-triple",Y(e,c["forward-identity"][1],d),c.id,Y(e,t,n)])});return er(e,t,n,i)}function Bs({attrs:e},[t,n,r]){const i=Object.entries(r).flatMap(([s,o])=>{const u=Array.isArray(o)?o:[o],a=N(e,t,s),c=me(e,t,s);return u.map(d=>a?["retract-triple",Y(e,t,n),a.id,Y(e,a["reverse-identity"][1],d)]:["retract-triple",Y(e,c["forward-identity"][1],d),c.id,Y(e,t,n)])});return er(e,t,n,i)}function Qs(e,t,n){if(Array.isArray(n)){const[r,i]=n;for(const s of e||[]){const o=s==null?void 0:s.aev.get(r);if(o){for(const[u,a,c]of G(o,2))if(c===i)return!0}}}else for(const r of e||[]){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]==t)return!0}}return!1}function tr({stores:e,attrs:t},[n,r,i,s]){return(s==null?void 0:s.upsert)===!1?{mode:"update"}:(s==null?void 0:s.upsert)===!0?null:Qs(e,n,r)?{mode:"update"}:null}function Gs(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s);return[["id",c]].concat(Object.entries(a)).map(([l,h])=>{const p=N(r,i,l);return p["checked-data-type"]==="date"&&e.useDateObjects&&(h=it(h)),["add-triple",c,p.id,h,{mode:"create"}]})}function Ys(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s),d=tr(e,[i,c,o,u]);return[["id",c]].concat(Object.entries(a)).map(([h,p])=>{const b=N(r,i,h);return b["checked-data-type"]==="date"&&e.useDateObjects&&(p=it(p)),["add-triple",c,b.id,p,...d?[d]:[]]})}function Hs({attrs:e},[t,n]){return[["delete-entity",Y(e,t,n),t]]}function Js(e,t){const{stores:n,attrs:r}=e,[i,s,o,u]=t,a=Dt(o),c=Y(r,i,s),d=tr(e,[i,c,o,u]),l=Object.entries(a).map(([p,b])=>{const g=N(r,i,p);return["deep-merge-triple",c,g.id,b,...d?[d]:[]]});return[["add-triple",c,N(r,i,"id").id,c,...d?[d]:[]]].concat(l)}function Zs({attrs:e},[t,n,r]){return[["rule-params",Y(e,t,n),t,r]]}function Xs(e){const[t,n,r,i,s]=e;if(!i)return e;const o=Object.assign({},i);return delete o.id,[t,n,r,o,...s?[s]:[]]}function eo(e,t){const[n,...r]=Xs(t);switch(n){case"merge":return Js(e,r);case"create":return Gs(e,r);case"update":return Ys(e,r);case"link":return qs(e,r);case"unlink":return Bs(e,r);case"delete":return Hs(e,r);case"ruleParams":return Zs(e,r);default:throw new Error(`unsupported action ${n}`)}}function to(e){switch(e){case"string":case"date":case"boolean":case"number":return e;default:return}}function no(e,t,n){var r,i;const s=(i=(r=e.entities[t])===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(`${t}.${n} does not exist in your schema`);const{unique:o,indexed:u}=s==null?void 0:s.config,a=to(s==null?void 0:s.valueType);return{"index?":u,"unique?":o,"checked-data-type":a}}function dt(e,t,n,r){const i=e?no(e,t,n):null,s=V(),u=[V(),t,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 ro(e,t,n){return Object.values(e.links).find(i=>i.forward.on===t&&i.forward.label===n||i.reverse.on===t&&i.reverse.label===n)}function io(e,t,n){const r=ro(e,t,n);if(!r)throw new Error(`Couldn't find the link ${t}.${n} in your schema`);const{forward:i,reverse:s}=r;return{"forward-identity":[V(),i.on,i.label],"reverse-identity":[V(),s.on,s.label],cardinality:i.has==="one"?"one":"many","unique?":s.has==="one","on-delete":i.onDelete,"on-delete-reverse":s.onDelete}}function nr(e,t,n,r){const i=e?io(e,t,n):null,s=V(),o=[V(),t,n],u=[V(),n,t];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 so=new Set(["create","update","merge","link","unlink"]),oo=new Set(["link","unlink"]),uo=new Set(["create","update","merge"]),ao=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),Jt={"unique?":!0,"index?":!0},co=Object.assign(Object.assign({},Jt),{cardinality:"one"});function fo(e){const t=[],[n,r,i,s]=e;if(!ao.has(n))return t;const o=Ht(i);if(o&&t.push({etype:r,lookupPair:o}),n==="link")for(const[u,a]of Object.entries(s)){const c=Array.isArray(a)?a:[a];for(const d of c){const l=Ht(d);l&&t.push({etype:r,lookupPair:l,linkLabel:u})}}return t}function lo({attrs:e,schema:t},n){var r,i;const[s,o,u]=[new Set,Object.assign({},e),[]];function a(l){o[l.id]=l,u.push(["add-attr",l]),s.add(l.id)}function c(l){l!=null&&l.isUnsynced&&!s.has(l.id)&&(u.push(["add-attr",l]),s.add(l.id))}function d(l,h){const p=N(o,l,h),b=me(o,l,h);c(p),c(b),!p&&!b&&a(nr(t,l,h,co))}for(const l of n)for(const{etype:h,lookupPair:p,linkLabel:b}of fo(l)){const g=p[0];if(b){d(h,b);const w=N(o,h,b),T=me(o,h,b);c(w),c(T);const v=((r=w==null?void 0:w["reverse-identity"])===null||r===void 0?void 0:r[1])||((i=T==null?void 0:T["forward-identity"])===null||i===void 0?void 0:i[1])||b;if(Gt(o,v,g))d(v,Yt(g));else{const S=N(o,v,g);S||a(dt(t,v,g,Jt)),c(S)}}else if(Gt(o,h,g))d(h,Yt(g));else{const w=N(o,h,g);w||a(dt(t,h,g,Jt)),c(w)}}for(const l of n){const[h,p,b,g]=l;if(so.has(h)){const w=N(o,p,"id");c(w),w||a(dt(t,p,"id",{"unique?":!0}));for(const T of Object.keys(g)){const v=N(o,p,T);if(c(v),uo.has(h)&&(v||a(dt(t,p,T,T==="id"?{"unique?":!0}:null))),oo.has(h)){const S=me(o,p,T);!v&&!S&&a(nr(t,p,T)),c(S)}}}}return[o,u]}function ho(e,t){const r=(Array.isArray(t)?t:[t]).flatMap(a=>Vs(a)),[i,s]=lo(e,r),o=Object.assign(Object.assign({},e),{attrs:i}),u=r.flatMap(a=>eo(o,a));return[...s,...u]}var rr=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class ir{constructor(t){this.dbName=t,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((t,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=i=>{n(i)},r.onsuccess=i=>{const s=i.target;t(s.result)},r.onupgradeneeded=i=>{i.target.result.createObjectStore(this._storeName)}})}getItem(t){return rr(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(t);u.onerror=a=>{i(a)},u.onsuccess=a=>{u.result?r(u.result):r(null)}})})}setItem(t,n){return rr(this,void 0,void 0,function*(){const r=yield this._dbPromise;return new Promise((i,s)=>{const a=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,t);a.onerror=c=>{s(c)},a.onsuccess=c=>{i()}})})}}var po=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class sr{static getIsOnline(){return po(this,void 0,void 0,function*(){return navigator.onLine})}static listen(t){const n=()=>{t(!0)},r=()=>{t(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class ke extends Error{constructor(t,n){super(t),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,ke),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}var yo=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};class ft extends ke{constructor(t){var n;const r=((n=t.body)===null||n===void 0?void 0:n.message)||`API Error (${t.status})`;super(r,t.body.hint);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,ft),this.name="InstantAPIError",this.status=t.status,this.body=t.body}get[Symbol.toStringTag](){return"InstantAPIError"}}function ie(e,t){return yo(this,void 0,void 0,function*(){const n=yield fetch(e,t),r=yield n.json();return n.status===200?Promise.resolve(r):Promise.reject(new ft({status:n.status,body:r}))})}var Pe=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function bo({apiURI:e,appId:t,email:n}){return ie(`${e}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":t,email:n})})}function _o(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,email:r,code:i,refreshToken:s}){return yield ie(`${t}/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 go(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield ie(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n,"refresh-token":r})})})}function To(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n}){return yield ie(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":n})})})}function or(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,code:r,codeVerifier:i,refreshToken:s}){return yield ie(`${t}/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 wo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,nonce:r,idToken:i,clientName:s,refreshToken:o}){return yield ie(`${t}/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 mo(e){return Pe(this,arguments,void 0,function*({apiURI:t,appId:n,refreshToken:r}){return yield ie(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:n,refresh_token:r})})})}var ze=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function So(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,file:i,refreshToken:s,contentType:o,contentDisposition:u}){const a={app_id:n,path:r,authorization:`Bearer ${s}`,"content-type":o||i.type};return u&&(a["content-disposition"]=u),yield ie(`${t}/storage/upload`,{method:"PUT",headers:a,body:i})})}function vo(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield ie(`${t}/storage/files?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}function Oo(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,fileName:r,refreshToken:i,metadata:s={}}){const{data:o}=yield ie(`${t}/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 Eo(e,t){return ze(this,void 0,void 0,function*(){return(yield fetch(e,{method:"PUT",body:t,headers:{"Content-Type":t.type}})).ok})}function Ao(e){return ze(this,arguments,void 0,function*({apiURI:t,appId:n,path:r,refreshToken:i}){const{data:s}=yield ie(`${t}/storage/signed-download-url?app_id=${n}&filename=${encodeURIComponent(r)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${i}`}});return s})}let Zt=!1,ur=!1,ar=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(Zt=!!window.localStorage.getItem("devBackend"),ur=!!window.localStorage.getItem("__instantLogging"),ar=!!window.localStorage.getItem("__devtoolLocalDash"));function cr(e,t){if(!t)return e;const n={};return t.forEach(r=>{n[r]=e[r]}),n}function Co(e,t,n){var r,i;const s={peers:{}};if(t&&"user"in t?t.user:!0){const u=cr((r=e.user)!==null&&r!==void 0?r:{},t==null?void 0:t.keys);s.user=Object.assign(Object.assign({},u),{peerId:n})}for(const u of Object.keys((i=e.peers)!==null&&i!==void 0?i:{})){const a=(t==null?void 0:t.peers)===void 0,c=Array.isArray(t==null?void 0:t.peers)&&(t==null?void 0:t.peers.includes(u));if(a||c){const d=cr(e.peers[u],t==null?void 0:t.keys);s.peers[u]=Object.assign(Object.assign({},d),{peerId:u})}}return s}function jo(e,t){if(e.isLoading!==t.isLoading||e.error!==t.error||(e.user||t.user)&&(!e.user||!t.user||!kn(e.user,t.user))||!jn(e.peers,t.peers))return!0;for(const r of Object.keys(e.peers))if(!kn(e.peers[r],t.peers[r]))return!0;return!1}class dr{constructor(){this.promise=new Promise((t,n)=>{this._resolve=t,this._reject=n})}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}var qe=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};function ko(e,t){typeof requestIdleCallback>"u"?e():requestIdleCallback(e,{timeout:t})}class fr{constructor(t,n,r,i,s=c=>c,o=c=>c,u=100,a=1e3){this._subs=[],this._nextSave=null,this._persister=t,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=a,this._load()}_getFromStorage(){return qe(this,void 0,void 0,function*(){try{return this.parse(yield this._persister.getItem(this._key))}catch(t){return console.error(`Unable to read from storage for key=${this._key}`,t),null}})}_load(){return qe(this,void 0,void 0,function*(){const t=yield this._getFromStorage();this._isLoading=!1,this._onMerge(t,this.currentValue);for(const n of this._loadedCbs)n()})}waitForLoaded(){return qe(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 qe(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 t of this._pendingSaveCbs)t();this._pendingSaveCbs.length=0}flush(){return qe(this,void 0,void 0,function*(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())})}_enqueuePersist(t){if(this._nextSave){t&&this._pendingSaveCbs.push(t);return}this._nextSave=setTimeout(()=>{ko(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(t,n){this._version++,this.currentValue=t(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue)}subscribe(t){return this._subs.push(t),t(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==t)}}}function lr(e,t=[]){e.forEach(n=>{const{data:r}=n,{"datalog-result":i}=r,{"join-rows":s}=i;for(const o of s)for(const u of o)t.push(u);lr(n["child-nodes"],t)})}function hr(e){const t=[];return lr(e,t),t}function pr(e){return Object.values(e.links).reduce((t,n)=>{var r,i,s,o;return(r=t[s=n.forward.on])!==null&&r!==void 0||(t[s]={}),t[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},(i=t[o=n.reverse.on])!==null&&i!==void 0||(t[o]={}),t[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},t},{})}const yr="v0.22.30-experimental.adtk6.18724548131.1";function Po(e){return{info:e?console.info.bind(console):()=>{},debug:e?console.debug.bind(console):()=>{},error:e?console.error.bind(console):()=>{}}}class de{constructor(t,n,r,i={indexed:!1,unique:!1}){this.valueType=t,this.required=n,this.isIndexed=r,this.config=i,this.metadata={}}clientRequired(){return new de(this.valueType,!1,this.isIndexed,this.config)}optional(){return new de(this.valueType,!1,this.isIndexed,this.config)}unique(){return new de(this.valueType,this.required,this.isIndexed,Object.assign(Object.assign({},this.config),{unique:!0}))}indexed(){return new de(this.valueType,this.required,!0,Object.assign(Object.assign({},this.config),{indexed:!0}))}}class R extends Error{constructor(t,n){const r=n?`At path '${n}': ${t}`:t;super(r),this.name="QueryValidationError"}}const br=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Io=e=>e.valueType||"unknown",_r=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Ro=(e,t,n,r,i,s,o)=>{const u=s.valueType==="json",a=(c,d,l)=>{if(!_r(l,d,u))throw new R(`Invalid value for operator '${c}' on attribute '${r}' in entity '${i}'. Expected ${d}, but received: ${typeof l}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new R(`Operator '${e}' for attribute '${r}' in entity '${i}' must be an array, but received: ${typeof t}`,o);for(const c of t)a(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":a(e,n,t);break;case"$like":case"$ilike":if(a(e,"string",t),e==="$ilike"&&!s.isIndexed)throw new R(`Operator '${e}' can only be used with indexed attributes, but '${r}' in entity '${i}' is not indexed`,o);break;case"$isNull":a(e,"boolean",t);break;default:throw new R(`Unknown operator '${e}' for attribute '${r}' in entity '${i}'`,o)}},Ie=(e,t,n,r,i)=>{const s=Io(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const a=e;for(const[c,d]of Object.entries(a))Ro(c,d,s,t,r,n,`${i}.${c}`)}else if(!_r(e,s,o))throw new R(`Invalid value for attribute '${t}' in entity '${r}'. Expected ${s}, but received: ${typeof e}`,i)},Mo=(e,t,n,r,i)=>{const s=e.split(".");if(s.length<2)throw new R(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let d=0;d<s.length-1;d++){const l=s[d],h=r.entities[o];if(!h)throw new R(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const p=h.links[l];if(!p){const b=Object.keys(h.links);throw new R(`Link '${l}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${b.length>0?b.join(", "):"none"}`,i)}o=p.entityName}const u=s[s.length-1],a=r.entities[o];if(!a)throw new R(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(u==="id"){if(typeof t=="string"&&!Ce(t))throw new R(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ie(t,e,new de("string",!1,!0),n,i);return}const c=a.attrs[u];if(Object.keys(a.links).includes(u)){if(typeof t=="string"&&!Ce(t))throw new R(`Invalid value for link '${u}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ie(t,e,new de("string",!1,!0),n,i);return}if(!c){const d=Object.keys(a.attrs);throw new R(`Attribute '${u}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,i)}Ie(t,e,c,n,i)},gr=(e,t,n,r)=>{for(const[i,s]of Object.entries(e)){if(i==="or"||i==="and"){if(Array.isArray(s))for(const c of s)typeof c=="object"&&c!==null&&gr(c,t,n,`${r}.${i}[${c}]`);continue}if(i==="id"){Ie(s,"id",new de("string",!1,!0),t,`${r}.id`);continue}if(i.includes(".")){Mo(i,s,t,n,`${r}.${i}`);continue}const o=n.entities[t];if(!o)continue;const u=o.attrs[i],a=o.links[i];if(!u&&!a){const c=Object.keys(o.attrs),d=Object.keys(o.links);throw new R(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${r}.${i}`)}if(u)Ie(s,i,u,t,`${r}.${i}`);else if(a){if(typeof s=="string"&&!Ce(s))throw new R(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${s}`,`${r}.${i}`);const c=new de("string",!1,!0);Ie(s,i,c,t,`${r}.${i}`)}}},Do=(e,t,n,r,i=0)=>{for(const o of Object.keys(e))if(!br.includes(o))throw new R(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${br.join(", ")}. Found: ${o}`,r);const s=["limit","offset","before","after","first","last"];for(const o of s)if(e[o]!==void 0&&i>0)throw new R(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new R(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,r?`${r}.where`:void 0);gr(e.where,t,n,r?`${r}.where`:"where")}},Tr=(e,t,n,r,i=0)=>{var s;if(!e||typeof e!="object")throw new R(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,r);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const a=Object.keys(n.entities[t].links);throw new R(`Link '${o}' does not exist on entity '${t}'. Available links: ${a.length>0?a.join(", "):"none"}`,`${r}.${o}`)}const u=e[o];if(typeof u=="object"&&u!==null){const a=(s=n==null?void 0:n.entities[t].links[o])===null||s===void 0?void 0:s.entityName;a&&Tr(u,a,n,`${r}.${o}`,i+1)}}else{const u=e[o];if(typeof u!="object"||u===null)throw new R(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof u}`,`${r}.$`);Do(u,t,n,`${r}.$`,i)}},wr=(e,t)=>{if(typeof e!="object"||e===null)throw new R(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new R(`Query must be an object, but received: ${typeof e}`);const n=e;for(const r of Object.keys(n)){if(Array.isArray(e[r]))throw new R(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new R(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(t&&!t.entities[r]){const i=Object.keys(t.entities);throw new R(`Entity '${r}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,r)}Tr(n[r],r,t,r,0)}}},mr=e=>typeof e!="string"?!1:ct(e)?!0:Ce(e);class ee extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const Sr=e=>e.length>0?e.join(", "):"none",xo=(e,t)=>new ee(`Entity '${e}' does not exist in schema. Available entities: ${Sr(t)}`),vr={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},$o=(e,t)=>{var n,r;return e==null?!0:(r=(n=vr[t.valueType])===null||n===void 0?void 0:n.call(vr,e))!==null&&r!==void 0?r:!1},Or=(e,t)=>{const n=t.entities[e];if(!n)throw xo(e,Object.keys(t.entities));return n},Xt=(e,t,n)=>{const r=Or(e,n);if(typeof t!="object"||t===null)throw new ee(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(i==="id")continue;const o=r.attrs[i];if(o&&!$o(s,o))throw new ee(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof s}`)}},Er=(e,t,n)=>{const r=Or(e,n);if(typeof t!="object"||t===null)throw new ee(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,s]of Object.entries(t)){if(!r.links[i]){const u=Object.keys(r.links);throw new ee(`Link '${i}' does not exist on entity '${e}'. Available links: ${Sr(u)}`)}if(s!=null){if(Array.isArray(s)){for(const u of s)if(!mr(u))throw new ee(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${u}`)}else if(!mr(s))throw new ee(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${s}`)}}},Uo={create:Xt,update:Xt,merge:Xt,link:Er,unlink:Er,delete:()=>{}},Lo=(e,t)=>{if(!t)return;const[n,r,i,s]=e;if(!Array.isArray(i)&&!Ce(i))throw new ee(`Invalid id for entity '${r}'. Expected a UUID, but received: ${i}`);if(typeof r!="string")throw new ee(`Entity name must be a string, but received: ${typeof r}`);const o=Uo[n];o&&s!==void 0&&o(r,s,t)},Fo=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const r of n){if(!r||typeof r!="object")throw new ee(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new ee(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const i of r.__ops){if(!Array.isArray(i))throw new ee(`Transaction operation must be an array, but received: ${typeof i}`);Lo(i,t)}}};var Ar=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})};let Cr=0;class jr{constructor(t){this.type="ws",this.id=`${this.type}_${Cr++}`,this.conn=new WebSocket(t),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(t){return this.conn.send(JSON.stringify(t))}}class No{constructor(t,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Cr++}`,this.url=n,this.ES=t,this.conn=new t(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(t){return Ar(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:t})})).ok||this.handleError()}catch{this.handleError()}})}flushQueue(){return Ar(this,void 0,void 0,function*(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})})}send(t){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(t),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 x=function(e,t,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(d){try{c(r.next(d))}catch(l){o(l)}}function a(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?s(d.value):i(d.value).then(u,a)}c((r=r.apply(e,t||[])).next())})},Vo=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const fe={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Wo=3e4,Ko=3e4,zo={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},en="_instant_oauth_redirect",tn="currentUser";function qo({transportType:e,appId:t,apiURI:n,wsURI:r,EventSourceImpl:i}){if(!i)return new jr(`${r}?app_id=${t}`);switch(e){case"ws":return new jr(`${r}?app_id=${t}`);case"sse":return new No(i,`${n}/runtime/sse?app_id=${t}`);default:throw new Error("Unknown transport type "+e)}}function Bo(){return typeof window<"u"||typeof chrome<"u"}const kr={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Qo(e,t){var n;const r=typeof e=="string"?JSON.parse(e):e;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=ki(Object.assign(Object.assign({},o),{useDateObjects:t}))}}return r}function Go(e){var t;const n={};for(const r in e){const i=e[r],s=Object.assign({},i);!((t=i.result)===null||t===void 0)&&t.store&&(s.result=Object.assign(Object.assign({},i.result),{store:ji(i.result.store)})),n[r]=s}return n}function Pr(e){return[...e].sort((t,n)=>{const[r,i]=t,[s,o]=n,u=i.order||0,a=o.order||0;return u==a?r<s?-1:r>s?1:0:u-a})}class Yo{constructor(t,n=ir,r=sr,i,s){var o;if(this._isOnline=!0,this._isShutdown=!1,this.status=fe.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._onMergeQuerySubs=(u,a)=>{const c=u||{},d=Object.assign({},a);Object.entries(a).forEach(([h,p])=>{var b;const g=(b=c==null?void 0:c[h])===null||b===void 0?void 0:b.result,w=p.result;g&&!w&&(d[h].result=g)}),Object.keys(c).filter(h=>!a[h]).sort((h,p)=>{var b,g;const w=((b=c[h])===null||b===void 0?void 0:b.lastAccessed)||0;return(((g=c[p])===null||g===void 0?void 0:g.lastAccessed)||0)-w}).slice(0,this.queryCacheLimit).forEach(h=>{d[h]=c[h]}),this.querySubs.set(h=>d),this.loadedNotifyAll()},this._onMergePendingMutations=(u,a)=>{const c=new Map([...u.entries(),...a.entries()]);this.pendingMutations.set(l=>c),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,u).forEach(([l,h])=>{!a.has(l)&&!h["tx-id"]&&this._sendMutation(l,h)})},this.getPreviousResult=u=>{const a=B(u);return this.dataForQuery(a)},this.notifyOne=u=>{var a,c;const d=(a=this.queryCbs[u])!==null&&a!==void 0?a:[],l=(c=this._dataForQueryCache[u])===null||c===void 0?void 0:c.data,h=this.dataForQuery(u);h&&(rt(h,l)||d.forEach(p=>p.cb(h)))},this.notifyOneQueryOnce=u=>{var a;const c=(a=this.queryOnceDfds[u])!==null&&a!==void 0?a:[],d=this.dataForQuery(u);c.forEach(l=>{this._completeQueryOnce(l.q,u,l.dfd),l.dfd.resolve(d)})},this.notifyQueryError=(u,a)=>{(this.queryCbs[u]||[]).forEach(d=>d.cb({error:a}))},this.pushTx=u=>{this.config.disableValidation||Fo(u,this.config.schema);try{const a=ho({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(c=>{var d;return(d=c==null?void 0:c.result)===null||d===void 0?void 0:d.store}),useDateObjects:this.config.useDateObjects},u);return this.pushOps(a)}catch(a){return this.pushOps([],a)}},this.pushOps=(u,a)=>{const c=V(),d=[...this.pendingMutations.currentValue.values()],l=Math.max(0,...d.map(b=>b.order||0))+1,h={op:"transact","tx-steps":u,created:Date.now(),error:a,order:l};this.pendingMutations.set(b=>(b.set(c,h),b));const p=new dr;return this.mutationDeferredStore.set(c,p),this._sendMutation(c,h),this.notifyAll(),p.promise},this._transportOnOpen=u=>{const a=u.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(fe.OPENED),this.getCurrentUser().then(c=>{var d;this._trySend(V(),{op:"init","app-id":this.config.appId,"refresh-token":(d=c.user)===null||d===void 0?void 0:d.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(c=>{this._log.error("[socket][error]",a.id,c)})},this._transportOnMessage=u=>{const a=u.target,c=u.message;if(this._transport!==a){this._log.info("[socket][message]",a.id,c,"skip; this is no longer the current transport");return}!this._wsOk&&a.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(a.id,u.message)},this._transportOnError=u=>{const a=u.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,u)},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=u=>{const a=u.target;if(this._transport!==a){this._log.info("[socket][close]",a.id,"skip; this is no longer the current transport");return}this._setStatus(fe.CLOSED);for(const c of Object.values(this._rooms))c.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({},zo),t),this.queryCacheLimit=(o=this.config.queryCacheLimit)!==null&&o!==void 0?o:10,this._log=Po(t.verbose||Zt||ur),this.versions=Object.assign(Object.assign({},i||{}),{"@instantdb/core":yr}),this.config.schema&&(this._linkIndex=pr(this.config.schema)),!!Bo()){if(!t.appId)throw new Error("Instant must be initialized with an appId.");if(!Ce(t.appId))throw new Error(`Instant must be initialized with a valid appId. \`${t.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",u=>x(this,void 0,void 0,function*(){var a;try{if(((a=u.data)===null||a===void 0?void 0:a.type)==="auth"){const c=yield this.getCurrentUser();this.updateUser(c.user)}}catch(c){this._log.error("[error] handle broadcast channel",c)}}))),this._initStorage(n),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(u=>{this._isOnline=u,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",fe.CLOSED),this._setStatus(fe.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(t){this.config=Object.assign(Object.assign({},this.config),{schema:t,cardinalityInference:!!t}),this._linkIndex=t?pr(this.config.schema):null}_initStorage(t){this._persister=new t(`instant_${this.config.appId}_5`),this.querySubs=new fr(this._persister,"querySubs",{},this._onMergeQuerySubs,Go,n=>Qo(n,this.config.useDateObjects)),this.pendingMutations=new fr(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 t of this._beforeUnloadCbs)t()}_finishTransaction(t,n,r){const i=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const s=t!=="error"&&t!=="timeout";if(!i&&!s&&console.error("Mutation failed",Object.assign({status:t,eventId:n},r)),!!i)if(s)i.resolve({status:t,eventId:n});else if(r.type){const{status:o}=r,u=Vo(r,["status"]);i.reject(new ft({body:u,status:o}))}else i.reject(new ke(r.message,r.hint))}_setStatus(t,n){this.status=t,this._errorMessage=n,this.notifyConnectionStatusSubs(t)}_flushEnqueuedRoomData(t){var n,r;const i=(r=(n=this._presence[t])===null||n===void 0?void 0:n.result)===null||r===void 0?void 0:r.user,s=this._broadcastQueue[t];if(this._broadcastQueue[t]=[],i&&this._trySetPresence(t,i),s)for(const o of s){const{topic:u,roomType:a,data:c}=o;this._tryBroadcast(t,a,u,c)}}_handleReceive(t,n){var r,i,s,o,u,a;const c=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(kr[n.op]||this._log.info("[receive]",t,n.op,n),n.op){case"init-ok":this._setStatus(fe.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const P of Object.keys(this._rooms)){const X=(i=(r=this._presence[P])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.user;this._tryJoinRoom(P,X)}break;case"add-query-exists":this.notifyOneQueryOnce(B(n.q));break;case"add-query-ok":const{q:d,result:l}=n,h=B(d),p=(o=(s=l==null?void 0:l[0])===null||s===void 0?void 0:s.data)===null||o===void 0?void 0:o["page-info"],b=(a=(u=l==null?void 0:l[0])===null||u===void 0?void 0:u.data)===null||a===void 0?void 0:a.aggregate,g=hr(l),w=Ft(this.attrs,g,c,this._linkIndex,this.config.useDateObjects);this.querySubs.set(P=>(P[h].result={store:w,pageInfo:p,aggregate:b,processedTxId:n["processed-tx-id"]},P)),this._cleanupPendingMutationsQueries(),this.notifyOne(h),this.notifyOneQueryOnce(h),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:T,attrs:v}=n,S=n["processed-tx-id"];v&&this._setAttrs(v),this._cleanupPendingMutationsTimeout();const K=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,S);K!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>K);const O=Pr(K.entries()),L=T.map(P=>{var X,ye,be,he;const yt=P["instaql-query"],ue=P["instaql-result"],an=B(yt),cn=hr(ue),Ge=Ft(this.attrs,cn,c,this._linkIndex,this.config.useDateObjects),Ye=this._applyOptimisticUpdates(Ge,O,S),Re=(ye=(X=ue==null?void 0:ue[0])===null||X===void 0?void 0:X.data)===null||ye===void 0?void 0:ye["page-info"],He=(he=(be=ue==null?void 0:ue[0])===null||be===void 0?void 0:be.data)===null||he===void 0?void 0:he.aggregate;return{hash:an,store:Ye,pageInfo:Re,aggregate:He}});L.forEach(({hash:P,store:X,pageInfo:ye,aggregate:be})=>{this.querySubs.set(he=>(he[P].result={store:X,pageInfo:ye,aggregate:be,processedTxId:S},he))}),this._cleanupPendingMutationsQueries(),L.forEach(({hash:P})=>{this.notifyOne(P)});break;case"transact-ok":const{"client-event-id":U,"tx-id":le}=n,Be=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(U);if(!Be)break;this.pendingMutations.set(P=>(P.set(U,Object.assign(Object.assign({},P.get(U)),{"tx-id":le,confirmed:Date.now()})),P)),this._cleanupPendingMutationsTimeout();const on=Be["tx-steps"].filter(([P,...X])=>P==="add-attr").map(([P,X])=>X).concat(Object.values(this.attrs));this._setAttrs(on),this._finishTransaction("synced",U);break;case"patch-presence":{const P=n["room-id"];this._patchPresencePeers(P,n.edits),this._notifyPresenceSubs(P);break}case"refresh-presence":{const P=n["room-id"];this._setPresencePeers(P,n.data),this._notifyPresenceSubs(P);break}case"server-broadcast":const un=n["room-id"],pt=n.topic;this._notifyBroadcastSubs(un,pt,n);break;case"join-room-ok":const z=n["room-id"],oe=this._rooms[z];if(!oe){this._roomsPendingLeave[z]&&(this._tryLeaveRoom(z),delete this._roomsPendingLeave[z]);break}oe.isConnected=!0,this._notifyPresenceSubs(z),this._flushEnqueuedRoomData(z);break;case"join-room-error":const pe=n["room-id"],Qe=this._rooms[pe];Qe&&(Qe.error=n.error),this._notifyPresenceSubs(pe);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(t,n,r){const i=this.pendingMutations.currentValue.get(n);if(i&&(t!=="timeout"||!i["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o));const s={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(s),this._finishTransaction(t,n,r)}}_handleReceiveError(t){var n,r,i,s,o;console.log("error",t);const u=t["client-event-id"],a=this.pendingMutations.currentValue.get(u),c={message:t.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(t.hint&&(c.hint=t.hint),a){this._handleMutationError("error",u,t);return}if(!((n=t["original-event"])===null||n===void 0)&&n.hasOwnProperty("q")&&((r=t["original-event"])===null||r===void 0?void 0:r.op)==="add-query"){const h=(i=t["original-event"])===null||i===void 0?void 0:i.q,p=B(h);this.notifyQueryError(B(h),c),this.notifyQueryOnceError(h,p,u,c);return}if(((s=t["original-event"])===null||s===void 0?void 0:s.op)==="init"){if(t.type==="record-not-found"&&((o=t.hint)===null||o===void 0?void 0:o["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(fe.ERRORED,c),this.notifyAll();return}const l=Object.assign({},t);delete l.message,delete l.hint,console.error(t.message,l),t.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
31
|
+
`,t.hint)}notifyQueryOnceError(t,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(t,n,o.dfd))}_setAttrs(t){this.attrs=t.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(t,n){const r=V();return this.querySubs.set(i=>(i[n]=i[n]||{q:t,result:null,eventId:r},i[n].lastAccessed=Date.now(),i)),this._trySendAuthed(r,{op:"add-query",q:t}),r}subscribeQuery(t,n,r){var i;this.config.disableValidation||wr(t,this.config.schema),r&&"ruleParams"in r&&(t=Object.assign({$$ruleParams:r.ruleParams},t));const s=B(t),o=this.getPreviousResult(t);return o&&n(o),this.queryCbs[s]=(i=this.queryCbs[s])!==null&&i!==void 0?i:[],this.queryCbs[s].push({q:t,cb:n}),this._startQuerySub(t,s),()=>{this._unsubQuery(t,s,n)}}queryOnce(t,n){var r;this.config.disableValidation||wr(t,this.config.schema),n&&"ruleParams"in n&&(t=Object.assign({$$ruleParams:n.ruleParams},t));const i=new dr;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=B(t),o=this._startQuerySub(t,s);return this.queryOnceDfds[s]=(r=this.queryOnceDfds[s])!==null&&r!==void 0?r:[],this.queryOnceDfds[s].push({q:t,dfd:i,eventId:o}),setTimeout(()=>i.reject(new Error("Query timed out")),Wo),i.promise}_completeQueryOnce(t,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(i=>i.dfd!==r),this._cleanupQuery(t,n))}_unsubQuery(t,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(i=>i.cb!==r),this._cleanupQuery(t,n))}_cleanupQuery(t,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(V(),{op:"remove-query",q:t}))}_rewriteMutations(t,n,r){if(!t)return n;const i=d=>{const[l,h,p]=d["forward-identity"];return N(t,h,p)},s=d=>{const[l,h,p]=d["forward-identity"];return me(t,h,p)},o={attrIdMap:{},refSwapAttrIds:new Set};let u=!1;const a=(d,l)=>{const h=[];for(const p of d){const[b]=p;if(b==="add-attr"){const[w,T]=p,v=i(T);if(v&&T.id!==v.id){o.attrIdMap[T.id]=v.id,u=!0;continue}if(T["value-type"]==="ref"){const S=s(T);if(S){o.attrIdMap[T.id]=S.id,o.refSwapAttrIds.add(T.id),u=!0;continue}}}if(r&&l&&r>=l&&b==="add-attr"||b==="update-attr"||b==="delete-attr"){u=!0;continue}const g=u?Ws(o,p):p;h.push(g)}return u?h:d},c=new Map;for(const[d,l]of n.entries())c.set(d,Object.assign(Object.assign({},l),{"tx-steps":a(l["tx-steps"],l["tx-id"])}));return u?c:n}_rewriteMutationsSorted(t,n){return Pr(this._rewriteMutations(t,n).entries())}optimisticAttrs(){var t;const n=[...this.pendingMutations.currentValue.values()].flatMap(u=>u["tx-steps"]),r=new Set(n.filter(([u,a])=>u==="delete-attr").map(([u,a])=>a)),i=[];for(const[u,a]of n)if(u==="add-attr")i.push(a);else if(u==="update-attr"&&a.id&&(!((t=this.attrs)===null||t===void 0)&&t[a.id])){const c=Object.assign(Object.assign({},this.attrs[a.id]),a);i.push(c)}const s=[...Object.values(this.attrs||{}),...i].filter(u=>!r.has(u.id));return Object.fromEntries(s.map(u=>[u.id,u]))}dataForQuery(t){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:a}=i[t]||{};if(!a)return;const c=this._dataForQueryCache[t];if(c&&r===c.querySubVersion&&s===c.pendingMutationsVersion)return c.data;const{store:d,pageInfo:l,aggregate:h,processedTxId:p}=a,b=this._rewriteMutationsSorted(d.attrs,o),g=this._applyOptimisticUpdates(d,b,p),w=Us({store:g,pageInfo:l,aggregate:h},u);return this._dataForQueryCache[t]={querySubVersion:r,pendingMutationsVersion:s,data:w},w}_applyOptimisticUpdates(t,n,r){for(const[i,s]of n)(!s["tx-id"]||r&&s["tx-id"]>r)&&(t=Ki(t,s["tx-steps"]));return t}notifyAll(){Object.keys(this.queryCbs).forEach(t=>{this.notifyOne(t)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var t;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(t=this._transport)===null||t===void 0||t.close()}_sendMutation(t,n){if(n.error){this._handleMutationError("error",t,{message:n.error.message});return}if(this.status!==fe.AUTHENTICATED){this._finishTransaction("enqueued",t);return}const r=Math.max(5e3,this.pendingMutations.currentValue.size*5e3);this._isOnline?(this._trySend(t,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",t,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",t)}_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)})}_cleanupPendingMutationsQueries(){let t=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(t=Math.min(t,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"]<=t&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){const t=Date.now();this.pendingMutations.currentValue.size<200||this.pendingMutations.set(n=>{let r=!1,i=!1;for(const[s,o]of Array.from(n.entries()))o.confirmed||(i=!0),o.confirmed&&o.confirmed+Ko<t&&(n.delete(s),r=!0);if(r&&i)for(const[s,o]of Array.from(n.entries()))o.confirmed||n.delete(s);return n})}_trySendAuthed(...t){this.status===fe.AUTHENTICATED&&this._trySend(...t)}_trySend(t,n,r){this._transport.isOpen()&&(kr[n.op]||this._log.info("[send]",this._transport.id,n.op,n),this._transport.send(Object.assign({"client-event-id":t},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 t=this._transport;this._transport=qo({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),t!=null&&t.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",t.id),t.close())}getLocalId(t){return x(this,void 0,void 0,function*(){const n=`localToken_${t}`,r=yield this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const i=V();return this._localIdPromises[n]=this._persister.setItem(n,i).then(()=>i),this._localIdPromises[n]})}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const t=new URL(window.location.href);if(t.searchParams.get(en)){const n=t.toString();t.searchParams.delete(en),t.searchParams.delete("code"),t.searchParams.delete("error");const r=t.pathname+(t.searchParams.size?"?"+t.searchParams:"")+t.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 x(this,void 0,void 0,function*(){var t,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(en))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 a=yield this._getCurrentUser(),c=(a==null?void 0:a.type)==="guest",{user:d}=yield or({apiURI:this.config.apiURI,appId:this.config.appId,code:u,refreshToken:c?a.refresh_token:void 0});return this.setCurrentUser(d),null}catch(a){return((t=a==null?void 0:a.body)===null||t===void 0?void 0:t.type)==="record-not-found"&&((r=(n=a==null?void 0:a.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=a==null?void 0:a.body)===null||i===void 0?void 0:i.message)||"Error logging in."}}}})}_waitForOAuthCallbackResponse(){return x(this,void 0,void 0,function*(){return yield this._oauthCallbackResponse})}__subscribeMutationErrors(t){return this.mutationErrorCbs.push(t),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==t)}}subscribeAuth(t){this.authCbs.push(t);const n=this._currentUserCached;n.isLoading||t(this._currentUserCached);let r=!1;return this.getCurrentUser().then(i=>{r||rt(i,n)||t(i)}),()=>{r=!0,this.authCbs=this.authCbs.filter(i=>i!==t)}}getAuth(){return x(this,void 0,void 0,function*(){const{user:t,error:n}=yield this.getCurrentUser();if(n)throw new ke("Could not get current user: "+n.message);return t})}subscribeConnectionStatus(t){return this.connectionStatusCbs.push(t),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==t)}}subscribeAttrs(t){return this.attrsCbs.push(t),this.attrs&&t(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==t)}}notifyAuthSubs(t){this.authCbs.forEach(n=>n(t))}notifyMutationErrorSubs(t){this.mutationErrorCbs.forEach(n=>n(t))}notifyAttrsSubs(){if(!this.attrs)return;const t=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(t))}notifyConnectionStatusSubs(t){this.connectionStatusCbs.forEach(n=>n(t))}setCurrentUser(t){return x(this,void 0,void 0,function*(){yield this._persister.setItem(tn,t)})}getCurrentUserCached(){return this._currentUserCached}_getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(tn);return typeof t=="string"?JSON.parse(t):t})}getCurrentUser(){return x(this,void 0,void 0,function*(){const t=yield this._waitForOAuthCallbackResponse();if(t!=null&&t.error){const i={error:t.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 x(this,void 0,void 0,function*(){const t=yield this._persister.getItem(tn);return JSON.parse(t)!=null})}changeCurrentUser(t){return x(this,void 0,void 0,function*(){var n;const{user:r}=yield this.getCurrentUser();if(!rt(r,t)){yield this.setCurrentUser(t),this.updateUser(t);try{(n=this._broadcastChannel)===null||n===void 0||n.postMessage({type:"auth"})}catch(i){console.error("Error posting message to broadcast channel",i)}}})}updateUser(t){const n={error:void 0,user:t};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:t}){return bo({apiURI:this.config.apiURI,appId:this.config.appId,email:t})}signInWithMagicCode(t){return x(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 _o({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(t){return x(this,void 0,void 0,function*(){const n=yield go({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:t});return yield this.changeCurrentUser(n.user),n})}signInAsGuest(){return x(this,void 0,void 0,function*(){const t=yield To({apiURI:this.config.apiURI,appId:this.config.appId});return yield this.changeCurrentUser(t.user),t})}potentiallyInvalidateToken(t,n){var r;const i=(r=t==null?void 0:t.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}mo({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:i}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}signOut(t){return x(this,void 0,void 0,function*(){const n=yield this.getCurrentUser();this.potentiallyInvalidateToken(n,t),yield this.changeCurrentUser(null)})}createAuthorizationURL({clientName:t,redirectURL:n}){const{apiURI:r,appId:i}=this.config;return`${r}/runtime/oauth/start?app_id=${i}&client_name=${t}&redirect_uri=${n}`}exchangeCodeForToken(t){return x(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 or({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:t,appId:n}=this.config;return`${t}/runtime/${n}`}signInWithIdToken(t){return x(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,a=yield wo({apiURI:this.config.apiURI,appId:this.config.appId,idToken:n,clientName:r,nonce:i,refreshToken:u});return yield this.changeCurrentUser(a.user),a})}joinRoom(t,n){return this._rooms[t]||(this._rooms[t]={isConnected:!1,error:void 0}),this._presence[t]=this._presence[t]||{},n&&(this._presence[t].result=this._presence[t].result||{},this._presence[t].result.user=n,this._notifyPresenceSubs(t)),this._tryJoinRoom(t,n),()=>{this._cleanupRoom(t)}}_cleanupRoom(t){var n,r,i,s;if(!(!((r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0)&&r.length)&&!Object.keys((i=this._broadcastSubs[t])!==null&&i!==void 0?i:{}).length){const o=(s=this._rooms[t])===null||s===void 0?void 0:s.isConnected;delete this._rooms[t],delete this._presence[t],delete this._broadcastSubs[t],o?this._tryLeaveRoom(t):this._roomsPendingLeave[t]=!0}}getPresence(t,n,r={}){const i=this._rooms[n],s=this._presence[n];return!i||!s||!s.result?null:Object.assign(Object.assign({},Co(s.result,r,this._sessionId)),{isLoading:!i.isConnected,error:i.error})}publishPresence(t,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(t,n){this._trySendAuthed(V(),{op:"set-presence","room-id":t,data:n})}_tryJoinRoom(t,n){this._trySendAuthed(V(),{op:"join-room","room-id":t,data:n}),delete this._roomsPendingLeave[t]}_tryLeaveRoom(t){this._trySendAuthed(V(),{op:"leave-room","room-id":t})}subscribePresence(t,n,r,i){const s=this.joinRoom(n,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,a,c;this._presence[n].handlers=(c=(a=(u=this._presence[n])===null||u===void 0?void 0:u.handlers)===null||a===void 0?void 0:a.filter(d=>d!==o))!==null&&c!==void 0?c:[],s()}}_notifyPresenceSubs(t){var n,r;(r=(n=this._presence[t])===null||n===void 0?void 0:n.handlers)===null||r===void 0||r.forEach(i=>{this._notifyPresenceSub(t,i)})}_notifyPresenceSub(t,n){const r=this.getPresence("",t,n);r&&(n.prev&&!jo(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(t,n){var r,i,s;const o=((i=(r=this._presence[t])===null||r===void 0?void 0:r.result)===null||i===void 0?void 0:i.peers)||{};let u=Object.fromEntries(Object.entries(o).map(([c,d])=>[c,{data:d}]));(s=this._presence[t])===null||s===void 0||s.result;const a=Mt(u,c=>{for(let[d,l,h]of n)switch(l){case"+":ci(c,d,h);break;case"r":In(c,d,h);break;case"-":Rn(c,d);break}delete c[this._sessionId]});this._setPresencePeers(t,a)}_setPresencePeers(t,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=Mt(this._presence,s=>{In(s,[t,"result","peers"],i)})}publishTopic({roomType:t,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:t,data:i});return}this._tryBroadcast(n,t,r,i)}}_tryBroadcast(t,n,r,i){this._trySendAuthed(V(),{op:"client-broadcast","room-id":t,roomType:n,topic:r,data:i})}subscribeTopic(t,n,r){const i=this.joinRoom(t);return this._broadcastSubs[t]=this._broadcastSubs[t]||{},this._broadcastSubs[t][n]=this._broadcastSubs[t][n]||[],this._broadcastSubs[t][n].push(r),this._presence[t]=this._presence[t]||{},()=>{this._broadcastSubs[t][n]=this._broadcastSubs[t][n].filter(s=>s!==r),this._broadcastSubs[t][n].length||delete this._broadcastSubs[t][n],i()}}_notifyBroadcastSubs(t,n,r){var i,s,o;(o=(s=(i=this._broadcastSubs)===null||i===void 0?void 0:i[t])===null||s===void 0?void 0:s[n])===null||o===void 0||o.forEach(u=>{var a,c,d,l,h,p;const b=(a=r.data)===null||a===void 0?void 0:a.data,g=r.data["peer-id"]===this._sessionId?(d=(c=this._presence[t])===null||c===void 0?void 0:c.result)===null||d===void 0?void 0:d.user:(p=(h=(l=this._presence[t])===null||l===void 0?void 0:l.result)===null||h===void 0?void 0:h.peers)===null||p===void 0?void 0:p[r.data["peer-id"]];return u(b,g)})}uploadFile(t,n,r){return x(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 So(Object.assign(Object.assign({},r),{apiURI:this.config.apiURI,appId:this.config.appId,path:t,file:n,refreshToken:o}))})}deleteFile(t){return x(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 vo({apiURI:this.config.apiURI,appId:this.config.appId,path:t,refreshToken:i})})}upload(t,n){return x(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=t||n.name,u=yield Oo({apiURI:this.config.apiURI,appId:this.config.appId,fileName:o,refreshToken:s});return yield Eo(u,n)})}getDownloadUrl(t){return x(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:t,refreshToken:i})})}}let lt;function Ho(e,t){lt==null||lt.dispose();const n=nu(t),r=Xo(t,u),i=Zo(Jo(e));function s(d){var l;d.source===i.element.contentWindow&&((l=d.data)===null||l===void 0?void 0:l.type)==="close"&&n.isVisible()&&u()}function o(d){const l=d.shiftKey&&d.ctrlKey&&d.key==="0",h=d.key==="Escape"||d.key==="Esc";(l||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 a(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",s)}function c(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",s),lt={dispose:a}}return c()}function Jo(e){return`${Zt||ar?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${e}`}function Zo(e){const t=document.createElement("iframe");return t.src=e,t.className="instant-devtool-iframe",Object.assign(t.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:t}}function Xo(e,t){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"/>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@instantdb/react-common",
|
|
3
|
-
"version": "v0.22.
|
|
3
|
+
"version": "v0.22.30-experimental.adtk6.18724548131.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.
|
|
57
|
-
"@instantdb/version": "v0.22.
|
|
56
|
+
"@instantdb/core": "v0.22.30-experimental.adtk6.18724548131.1",
|
|
57
|
+
"@instantdb/version": "v0.22.30-experimental.adtk6.18724548131.1"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"test": "vitest",
|