UNPKG

y-op-sqlite

Version:

<p align="center"> <img src="https://cdn.malts.me/6Wu0Fj.svg" /> </p>

3 lines (2 loc) 2.52 kB
"use strict";var a=Object.defineProperty;var h=(r,t,e)=>t in r?a(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var n=(r,t,e)=>(h(r,typeof t!="symbol"?t+"":t,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("yjs"),f=require("@op-engineering/op-sqlite");function l(r){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const e in r)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(r,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:()=>r[e]})}}return t.default=r,Object.freeze(t)}const d=l(u),b=r=>new Promise(r);Promise.all.bind(Promise);const i=()=>new Map,p=(r,t,e)=>{let s=r.get(t);return s===void 0&&r.set(t,s=e()),s},y=()=>new Set,_=Array.from;class E{constructor(){this._observers=i()}on(t,e){return p(this._observers,t,y).add(e),e}once(t,e){const s=(...o)=>{this.off(t,s),e(...o)};this.on(t,s)}off(t,e){const s=this._observers.get(t);s!==void 0&&(s.delete(e),s.size===0&&this._observers.delete(t))}emit(t,e){return _((this._observers.get(t)||i()).values()).forEach(s=>s(...e))}destroy(){this._observers=i()}}const S=500,R="opssqlite-persistence-";class g extends E{constructor(e,s){super();n(this,"doc");n(this,"name");n(this,"whenSynced");n(this,"db");n(this,"synced",!1);n(this,"_dbref",0);n(this,"_dbsize",0);n(this,"_destroyed",!1);this.doc=s,this.name=e,this.whenSynced=b(o=>this.on("synced",()=>o(this))),this.db=f.open({name:R+e+".sqlite"}),this.db.executeAsync("CREATE TABLE IF NOT EXISTS updates (id INTEGER PRIMARY KEY, content BLOB)").then(()=>{const o=d.encodeStateAsUpdate(s);o.length>0&&this._storeUpdate(o,null)}).then(()=>this.db.executeAsync("SELECT content FROM updates").catch(o=>console.error("error loading updates",o))).then(o=>{if(o!=null&&o.rows!=null)for(const c of o.rows._array)d.applyUpdate(s,new Uint8Array(c.content));this.synced=!0,this.emit("synced",[this])}),this.destroy=this.destroy.bind(this),this._storeUpdate.bind(this),s.on("update",this._storeUpdate.bind(this)),s.on("destroy",this.destroy.bind(this))}_storeUpdate(e,s){if(!this.db||s==this){!this.db&&console.error("trying to store update without db");return}return this.db.executeAsync("INSERT INTO updates (content) VALUES (?)",[e]).catch(o=>console.error("error storing update",o))}destroy(){return this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this.db.close()}}exports.OPSQLitePersistence=g;exports.PREFERRED_TRIM_SIZE=S; //# sourceMappingURL=y-op-sqlite.cjs.map