import{existsSync as t,writeFileSync as a,watch as e}from"fs";import{readFile as s,writeFile as r}from"fs/promises";const n="utf8",o=t=>null==t,i=(t,a,e)=>o(t)?e?.():a(t),c=t=>Array.isArray(t),y=t=>{throw Error(t)},g=Object,l=t=>g.getPrototypeOf(t),p=g.keys,d=g.freeze,u=t=>(t=>!o(t)&&i(l(t),(t=>t==g.prototype||o(l(t))),(()=>!0)))(t)&&0==(t=>p(t).length)(t),h=JSON.stringify,v=JSON.parse,w=t=>new Map(t),f=(t,a)=>t?.get(a),C=(t,a,e)=>{return o(e)?(s=t,r=a,s?.delete(r),t):t?.set(a,e);var s,r},A=(t,a,e,s)=>{var r,n;return r=t,n=a,r?.has(n)||C(t,a,e()),f(t,a)},S=w(),b=w(),M=(g,l,p)=>((t,a,e,s,r,n,g,l={},p=[])=>{let h,v,w,M=0,m=0,L=0;A(S,p,(()=>0)),A(b,p,(()=>[]));const[O,P,T,D,F]=((t=1,a)=>1!=t&&a.isMergeable()?[1,a.getMergeableContent,a.getTransactionMergeableChanges,([[t],[a]])=>!u(t)||!u(a),a.setDefaultContent]:2!=t?[0,a.getContent,a.getTransactionChanges,([t,a])=>!u(t)||!u(a),a.setContent]:y("Store type not supported by this Persister"))(g,t),J=a=>{(O&&c(a?.[0])?1===a?.[2]?t.applyMergeableChanges:t.setMergeableContent:1===a?.[2]?t.applyChanges:t.setContent)(a)},N=async t=>(2!=M&&(M=1,m++,await z((async()=>{try{const t=await a();c(t)?J(t):y("Content is not an array "+t)}catch(a){n?.(a),t&&F(t)}M=0}))),E),j=()=>(v&&(r(v),v=void 0),E),k=async t=>(1!=M&&(M=2,L++,await z((async()=>{try{await e(P,t)}catch(t){n?.(t)}M=0}))),E),x=()=>(i(w,t.delListener),w=void 0,E),z=async(...t)=>(((t,...a)=>{t.push(...a)})(f(b,p),...t),await(async()=>{if(!f(S,p)){for(C(S,p,1);!o((t=f(b,p),h=t.shift()));)try{await h()}catch(t){n?.(t)}C(S,p,0)}var t})(),E),E={load:N,startAutoLoad:async t=>{await j().load(t);try{v=await s((async(t,a)=>{a||t?2!=M&&(M=1,m++,J(a??t),M=0):await N()}))}catch(t){n?.(t)}return E},stopAutoLoad:j,isAutoLoading:()=>!o(v),save:k,startAutoSave:async()=>(await x().save(),w=t.addDidFinishTransactionListener((()=>{const t=T();D(t)&&k(t)})),E),stopAutoSave:x,isAutoSaving:()=>!o(w),schedule:z,getStore:()=>t,destroy:()=>(f(b,p).splice(0,void 0),j().stopAutoSave()),getStats:()=>({loads:m,saves:L}),...l};return d(E)})(g,(async()=>{return t=await s(l,n),v(t,((t,a)=>"￼"===a?void 0:a));var t}),(async t=>{return await r(l,(a=t(),h(a,((t,a)=>void 0===a?"￼":a))),n);var a}),(s=>(t(l)||a(l,"",n),e(l,(()=>s())))),(t=>t?.close()),p,3,{getFilePath:()=>l});export{M as createFilePersister};
