const t=t=>typeof t,e="",a=t(e),s=t=>null==t,o=(t,e,a)=>s(t)?a?.():e(t),n=e=>t(e)==a,r=t=>Array.isArray(t),i=t=>t.length,c=t=>{throw Error(t)},y=Object,d=t=>y.getPrototypeOf(t),g=y.keys,p=y.freeze,h=t=>(t=>!s(t)&&o(d(t),(t=>t==y.prototype||s(d(t))),(()=>!0)))(t)&&0==(t=>i(g(t)))(t),l=JSON.stringify,v=JSON.parse,u=t=>l(t,((t,e)=>e instanceof Map?y.fromEntries([...e]):e)),w="/store",f=t=>new Map(t),C=(t,e)=>t?.get(e),S=(t,e,a)=>{return s(a)?(o=t,n=e,o?.delete(n),t):t?.set(e,a);var o,n},A=(t,e,a,s)=>{var o,n;return o=t,n=e,o?.has(n)||S(t,e,a()),C(t,e)},b=f(),m=f(),L="message",M=(t,a,y,d)=>{const{host:g,room:l}=a.partySocketOptions,{storeProtocol:f="https",storePath:M=w,messagePrefix:P=e}={...n(y)?{storeProtocol:y}:y},O=f+"://"+g+"/parties/"+a.name+"/"+l+M,E=async t=>await(await fetch(O,{...t?{method:"PUT",body:u(t)}:{},mode:"cors",cache:"no-store"})).json();return((t,e,a,n,i,y,d,g={},l=[])=>{let v,u,w,f=0,L=0,M=0;A(b,l,(()=>0)),A(m,l,(()=>[]));const[P,O,E,T,j]=((t=1,e)=>1!=t&&e.isMergeable()?[1,e.getMergeableContent,e.getTransactionMergeableChanges,([[t],[e]])=>!h(t)||!h(e),e.setDefaultContent]:2!=t?[0,e.getContent,e.getTransactionChanges,([t,e])=>!h(t)||!h(e),e.setContent]:c("Store type not supported by this Persister"))(d,t),k=e=>{(P&&r(e?.[0])?1===e?.[2]?t.applyMergeableChanges:t.setMergeableContent:1===e?.[2]?t.applyChanges:t.setContent)(e)},x=async t=>(2!=f&&(f=1,L++,await z((async()=>{try{const t=await e();r(t)?k(t):c("Content is not an array "+t)}catch(e){y?.(e),t&&j(t)}f=0}))),F),D=()=>(u&&(i(u),u=void 0),F),J=async t=>(1!=f&&(f=2,M++,await z((async()=>{try{await a(O,t)}catch(t){y?.(t)}f=0}))),F),N=()=>(o(w,t.delListener),w=void 0,F),z=async(...t)=>(((t,...e)=>{t.push(...e)})(C(m,l),...t),await(async()=>{if(!C(b,l)){for(S(b,l,1);!s((t=C(m,l),v=t.shift()));)try{await v()}catch(t){y?.(t)}S(b,l,0)}var t})(),F),F={load:x,startAutoLoad:async t=>{await D().load(t);try{u=await n((async(t,e)=>{e||t?2!=f&&(f=1,L++,k(e??t),f=0):await x()}))}catch(t){y?.(t)}return F},stopAutoLoad:D,isAutoLoading:()=>!s(u),save:J,startAutoSave:async()=>(await N().save(),w=t.addDidFinishTransactionListener((()=>{const t=E();T(t)&&J(t)})),F),stopAutoSave:N,isAutoSaving:()=>!s(w),schedule:z,getStore:()=>t,destroy:()=>(C(m,l).splice(0,void 0),D().stopAutoSave()),getStats:()=>({loads:L,saves:M}),...g};return p(F)})(t,(async()=>await E()),(async(t,e)=>{var s;e?a.send(P+"s"+(n(s=e)?s:u(s))):await E(t())}),(t=>{const e=e=>o(((t,e)=>{const a=i(t);return((t,e)=>t.startsWith(e))(e,t)?[e[a],v((s=e,o=a+1,s.slice(o,void 0)))]:void 0;var s,o})(P,e.data),(([e,a])=>{"s"==e&&t(void 0,a)}));return a.addEventListener(L,e),e}),(t=>{a.removeEventListener(L,t)}),d,1,{getConnection:()=>a})};export{M as createPartyKitPersister};
