replicache
Version:
Realtime sync for any backend stack
1 lines • 99.8 kB
JavaScript
var bo=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var Ti=Object.prototype.hasOwnProperty;var Fi=(t,e)=>{for(var n in e)bo(t,n,{get:e[n],enumerable:!0})},So=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ei(e))!Ti.call(t,o)&&o!==n&&bo(t,o,{get:()=>e[o],enumerable:!(r=Vi(e,o))||r.enumerable});return t},K=(t,e,n)=>(So(t,e,"default"),n&&So(n,e,"default"));import{consoleLogSink as Dl}from"@rocicorp/logger";import{resolver as rr}from"@rocicorp/resolver";var X=class extends Error{name="AbortError"};function f(t,e="Assertion failed"){if(!t)throw new Error(e)}function R(t){Ut(t,"string")}function L(t){Ut(t,"number")}function Co(t){Ut(t,"boolean")}function Ut(t,e){typeof t!==e&&se(t,e)}function k(t){t===null&&se(t,"object"),Ut(t,"object")}function oe(t){Array.isArray(t)||se(t,"array")}function Li(t,e){let n="Invalid type: ";return t==null?n+=t:n+=`${typeof t} \`${t}\``,n+`, expected ${e}`}function se(t,e){throw new Error(Li(t,e))}function Io(t){if(t===null)throw new Error("Expected non-null value")}function sr(t,e="Expected non undefined value"){if(t===void 0)throw new Error(e)}function ir(t){throw new Error("Unreachable")}function ct(){return typeof document<"u"?document:void 0}import{resolver as Ai}from"@rocicorp/resolver";function wo(t,e,n){return t?new ar(t,e,n):new ur}var ar=class{#e;#t;#n=0;visibilityState;#r=new Set;constructor(e,n,r){this.#e=e,this.#t=n,this.visibilityState=e.visibilityState,this.#e.addEventListener("visibilitychange",this.#o,{signal:r})}#o=()=>{this.#e.visibilityState==="visible"?(clearTimeout(this.#n),this.#s("visible")):this.#n=setTimeout(()=>{this.#s("hidden")},this.#t)};#s(e){if(e!==this.visibilityState){this.visibilityState=e;for(let n of this.#r){let{resolve:r,state:o}=n;o===e&&(r(),this.#r.delete(n))}}}waitForVisible(){return this.#i("visible")}waitForHidden(){return this.#i("hidden")}#i(e){if(this.visibilityState===e)return Promise.resolve();let{promise:n,resolve:r}=Ai();return this.#r.add({resolve:r,state:e}),n}},ji=Promise.resolve(),Ji=new Promise(()=>{}),ur=class{visibilityState="visible";waitForVisible(){return ji}waitForHidden(){return Ji}};var $t=class{rep;invokeSend;maxConnections=1;constructor(e,n){this.rep=e,this.invokeSend=n}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},Yt=class extends $t{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},Xt=class extends $t{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null};import{resolver as ce}from"@rocicorp/resolver";import{resolver as Ll}from"@rocicorp/resolver";var zi=Promise.resolve(),jl=new Promise(()=>{});function le(t,e){return t===0?zi:new Promise((n,r)=>{let o;e&&(o=()=>{clearTimeout(s),r(new X("Aborted"))},e.addEventListener("abort",o,{once:!0}));let s=setTimeout(()=>{n(),e?.removeEventListener("abort",o)},t)})}var Ro=30,Mo=6e4,pt=class{#e=ce();#t=ce();#n=ce();#r;#o=!1;#s=0;#i;#l;constructor(e,n,r){this.#i=e,this.#r=n,this.#l=r,this.run()}close(){this.#o=!0,this.#s>0&&this.#n.resolve({error:xo()})}async send(e){if(this.#o)return{error:xo()};this.#s++,this.#i.debug?.("send",e),e?this.#t.resolve():await this.#l?.waitForVisible(),this.#e.resolve();let n=await this.#n.promise;return this.#s--,n}async run(){let e=[],n=ce(),r,o=0,s=this.#r,{debug:i}=this.#i,a=0;i?.("Starting connection loop");let u=l=>Promise.race([this.#t.promise,le(l)]);for(;!this.#o;){i?.(lr(e)?"Last request failed. Trying again":"Waiting for a send");let l=[this.#e.promise],c=s.watchdogTimer;if(c!==null&&l.push(le(c)),await Promise.race(l),this.#o||(i?.("Waiting for debounce"),await u(s.debounceDelay),this.#o))break;if(i?.("debounced"),this.#e=ce(),o>=s.maxConnections){if(i?.("Too many request in flight. Waiting until one finishes..."),await this.#p(),this.#o)break;i?.("...finished")}o>0||lr(e)?(a=Bi(a,s,e),i?.(lr(e)?"Last connection errored. Sleeping for":"More than one outstanding connection ("+o+"). Sleeping for",a,"ms")):a=0;let d=Math.min(s.maxDelayMs,Math.max(s.minDelayMs,a));if(r!==void 0){let p=Date.now()-r;if(d>p&&(await Promise.race([u(d-p),n.promise]),this.#o))break}o++,(async()=>{let p=Date.now(),m,g;try{r=p,i?.("Sending request"),this.#t=ce(),m=await s.invokeSend(),i?.("Send returned",m)}catch(b){i?.("Send failed",b),g=b,m=!1}if(this.#o){i?.("Closed after invokeSend");return}i?.("Request done",{duration:Date.now()-p,ok:m}),e.push({duration:Date.now()-p,ok:m}),_i(e)&&(n.resolve(),n=ce()),o--,this.#c();let y=this.#n;this.#n=ce(),g?y.resolve({error:g}):y.resolve(void 0),m||this.#e.resolve()})()}}#u=void 0;#c(){if(this.#u){let e=this.#u;this.#u=void 0,e()}}#p(){let{promise:e,resolve:n}=ce();return this.#u=n,e}},Gi=9;function xo(){return new Error("Closed")}function Bi(t,e,n){let{length:r}=n;if(r===0)return t;let{ok:o}=n[n.length-1],{maxConnections:s,minDelayMs:i}=e;if(!o)return t===0?i:t*2;if(r>1){let u=n[n.length-2];for(;n.length>Gi;)n.shift();if(o&&!u.ok)return i}return Ki(n.filter(({ok:u})=>u).map(({duration:u})=>u))/s|0}function Ki(t){t.sort();let{length:e}=t,n=e>>1;return e%2===1?t[n]:(t[n-1]+t[n])/2}function lr(t){return t.length>0&&!t[t.length-1].ok}function _i(t){return t.length>1&&!t[t.length-2].ok&&t[t.length-1].ok}var J=process.env.NODE_ENV==="production";var qi=Object.prototype.hasOwnProperty,Z=Object.hasOwn||((t,e)=>qi.call(t,e));function $(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;switch(typeof t){case"boolean":case"number":case"string":return!1}if(t=t,Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let o=0;o<t.length;o++)if(!$(t[o],e[o]))return!1;return!0}if(t===null||e===null||Array.isArray(e))return!1;t=t,e=e;let n=0;for(let o in t)if(Z(t,o)){if(!$(t[o],e[o]))return!1;n++}let r=0;for(let o in e)Z(e,o)&&r++;return n===r}function te(t){if(!J){switch(typeof t){case"boolean":case"number":case"string":return;case"object":return t===null?void 0:Array.isArray(t)?Wi(t):ko(t)}se(t,"JSON value")}}function Zt(t){k(t),ko(t)}function ko(t){for(let e in t)if(Z(t,e)){let n=t[e];n!==void 0&&te(n)}}function Wi(t){for(let e of t)te(e)}function Qt(t,e){switch(typeof t){case"boolean":case"number":case"string":return!0;case"object":return t===null?!0:Array.isArray(t)?Ui(t,e):vo(t,e)}return!1}function Po(t,e){return typeof t!="object"||t===null?!1:vo(t,e)}function vo(t,e){for(let n in t)if(Z(t,n)){e.push(n);let r=t[n];if(r!==void 0&&!Qt(r,e))return!1;e.pop()}return!0}function Ui(t,e){for(let n=0;n<t.length;n++){if(e.push(n),!Qt(t[n],e))return!1;e.pop()}return!0}function No(t,e){return t===e?0:t<e?-1:1}function Ae(t,e){if(t===e)return 0;if(t===null)return-1;if(e===null)return 1;let n=Oo(t),r=Oo(e);return typeof n=="string"||typeof r=="string"?No(String(n),String(r)):n-r}function Oo(t){return typeof t=="string"||typeof t=="number"?t:t.order}function en(t){if(!(t===null||typeof t=="string"||typeof t=="number")&&(Zt(t),!(typeof t.order=="string"||typeof t.order=="number")))throw new Error("Invalid cookie")}import{RWLock as la}from"@rocicorp/lock";function*dt(...t){for(let e of t)yield*e}var Ho=Promise.resolve(!0),Vo=Promise.resolve(!1),tc=Promise.resolve(void 0),A=Promise.resolve();var ie=1,je=4,$i=5,Yi=8;function pe(t){switch(typeof t){case"string":return ie+je+t.length;case"number":return Xi(t)?t<=-(2**30)||t>=2**30-1?ie+$i:ie+je:ie+Yi;case"boolean":return ie;case"object":if(t===null)return ie;if(Array.isArray(t)){let e=2*ie+je;for(let n of t)e+=pe(n);return e}{let e=t,n=2*ie+je;for(let r in e)if(Z(e,r)){let o=e[r];o!==void 0&&(n+=pe(r)+pe(o))}return n}}throw new Error(`Invalid value. type: ${typeof t}, value: ${t}`)}function Xi(t){return t===(t|0)}var Zi=2*ie+je+ie+je;function tn(t,e){return Zi+pe(t)+pe(e)}var nn=new WeakSet;function V(t){return J||pr(t,[]),t}function pr(t,e){switch(typeof t){case"undefined":throw new TypeError("Unexpected value undefined");case"boolean":case"number":case"string":return;case"object":{if(t===null||nn.has(t))return;nn.add(t),e.includes(t)&&se(t,"Cyclic JSON object"),e.push(t),Object.freeze(t),Array.isArray(t)?Qi(t,e):ea(t,e),e.pop();return}default:se(t,"JSON value")}}function Qi(t,e){for(let n of t)pr(n,e)}function ea(t,e){for(let n in t)if(Z(t,n)){let r=t[n];r!==void 0&&pr(r,e)}}function ae(t){if(!J&&!cr(t,[]))throw new Error("Expected frozen object")}function cr(t,e){switch(typeof t){case"boolean":case"number":case"string":return!0;case"object":if(t===null||nn.has(t))return!0;if(!Object.isFrozen(t))return!1;if(e.includes(t)&&se(t,"Cyclic JSON object"),e.push(t),Array.isArray(t)){for(let n of t)if(!cr(n,e))return e.pop(),!1}else for(let n in t)if(Z(t,n)){let r=t[n];if(r!==void 0&&!cr(r,e))return e.pop(),!1}return nn.add(t),e.pop(),!0;default:se(t,"JSON value")}}function rn(t){if(t!==void 0)return V(t)}function ge(t){if(Array.isArray(t)){t.sort();for(let n=1;n<t.length;n++)f(t[n-1]!==t[n],"Refs must not have duplicates");return t}let e=[...t];return e.sort(),e}var ht=class{hash;data;meta;constructor(e,n,r){f(!r.includes(e),"Chunk cannot reference itself"),ae(n),this.hash=e,this.data=n,this.meta=r}};function dr(t){if(!Array.isArray(t))throw new Error("Refs must be an array");if(t.length>0){R(t[0]);for(let e=1;e<t.length;e++)R(t[e])}}function on(t,e,n){let r=n();return new ht(r,t,e)}function hr(){throw new Error("unexpected call to compute chunk hash")}function Je(){let t=Math.floor(Math.random()*4294967295),e=Math.floor(Math.random()*4294967295);return BigInt(t)<<32n|BigInt(e)}var h={};Fi(h,{assert:()=>ne,is:()=>na,parse:()=>Eo,readonly:()=>ra,readonlyArray:()=>mt,readonlyObject:()=>Q,readonlyRecord:()=>ft,test:()=>gr});K(h,yc);import*as ze from"@badrap/valita";import*as yc from"@badrap/valita";function yr(t){switch(typeof t){case"string":case"number":case"boolean":return JSON.stringify(t);case"undefined":return"undefined";case"bigint":return t.toString()+"n";default:return t===null?"null":Array.isArray(t)?"array":typeof t}}function mr(t,e){if(!e?.length)return yr(t);let n=t;for(let r of e)n=n[r];return yr(n)}function fr(t,e,n=r=>String(r)){if(e.length===1)return n(e[0]);let r=`${n(e[e.length-2])} ${t} ${n(e[e.length-1])}`;return e.length===2?r:`${e.slice(0,-2).map(n).join(", ")}, ${r}`}function ta(t,e){let n=t.issues[0],{path:r}=n,o=r?.length?` at ${r.join(".")}`:"";switch(n.code){case"invalid_type":return`Expected ${fr("or",n.expected)}${o}. Got ${mr(e,r)}`;case"missing_value":{let s=r&&r.length>1?` at ${r.slice(0,-1).join(".")}`:"";return n.path?.length?`Missing property ${n.path.at(-1)}${s}`:`TODO Unknown missing property${s}`}case"invalid_literal":return`Expected literal value ${fr("or",n.expected,yr)}${o} Got ${mr(e,r)}`;case"invalid_length":return`Expected array with length ${n.minLength===n.maxLength?n.minLength:`between ${n.minLength} and ${n.maxLength}`}${o}. Got array with length ${e.length}`;case"unrecognized_keys":return n.keys.length===1?`Unexpected property ${n.keys[0]}${o}`:`Unexpected properties ${fr("and",n.keys)}${o}`;case"invalid_union":return`Invalid union value${o}`;case"custom_error":{let{error:s}=n;return`${s?typeof s=="string"?s:s.message??"unknown":"unknown"}${o}. Got ${mr(e,r)}`}}}function Eo(t,e,n){let r=gr(t,e,n);if(!r.ok)throw new TypeError(r.error);return r.value}function na(t,e,n){return gr(t,e,n).ok}function ne(t,e,n){Eo(t,e,n)}function gr(t,e,n){let r=e.try(t,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:ta(r,t)}}function ra(t){return t}function Q(t){return ze.object(t)}function mt(t){return ze.array(t)}function ft(t){return ze.record(t)}var oa=22,sa=/^[0-9a-v-]+$/;var ia="0".repeat(oa),T=ia,G=aa();function To(t,e){return t.toString(32).slice(-e).padStart(e,"0")}function aa(){let t="",e=0;return()=>{t||(t=To(Je(),12));let n=To(e++,10);return t+n}}function ua(t){return typeof t=="string"&&sa.test(t)}function W(t){ne(t,de)}var de=h.string().assert(ua,"Invalid hash");function sn(t,e,n){return new Dr(t,e,n).compute()}var Dr=class{#e;#t;#n;#r;#o;#s;#i;#l;constructor(e,n,r){let o=[],s=[];for(let i of e)i.old!==i.new&&(i.old&&s.push(i.old),i.new&&o.push(i.new));this.#e=o,this.#t=s,this.#n=n,this.#r=r,this.#s=new Map,this.#i=new Map,this.#l=r.areRefsCounted!==void 0,this.#o=this.#l?new Set:null}async compute(){for(let e of this.#e)await this.#u(e,1);if(await Promise.all(Array.from(this.#n.values(),e=>this.#p(e))),this.#l){f(this.#r.areRefsCounted),f(this.#o);let e;do{e=!1;for(let n of this.#n.values())if(!this.#r.areRefsCounted(n)&&!this.#o.has(n)&&this.#s.get(n)!==0){await this.#c(n,1),e=!0;break}}while(e)}for(let e of this.#t)await this.#u(e,-1);if(!J)for(let[e,n]of this.#s)f(n>=0,`ref count update must be non-negative. ${e}:${n}`);return this.#s}async#u(e,n){await this.#p(e),this.#f(e,n)&&await this.#c(e,n)}async#c(e,n){if(e===T)return;let r=await this.#r.getRefs(e);if(J||f(r||this.#l&&!this.#n.has(e),"refs must be defined"),r!==void 0){this.#o?.add(e);let o=r.map(s=>this.#u(s,n));await Promise.all(o)}}#p(e){let n=this.#i.get(e);return n===void 0&&(n=(async()=>{let r=await this.#r.getRefCount(e)||0;return this.#s.set(e,r),r})(),this.#i.set(e,n)),n}#f(e,n){let r=this.#s.get(e);return L(r),this.#s.set(e,r+n),r===0&&n===1||r===1&&n===-1}};var yt=class extends Error{name="ChunkNotFoundError";hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function an(t,e){let n=await t.getChunk(e);if(n)return n;throw new yt(e)}async function Ge(t,e){let n=await e.getHead(t);return f(n,`Missing head ${t}`),n}var Me=class{#e=new la;#t=new Map;#n;#r;#o;t=new Map;n;h=new Map;m=new Map;constructor(e,n,r,o,s=pe){this.n=new br(n,s,this.h,this.m),this.#n=e,this.#r=r,this.#o=o}async read(){let e=await this.#e.read();return new un(this.#t,this.t,this.n,this.#n,e,this.#o)}async write(){let e=await this.#e.write();return new Sr(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#o)}close(){return A}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},un=class{a;t;n;f;#e=void 0;#t;#n=!1;assertValidHash;constructor(e,n,r,o,s,i){this.a=e,this.t=n,this.n=r,this.f=o,this.#t=s,this.assertValidHash=i}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let n=this.t.get(e);if(n!==void 0)return n;let r=this.n.get(e);return r===void 0&&(r=await(await this.y()).getChunk(e),r!==void 0&&this.n.put(r)),r}mustGetChunk(e){return an(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#n||(this.#t(),this.#e?.then(e=>e.release()).catch(e=>{}),this.#n=!0)}get closed(){return this.#n}y(){return this.#e||(this.#e=this.f.read()),this.#e}},Sr=class extends un{#e;#t;#n;i=new Map;o=new Map;s=new Map;#r=new Set;constructor(e,n,r,o,s,i,a,u,l){super(e,n,r,o,a,l),this.#e=s,this.#t=i,this.#n=u}createChunk=(e,n)=>{let r=on(e,n,this.#n);return this.#r.add(r.hash),r};putChunk(e,n){let{hash:r,meta:o}=e;if(this.assertValidHash(r),o.length>0)for(let s of o)this.assertValidHash(s);return this.#r.has(r)||this.isMemOnlyChunkHash(r)?this.o.set(r,e):this.s.set(r,{chunk:e,size:n??-1}),A}async setHead(e,n){await this.#o(e,n)}async removeHead(e){await this.#o(e,void 0)}async#o(e,n){let r=await this.getHead(e),o=this.i.get(e);o===void 0?this.i.set(e,{new:n,old:r}):o.new=n}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let n=this.o.get(e);if(n!==void 0)return n;let r=this.t.get(e);if(r!==void 0)return r;let o=this.s.get(e);if(o!==void 0)return o.chunk;let s=this.n.get(e);return s===void 0&&(s=await(await this.y()).getChunk(e),s!==void 0&&this.s.set(s.hash,{chunk:s,size:-1})),s}getHead(e){let n=this.i.get(e);return n?Promise.resolve(n.new):super.getHead(e)}async commit(){let e=new Set(dt(this.o.keys(),this.s.keys())),n=await sn(this.i.values(),e,this);for(let[r,o]of n)if(this.isMemOnlyChunkHash(r)){if(o===0)this.#e.delete(r),this.t.delete(r),this.#t.delete(r);else{this.#e.set(r,o);let s=this.o.get(r);s&&(this.#t.set(r,s.meta),this.t.set(r,s))}n.delete(r)}this.n.updateForCommit(this.s,n);for(let[r,o]of this.i)o.new?this.a.set(r,o.new):this.a.delete(r);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#e.get(e)}getRefs(e){let n=this.o.get(e);if(n)return n.meta;let r=this.t.get(e);if(r)return r.meta;let o=this.s.get(e);return o!==void 0?o.chunk.meta:this.#t.get(e)}areRefsCounted(e){return this.#t.has(e)}chunksPersisted(e){let n=[];for(let r of e){let o=this.t.get(r);o&&(this.t.delete(r),n.push(o))}this.n.persisted(n)}},br=class{#e;#t;#n;#r;#o=0;#s=!1;#i=[];cacheEntries=new Map;constructor(e,n,r,o){this.#e=e,this.#t=n,this.#n=r,this.#r=o}get(e){let n=this.cacheEntries.get(e);return n&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,n)),n?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:n}=e,r=this.cacheEntries.get(n);if(r){this.cacheEntries.delete(n),this.cacheEntries.set(n,r);return}let o=this.#n.get(n);if(!(o===void 0||o<1)&&this.#u(e)){if(!this.#r.has(n)){for(let s of e.meta)this.#n.set(s,(this.#n.get(s)||0)+1);this.#r.set(n,e.meta)}this.#l()}}#l(){if(!this.#s)for(let e of this.cacheEntries.values()){if(this.#o<=this.#e)break;this.#c(e)}}#u(e,n){let r=n??this.#t(e);return r>this.#e?!1:(this.#o+=r,this.cacheEntries.set(e.hash,{chunk:e,size:r}),!0)}#c(e){let{hash:n}=e.chunk;this.#o-=e.size,this.cacheEntries.delete(n)}#p(e){this.#n.delete(e),this.#r.delete(e);let n=this.cacheEntries.get(e);n&&(this.#o-=n.size,this.cacheEntries.delete(e))}updateForCommit(e,n){for(let[r,o]of n)if(o===0)this.#s?(this.#n.set(r,0),this.#i.push(r)):this.#p(r);else{this.#n.set(r,o);let s=e.get(r);if(s){let{chunk:i,size:a}=s,u=this.cacheEntries.get(r);u?(this.cacheEntries.delete(r),this.cacheEntries.set(r,u)):(this.#u(i,a!==-1?a:void 0),this.#r.set(r,i.meta))}}this.#l()}persisted(e){for(let n of e)this.#u(n);this.#l()}async withSuspendedEvictsAndDeletes(e){this.#s=!0;try{return await e()}finally{this.#s=!1;for(let n of this.#i)this.#n.get(n)===0&&this.#p(n);this.#l()}}};function gt(t){return`c/${t}/d`}function Dt(t){return`c/${t}/m`}function ln(t){return`c/${t}/r`}function Cr(t){return`h/${t}`}var De=class{#e;#t;#n;constructor(e,n,r){this.#e=e,this.#t=n,this.#n=r}async read(){return new cn(await this.#e.read(),this.#n)}async write(){return new Ir(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},cn=class{e;assertValidHash;constructor(e,n){this.e=e,this.assertValidHash=n}hasChunk(e){return this.e.has(gt(e))}async getChunk(e){let n=await this.e.get(gt(e));if(n===void 0)return;let r=await this.e.get(Dt(e)),o;return r!==void 0?(dr(r),o=r):o=[],new ht(e,n,o)}mustGetChunk(e){return an(this,e)}async getHead(e){let n=await this.e.get(Cr(e));if(n!==void 0)return W(n),n}release(){this.e.release()}get closed(){return this.e.closed}},Ir=class extends cn{#e;#t=new Set;#n=new Map;constructor(e,n,r){super(e,r),this.#e=n}createChunk=(e,n)=>on(e,n,this.#e);get kvWrite(){return this.e}async putChunk(e){let{hash:n,data:r,meta:o}=e;this.assertValidHash(n);let s=gt(n),i=this.e.put(s,r),a;if(o.length>0){for(let u of o)this.assertValidHash(u);a=this.e.put(Dt(n),o)}this.#t.add(n),await i,await a}setHead(e,n){return this.#r(e,n)}removeHead(e){return this.#r(e,void 0)}async#r(e,n){let r=await this.getHead(e),o=Cr(e),s;n===void 0?s=this.e.del(o):s=this.e.put(o,n);let i=this.#n.get(e);i===void 0?this.#n.set(e,{new:n,old:r}):i.new=n,await s}async commit(){let e=await sn(this.#n.values(),this.#t,this);await this.#o(e),await this.e.commit()}async getRefCount(e){let n=await this.e.get(ln(e));if(n!==void 0){if(L(n),n<0||n>65535||n!==(n|0))throw new Error(`Invalid ref count ${n}. We expect the value to be a Uint16`);return n}}async getRefs(e){let n=await this.e.get(Dt(e));return n===void 0?[]:(dr(n),n)}async#o(e){let n=[];for(let[r,o]of e)if(o===0)n.push(this.#s(r));else{let s=ln(r);n.push(this.e.put(s,o))}await Promise.all(n)}async#s(e){await Promise.all([this.e.del(gt(e)),this.e.del(Dt(e)),this.e.del(ln(e))]),this.#t.delete(e)}release(){this.e.release()}};var v="main";function wr(t){return ma(t.meta)}function ke(t){return Ke(t.meta)}function ca(t){return ke(t)||wr(t)}function pa(t){return jo(t.meta)}function da(t){return ga(t.meta)}function xr(t){return pa(t)||da(t)}var pn=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,n){return dn(e,n,this.meta)}async getNextMutationID(e,n){return await this.getMutationID(e,n)+1}get indexes(){return this.chunk.data.indexes}};async function dn(t,e,n){switch(n.type){case 1:return n.lastMutationID;case 3:return n.lastMutationID;case 5:return n.lastMutationIDs[t]??0;case 2:return n.mutationID;case 4:{if(n.clientID===t)return n.mutationID;let{basisHash:r}=n,o=await O(r,e);return dn(t,e,o.meta)}default:ir(n)}}async function hn(t,e){return(await gn(t,e)).filter(r=>ca(r))}async function mn(t,e){return(await gn(t,e)).filter(r=>ke(r))}async function fn(t,e,n){let r=[],o=new Map(Object.entries(e));for(;!xr(t)&&o.size>0;){if(ke(t)){let{meta:i}=t,a=o.get(i.clientID);a!==void 0&&(i.mutationID<=a?o.delete(i.clientID):r.push(t))}let{basisHash:s}=t.meta;if(s===null)throw new Error(`Commit ${t.chunk.hash} has no basis`);t=await O(s,n)}return r}async function Fo(t,e){let n=await e.getHead(t);return f(n,`Missing head ${t}`),_(n,e)}async function Rr(t,e){return(await _(t,e)).chunk.hash}async function _(t,e){let n=await O(t,e);return Pe(n,e)}async function Pe(t,e){for(;!xr(t);){let{meta:n}=t;if(Ke(n))t=await O(n.baseSnapshotHash,e);else{let{basisHash:r}=n;if(r===null)throw new Error(`Commit ${t.chunk.hash} has no basis`);t=await O(r,e)}}return t}function yn(t,e){let n=t.meta;return jo(n)?[n.lastMutationIDs[e]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function St(t,e){return Ae(t.meta.cookieJSON,e.meta.cookieJSON)}async function gn(t,e){let n=await O(t,e),r=[];for(;!xr(n);){let{meta:o}=n,{basisHash:s}=o;if(s===null)throw new Error(`Commit ${n.chunk.hash} has no basis`);r.push(n),n=await O(s,e)}return r.push(n),r}async function O(t,e){let n=await e.mustGetChunk(t);return wa(n)}async function Be(t,e){let n=await Ge(t,e);return O(n,e)}function ha(t){L(t.lastMutationID)}function Lo(t){if(L(t.mutationID),R(t.mutatorName),!t.mutatorName)throw new Error("Missing mutator name");te(t.mutatorArgsJSON),t.originalHash!==null&&W(t.originalHash),L(t.timestamp)}function Mr(t){R(t.clientID),Lo(t)}function Ke(t){return t.type===4}function ma(t){return t.type===2}function Ao(t){t.basisHash!==null&&W(t.basisHash),te(t.cookieJSON)}function fa(t){Ao(t),L(t.lastMutationID)}function bt(t){Ao(t),ya(t.lastMutationIDs)}function ya(t){k(t);for(let e of Object.values(t))L(e)}function ue(t){bt(t.meta)}function jo(t){return t.type===5}function ga(t){return t.type===3}function Da(t){switch(k(t),ae(t),t.basisHash!==null&&R(t.basisHash),L(t.type),t.type){case 1:ha(t);break;case 2:Lo(t);break;case 4:Mr(t);break;case 3:fa(t);break;case 5:bt(t);break;default:throw new Error(`Invalid enum value ${t.type}`)}}function Jo(t,e){return t.jsonPointer===e.jsonPointer&&(t.allowEmpty??!1)===(e.allowEmpty??!1)&&t.keyPrefix===e.keyPrefix}function Sa(t){k(t),ae(t),R(t.name),R(t.keyPrefix),R(t.jsonPointer),t.allowEmpty!==void 0&&Co(t.allowEmpty)}function zo(t,e){return{name:t,keyPrefix:e.prefix??"",jsonPointer:e.jsonPointer,allowEmpty:e.allowEmpty??!1}}function ba(t){k(t),ae(t),Sa(t.definition),R(t.valueHash)}function Ca(t){oe(t),ae(t);for(let e of t)ba(e)}function Go(t,e,n,r,o,s,i,a,u){return Ct(t,It({type:2,basisHash:e,mutationID:n,mutatorName:r,mutatorArgsJSON:o,originalHash:s,timestamp:u},i,a))}function Bo(t,e,n,r,o,s,i,a,u,l,c){return Ct(t,It({type:4,basisHash:e,baseSnapshotHash:n,mutationID:r,mutatorName:o,mutatorArgsJSON:s,originalHash:i,timestamp:l,clientID:c},a,u))}function Ko(t,e,n,r,o,s){return Ct(t,Ia(e,n,r,o,s))}function _o(t,e,n,r,o,s){return Ct(t,kr(e,n,r,o,s))}function Ia(t,e,n,r,o){return It({type:3,basisHash:t,lastMutationID:e,cookieJSON:n},r,o)}function kr(t,e,n,r,o){return It({type:5,basisHash:t,lastMutationIDs:e,cookieJSON:n},r,o)}function qo(t,e,n,r,o){return Ct(t,It({type:1,basisHash:e,lastMutationID:n},r,o))}function wa(t){return Ra(t),new pn(t)}function Ct(t,e){return new pn(t(e,Pr(e)))}function Pr(t){let e=new Set;e.add(t.valueHash);let{meta:n}=t;switch(n.type){case 1:n.basisHash&&e.add(n.basisHash);break;case 2:case 4:n.basisHash&&e.add(n.basisHash);break;case 3:case 5:break;default:ir(n)}for(let r of t.indexes)e.add(r.valueHash);return ge(e)}function It(t,e,n){return V({meta:t,valueHash:e,indexes:n})}function xa(t){J||(k(t),ae(t),Da(t.meta),R(t.valueHash),Ca(t.indexes))}function Ra(t){let{data:e}=t;xa(e);let n=new Set;for(let r of e.indexes){let{name:o}=r.definition;if(n.has(o))throw new Error(`Duplicate index ${o}`);n.add(o)}}function ve(t,e){let n=t.length,r=e.length,o=Math.min(n,r);for(let s=0;s<o;){let i=t.codePointAt(s),a=e.codePointAt(s);if(i!==a){if(i<128&&a<128)return i-a;let u=$o(i,Wo),l=$o(a,Uo);return Ma(Wo,u,Uo,l)}s+=ka(i)}return n-r}function Ma(t,e,n,r){let o=Math.min(e,r);for(let s=0;s<o;s++){let i=t[s],a=n[s];if(i!==a)return i-a}return e-r}function ka(t){return t>65535?2:1}var Yo=()=>Array.from({length:4},()=>0),Wo=Yo(),Uo=Yo();function $o(t,e){if(t<128)return e[0]=t,1;let n,r;if(t<=2047)n=1,r=192;else if(t<=65535)n=2,r=224;else if(t<=1114111)n=3,r=240;else throw new Error("Invalid code point");e[0]=(t>>6*n)+r;let o=1;for(;n>0;n--){let s=t>>6*(n-1);e[o++]=128|s&63}return o}function Ne(t,e){return ve(t,e)>0}function Dn(t,e){return ve(t,e)<0}function Sn(t,e){return ve(t,e)<=0}function bn(t,e){let n=0;for(;n<t;){let r=n+(t-n>>1),o=e(r);if(o===0)return r;o>0?n=r+1:t=r}return n}function vr(t){if(t!==(t|0)||t<4||t>7)throw new Error(`Unsupported format version: ${t}`);return t}var Nr=0,Or=1;function Xo(t,e,n){return V([t,n>=7?e:e.map(r=>r.slice(0,2))])}async function xt(t,e,n,r){let o=await n.getNode(e);if(r!==n.rootHash)return xt(t,n.rootHash,n,n.rootHash);if(_e(o))return o;let{entries:s}=o,i=he(t,s);i===s.length&&i--;let a=s[i];return xt(t,a[1],n,r)}function he(t,e){return bn(e.length,n=>ve(t,e[n][0]))}function Rt(t,e,n){return t!==e.length&&e[t][0]===n}function Hr(t,e,n){if(J&&e>=7)return t;oe(t),ae(t),f(t.length>=2);let[r,o]=t;L(r),oe(o);let s=r>0?R:te;if(e>=7){for(let a of o)Pa(a,s);return t}let i=o.map(a=>va(a,s,n));return[r,i]}function Pa(t,e){oe(t),f(t.length>=3),R(t[0]),e(t[1]),L(t[2])}function va(t,e,n){oe(t),f(t.length>=2),R(t[0]),e(t[1]);let r=n(t[0],t[1]);return[t[0],t[1],r]}var In=class{entries;hash;isMutable;#e=-1;constructor(e,n,r){this.entries=e,this.hash=n,this.isMutable=r}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(this.#e!==-1)return this.#e;let n=e.chunkHeaderSize;for(let r of this.entries)n+=r[2];return this.#e=n}c(e){this.#e=-1,e.updateNode(this)}};function Vr(t,e){return Xo(t.level,t.entries,e)}var Oe=class extends In{level=0;set(e,n,r,o){let s,i=he(e,this.entries);return Rt(i,this.entries,e)?s=1:s=0,Promise.resolve(this.#e(o,i,s,[e,n,r]))}#e(e,n,r,...o){if(this.isMutable)return this.entries.splice(n,r,...o),this.c(e),this;let s=Cn(this.entries,n,r,...o);return e.newDataNodeImpl(s)}del(e,n){let r=he(e,this.entries);return Rt(r,this.entries,e)?Promise.resolve(this.#e(n,r,1)):Promise.resolve(this)}async*keys(e){for(let n of this.entries)yield n[0]}async*entriesIter(e){for(let n of this.entries)yield n}};function Cn(t,e,n,...r){let o=t.slice(0,e);for(let s=0;s<r.length;s++)o.push(r[s]);for(let s=e+n;s<t.length;s++)o.push(t[s]);return o}var Mt=class t extends In{level;constructor(e,n,r,o){super(e,n,o),this.level=r}async set(e,n,r,o){let s=he(e,this.entries);s===this.entries.length&&s--;let i=this.entries[s][1],u=await(await o.getNode(i)).set(e,n,r,o),l=u.getChildNodeSize(o);if(l>o.maxSize||l<o.minSize)return this.#e(o,s,u);let c=wt(u,o.getEntrySize);return this.#t(o,s,c)}async#e(e,n,r){let o=this.level-1,s=this.entries,i,a,u;if(n>0){let p=s[n-1][1],m=await e.getNode(p);i=dt(m.entries,r.entries),a=n-1,u=2}else if(n<s.length-1){let p=s[n+1][1],m=await e.getNode(p);i=dt(r.entries,m.entries),a=n,u=2}else i=r.entries,a=n,u=1;let l=Er(i,p=>p[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),c=[];for(let p of l){let m=e.newNodeImpl(p,o),g=wt(m,e.getEntrySize);c.push(g)}if(this.isMutable)return this.entries.splice(a,u,...c),this.c(e),this;let d=Cn(s,a,u,...c);return e.newInternalNodeImpl(d,this.level)}#t(e,n,r){if(this.isMutable)return this.entries.splice(n,1,r),this.c(e),this;let o=Cn(this.entries,n,1,r);return e.newInternalNodeImpl(o,this.level)}async del(e,n){let r=he(e,this.entries);if(r===this.entries.length)return this;let o=this.entries[r][1],s=await n.getNode(o),i=s.hash,a=await s.del(e,n);if(a.hash===i)return this;if(a.entries.length===0){let u=Cn(this.entries,r,1);return n.newInternalNodeImpl(u,this.level)}if(r===0&&this.entries.length===1)return a;if(a.getChildNodeSize(n)>n.minSize){let u=wt(a,n.getEntrySize);return this.#t(n,r,u)}return this.#e(n,r,a)}async*keys(e){for(let n of this.entries)yield*(await e.getNode(n[1])).keys(e)}async*entriesIter(e){for(let n of this.entries)yield*(await e.getNode(n[1])).entriesIter(e)}getChildren(e,n,r){let o=[];for(let s=e;s<n&&s<this.entries.length;s++)o.push(r.getNode(this.entries[s][1]));return Promise.all(o)}async getCompositeChildren(e,n,r){let{level:o}=this;if(n===0)return new t([],G(),o-1,!0);let s=await this.getChildren(e,e+n,r);if(o>1){let a=[];for(let u of s)a.push(...u.entries);return new t(a,G(),o-1,!0)}f(o===1);let i=[];for(let a of s)i.push(...a.entries);return new Oe(i,G(),!0)}};function wn(t,e,n,r){return n===0?new Oe(t,e,r):new Mt(t,e,n,r)}function _e(t){return t.level===0}function Er(t,e,n,r){let o=[],s=[],i=0,a=[];for(let u of t){let l=e(u);l>=r?(a.length>0&&(o.push(a),s.push(i)),o.push([u]),s.push(l),i=0,a=[]):i+l>=n?(a.push(u),o.push(a),s.push(i+l),i=0,a=[]):(i+=l,a.push(u))}return i>0&&(s.length>0&&i+s[s.length-1]<=r?o[o.length-1].push(...a):o.push(a)),o}var xn=Xo(0,[],7),Zo=new Oe([],T,!1);function wt(t,e){let n=t.maxKey(),r=t.hash,o=e(n,r);return[n,r,o]}var Qo=-1,ts=0,kt=1,Pt=2,Mn=3,Rn=0,es=1;function*ns(t,e){let n=0,r=0,o;function s(a,u){a[Mn]===Qo&&(a[Mn]=u)}function i(){return[n,0,0,Qo]}for(;n<t.length&&r<e.length;)t[n][Rn]===e[r][Rn]?($(t[n][es],e[r][es])?o&&(s(o,0),yield o,o=void 0):(o||(o=i()),o[Pt]++,o[kt]++,s(o,r)),n++,r++):t[n][Rn]<e[r][Rn]?(o||(o=i()),o[kt]++,n++):(o||(o=i()),o[Pt]++,s(o,r),r++);r<e.length&&(o||(o=i()),o[Pt]+=e.length-r,s(o,r)),n<t.length&&(o||(o=i()),o[kt]+=t.length-n),o&&(s(o,0),yield o)}var Na=11,z=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,n,r=T,o=tn,s=Na){this.l=e,this.u=n,this.rootHash=r,this.getEntrySize=o,this.chunkHeaderSize=s}async getNode(e){if(e===T)return Zo;let n=this.p.get(e);if(n)return n;let r=await this.l.mustGetChunk(e),o=Hr(r.data,this.u,this.getEntrySize),s=wn(o[Or],e,o[Nr],!1);return this.p.set(e,s),s}async get(e){let n=await xt(e,this.rootHash,this,this.rootHash),r=he(e,n.entries);if(Rt(r,n.entries,e))return n.entries[r][1]}async has(e){let n=await xt(e,this.rootHash,this,this.rootHash),r=he(e,n.entries);return Rt(r,n.entries,e)}async isEmpty(){let{rootHash:e}=this,n=await this.getNode(this.rootHash);return this.rootHash!==e?this.isEmpty():n.entries.length===0}scan(e){return Tr(this.rootHash,()=>this.rootHash,this.rootHash,e,async n=>{let r=await this.getNode(n);if(r)return[r.level,r.isMutable?r.entries.slice():r.entries];let o=await this.l.mustGetChunk(n);return Hr(o.data,this.u,this.getEntrySize)})}async*keys(){yield*(await this.getNode(this.rootHash)).keys(this)}async*entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async*diff(e){let[n,r]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*kn(r,n,e,this)}};async function*kn(t,e,n,r){if(t.level>e.level){let s=await t.getCompositeChildren(0,t.entries.length,n);yield*kn(s,e,n,r);return}if(e.level>t.level){let s=await e.getCompositeChildren(0,e.entries.length,r);yield*kn(t,s,n,r);return}if(_e(t)&&_e(e)){yield*Oa(t.entries,e.entries);return}let o=ns(t.entries,e.entries);for(let s of o){let[i,a]=await Promise.all([t.getCompositeChildren(s[ts],s[kt],n),e.getCompositeChildren(s[Mn],s[Pt],r)]);yield*kn(i,a,n,r)}}function*Oa(t,e){let n=t.length,r=e.length,o=0,s=0;for(;o<n&&s<r;){let i=t[o][0],a=e[s][0];i===a?($(t[o][1],e[s][1])||(yield{op:"change",key:i,oldValue:t[o][1],newValue:e[s][1]}),o++,s++):i<a?(yield{op:"del",key:i,oldValue:t[o][1]},o++):(yield{op:"add",key:a,newValue:e[s][1]},s++)}for(;o<n;o++)yield{op:"del",key:t[o][0],oldValue:t[o][1]};for(;s<r;s++)yield{op:"add",key:e[s][0],newValue:e[s][1]}}async function*Tr(t,e,n,r,o){if(n===T)return;let s=await o(n),i=s[Or],a=0;if(r&&(a=he(r,i)),s[Nr]>0)for(;a<i.length;a++)yield*Tr(t,e,i[a][1],r,o),r="";else for(;a<i.length;a++){let u=e();if(t!==u){yield*Tr(u,e,u,i[a][0],o);return}yield i[a]}}async function qe(t,e){let n=[],r=e==="add"?o=>({op:"add",key:o[0],newValue:o[1]}):o=>({op:"del",key:o[0],oldValue:o[1]});for await(let o of t.entries())n.push(r(o));return n}var vt=class{meta;map;constructor(e,n){this.meta=e,this.map=n}},Pn=class extends vt{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function vn(t,e,n,r,o,s,i){try{for(let a of Ha(r,o,s,i))switch(n){case 0:await e.put(a,o);break;case 1:await e.del(a);break}}catch(a){t.info?.("Not indexing value",o,":",a)}}function Ha(t,e,n,r){let o=Va(e,n);if(o===void 0){if(r)return[];throw new Error(`No value at path: ${n}`)}let s=Array.isArray(o)?o:[o],i=[];for(let a of s)if(typeof a=="string")i.push(rs([a,t]));else throw new Error("Unsupported target type");return i}var Fr="\0",Lr="\0";function rs(t){let e=t[0],n=t[1];if(e.includes("\0"))throw new Error("Secondary key cannot contain null byte");return Fr+e+Lr+n}function Ar(t,e){let n=rs([t,e||""]);return e===void 0?n.slice(0,n.length-1):n}function We(t){if(t[0]!==Fr)throw new Error("Invalid version");let e=Fr.length,n=Lr.length,r=t.indexOf(Lr,e);if(r===-1)throw new Error("Invalid formatting");let o=t.slice(e,r),s=t.slice(r+n);return[o,s]}function Va(t,e){function n(s){if(!(s.startsWith("+")||s.startsWith("0")&&s.length!==1))return parseInt(s,10)}if(e==="")return t;if(!e.startsWith("/"))throw new Error(`Invalid JSON pointer: ${e}`);let r=e.split("/").slice(1).map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),o=t;for(let s of r){let i;if(Array.isArray(o)){let a=n(s);if(a===void 0)return;i=o[a]}else{if(o===null)return;typeof o=="object"&&(o=o,i=o[s])}if(i===void 0)return;o=i}return o}var Nt=class{#e;map;indexes;constructor(e,n,r){this.#e=e,this.map=n,this.indexes=r}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let n=this.indexes.get(e);if(n===void 0)throw new Error(`Unknown index name: ${e}`);return n.map}get closed(){return this.#e.closed}close(){this.#e.release()}};function os(t,e){return Ea(v,t,e)}async function Ea(t,e,n){let r=await Be(t,e);return Ta(r,e,n)}function Ta(t,e,n){let r=Ue(t,e,n),o=new z(e,n,t.valueHash);return new Nt(e,o,r)}function Ue(t,e,n){let r=new Map;for(let o of t.indexes)r.set(o.definition.name,new vt(o,new z(e,n,o.valueHash)));return r}async function Nn(t){let e=[];for await(let n of t)e.push(n);return e}function Ot(t){return t.indexName!==void 0}function Ht(t){return typeof t=="string"?[t]:t}function ss(t){if(!t)return{};let e,n,r,o;return t.start&&({key:e,exclusive:n}=t.start,t.indexName?typeof e=="string"?o=e:(o=e[0],r=e[1]):r=e),{prefix:t.prefix,startSecondaryKey:o,startKey:r,startExclusive:n,limit:t.limit,indexName:t.indexName}}var On=class extends Error{constructor(){super("Transaction is closed")}};function Se(t){if(t.closed)throw new On}function jr(t){return t.closed?Promise.reject(new On):void 0}var $e=class{#e;#t;#n;#r;constructor(e,n,r,o){this.#e=e,this.#t=n,this.#n=r,this.#r=o}[Symbol.asyncIterator](){return this.values()}values(){return new Vt(this.#o(e=>e[1]))}keys(){return new Vt(this.#o(e=>e[0]))}entries(){return new Vt(this.#o(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#o(e){return Fa(e,this.#e,this.#t,this.#n,this.#r)}},Vt=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return Nn(this.#e)}};async function*Fa(t,e,n,r,o){Se(r);let{limit:s=1/0}=n,{prefix:i=""}=n,a=n.start?.exclusive,u=Ot(n);for await(let l of e){let c=l[0];if(!(u?c[0]:c).startsWith(i))return;if(a){if(a=!0,u){if(La(c,n.start.key))continue}else if(Aa(c,n.start.key))continue}if(yield t(l),--s===0){u||o(c);return}}}function La(t,e){let[n,r]=Ht(e),[o,s]=Ht(t);return o!==n?!1:r===void 0?!0:s===r}function Aa(t,e){return t===e}function Ap(t,e){if(Ot(t)){let[r,o]=ja(t);return new $e(e(t.indexName,r,o),t,{closed:!1},s=>{})}let n=Jr(t);return new $e(e(n),t,{closed:!1},r=>{})}function ja(t){let{prefix:e,start:n}=t,r=[e??"",void 0];if(!n)return r;let o=Ht(n.key);return Ne(o[0],r[0])||o[0]===r[0]&&o[1]!==void 0?o:r}function is(t){let{prefix:e,start:n}=t,r="";if(e!==void 0&&(r=Ar(e,void 0)),!n)return r;let{key:o}=n,[s,i]=Ht(o),a=Ar(s,i);return Ne(a,r)?a:r}var Ja=0,Et=class{clientID;dbtx;d;location;environment;constructor(e,n,r,o="openReadTransaction"){this.clientID=e,this.dbtx=n,this.d=r.withContext(o).withContext("txid",Ja++),this.environment="client",this.location="client"}get(e){return jr(this.dbtx)||this.dbtx.get(e)}async has(e){return Se(this.dbtx),this.dbtx.has(e)}async isEmpty(){return Se(this.dbtx),this.dbtx.isEmpty()}scan(e){return as(e,this.dbtx,za)}};function za(t){}function as(t,e,n){let r=Ga(e,t);return Ba(r,t??{},e,n)}var Hn=class{#e=new Set;#t=[];#n;constructor(e){this.#n=e}get environment(){return this.#n.location}get location(){return this.#n.location}get clientID(){return this.#n.clientID}isEmpty(){return this.#t.push({options:{}}),this.#n.isEmpty()}get(e){return this.#e.add(e),this.#n.get(e)}has(e){return this.#e.add(e),this.#n.has(e)}scan(e){let n={options:ss(e),inclusiveLimitKey:void 0};return this.#t.push(n),as(e,this.#n.dbtx,r=>{n.inclusiveLimitKey=r})}get keys(){return this.#e}get scans(){return this.#t}},Ye=class extends Et{reason;mutationID;constructor(e,n,r,o,s,i="openWriteTransaction"){super(e,o,s,i),this.mutationID=n,this.reason=r}put(e,n){return this.set(e,n)}async set(e,n){Se(this.dbtx),await this.dbtx.put(this.d,e,V(n))}del(e){return jr(this.dbtx)??this.dbtx.del(this.d,e)}};function Ga(t,e){return e&&Ot(e)?Ka(t,e):t.map.scan(Jr(e))}function Jr(t){if(!t)return"";let{prefix:e="",start:n}=t;return n&&Ne(n.key,e)?n.key:e}function Ba(t,e,n,r){return new $e(t,e,n,r)}async function*Ka(t,e){let n=t.getMapForIndex(e.indexName);for await(let r of n.scan(is(e)))yield[We(r[0]),r[1]]}function be(t,e){return Nn(e.diff(t))}import{Lock as _a}from"@rocicorp/lock";var Ce=class extends z{#e=new _a;#t=new Map;minSize;maxSize;constructor(e,n,r=T,o=8*1024,s=16*1024,i=tn,a){super(e,n,r,i,a),this.minSize=o,this.maxSize=s}#n(e){f(e.isMutable),this.#t.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){f(e.isMutable),this.#t.delete(e.hash),e.hash=G(),this.#n(e)}newInternalNodeImpl(e,n){let r=new Mt(e,G(),n,!0);return this.#n(r),r}newDataNodeImpl(e){let n=new Oe(e,G(),!0);return this.#n(n),n}newNodeImpl(e,n){let r=wn(e,G(),n,!0);return this.#n(r),r}put(e,n){return this.#e.withLock(async()=>{let r=await this.getNode(this.rootHash),o=this.getEntrySize(e,n),s=await r.set(e,n,o,this);if(s.getChildNodeSize(this)>this.maxSize){let i=this.chunkHeaderSize,a=Er(s.entries,d=>d[2],this.minSize-i,this.maxSize-i),{level:u}=s,l=a.map(d=>{let p=this.newNodeImpl(d,u);return wt(p,this.getEntrySize)}),c=this.newInternalNodeImpl(l,u+1);this.rootHash=c.hash;return}this.rootHash=s.hash})}del(e){return this.#e.withLock(async()=>{let r=await(await this.getNode(this.rootHash)).del(e,this),o=this.rootHash!==r.hash;return o&&(r.level>0&&r.entries.length===1?this.rootHash=r.entries[0][1]:this.rootHash=r.hash),o})}clear(){return this.#e.withLock(()=>{this.#t.clear(),this.rootHash=T})}flush(){return this.#e.withLock(async()=>{let e=this.l;if(this.rootHash===T){let o=e.createChunk(xn,[]);return await e.putChunk(o),o.hash}let n=[],r=us(this.rootHash,n,e.createChunk,this.#t,this.u);return await Promise.all(n.map(o=>e.putChunk(o))),this.#t.clear(),this.rootHash=r,r})}};function us(t,e,n,r,o){let s=r.get(t);if(s===void 0)return t;if(_e(s)){let l=n(Vr(s,o),[]);return e.push(l),l.hash}let i=[],{entries:a}=s;for(let l=0;l<a.length;l++){let c=a[l],d=c[1],p=us(d,e,n,r,o);p!==d&&(a[l]=[c[0],p,c[2]]),i.push(p)}let u=n(Vr(s,o),ge(i));return e.push(u),u.hash}function zr(t){let e;return()=>(e===void 0&&(e=t()),e)}var Ve=class extends Map{set(e,n){return n.length===0?this:super.set(e,n)}};async function ls(t,e,n,r,o){let s=new Ve;if(!r.shouldComputeDiffs())return s;let i=new z(n,o,t.valueHash),a=new z(n,o,e.valueHash),u=await be(i,a);return s.set("",u),await Gr(t,e,n,s,r,o),s}async function Gr(t,e,n,r,o,s){let i=Ue(t,n,s),a=Ue(e,n,s);for(let[u,l]of i){if(!o.shouldComputeDiffsForIndex(u))continue;let c=a.get(u);if(c!==void 0){f(c!==l);let d=await be(l.map,c.map);a.delete(u),r.set(u,d)}else{let d=await qe(l.map,"del");r.set(u,d)}}for(let[u,l]of a){if(!o.shouldComputeDiffsForIndex(u))continue;let c=await qe(l.map,"add");r.set(u,c)}}var Tt=class extends Nt{#e;#t;#n;#r;#o;constructor(e,n,r,o,s,i,a){super(e,n,s),this.#e=e,this.#t=r,this.#n=o,this.#r=i,this.#o=a,r===void 0?f(o.basisHash===T):f(o.basisHash===r.chunk.hash)}async put(e,n,r){if(this.#n.type===1)throw new Error("Not allowed");let o=zr(()=>this.map.get(n));await Vn(e,this.indexes,n,o,r),await this.map.put(n,r)}getMutationID(){return dn(this.#r,this.#e,this.#n)}async del(e,n){if(this.#n.type===1)throw new Error("Not allowed");let r=zr(()=>this.map.get(n));return r!==void 0&&await Vn(e,this.indexes,n,r,void 0),this.map.del(n)}async clear(){if(this.#n.type===1)throw new Error("Not allowed");await this.map.clear();let e=[];for(let n of this.indexes.values())e.push(n.clear());await Promise.all(e)}async putCommit(){let e=await this.map.flush(),n=[];for(let s of this.indexes.values()){let i=await s.flush(),a={definition:s.meta.definition,valueHash:i};n.push(a)}let r,o=this.#n;switch(o.type){case 2:{let{basisHash:s,mutationID:i,mutatorName:a,mutatorArgsJSON:u,originalHash:l,timestamp:c}=o;r=Go(this.#e.createChunk,s,i,a,u,l,e,n,c);break}case 4:{f(this.#o>=5);let{basisHash:s,mutationID:i,mutatorName:a,mutatorArgsJSON:u,originalHash:l,timestamp:c}=o;r=Bo(this.#e.createChunk,s,await Rr(s,this.#e),i,a,u,l,e,n,c,this.#r);break}case 3:{f(this.#o<=4);let{basisHash:s,lastMutationID:i,cookieJSON:a}=o;r=Ko(this.#e.createChunk,s,i,a,e,n);break}case 5:{f(this.#o>5);let{basisHash:s,lastMutationIDs:i,cookieJSON:a}=o;r=_o(this.#e.createChunk,s,i,a,e,n);break}case 1:{let{basisHash:s,lastMutationID:i}=o;if(this.#t!==void 0){if(await this.#t.getMutationID(this.#r,this.#e)!==i)throw new Error("Index change must not change mutationID");if(this.#t.valueHash!==e)throw new Error("Index change must not change valueHash")}r=qo(this.#e.createChunk,s,i,e,n);break}}return await this.#e.putChunk(r.chunk),r}async commit(e){let r=(await this.putCommit()).chunk.hash;return await this.#e.setHead(e,r),await this.#e.commit(),r}async commitWithDiffs(e,n){let r=this.putCommit(),o=await this.#s(n),s=(await r).chunk.hash;return await this.#e.setHead(e,s),await this.#e.commit(),o}async#s(e){let n=new Ve;if(!e.shouldComputeDiffs())return n;let r=[];if(this.#t){let s=new z(this.#e,this.#o,this.#t.valueHash);r=await be(s,this.map)}n.set("",r);let o;this.#t?o=Ue(this.#t,this.#e,this.#o):o=new Map;for(let[s,i]of this.indexes){if(!e.shouldComputeDiffsForIndex(s))continue;let a=o.get(s);f(i!==a);let u=await(a?be(a.map,i.map):qe(i.map,"add"));n.set(s,u)}for(let[s,i]of o)if(!this.indexes.has(s)&&e.shouldComputeDiffsForIndex(s)){let a=await qe(i.map,"del");n.set(s,a)}return n}close(){this.#e.release()}};async function En(t,e,n,r,o,s,i,a){let u=await O(t,o),l=new Ce(o,a,u.valueHash),c=await u.getNextMutationID(i,o),d=Tn(u,o,a);return new Tt(o,l,u,a>=5?{type:4,basisHash:t,baseSnapshotHash:await Rr(t,o),mutatorName:e,mutatorArgsJSON:n,mutationID:c,originalHash:r,timestamp:s,clientID:i}:{type:2,basisHash:t,mutatorName:e,mutatorArgsJSON:n,mutationID:c,originalHash:r,timestamp:s},d,i,a)}async function cs(t,e,n,r,o,s,i){f(i<=4);let a=await O(t,r),u=new Ce(r,i,a.valueHash);return new Tt(r,u,a,{basisHash:t,type:3,lastMutationID:e,cookieJSON:n},o,s,i)}async function ps(t,e,n,r,o,s){let i=await O(t,r),a=new Ce(r,s,i.valueHash);return new Tt(r,a,i,{basisHash:t,type:5,lastMutationIDs:e,cookieJSON:n},Tn(i,r,s),o,s)}async function Vn(t,e,n,r,o){let s=[];for(let i of e.values()){let{keyPrefix:a}=i.meta.definition;if(!a||n.startsWith(a)){let u=await r();u!==void 0&&s.push(vn(t,i.map,1,n,u,i.meta.definition.jsonPointer,i.meta.definition.allowEmpty??!1)),o!==void 0&&s.push(vn(t,i.map,0,n,o,i.meta.definition.jsonPointer,i.meta.definition.allowEmpty??!1))}}await Promise.all(s)}function Tn(t,e,n){let r=new Map;for(let o of t.indexes)r.set(o.definition.name,new Pn(o,new Ce(e,n,o.valueHash)));return r}async function ds(t,e,n,r,o,s,i){let a=new Ce(e,i);for await(let u of n.scan(r)){let l=u[0];if(!l.startsWith(r))break;await vn(t,a,0,l,u[1],o,s)}return a}async function hs(t,e,n,r,o,s,i){let a=t.meta,u=a.mutatorName;Ke(a)&&f(a.clientID===s,"mutationClientID must match clientID of LocalMeta");let l=r[u];l||o.error?.(`Cannot rebase unknown mutator ${u}`);let c=l||(async()=>{}),d=a.mutatorArgsJSON,m=await(await O(n,e)).getNextMutationID(s,e);if(m!==a.mutationID)throw new Error(`Inconsistent mutation ID: original: ${a.mutationID}, next: ${m} - mutationClientID: ${s} mutatorName: ${u}`);i>=5&&Mr(a);let g=await En(n,u,d,t.chunk.hash,e,a.timestamp,s,i),y=new Ye(s,await g.getMutationID(),"rebase",g,o);return await c(y,d),g}async function Fn(t,e,n,r,o,s,i){return(await hs(t,e,n,r,o,s,i)).putCommit()}async function ms(t,e,n,r,o,s,i,a){return(await hs(t,e,n,o,s,i,a)).commit(r)}function fs(t,e){return typeof t=="object"&&t!==null&&t.error===e}function Br(t){return typeof t.error=="string"}function B(t){return fs(t,"ClientStateNotFound")}function q(t){if(!fs(t,"VersionNotSupported"))return!1;let{versionType:e}=t;switch(e){case void 0:case"pull":case"push":case"schema":return!0}return!1}function ys(t){f(q(t))}async function Ln(t,e,n,r){let o={headers:{"Content-type":"application/json",Authorization:e,"X-Replicache-RequestID":n},body:JSON.stringify(r),method:"POST"},s=new Request(t,o),i=await fetch(s),a=i.status;return a!==200?[void 0,{httpStatusCode:a,errorMessage:await i.text()}]:[i,{httpStatusCode:a,errorMessage:""}]}function Ft(t){k(t),L(t.httpStatusCode),R(t.errorMessage)}function Kr(t){oe(t);for(let e of t)qa(e)}function qa(t){switch(k(t),t.op){case"put":R(t.key),te(t.value);break;case"update":if(R(t.key),t.merge!==void 0&&Zt(t.merge),t.constrain!==void 0){oe(t.constrain);for(let e of t.constrain)R(e)}break;case"del":R(t.key);break;case"clear":break;default:throw new Error(`unknown patch op \`${t.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}function gs(t){async function e(n,r){let[o,s]=await Ln(t.pullURL,t.auth,r,n);return o?{response:await o.json(),httpRequestInfo:s}:{httpRequestInfo:s}}return Ds.add(e),e}var Ds=new WeakSet;function Ss(t){return Ds.has(t)}function Wa(t){if(k(t),B(t)||q(t))return;let e=t;e.cookie!==void 0&&te(e.cookie),L(e.lastMutationID),Kr(e.patch)}function Ua(t){if(k(t),B(t)||q(t))return;let e=t;e.cookie!==void 0&&en(e.cookie),$a(e.lastMutationIDChanges),Kr(e.patch)}function $a(t){k(t);for(let[e,n]of Object.entries(t))R(e),L(n)}function bs(t){k(t),Ft(t.httpRequestInfo),t.response!==void 0&&Ua(t.response)}function Cs(t){k(t),Ft(t.httpRequestInfo),t.response!==void 0&&Wa(t.response)}function Is(t){async function e(n,r){let[o,s]=await Ln(t.pushURL,t.auth,r,n);if(!o)return{httpRequestInfo:s};let i={httpRequestInfo:s},a;try{a=await o.json()}catch{return i}return(B(a)||q(a))&&(i.response=a),i}return ws.add(e),e}var ws=new WeakSet;function xs(t){return ws.has(t)}import{consoleLogSink as Ya,LogContext as Xa,TeeLogSink as Za}from"@rocicorp/logger";function Lt(t="info",e=[Ya],n){let r=e.length===1?e[0]:new Za(e);return new Xa(t,n,r)}var Qa=Q({prefix:h.string().optional(),jsonPointer:h.string(),allowEmpty:h.boolean().optional()}),Rs=ft(Qa);function eu(t,e){return t.jsonPointer===e.jsonPointer&&(t.allowEmpty??!1)===(e.allowEmpty??!1)&&(t.prefix??"")===(e.prefix??"")}function An(t,e){if(Object.keys(t).length!==Object.keys(e).length)return!1;for(let[n,r]of Object.entries(t)){let o=e[n];if(!o||!eu(r,o))return!1}return!0}var tu=Q({headHash:de,mutatorNames:mt(h.string()),indexes:Rs,mutationIDs:ft(h.number()),lastServerAckdMutationIDs:h.record(h.number()),disabled:h.boolean()}),Ms="client-groups";function nu(t){ne(t,tu)}function ru(t){k(t);let e=new Map;for(let[n,r]of Object.entries(t))r!==void 0&&(nu(r),e.set(n,r));return e}function ou(t,e){let n={};for(let[r,o]of t.entries())e.assertValidHash(o.headHash),n[r]={...o,mutatorNames:[...o.mutatorNames.values()]};return V(n)}async function su(t,e){let n=await e.getChunk(t);return ru(n?.data)}async function ee(t){let e=await t.getHead(Ms);return e?su(e,t):new Map}async function jn(t,e){let n=await ee(e);for(let[r,o]of t){let s=n.get(r);ks(o,s)}return Ps(t,e)}async function At(t,e,n){let r=await ee(n),o=r.get(t);ks(e,o);let s=new Map(r);return s.set(t,e),Ps(s,n)}function ks(t,e){let n=new Set(t.mutatorNames);f(n.size===t.mutatorNames.length,"A client group's mutatorNames must be a set."),e!==void 0&&(f(An(e.indexes,t.indexes),"A client group's index definitions must never change."),f(_r(n,e.mutatorNames),"A client group's mutatorNames must never change."))}async function Ps(t,e){let n=ou(t,e),r=new Set;for(let s of t.values())r.add(s.headHash);let o=e.createChunk(n,ge(r));return await e.putChunk(o),await e.setHead(Ms,o.hash),t}function _r(t,e){if(e.length!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}async function Ee(t,e){return(await ee(e)).get(t)}function Jn(t){for(let[e,n]of Object.entries(t.mutationIDs)){let r=t.lastServerAckdMutation