@instantdb/resumable-stream 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ (function(k,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(k=typeof globalThis<"u"?globalThis:k||self,_(k.instant={}))})(this,function(k){"use strict";var Ji=Object.defineProperty;var wn=k=>{throw TypeError(k)};var Qi=(k,_,x)=>_ in k?Ji(k,_,{enumerable:!0,configurable:!0,writable:!0,value:x}):k[_]=x;var d=(k,_,x)=>Qi(k,typeof _!="symbol"?_+"":_,x),Pt=(k,_,x)=>_.has(k)||wn("Cannot "+x);var b=(k,_,x)=>(Pt(k,_,"read from private field"),x?x.call(k):_.get(k)),X=(k,_,x)=>_.has(k)?wn("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add(k):_.set(k,x),de=(k,_,x,R)=>(Pt(k,_,"write to private field"),R?R.call(k,x):_.set(k,x),x),Y=(k,_,x)=>(Pt(k,_,"access private method"),x);var Pe,L,ve,F,z,U,In,st,vn,On,$n,et,tt,nt,jt,kn,it;const _=/^(?:[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 x(e){return typeof e=="string"&&_.test(e)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function En(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}let rt;const _n=new Uint8Array(16);function Cn(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(_n)}const Mt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function xn(e,t,n){var s;if(Mt.randomUUID&&!e)return Mt.randomUUID();e=e||{};const i=e.random??((s=e.rng)==null?void 0:s.call(e))??Cn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,En(i)}const P={Remove:"remove",Replace:"replace",Add:"add"},Ut=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,Z={mutable:"mutable",immutable:"immutable"},ot={};function je(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Dt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Nt(e){return Object.getPrototypeOf(e)===Set.prototype}function Lt(e){return Object.getPrototypeOf(e)===Map.prototype}function G(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function at(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[Ut]}function ct(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function be(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,Z))===Z.immutable||typeof n=="function")}function Wt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=E(he(n,e.key));if(i!==null&&(i==null?void 0:i.original)!==e.original)return null;const s=e.parent.type===3,r=s?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(s&&n.size>r||je(n,r)))return null;t.push(r)}if(e.parent)return Wt(e.parent,t);t.reverse();try{Tn(e.copy,t)}catch{return null}return t}function Me(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function he(e,t){return Me(e)===2?e.get(t):e[t]}function ut(e,t,n){Me(e)===2?e.set(t,n):e[t]=n}function ft(e,t){const n=E(e);return(n?G(n):e)[t]}function ge(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function we(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Tn(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=he(Me(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Rn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const An=Object.prototype.propertyIsEnumerable;function Pn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Nt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Lt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,Z),n!==void 0)&&n!==Z.mutable){if(n===Z.immutable)return Rn(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 i={};return Object.keys(e).forEach(s=>{i[s]=e[s]}),Object.getOwnPropertySymbols(e).forEach(s=>{An.call(e,s)&&(i[s]=e[s])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function W(e){e.copy||(e.copy=Pn(e.original,e.options))}function Ue(e){if(!be(e))return ct(e);if(Array.isArray(e))return e.map(Ue);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,s])=>[i,Ue(s)]);if(!Lt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Ue);if(!Nt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Ue(e[n]);return t}function Ge(e){return at(e)?Ue(e):e}function ie(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ie(e.parent))}function jn(e,t){const n=Me(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const s of e)t(i,s,e),i+=1}else e.forEach((i,s)=>t(s,i,e))}function Ft(e,t,n){if(at(e)||!be(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,s=i?new Map:void 0;if(t.add(e),jn(e,(r,o)=>{var a;if(at(o)){const u=E(o);W(u);const c=!((a=u.assignedMap)===null||a===void 0)&&a.size||u.operated?u.copy:u.original;ut(i?s:e,r,c)}else Ft(o,t,n)}),s){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(s.has(a)?s.get(a):a)})}}function Mn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Ft(he(n,t),e.finalities.handledSet,e.options)}function lt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(ct(t))}))}function dt(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const r=Wt(e);r&&t(e,r,n,i)}e.finalized=!0}}function ht(e,t,n,i){const s=E(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((r,o)=>{var a;const u=e.type===3?e.setMap:e.copy;if(ge(he(u,t),n)){let c=s.original;s.copy&&(c=s.copy),lt(e),dt(e,i,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(c,s.original)),ut(u,t,c)}}),e.options.enableAutoFreeze&&s.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),be(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;ge(he(r,t),n)&&Mn(e,t)})}function Un(e,t,n,i,s){let{original:r,assignedMap:o,options:a}=e,u=e.copy;u.length<r.length&&([r,u]=[u,r],[n,i]=[i,n]);for(let c=0;c<r.length;c+=1)if(o.get(c.toString())&&u[c]!==r[c]){const l=t.concat([c]),f=we(l,s);n.push({op:P.Replace,path:f,value:Ge(u[c])}),i.push({op:P.Replace,path:f,value:Ge(r[c])})}for(let c=r.length;c<u.length;c+=1){const l=t.concat([c]),f=we(l,s);n.push({op:P.Add,path:f,value:Ge(u[c])})}if(r.length<u.length){const{arrayLengthAssignment:c=!0}=a.enablePatches;if(c){const l=t.concat(["length"]),f=we(l,s);i.push({op:P.Replace,path:f,value:r.length})}else for(let l=u.length;r.length<l;l-=1){const f=t.concat([l-1]),m=we(f,s);i.push({op:P.Remove,path:m})}}}function Dn({original:e,copy:t,assignedMap:n},i,s,r,o){n.forEach((a,u)=>{const c=he(e,u),l=Ge(he(t,u)),f=a?je(e,u)?P.Replace:P.Add:P.Remove;if(ge(c,l)&&f===P.Replace)return;const m=i.concat(u),p=we(m,o);s.push(f===P.Remove?{op:f,path:p}:{op:f,path:p,value:l}),r.push(f===P.Add?{op:P.Remove,path:p}:f===P.Remove?{op:P.Add,path:p,value:c}:{op:P.Replace,path:p,value:c})})}function Nn({original:e,copy:t},n,i,s,r){let o=0;e.forEach(a=>{if(!t.has(a)){const u=n.concat([o]),c=we(u,r);i.push({op:P.Remove,path:c,value:a}),s.unshift({op:P.Add,path:c,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const u=n.concat([o]),c=we(u,r);i.push({op:P.Add,path:c,value:a}),s.unshift({op:P.Remove,path:c,value:a})}o+=1})}function De(e,t,n,i){const{pathAsArray:s=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Dn(e,t,n,i,s);case 1:return Un(e,t,n,i,s);case 3:return Nn(e,t,n,i,s)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!be(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},pt={get size(){return G(E(this)).size},has(e){return G(E(this)).has(e)},set(e,t){const n=E(this),i=G(n);return(!i.has(e)||!ge(i.get(e),t))&&(W(n),ie(n),n.assignedMap.set(e,!0),n.copy.set(e,t),ht(n,e,t,De)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return W(t),ie(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),ie(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);G(n).forEach((i,s)=>{e.call(t,this.get(s),s,this)})},get(e){var t,n;const i=E(this),s=G(i).get(e),r=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,s,Z))===Z.mutable;if(i.options.strict&&He(s,i.options,r),r||i.finalized||!be(s,i.options)||s!==i.original.get(e))return s;const o=ot.createDraft({original:s,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return W(i),i.copy.set(e,o),o},keys(){return G(E(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>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]}}}},[Qe](){return this.entries()}},Ln=Reflect.ownKeys(pt),zt=(e,t,{isValuesIterator:n})=>()=>{var i,s;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const u=E(a),c=((s=(i=e.options).mark)===null||s===void 0?void 0:s.call(i,a,Z))===Z.mutable;if(e.options.strict&&He(o,e.options,c),!c&&!u&&be(o,e.options)&&!e.finalized&&e.original.has(o)){const l=ot.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,l),a=l}else u&&(a=u.proxy);return{done:!1,value:n?a:[a,a]}},Be={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),ie(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),ht(t,e,e,De)),this},delete(e){if(!this.has(e))return!1;const t=E(this);W(t),ie(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),ie(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:zt(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);W(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:zt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Be,{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 Wn=Reflect.ownKeys(Be),Vt=new WeakSet,Jt={get(e,t,n){var i,s;const r=(i=e.copy)===null||i===void 0?void 0:i[t];if(r&&Vt.has(r))return r;if(t===Ut)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,Z),o===Z.mutable)return e.options.strict&&He(c,e.options,!0),c}const a=G(e);if(a instanceof Map&&Ln.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(a instanceof Set&&Wn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const c=Be[t];if(c)return c.bind(e.proxy)}if(!je(a,t)){const c=Dt(a,t);return c?"value"in c?c.value:(s=c.get)===null||s===void 0?void 0:s.call(e.proxy):void 0}const u=a[t];if(e.options.strict&&He(u,e.options),e.finalized||!be(u,e.options))return u;if(u===ft(e.original,t)){if(W(e),e.copy[t]=Qt({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),ie(c),c.copy}return e.copy[t]}return u},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(e.type===1&&t!=="length"&&!(Number.isInteger(s=Number(t))&&s>=0&&(t===0||s===0||String(s)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Dt(G(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ft(G(e),t),a=E(o);return a&&ge(a.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(ge(n,o)&&(n!==void 0||je(e.original,t))||(W(e),ie(e),je(e.original,t)&&ge(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,ht(e,t,n,De)),!0)},has(e,t){return t in G(e)},ownKeys(e){return Reflect.ownKeys(G(e))},getOwnPropertyDescriptor(e,t){const n=G(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.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?Jt.set.call(this,e,t,void 0,e.proxy):(ft(e.original,t)!==void 0||t in e.original?(W(e),ie(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 Qt(e){const{original:t,parentDraft:n,key:i,finalities:s,options:r}=e,o=Me(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:s,options:r,setMap:o===3?new Map(t.entries()):void 0};(i||"key"in e)&&(a.key=i);const{proxy:u,revoke:c}=Proxy.revocable(o===1?Object.assign([],a):a,Jt);if(s.revoke.push(c),Vt.add(u),a.proxy=u,n){const l=n;l.finalities.draft.push((f,m)=>{var p,I;const g=E(u);let h=l.type===3?l.setMap:l.copy;const $=he(h,i),w=E($);if(w){let O=w.original;w.operated&&(O=ct($)),lt(w),dt(w,De,f,m),l.options.enableAutoFreeze&&(l.options.updatedValues=(p=l.options.updatedValues)!==null&&p!==void 0?p:new WeakMap,l.options.updatedValues.set(O,w.original)),ut(h,i,O)}(I=g.callbacks)===null||I===void 0||I.forEach(O=>{O(f,m)})})}else{const l=E(u);l.finalities.draft.push((f,m)=>{lt(l),dt(l,De,f,m)})}return u}ot.createDraft=Qt,Object.prototype.constructor.toString();function ke(){return xn()}function Fn(e,t){return e.localeCompare(t)}function zn(){let e=Fn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}zn();function Vn(){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 Jn=Vn();function qe(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(s,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Jn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Qn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function Gt(e){return e.startsWith("lookup__")}function Ht(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Gn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(s,r)=>qe(e,Ht(Qn(s,r)),[]);if(n==="__etype")return e;const i=n;return Gt(i)?qe(e,Ht(i),[]):qe(e,i,[])}})}function Bt(){return new Proxy({},{get(e,t){return Gn(t)}})}Bt();function Hn(e){return e.__ops}class q extends Error{constructor(n,i){super(n);d(this,"hint");this.hint=i;const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,q),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class Se extends q{constructor(n){var r;const i=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(i,n.body.hint);d(this,"body");d(this,"status");const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,Se),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const Ee="v0.22.145";class re{constructor(t,n,i,s={indexed:!1,unique:!1}){d(this,"valueType");d(this,"required");d(this,"isIndexed");d(this,"config");d(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=i,this.config=s}clientRequired(){return new re(this.valueType,!1,this.isIndexed,this.config)}optional(){return new re(this.valueType,!1,this.isIndexed,this.config)}unique(){return new re(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new re(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class C extends Error{constructor(t,n){const i=n?`At path '${n}': ${t}`:t;super(i),this.name="QueryValidationError"}}const qt=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Bn=e=>e.valueType||"unknown",Kt=(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}},qn=(e,t,n,i,s,r,o)=>{const a=r.valueType==="json",u=(c,l,f)=>{if(!Kt(f,l,a))throw new C(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${l}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new C(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`,o);for(const c of t)u(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":u(e,n,t);break;case"$like":case"$ilike":if(u(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new C(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`,o);break;case"$isNull":u(e,"boolean",t);break;default:throw new C(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`,o)}},_e=(e,t,n,i,s)=>{const r=Bn(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const u=e;for(const[c,l]of Object.entries(u))qn(c,l,r,t,i,n,`${s}.${c}`)}else if(!Kt(e,r,o))throw new C(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`,s)},Kn=(e,t,n,i,s)=>{const r=e.split(".");if(r.length<2)throw new C(`Invalid dot notation path '${e}'. Must contain at least one dot.`,s);let o=n;for(let l=0;l<r.length-1;l++){const f=r[l],m=i.entities[o];if(!m)throw new C(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,s);const p=m.links[f];if(!p){const I=Object.keys(m.links);throw new C(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length>0?I.join(", "):"none"}`,s)}o=p.entityName}const a=r[r.length-1],u=i.entities[o];if(!u)throw new C(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,s);if(a==="id"){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,s);_e(t,e,new re("string",!1,!0),n,s);return}const c=u.attrs[a];if(Object.keys(u.links).includes(a)){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,s);_e(t,e,new re("string",!1,!0),n,s);return}if(!c){const l=Object.keys(u.attrs);throw new C(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${l.length>0?l.join(", ")+", id":"id"}`,s)}_e(t,e,c,n,s)},Xt=(e,t,n,i)=>{for(const[s,r]of Object.entries(e)){if(s==="or"||s==="and"){if(Array.isArray(r))for(const c of r)typeof c=="object"&&c!==null&&Xt(c,t,n,`${i}.${s}[${c}]`);continue}if(s==="id"){_e(r,"id",new re("string",!1,!0),t,`${i}.id`);continue}if(s.includes(".")){Kn(s,r,t,n,`${i}.${s}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[s],u=o.links[s];if(!a&&!u){const c=Object.keys(o.attrs),l=Object.keys(o.links);throw new C(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${l.length>0?l.join(", "):"none"}`,`${i}.${s}`)}if(a)_e(r,s,a,t,`${i}.${s}`);else if(u){if(typeof r=="string"&&!x(r))throw new C(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${i}.${s}`);const c=new re("string",!1,!0);_e(r,s,c,t,`${i}.${s}`)}}},Xn=(e,t,n,i,s=0)=>{for(const o of Object.keys(e))if(!qt.includes(o))throw new C(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${qt.join(", ")}. Found: ${o}`,i);const r=["offset","before","after","first","last"];for(const o of r)if(e[o]!==void 0&&s>0)throw new C(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,i);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new C(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,i?`${i}.where`:void 0);Xt(e.where,t,n,i?`${i}.where`:"where")}},Yt=(e,t,n,i,s=0)=>{var r;if(!e||typeof e!="object")throw new C(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,i);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const u=Object.keys(n.entities[t].links);throw new C(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length>0?u.join(", "):"none"}`,`${i}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const u=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;u&&Yt(a,u,n,`${i}.${o}`,s+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new C(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${i}.$`);Xn(a,t,n,`${i}.$`,s)}},Zt=(e,t)=>{if(typeof e!="object"||e===null)throw new C(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new C(`Query must be an object, but received: ${typeof e}`);const n=e;for(const i of Object.keys(n)){if(Array.isArray(e[i]))throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(typeof i!="string")throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(i!=="$$ruleParams"){if(t&&!t.entities[i]){const s=Object.keys(t.entities);throw new C(`Entity '${i}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,i)}Yt(n[i],i,t,i,0)}}},en=e=>typeof e!="string"?!1:Gt(e)?!0:x(e);class K extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const tn=e=>e.length>0?e.join(", "):"none",Yn=(e,t)=>new K(`Entity '${e}' does not exist in schema. Available entities: ${tn(t)}`),mt={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},Zn=(e,t)=>{var n;return e==null?!0:((n=mt[t.valueType])==null?void 0:n.call(mt,e))??!1},nn=(e,t)=>{const n=t.entities[e];if(!n)throw Yn(e,Object.keys(t.entities));return n},yt=(e,t,n)=>{const i=nn(e,n);if(typeof t!="object"||t===null)throw new K(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(s==="id")continue;const o=i.attrs[s];if(o&&!Zn(r,o))throw new K(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},sn=(e,t,n)=>{const i=nn(e,n);if(typeof t!="object"||t===null)throw new K(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(!i.links[s]){const a=Object.keys(i.links);throw new K(`Link '${s}' does not exist on entity '${e}'. Available links: ${tn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!en(a))throw new K(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!en(r))throw new K(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},ei={create:yt,update:yt,merge:yt,link:sn,unlink:sn,delete:()=>{}},ti=(e,t)=>{if(!t)return;const[n,i,s,r]=e;if(!Array.isArray(s)&&!x(s))throw new K(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);if(typeof i!="string")throw new K(`Entity name must be a string, but received: ${typeof i}`);const o=ei[n];o&&r!==void 0&&o(i,r,t)},ni=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const i of n){if(!i||typeof i!="object")throw new K(`Transaction chunk must be an object, but received: ${typeof i}`);if(!Array.isArray(i.__ops))throw new K(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);for(const s of i.__ops){if(!Array.isArray(s))throw new K(`Transaction operation must be an array, but received: ${typeof s}`);ti(s,t)}}};let ii=0;class si{constructor(t,n,i){d(this,"type","sse");d(this,"initParams",null);d(this,"sendQueue",[]);d(this,"sendPromise");d(this,"closeFired",!1);d(this,"sseInitTimeout");d(this,"ES");d(this,"messageUrl");d(this,"conn");d(this,"url");d(this,"id");d(this,"onopen");d(this,"onmessage");d(this,"onclose");d(this,"onerror");this.id=`${this.type}_${ii++}`,this.url=n,this.messageUrl=i||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const r=JSON.parse(s.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=s=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}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}))}async postMessages(t){var n,i,s;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(i=this.initParams)==null?void 0:i.sessionId,sse_token:(s=this.initParams)==null?void 0:s.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){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 rn;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(rn||(rn={}));function ri({WStream:e,opts:t,startStream:n,appendStream:i,registerStream:s}){const r=t.clientId;let o=null,a=null;const u=ke();let c=!1,l=!1;const f=[],m=[],p=[];let I=!1,g=0,h=0;const $=[],w=new TextEncoder;function O(){l=!0;for(const y of f)y()}function ce(y){return f.push(y),()=>{const v=f.indexOf(y);v!==-1&&f.splice(v,1)}}function D(y){return p.push(y),()=>{const v=p.indexOf(y);v!==-1&&p.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(y=>{p.push(y)}));function N(){for(const y of p)try{y()}catch{}}function te(y){return m.push(y),()=>{const v=m.indexOf(y);v!==-1&&m.splice(v,1)}}function ue(y){o=y;for(const v of m)v(o)}function H(){I=!0}function ze(y){let v=g,V=0,Q=0;for(const{byteLen:ne}of $){const le=v+ne;if(le>y)break;v=le,V++,Q+=ne}V>0&&(g+=Q,h-=Q,$.splice(0,V))}function Oe(y,v){O(),y.error(v),N()}async function $e(){const y=await n({clientId:r,reconnectToken:u,ruleParams:t.ruleParams});switch(y.type){case"ok":{const{streamId:v,offset:V}=y;o=v,ze(V),$.length&&i({streamId:v,chunks:$.map(Q=>Q.chunk),offset:g}),I=!1;break}case"disconnect":{H();break}case"error":{a&&Oe(a,y.error);break}}}function fe(){H(),$e()}function B({offset:y,done:v}){ze(y),v&&(c=!0,N())}function Ve(y){return c?(Oe(y,new q("Stream has been closed.")),null):o||(Oe(y,new q("Stream has not been initialized.")),null)}async function zi(y){a=y;let v=!0,V=0;for(;v;){let Q=Date.now()+Math.min(15e3,500*(V-1));v=!1;const ne=await n({clientId:t.clientId,reconnectToken:u,ruleParams:t.ruleParams});switch(ne.type){case"ok":{const{streamId:le,offset:At}=ne;if(At!==0){const Je=new q("Write stream is corrupted");Oe(y,Je);return}ue(le),s(le,{onDisconnect:H,onFlush:B,onConnectionReconnect:$e,onAppendFailed:fe}),I=!1;return}case"disconnect":{v=!0,H(),V++,await new Promise(le=>{setTimeout(le,Math.max(0,Q-Date.now()))});break}case"error":{Oe(y,ne.error);return}}}}class Vi extends e{constructor(v,V){super(v,V)}async streamId(){return o||new Promise((v,V)=>{const Q=[],ne=()=>{for(const Je of Q)Je()},le=Je=>{v(Je),ne()},At=()=>{V(new q("Stream is closed.")),ne()};Q.push(te(le)),Q.push(ce(At))})}}return{stream:new Vi({async start(y){try{await zi(y)}catch(v){Oe(y,v)}},write(y,v){const V=Ve(v);if(V){const Q=w.encode(y).length;$.push({chunk:y,byteLen:Q});const ne=g+h;h+=Q,I||i({streamId:V,chunks:[y],offset:ne})}},close(){o?i({streamId:o,chunks:[],offset:g+h,isDone:!0}):N(),O()},abort(y){o?i({streamId:o,chunks:[],offset:g+h,isDone:!0,abortReason:y}):N(),O()}}),addCompleteCb:D,closed(){return l}}}class oi{constructor(){d(this,"items",[]);d(this,"resolvers",[]);d(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(i=>{this.resolvers.push(i)});if(n||!t)return;yield t}}}}function ai({RStream:e,opts:t,startStream:n,cancelStream:i}){let s=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let u,c=!1;const l=[];function f(){c=!0;for(const w of l)w()}function m(w){return l.push(w),()=>{const O=l.indexOf(w);O!==-1&&l.splice(O,1)}}function p(w,O){w.error(O),f()}let I=0;async function g(w,O){u=ke();const ce={...w||{},eventId:u};for await(const D of n(ce)){if(r)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){p(O,D.error);return}if(D.offset>s){p(O,new q("Stream is corrupted.")),r=!0;return}let N=s-D.offset;if(D.files&&D.files.length){const te=new AbortController;let ue=fetch(D.files[0].url,{signal:te.signal});for(let H=0;H<D.files.length;H++){const ze=D.files[H+1],$e=await ue;if(ze&&(ue=fetch(ze.url,{signal:te.signal})),!$e.ok){if(I++,I>10){p(O,new q("Unable to process stream."));return}return{retry:!0}}if($e.body)for await(const fe of $e.body){if(r){te.abort();return}let B=fe;if(N>0&&(B=fe.subarray(N),N-=fe.length-B.length),!B.length)continue;s+=B.length;const Ve=o.decode(B);O.enqueue(Ve)}else{const fe=await $e.arrayBuffer();let B=fe;if(r){te.abort();return}if(N>0&&(B=new Uint8Array(fe).subarray(N),N-=fe.byteLength-B.length),!B.byteLength)continue;s+=B.byteLength;const Ve=o.decode(B);O.enqueue(Ve)}}}if(I=0,D.content){let te=D.content,ue=a.encode(D.content);if(N>0){const H=ue.subarray(N);if(N-=ue.length-H.length,!H.length)continue;ue=H,te=o.decode(H)}s+=ue.length,O.enqueue(te)}}}async function h(w){let O=!0,ce=0;for(;O;){O=!1;let D=Date.now()+Math.min(15e3,500*(ce-1));const N=await g({...t,offset:s},w);N!=null&&N.retry&&(O=!0,ce++,D<Date.now()-3e5&&(ce=0),await new Promise(te=>{setTimeout(te,Math.max(0,D-Date.now()))}))}!r&&!c&&(w.close(),f())}return{stream:new e({start(w){h(w)},cancel(w){r=!0,u&&i({eventId:u}),f()}}),addCloseCb:m,closed(){return c}}}class ci{constructor({WStream:t,RStream:n,trySend:i,log:s}){d(this,"trySend");d(this,"WStream");d(this,"RStream");d(this,"writeStreams",{});d(this,"startWriteStreamCbs",{});d(this,"readStreamIterators",{});d(this,"log");d(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=i,this.log=s}createWriteStream(t){const{stream:n,addCompleteCb:i}=ri({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:i}=ai({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=ke();let i=null;const s=new Promise(o=>{i=o});this.startWriteStreamCbs[n]=i;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),s}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:i,offset:s,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:s,done:!!i};r&&(o["abort-reason"]=r),this.trySend(ke(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],i=this.writeStreams[n];if(!i){this.log.info("No stream cbs for stream-flushed",t);return}i.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:i,offset:s,ruleParams:r}){const o={op:"subscribe-stream"};if(!i&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");i&&(o["stream-id"]=i),n&&(o["client-id"]=n),s&&(o.offset=s),r&&(o["rule-params"]=r);const a=new oi;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(ke(),n),delete this.readStreamIterators[t]}onStreamAppend(t){var s;const n=t["client-event-id"],i=this.readStreamIterators[n];if(!i){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?i.push({type:"reconnect"}):i.push({type:"error",error:new q(t.error)}),i.close(),delete this.readStreamIterators[n];return}((s=t.files)!=null&&s.length||t.content)&&i.push({type:"append",offset:t.offset,files:t.files,content:t.content}),t.done&&(i.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==ui.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const i=n["stream-id"],s=this.writeStreams[i];s==null||s.onAppendFailed();break}case"start-stream":{const i=t["client-event-id"],s=this.startWriteStreamCbs[i];s&&(s({type:"error",error:new q(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[i]);break}case"subscribe-stream":{const i=t["client-event-id"],s=this.readStreamIterators[i];s&&(s.push({type:"error",error:new q(t.message||"Unknown error",t.hint)}),s.close(),delete this.readStreamIterators[i]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const ui={AUTHENTICATED:"authenticated"};function fi(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function li(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}li(),fi();class on extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function bt(e){}function di(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=bt,onError:n=bt,onRetry:i=bt,onComment:s}=e;let r="",o=!0,a,u="",c="";function l(g){const h=o?g.replace(/^\xEF\xBB\xBF/,""):g,[$,w]=hi(`${r}${h}`);for(const O of $)f(O);r=w,o=!1}function f(g){if(g===""){p();return}if(g.startsWith(":")){s&&s(g.slice(g.startsWith(": ")?2:1));return}const h=g.indexOf(":");if(h!==-1){const $=g.slice(0,h),w=g[h+1]===" "?2:1,O=g.slice(h+w);m($,O,g);return}m(g,"",g)}function m(g,h,$){switch(g){case"event":c=h;break;case"data":u=`${u}${h}
2
+ `;break;case"id":a=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?i(parseInt(h,10)):n(new on(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:$}));break;default:n(new on(`Unknown field "${g.length>20?`${g.slice(0,20)}…`:g}"`,{type:"unknown-field",field:g,value:h,line:$}));break}}function p(){u.length>0&&t({id:a,event:c||void 0,data:u.endsWith(`
3
+ `)?u.slice(0,-1):u}),a=void 0,u="",c=""}function I(g={}){r&&g.consume&&f(r),o=!0,a=void 0,u="",c="",r=""}return{feed:l,reset:I}}function hi(e){const t=[];let n="",i=0;for(;i<e.length;){const s=e.indexOf("\r",i),r=e.indexOf(`
4
+ `,i);let o=-1;if(s!==-1&&r!==-1?o=Math.min(s,r):s!==-1?o=s:r!==-1&&(o=r),o===-1){n=e.slice(i);break}else{const a=e.slice(i,o);t.push(a),i=o+1,e[i-1]==="\r"&&e[i]===`
5
+ `&&i++}}return[t,n]}class an extends Event{constructor(t,n){var i,s;super(t),this.code=(i=n==null?void 0:n.code)!=null?i:void 0,this.message=(s=n==null?void 0:n.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,i){return i(cn(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(cn(this),n)}}function pi(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function gt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(gt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${gt(e.cause)}`:e.message:`${e}`}function cn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var un=e=>{throw TypeError(e)},wt=(e,t,n)=>t.has(e)||un("Cannot "+n),S=(e,t,n)=>(wt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?un("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,i)=>(wt(e,t,"write to private field"),t.set(e,n),n),oe=(e,t,n)=>(wt(e,t,"access private method"),n),J,Ie,Ce,Ke,Xe,Ne,xe,Le,pe,Te,Re,Ae,We,ee,St,It,vt,fn,Ot,$t,Fe,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),j(this,ee),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,J),j(this,Ie),j(this,Ce),j(this,Ke),j(this,Xe),j(this,Ne),j(this,xe),j(this,Le,null),j(this,pe),j(this,Te),j(this,Re,null),j(this,Ae,null),j(this,We,null),j(this,It,async r=>{var o;S(this,Te).reset();const{body:a,redirected:u,status:c,headers:l}=r;if(c===204){oe(this,ee,Fe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Ce,new URL(r.url)):T(this,Ce,void 0),c!==200){oe(this,ee,Fe).call(this,`Non-200 status code (${c})`,c);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){oe(this,ee,Fe).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(S(this,J)===this.CLOSED)return;T(this,J,this.OPEN);const f=new Event("open");if((o=S(this,We))==null||o.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){oe(this,ee,Fe).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const m=new TextDecoder,p=a.getReader();let I=!0;do{const{done:g,value:h}=await p.read();h&&S(this,Te).feed(m.decode(h,{stream:!g})),g&&(I=!1,S(this,Te).reset(),oe(this,ee,kt).call(this))}while(I)}),j(this,vt,r=>{T(this,pe,void 0),!(r.name==="AbortError"||r.type==="aborted")&&oe(this,ee,kt).call(this,gt(r))}),j(this,Ot,r=>{typeof r.id=="string"&&T(this,Le,r.id);const o=new MessageEvent(r.event||"message",{data:r.data,origin:S(this,Ce)?S(this,Ce).origin:S(this,Ie).origin,lastEventId:r.id||""});S(this,Ae)&&(!r.event||r.event==="message")&&S(this,Ae).call(this,o),this.dispatchEvent(o)}),j(this,$t,r=>{T(this,Ne,r)}),j(this,Et,()=>{T(this,xe,void 0),S(this,J)===this.CONNECTING&&oe(this,ee,St).call(this)});try{if(t instanceof URL)T(this,Ie,t);else if(typeof t=="string")T(this,Ie,new URL(t,mi()));else throw new Error("Invalid URL")}catch{throw pi("An invalid or illegal string was specified")}T(this,Te,di({onEvent:S(this,Ot),onRetry:S(this,$t)})),T(this,J,this.CONNECTING),T(this,Ne,3e3),T(this,Xe,(i=n==null?void 0:n.fetch)!=null?i:globalThis.fetch),T(this,Ke,(s=n==null?void 0:n.withCredentials)!=null?s:!1),oe(this,ee,St).call(this)}get readyState(){return S(this,J)}get url(){return S(this,Ie).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,Re)}set onerror(t){T(this,Re,t)}get onmessage(){return S(this,Ae)}set onmessage(t){T(this,Ae,t)}get onopen(){return S(this,We)}set onopen(t){T(this,We,t)}addEventListener(t,n,i){const s=n;super.addEventListener(t,s,i)}removeEventListener(t,n,i){const s=n;super.removeEventListener(t,s,i)}close(){S(this,xe)&&clearTimeout(S(this,xe)),S(this,J)!==this.CLOSED&&(S(this,pe)&&S(this,pe).abort(),T(this,J,this.CLOSED),T(this,pe,void 0))}}J=new WeakMap,Ie=new WeakMap,Ce=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Ne=new WeakMap,xe=new WeakMap,Le=new WeakMap,pe=new WeakMap,Te=new WeakMap,Re=new WeakMap,Ae=new WeakMap,We=new WeakMap,ee=new WeakSet,St=function(){T(this,J,this.CONNECTING),T(this,pe,new AbortController),S(this,Xe)(S(this,Ie),oe(this,ee,fn).call(this)).then(S(this,It)).catch(S(this,vt))},It=new WeakMap,vt=new WeakMap,fn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,Le)?{"Last-Event-ID":S(this,Le)}:void 0},cache:"no-store",signal:(e=S(this,pe))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ot=new WeakMap,$t=new WeakMap,Fe=function(e,t){var n;S(this,J)!==this.CLOSED&&T(this,J,this.CLOSED);const i=new an("error",{code:t,message:e});(n=S(this,Re))==null||n.call(this,i),this.dispatchEvent(i)},kt=function(e,t){var n;if(S(this,J)===this.CLOSED)return;T(this,J,this.CONNECTING);const i=new an("error",{code:t,message:e});(n=S(this,Re))==null||n.call(this,i),this.dispatchEvent(i),T(this,xe,setTimeout(S(this,Et),S(this,Ne)))},Et=new WeakMap,se.CONNECTING=0,se.OPEN=1,se.CLOSED=2;function mi(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function yi(e,t,n,i){let s=null,r=!1;const o=[],a=f=>{o.push(f),o.length>100&&o.shift(),s&&(s(),s=null)};e(a);const u=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,s&&s(),u()}),{next:async()=>{for(;;){if(i()==="closed"||r)return u();const f=o.shift();if(f)return{value:f,done:!1};await new Promise(p=>{s=p})}},return:u,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function me(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function bi(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function ln(e){if(!e)return;const t={};for(const[n,i]of Object.entries(e))t[n]={startCursor:i["start-cursor"],endCursor:i["end-cursor"],hasNextPage:i["has-next-page?"],hasPreviousPage:i["has-previous-page?"]};return t}function gi(e,t,n){let i,s=!1;const r=ke(),o=new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{fetch(h,$){return i=null,fetch(h,{...$,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":Ee,"@instantdb/core":Ee}})}).then(w=>(w.ok||(i=bi(w)),w))}}),a=[],u=[],c=h=>{a.push(h)},l=h=>{a.splice(a.indexOf(h),1)},f=h=>{u.push(h)};t&&c(t);let m=null;function p(h){if(!s)for(const $ of a)try{$(h)}catch(w){console.error("Error in subscribeQuery callback",w)}}function I(h){var $,w;switch(h.op){case"sse-init":{const O=h["machine-id"],ce=h["session-id"];m={machineId:O,sessionId:ce};break}case"add-query-ok":{p({type:"ok",data:h.result,pageInfo:ln(($=h["result-meta"])==null?void 0:$["page-info"]),sessionInfo:m});break}case"refresh-ok":{h.computations.length&&p({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:ln((w=h.computations[0]["result-meta"])==null?void 0:w["page-info"]),sessionInfo:m});break}case"error":{p({type:"error",error:new Se({body:h,status:h.status}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:m});break}}}return o.onerror=h=>{if(i)i.text().then($=>{let w={type:void 0,message:$};try{w=JSON.parse($)}catch{}p({type:"error",error:new Se({status:i.status,body:w}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:m})});else{const $=()=>{p({type:"error",error:new Se({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:m})};if(o.readyState===se.CLOSED){$();return}setTimeout(()=>{o.readyState!==se.OPEN&&$()},5e3)}},o.onmessage=h=>{I(JSON.parse(h.data))},{close:()=>{s=!0;for(const h of u)try{h()}catch($){console.error("Error in onClose callback",$)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return m},get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},[Symbol.asyncIterator]:yi.bind(this,c,f,l,()=>1)}}var ae={};Object.defineProperty(ae,"__esModule",{value:!0});var wi=ae.parseCookie=pn;ae.parse=pn,ae.stringifyCookie=ki,ae.stringifySetCookie=Ye,ae.serialize=Ye,ae.parseSetCookie=Ei,ae.stringifySetCookie=Ye,ae.serialize=Ye;const dn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,hn=/^[\u0021-\u003A\u003C-\u007E]*$/,Si=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ii=/^[\u0020-\u003A\u003D-\u007E]*$/,vi=/^-?\d+$/,Oi=Object.prototype.toString,$i=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function pn(e,t){const n=new $i,i=e.length;if(i<2)return n;const s=(t==null?void 0:t.decode)||mn;let r=0;do{const o=Ct(e,r,i);if(o===-1)break;const a=_t(e,r,i);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const u=ye(e,r,o);n[u]===void 0&&(n[u]=s(ye(e,o+1,a))),r=a+1}while(r<i);return n}function ki(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,i=[];for(const s of Object.keys(e)){const r=e[s];if(r===void 0)continue;if(!dn.test(s))throw new TypeError(`cookie name is invalid: ${s}`);const o=n(r);if(!hn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);i.push(`${s}=${o}`)}return i.join("; ")}function Ye(e,t,n){const i=typeof e=="object"?e:{...n,name:e,value:String(t)},s=typeof t=="object"?t:n,r=(s==null?void 0:s.encode)||encodeURIComponent;if(!dn.test(i.name))throw new TypeError(`argument name is invalid: ${i.name}`);const o=i.value?r(i.value):"";if(!hn.test(o))throw new TypeError(`argument val is invalid: ${i.value}`);let a=i.name+"="+o;if(i.maxAge!==void 0){if(!Number.isInteger(i.maxAge))throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);a+="; Max-Age="+i.maxAge}if(i.domain){if(!Si.test(i.domain))throw new TypeError(`option domain is invalid: ${i.domain}`);a+="; Domain="+i.domain}if(i.path){if(!Ii.test(i.path))throw new TypeError(`option path is invalid: ${i.path}`);a+="; Path="+i.path}if(i.expires){if(!_i(i.expires)||!Number.isFinite(i.expires.valueOf()))throw new TypeError(`option expires is invalid: ${i.expires}`);a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.partitioned&&(a+="; Partitioned"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${i.sameSite}`)}return a}function Ei(e,t){const n=(t==null?void 0:t.decode)||mn,i=e.length,s=_t(e,0,i),r=Ct(e,0,s),o=r===-1?{name:"",value:n(ye(e,0,s))}:{name:ye(e,0,r),value:n(ye(e,r+1,s))};let a=s+1;for(;a<i;){const u=_t(e,a,i),c=Ct(e,a,u),l=c===-1?ye(e,a,u):ye(e,a,c),f=c===-1?void 0:ye(e,c+1,u);switch(l.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=f;break;case"path":o.path=f;break;case"max-age":f&&vi.test(f)&&(o.maxAge=Number(f));break;case"expires":if(!f)break;const m=new Date(f);Number.isFinite(m.valueOf())&&(o.expires=m);break;case"priority":if(!f)break;const p=f.toLowerCase();(p==="low"||p==="medium"||p==="high")&&(o.priority=p);break;case"samesite":if(!f)break;const I=f.toLowerCase();(I==="lax"||I==="strict"||I==="none")&&(o.sameSite=I);break}a=u+1}return o}function _t(e,t,n){const i=e.indexOf(";",t);return i===-1?n:i}function Ct(e,t,n){const i=e.indexOf("=",t);return i<n?i:-1}function ye(e,t,n){let i=t,s=n;do{const r=e.charCodeAt(i);if(r!==32&&r!==9)break}while(++i<s);for(;s>i;){const r=e.charCodeAt(s-1);if(r!==32&&r!==9)break;s--}return e.slice(i,s)}function mn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function _i(e){return Oi.call(e)==="[object Date]"}function Ci(e){return{...{apiURI:"https://api.instantdb.com"},...e}}function xi(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function Ti(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function A(e,t){Ti(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?xi(s,t):s}function Ri(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function Ai(){return Ri()?{cache:"no-store"}:{}}async function Pi(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new Se({status:t.status,body:i}))}catch{return e(new Se({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=Ai(),i={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":Ee,"Instant-Core-Version":Ee},s=await fetch(e,{...n,...t,headers:i});if(s.status===200){const r=await s.json();return Promise.resolve(r)}return Pi(r=>Promise.reject(r),s)}function ji(e){var t,n,Sn;return t=class{constructor(r){X(this,n);d(this,"source");d(this,"url");this.url=r,this.source=Y(this,n,Sn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,Sn=function(r){return new se(r,{fetch(a,u){return fetch(a,{...u,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":Ee,"@instantdb/core":Ee}})})}})},d(t,"OPEN",se.OPEN),d(t,"CONNECTING",se.CONNECTING),d(t,"CLOSED",se.CLOSED),t}function Mi(e){var n,i;(!e.appId||!x(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(i=e.adminToken)==null?void 0:i.trim(),useDateObjects:e.useDateObjects??!1};return new xt(t)}function yn(e){return(Array.isArray(e)?e:[e]).flatMap(Hn)}class Ui{constructor(t){d(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Di{constructor(t){d(this,"config");d(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));d(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));d(this,"verifyMagicCode",async(t,n)=>{const{user:i}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n})});return i});d(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);d(this,"getUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${encodeURIComponent(r)}`).join("&");return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});d(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});d(this,"getUserFromRequest",async(t,n)=>{const i=t.headers.get("cookie")||"",s=wi(i),r="instant_user_"+this.config.appId;if(!s[r])return null;const o=s[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await M(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(i),body:JSON.stringify(n)})}}const bn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Ni=e=>e&&typeof e.getReader=="function";class gn{constructor(t,n){d(this,"config");d(this,"impersonationOpts");d(this,"uploadFile",async(t,n,i={})=>{const s={...A(this.config,this.impersonationOpts),path:t};i.contentDisposition&&(s["content-disposition"]=i.contentDisposition),delete s["content-type"],i.contentType&&(s["content-type"]=i.contentType);let r;if(bn(n)&&(r="half"),bn(n)||Ni(n)){if(!i.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=i.fileSize.toString()}let o={method:"PUT",headers:s,body:n,...r&&{duplex:r}};return M(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});d(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));d(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));d(this,"upload",async(t,n,i={})=>{const{data:s}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=i.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(s,{method:"PUT",body:n,headers:r});return a});d(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});d(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Li{constructor(t){X(this,Pe);d(this,"createReadStream",t=>b(this,Pe).call(this).createReadStream(t));d(this,"createWriteStream",t=>b(this,Pe).call(this).createWriteStream(t));de(this,Pe,t)}}Pe=new WeakMap;function Wi(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Rt=class Rt{constructor(t){X(this,U);d(this,"config");d(this,"auth");d(this,"storage");d(this,"streams");d(this,"rooms");d(this,"impersonationOpts");X(this,L,null);X(this,ve,0);X(this,F,null);X(this,z);d(this,"tx",Bt());d(this,"asUser",t=>{const n=new Rt({...this.config});return n.impersonationOpts=t,n.storage=new gn(this.config,t),n});d(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||Zt(t,this.config.schema);const i=n.fetchOpts||{},s=i.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});d(this,"transact",t=>(this.config.disableValidation||ni(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:yn(t),"throw-on-missing-attrs?":!!this.config.schema})})));d(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const i={query:t,"rules-override":n==null?void 0:n.rules};n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin);const s=await M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)});return{result:s.result,checkResults:s["check-results"]}});d(this,"debugTransact",(t,n)=>{const i={steps:yn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)})});X(this,et,t=>{var n;if(t.target!==b(this,L)){b(this,z).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}b(this,z).info("[socket][open]",t.target.id),de(this,ve,0),(n=b(this,F))==null||n.onConnectionStatusChange("authenticated")});X(this,tt,t=>{var n;if(t.target!==b(this,L)){b(this,z).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}b(this,z).info("[socket][close]",t.target.id),(n=b(this,F))==null||n.onConnectionStatusChange("closed"),b(this,L)&&(de(this,L,null),Y(this,U,jt).call(this)||(setTimeout(()=>Y(this,U,st).call(this),b(this,ve)),de(this,ve,Math.min(15e3,Math.max(b(this,ve),500)*2))))});X(this,nt,t=>{var n;if(t.target!==b(this,L)){b(this,z).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}b(this,z).info("[socket][error]",t.target.id),(n=b(this,F))==null||n.onConnectionStatusChange("closed")});X(this,it,t=>{var i,s,r,o,a,u;if(t.target!==b(this,L)){b(this,z).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(b(this,z).info("[receive]",n),n.op){case"start-stream-ok":{(i=b(this,F))==null||i.onStartStreamOk(n);break}case"stream-flushed":{(s=b(this,F))==null||s.onStreamFlushed(n);break}case"append-failed":{(r=b(this,F))==null||r.onAppendFailed(n);break}case"stream-append":{(o=b(this,F))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(u=b(this,F))==null||u.onRecieveError(n);break}}break}}Y(this,U,kn).call(this)});this.config=Ci(t),this.auth=new Di(this.config),this.storage=new gn(this.config,this.impersonationOpts),this.streams=new Li(Y(this,U,$n).bind(this)),this.rooms=new Ui(this.config),de(this,z,Wi(!!this.config.verbose))}subscribeQuery(t,n,i={}){t&&i&&"ruleParams"in i&&(t={$$ruleParams:i.ruleParams,...t}),this.config.disableValidation||Zt(t,this.config.schema);const o={...(i.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return gi(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};L=new WeakMap,ve=new WeakMap,F=new WeakMap,z=new WeakMap,U=new WeakSet,In=function(){b(this,L)&&b(this,L).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,i=ji({headers:t,inference:n}),s=new si(i,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return s.onopen=b(this,et),s.onmessage=b(this,it),s.onclose=b(this,tt),s.onerror=b(this,nt),de(this,L,s),s},st=function(){return b(this,L)||Y(this,U,In).call(this)},vn=function(t,n){const i=Y(this,U,st).call(this);b(this,z).info("[send]",t,n,{isOpen:i.isOpen()}),i.isOpen()&&i.send({"client-event-id":t,...n})},On=function(){Y(this,U,st).call(this);const t=new ci({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,i)=>{Y(this,U,vn).call(this,n,i)},log:b(this,z)});return de(this,F,t),t},$n=function(){return b(this,F)||Y(this,U,On).call(this)},et=new WeakMap,tt=new WeakMap,nt=new WeakMap,jt=function(){return!b(this,F)||!b(this,F).hasActiveStreams()},kn=function(){if(b(this,L)&&Y(this,U,jt).call(this)){const t=b(this,L);b(this,z).info("cleaning up unused socket",t.id),de(this,L,null),t.close()}},it=new WeakMap;let xt=Rt;var Tt={};function Ze(e){let t=e;return new TransformStream({transform(n,i){if(!t){i.enqueue(n);return}if(t>n.length){t+=n.length;return}const s=n.slice(t);t=0,i.enqueue(s)}})}function Fi(e){const t=e.appId||Tt.INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.");const n=e.adminToken||Tt.INSTANT_APP_ADMIN_TOKEN;if(!t)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const i=e.apiURI||Tt.INSTANT_API_URI,s=Mi({appId:t,adminToken:n,apiURI:i});async function r(c,l,f){const m=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});try{const p=await m.streamId();l().pipeTo(m);const g=s.streams.createReadStream({streamId:p});return f?g.pipeThrough(Ze(f)):g}catch{const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}}async function o(c,l){const f=s.streams.createReadStream({clientId:c});return l?f.pipeThrough(Ze(l)):f}async function a(c,l,f){const m=l(),p=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});await p.streamId(),m.pipeTo(p);const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}async function u(c){var m;const l=await s.query({$streams:{$:{where:{clientId:c}}}}),f=(m=l==null?void 0:l.$streams)==null?void 0:m[0];return f!=null&&f.done?"DONE":f?!0:null}return{resumableStream:r,resumeExistingStream:o,createNewResumableStream:a,hasExistingStream:u}}k.createResumableStreamContext=Fi,Object.defineProperty(k,Symbol.toStringTag,{value:"Module"})});
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@instantdb/resumable-stream",
3
+ "version": "0.0.0",
4
+ "description": "Instant's drop-in replacement for Vercel's resumable-stream package.",
5
+ "homepage": "https://github.com/instantdb/instant/tree/main/client/packages/resumable-stream",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/instantdb/instant.git",
9
+ "directory": "client/packages/resumable-stream"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/commonjs/index.js",
13
+ "types": "./dist/commonjs/index.d.ts",
14
+ "module": "./dist/esm/index.js",
15
+ "unpkg": "standalone/index.umd.js",
16
+ "exports": {
17
+ "./package.json": "./package.json",
18
+ ".": {
19
+ "import": {
20
+ "types": "./dist/esm/index.d.ts",
21
+ "default": "./dist/esm/index.js"
22
+ },
23
+ "require": {
24
+ "types": "./dist/commonjs/index.d.ts",
25
+ "default": "./dist/commonjs/index.js"
26
+ }
27
+ }
28
+ },
29
+ "tshy": {
30
+ "selfLink": false,
31
+ "main": true,
32
+ "module": true,
33
+ "project": "./tsconfig.json",
34
+ "exports": {
35
+ "./package.json": "./package.json",
36
+ ".": "./src/index.ts"
37
+ }
38
+ },
39
+ "devDependencies": {
40
+ "@arethetypeswrong/cli": "^0.17.4",
41
+ "@babel/core": "^7.17.9",
42
+ "@babel/preset-env": "^7.16.11",
43
+ "@types/node": "^18.11.18",
44
+ "@types/uuid": "^10.0.0",
45
+ "@types/websocket": "^1.0.5",
46
+ "npm-run-all": "^4.1.5",
47
+ "tshy": "^3.0.2",
48
+ "typescript": "^5.9.3",
49
+ "vite": "^5.2.0",
50
+ "vitest": "^1.6.0"
51
+ },
52
+ "dependencies": {
53
+ "@instantdb/admin": "0.0.0"
54
+ },
55
+ "scripts": {
56
+ "test": "vitest",
57
+ "test:ci": "vitest run",
58
+ "check": "tsc --noEmit",
59
+ "check-exports": "attw --pack .",
60
+ "dev:module": "tsc --watch --preserveWatchOutput -p tsconfig.dev.json",
61
+ "dev:main": "tsc --watch --preserveWatchOutput -p tsconfig.cjs.dev.json",
62
+ "dev": "run-p dev:module dev:main",
63
+ "clean": "rm -rf dist",
64
+ "build": "rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports",
65
+ "build:tshy": "tshy",
66
+ "build:standalone": "vite build",
67
+ "publish-package": "pnpm pack && npm publish *.tgz --access public"
68
+ }
69
+ }
package/src/index.ts ADDED
@@ -0,0 +1,207 @@
1
+ import { init } from '@instantdb/admin';
2
+
3
+ export interface CreateResumableStreamContextOptions {
4
+ /**
5
+ * A function that takes a promise and ensures that the current program stays alive
6
+ * until the promise is resolved.
7
+ *
8
+ * If you are deploying to a server environment, where you don't have to worry about
9
+ * the function getting suspended, pass in null.
10
+ */
11
+ waitUntil: ((promise: Promise<unknown>) => void) | null;
12
+ /**
13
+ * The appId for your InstantDB app. It may also be provided with the INSTANT_APP_ID environment variable.
14
+ */
15
+ appId?: string;
16
+ /**
17
+ * The appId for your InstantDB app. It may also be provided with the INSTANT_ADMIN_TOKEN environment variable.
18
+ */
19
+ adminToken?: string;
20
+ /**
21
+ * Optional apiURI for the instantdb server.
22
+ */
23
+ apiURI?: string;
24
+ }
25
+
26
+ export interface ResumableStreamContext {
27
+ /**
28
+ * Creates or resumes a resumable stream.
29
+ *
30
+ * Does not throw if the underlying stream is already done. The output can always be read from the
31
+ * stream and does not have to be saved to a separate table after streaming is completed.
32
+ *
33
+ * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.
34
+ *
35
+ * @param streamId - The ID of the stream. Must be unique for each stream.
36
+ * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.
37
+ * @param skipCharacters - Number of characters to skip
38
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
39
+ */
40
+ resumableStream: (
41
+ streamId: string,
42
+ makeStream: () => ReadableStream<string>,
43
+ skipCharacters?: number,
44
+ ) => Promise<ReadableStream<string> | null>;
45
+ /**
46
+ * Resumes a stream that was previously created by `createNewResumableStream`.
47
+ *
48
+ * @param streamId - The ID of the stream. Must be unique for each stream.
49
+ * @param skipCharacters - Number of characters to skip
50
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
51
+ */
52
+ resumeExistingStream: (
53
+ streamId: string,
54
+ skipCharacters?: number,
55
+ ) => Promise<ReadableStream<string> | null | undefined>;
56
+ /**
57
+ * Creates a new resumable stream.
58
+ *
59
+ * @param streamId - The ID of the stream. Must be unique for each stream.
60
+ * @param makeStream - A function that returns a stream of strings.
61
+ * @param skipCharacters - Number of characters to skip
62
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
63
+ */
64
+ createNewResumableStream: (
65
+ streamId: string,
66
+ makeStream: () => ReadableStream<string>,
67
+ skipCharacters?: number,
68
+ ) => Promise<ReadableStream<string> | null>;
69
+
70
+ /**
71
+ * Checks if a stream with the given streamId exists.
72
+ * @param streamId - The ID of the stream.
73
+ * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. "DONE" if the stream is fully done.
74
+ */
75
+ hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;
76
+ }
77
+
78
+ function skipCharactersTransformer(skipCharacters: number) {
79
+ let skipLeft = skipCharacters;
80
+ return new TransformStream<string>({
81
+ transform(chunk, controller) {
82
+ if (!skipLeft) {
83
+ controller.enqueue(chunk);
84
+ return;
85
+ }
86
+ if (skipLeft > chunk.length) {
87
+ skipLeft += chunk.length;
88
+ return;
89
+ }
90
+ const remaining = chunk.slice(skipLeft);
91
+ skipLeft = 0;
92
+ controller.enqueue(remaining);
93
+ },
94
+ });
95
+ }
96
+
97
+ export function createResumableStreamContext(
98
+ options: CreateResumableStreamContextOptions,
99
+ ): ResumableStreamContext {
100
+ const appId = options.appId || process.env.INSTANT_APP_ID;
101
+ if (!appId) {
102
+ throw new Error(
103
+ 'Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.',
104
+ );
105
+ }
106
+ const adminToken = options.adminToken || process.env.INSTANT_APP_ADMIN_TOKEN;
107
+ if (!appId) {
108
+ throw new Error(
109
+ 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.',
110
+ );
111
+ }
112
+ const apiURI = options.apiURI || process.env.INSTANT_API_URI;
113
+
114
+ const db = init({
115
+ appId,
116
+ adminToken,
117
+ apiURI,
118
+ });
119
+
120
+ async function resumableStream(
121
+ streamId: string,
122
+ makeStream: () => ReadableStream<string>,
123
+ skipCharacters?: number,
124
+ ): Promise<ReadableStream<string> | null> {
125
+ const writeStream = db.streams.createWriteStream({
126
+ clientId: streamId,
127
+ waitUntil: options.waitUntil ?? undefined,
128
+ });
129
+ try {
130
+ const s = await writeStream.streamId();
131
+ const inputStream = makeStream();
132
+ inputStream.pipeTo(writeStream);
133
+ const readStream = db.streams.createReadStream({ streamId: s });
134
+ if (skipCharacters) {
135
+ return readStream.pipeThrough(
136
+ skipCharactersTransformer(skipCharacters),
137
+ );
138
+ }
139
+ return readStream;
140
+ } catch (e) {
141
+ const readStream = db.streams.createReadStream({ clientId: streamId });
142
+ if (skipCharacters) {
143
+ return readStream.pipeThrough(
144
+ skipCharactersTransformer(skipCharacters),
145
+ );
146
+ }
147
+ return readStream;
148
+ }
149
+ }
150
+
151
+ async function resumeExistingStream(
152
+ streamId: string,
153
+ skipCharacters?: number,
154
+ ): Promise<ReadableStream<string> | null | undefined> {
155
+ const readStream = db.streams.createReadStream({ clientId: streamId });
156
+ if (skipCharacters) {
157
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
158
+ }
159
+ return readStream;
160
+ }
161
+
162
+ async function createNewResumableStream(
163
+ streamId: string,
164
+ makeStream: () => ReadableStream<string>,
165
+ skipCharacters?: number,
166
+ ): Promise<ReadableStream<string> | null> {
167
+ const inputStream = makeStream();
168
+ const writeStream = db.streams.createWriteStream({
169
+ clientId: streamId,
170
+ waitUntil: options.waitUntil ?? undefined,
171
+ });
172
+
173
+ // Wait for stream to be acknowledged by the server
174
+ await writeStream.streamId();
175
+
176
+ inputStream.pipeTo(writeStream);
177
+ const readStream = db.streams.createReadStream({ clientId: streamId });
178
+ if (skipCharacters) {
179
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
180
+ }
181
+ return readStream;
182
+ }
183
+
184
+ async function hasExistingStream(
185
+ streamId: string,
186
+ ): Promise<null | true | 'DONE'> {
187
+ const data = await db.query({
188
+ $streams: { $: { where: { clientId: streamId } } },
189
+ });
190
+
191
+ const stream = data?.$streams?.[0];
192
+ if (stream?.done) {
193
+ return 'DONE';
194
+ }
195
+ if (stream) {
196
+ return true;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ return {
202
+ resumableStream,
203
+ resumeExistingStream,
204
+ createNewResumableStream,
205
+ hasExistingStream,
206
+ };
207
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "composite": true,
5
+
6
+ "module": "es2015",
7
+ "moduleResolution": "bundler",
8
+
9
+ "outDir": "./dist/commonjs",
10
+
11
+ "declaration": true,
12
+ "declarationDir": "./dist/commonjs",
13
+ "incremental": true
14
+ }
15
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "es2022",
5
+ "target": "es2022",
6
+ "moduleResolution": "bundler",
7
+
8
+ "outDir": "./dist/esm",
9
+
10
+ "declaration": true,
11
+ "declarationDir": "./dist/esm",
12
+ "incremental": true
13
+ }
14
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["src"],
4
+ "exclude": ["node_modules", "dist", "src/__types__", "src/__tests__"],
5
+ "compilerOptions": {
6
+ "outDir": "dist/tsc",
7
+ "rewriteRelativeImportExtensions": true,
8
+ "rootDir": "src",
9
+ "checkJs": false,
10
+ "strictNullChecks": true
11
+ }
12
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "include": ["src", "src/__types__"],
4
+ "exclude": ["node_modules", "dist"]
5
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { defineConfig } from 'vite';
2
+ import { resolve } from 'path';
3
+
4
+ export default defineConfig({
5
+ clearScreen: false,
6
+ build: {
7
+ outDir: 'dist/standalone',
8
+ lib: {
9
+ formats: ['umd', 'es'],
10
+ // this is the file that exports our components
11
+ entry: resolve(__dirname, 'src', 'index.ts'),
12
+ name: 'instant',
13
+ fileName: 'index',
14
+ },
15
+ },
16
+ define: {
17
+ 'process.env': {},
18
+ },
19
+ });