@gamention/pulse-core 0.3.5 → 0.3.7

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.
@@ -6436,14 +6436,10 @@ class fc extends Ye {
6436
6436
  this.destroyed = !0, this.persistTimer && (clearInterval(this.persistTimer), this.persistTimer = null), this.dirty && this.persist(), this.doc.destroy(), this.removeAll();
6437
6437
  }
6438
6438
  broadcastUpdate(e) {
6439
- if (this.transport === "p2p")
6440
- this.config.sendP2P(e);
6441
- else {
6442
- let s = "";
6443
- for (let r = 0; r < e.length; r++)
6444
- s += String.fromCharCode(e[r]);
6445
- this.config.sendWS(btoa(s));
6446
- }
6439
+ let s = "";
6440
+ for (let r = 0; r < e.length; r++)
6441
+ s += String.fromCharCode(e[r]);
6442
+ this.config.sendWS(btoa(s)), this.transport === "p2p" && this.config.sendP2P(e);
6447
6443
  }
6448
6444
  }
6449
6445
  class gc {
@@ -6454,10 +6450,10 @@ class gc {
6454
6450
  this.ymap = t, this.observer = (e) => {
6455
6451
  const s = [];
6456
6452
  if (e.changes.keys.forEach((r, i) => {
6457
- r.action === "add" ? s.push({ action: "add", key: i, value: this.ymap.get(i) }) : r.action === "update" ? s.push({
6453
+ r.action === "add" ? s.push({ action: "add", key: i, value: this.get(i) }) : r.action === "update" ? s.push({
6458
6454
  action: "update",
6459
6455
  key: i,
6460
- value: this.ymap.get(i),
6456
+ value: this.get(i),
6461
6457
  oldValue: r.oldValue
6462
6458
  }) : r.action === "delete" && s.push({
6463
6459
  action: "delete",
@@ -6470,7 +6466,9 @@ class gc {
6470
6466
  }, this.ymap.observe(this.observer);
6471
6467
  }
6472
6468
  get(t) {
6473
- return this.ymap.get(t);
6469
+ const e = this.ymap.get(t);
6470
+ if (e !== void 0)
6471
+ return e && typeof e == "object" && typeof e.toJSON == "function" ? e.toJSON() : e;
6474
6472
  }
6475
6473
  set(t, e) {
6476
6474
  this.ymap.set(t, e);
@@ -6485,19 +6483,23 @@ class gc {
6485
6483
  return Array.from(this.ymap.keys());
6486
6484
  }
6487
6485
  values() {
6488
- return Array.from(this.ymap.values());
6486
+ return this.keys().map((t) => this.get(t));
6489
6487
  }
6490
6488
  entries() {
6491
- return Array.from(this.ymap.entries());
6489
+ return this.keys().map((t) => [t, this.get(t)]);
6492
6490
  }
6493
6491
  forEach(t) {
6494
- this.ymap.forEach(t);
6492
+ for (const e of this.keys())
6493
+ t(this.get(e), e);
6495
6494
  }
6496
6495
  get size() {
6497
6496
  return this.ymap.size;
6498
6497
  }
6499
6498
  toJSON() {
6500
- return this.ymap.toJSON();
6499
+ const t = {};
6500
+ for (const e of this.keys())
6501
+ t[e] = this.get(e);
6502
+ return t;
6501
6503
  }
6502
6504
  on(t, e) {
6503
6505
  return this.listeners.add(e), () => this.listeners.delete(e);
@@ -2,4 +2,4 @@
2
2
  `)}}const ze=(n,t)=>n===t?!0:n==null||t==null||n.constructor!==t.constructor?!1:n[xt]?Wn(n,t):ue(n)?Ke(n,e=>Jn(t,s=>ze(e,s))):Jr(n)?$t(n,(e,s)=>ze(e,t[s])):!1;class M{extends(t){let[e,s]=[this.shape,t.shape];return this.constructor._dilutes&&([s,e]=[e,s]),ze(e,s)}equals(t){return this.constructor===t.constructor&&Kt(this.shape,t.shape)}[oi](){return!0}[xt](t){return this.equals(t)}validate(t){return this.check(t)}check(t,e){$()}get nullable(){return St(this,be)}get optional(){return new es(this)}cast(t){return xn(t,this),t}expect(t){return xn(t,this),t}}y(M,"_dilutes",!1);class nn extends M{constructor(t,e){super(),this.shape=t,this._c=e}check(t,e=void 0){const s=(t==null?void 0:t.constructor)===this.shape&&(this._c==null||this._c(t));return!s&&(e==null||e.extend(null,this.shape.name,t==null?void 0:t.constructor.name,(t==null?void 0:t.constructor)!==this.shape?"Constructor match failed":"Check failed")),s}}const S=(n,t=null)=>new nn(n,t);S(nn);class sn extends M{constructor(t){super(),this.shape=t}check(t,e){const s=this.shape(t);return!s&&(e==null||e.extend(null,"custom prop",t==null?void 0:t.constructor.name,"failed to check custom prop")),s}}const A=n=>new sn(n);S(sn);class we extends M{constructor(t){super(),this.shape=t}check(t,e){const s=this.shape.some(r=>r===t);return!s&&(e==null||e.extend(null,this.shape.join(" | "),t.toString())),s}}const ye=(...n)=>new we(n),Qn=S(we),li=RegExp.escape||(n=>n.replace(/[().|&,$^[\]]/g,t=>"\\"+t)),ts=n=>{if(pt.check(n))return[li(n)];if(Qn.check(n))return n.shape.map(t=>t+"");if(as.check(n))return["[+-]?\\d+.?\\d*"];if(us.check(n))return[".*"];if(te.check(n))return n.shape.map(ts).flat(1);N()};class hi extends M{constructor(t){super(),this.shape=t,this._r=new RegExp("^"+t.map(ts).map(e=>`(${e.join("|")})`).join("")+"$")}check(t,e){const s=this._r.exec(t)!=null;return!s&&(e==null||e.extend(null,this._r.toString(),t.toString(),"String doesn't match string template.")),s}}S(hi);const ai=Symbol("optional");class es extends M{constructor(t){super(),this.shape=t}check(t,e){const s=t===void 0||this.shape.check(t);return!s&&(e==null||e.extend(null,"undefined (optional)","()")),s}get[ai](){return!0}}const ui=S(es);class di extends M{check(t,e){return e==null||e.extend(null,"never",typeof t),!1}}S(di);const ae=class ae extends M{constructor(t,e=!1){super(),this.shape=t,this._isPartial=e}get partial(){return new ae(this.shape,!0)}check(t,e){return t==null?(e==null||e.extend(null,"object","null"),!1):$t(this.shape,(s,r)=>{const i=this._isPartial&&!Qe(t,r)||s.check(t[r],e);return!i&&(e==null||e.extend(r.toString(),s.toString(),typeof t[r],"Object property does not match")),i})}};y(ae,"_dilutes",!0);let Qt=ae;const fi=n=>new Qt(n),gi=S(Qt),pi=A(n=>n!=null&&(n.constructor===Object||n.constructor==null));class ns extends M{constructor(t,e){super(),this.shape={keys:t,values:e}}check(t,e){return t!=null&&$t(t,(s,r)=>{const i=this.shape.keys.check(r,e);return!i&&(e==null||e.extend(r+"","Record",typeof t,i?"Key doesn't match schema":"Value doesn't match value")),i&&this.shape.values.check(s,e)})}}const ss=(n,t)=>new ns(n,t),wi=S(ns);class rs extends M{constructor(t){super(),this.shape=t}check(t,e){return t!=null&&$t(this.shape,(s,r)=>{const i=s.check(t[r],e);return!i&&(e==null||e.extend(r.toString(),"Tuple",typeof s)),i})}}const yi=(...n)=>new rs(n);S(rs);class is extends M{constructor(t){super(),this.shape=t.length===1?t[0]:new me(t)}check(t,e){const s=ue(t)&&Ke(t,r=>this.shape.check(r));return!s&&(e==null||e.extend(null,"Array","")),s}}const os=(...n)=>new is(n),mi=S(is),ki=A(n=>ue(n));class cs extends M{constructor(t,e){super(),this.shape=t,this._c=e}check(t,e){const s=t instanceof this.shape&&(this._c==null||this._c(t));return!s&&(e==null||e.extend(null,this.shape.name,t==null?void 0:t.constructor.name)),s}}const bi=(n,t=null)=>new cs(n,t);S(cs);const Si=bi(M);class _i extends M{constructor(t){super(),this.len=t.length-1,this.args=yi(...t.slice(-1)),this.res=t[this.len]}check(t,e){const s=t.constructor===Function&&t.length<=this.len;return!s&&(e==null||e.extend(null,"function",typeof t)),s}}const Ci=S(_i),Ei=A(n=>typeof n=="function");class Di extends M{constructor(t){super(),this.shape=t}check(t,e){const s=Ke(this.shape,r=>r.check(t,e));return!s&&(e==null||e.extend(null,"Intersectinon",typeof t)),s}}S(Di,n=>n.shape.length>0);class me extends M{constructor(t){super(),this.shape=t}check(t,e){const s=Jn(this.shape,r=>r.check(t,e));return e==null||e.extend(null,"Union",typeof t),s}}y(me,"_dilutes",!0);const St=(...n)=>n.findIndex(t=>te.check(t))>=0?St(...n.map(t=>Tt(t)).map(t=>te.check(t)?t.shape:[t]).flat(1)):n.length===1?n[0]:new me(n),te=S(me),ls=()=>!0,ee=A(ls),Ai=S(sn,n=>n.shape===ls),rn=A(n=>typeof n=="bigint"),Ii=A(n=>n===rn),hs=A(n=>typeof n=="symbol");A(n=>n===hs);const at=A(n=>typeof n=="number"),as=A(n=>n===at),pt=A(n=>typeof n=="string"),us=A(n=>n===pt),ke=A(n=>typeof n=="boolean"),Oi=A(n=>n===ke),ds=ye(void 0);S(we,n=>n.shape.length===1&&n.shape[0]===void 0);ye(void 0);const be=ye(null),Mi=S(we,n=>n.shape.length===1&&n.shape[0]===null);S(Uint8Array);S(nn,n=>n.shape===Uint8Array);const xi=St(at,pt,be,ds,rn,ke,hs);(()=>{const n=os(ee),t=ss(pt,ee),e=St(at,pt,be,ke,n,t);return n.shape=e,t.shape.values=e,e})();const Tt=n=>{if(Si.check(n))return n;if(pi.check(n)){const t={};for(const e in n)t[e]=Tt(n[e]);return fi(t)}else{if(ki.check(n))return St(...n.map(Tt));if(xi.check(n))return ye(n);if(Ei.check(n))return S(n)}N()},xn=Zr?()=>{}:(n,t)=>{const e=new ci;if(!t.check(n,e))throw B(`Expected value to be of type ${t.constructor.name}.
3
3
  ${e.toString()}`)};class Li{constructor(t){this.patterns=[],this.$state=t}if(t,e){return this.patterns.push({if:Tt(t),h:e}),this}else(t){return this.if(ee,t)}done(){return(t,e)=>{for(let s=0;s<this.patterns.length;s++){const r=this.patterns[s];if(r.if.check(t))return r.h(t,e)}throw B("Unhandled pattern")}}}const Ti=n=>new Li(n),fs=Ti(ee).if(as,(n,t)=>Le(t,bn,Xt)).if(us,(n,t)=>ii(t)).if(Oi,(n,t)=>Mn(t)).if(Ii,(n,t)=>BigInt(Le(t,bn,Xt))).if(te,(n,t)=>ot(t,Te(t,n.shape))).if(gi,(n,t)=>{const e={};for(const s in n.shape){let r=n.shape[s];if(ui.check(r)){if(Mn(t))continue;r=r.shape}e[s]=fs(r,t)}return e}).if(mi,(n,t)=>{const e=[],s=Zn(t,0,42);for(let r=0;r<s;r++)e.push(ot(t,n.shape));return e}).if(Qn,(n,t)=>Te(t,n.shape)).if(Mi,(n,t)=>null).if(Ci,(n,t)=>{const e=ot(t,n.res);return()=>e}).if(Ai,(n,t)=>ot(t,Te(t,[at,pt,be,ds,rn,ke,os(at),ss(St("a","b","c"),at)]))).if(wi,(n,t)=>{const e={},s=Le(t,0,3);for(let r=0;r<s;r++){const i=ot(t,n.shape.keys),o=ot(t,n.shape.values);e[i]=o}return e}).done(),ot=(n,t)=>fs(Tt(t),n),Se=typeof document<"u"?document:{};A(n=>n.nodeType===$i);typeof DOMParser<"u"&&new DOMParser;A(n=>n.nodeType===Ui);A(n=>n.nodeType===Ni);const vi=n=>er(n,(t,e)=>`${e}:${t};`).join(""),Ui=Se.ELEMENT_NODE,Ni=Se.TEXT_NODE,Ri=Se.DOCUMENT_NODE,$i=Se.DOCUMENT_FRAGMENT_NODE;A(n=>n.nodeType===Ri);const P=Symbol,gs=P(),ps=P(),Vi=P(),ji=P(),Fi=P(),ws=P(),Bi=P(),on=P(),Ji=P(),zi=n=>{var r;n.length===1&&((r=n[0])==null?void 0:r.constructor)===Function&&(n=n[0]());const t=[],e=[];let s=0;for(;s<n.length;s++){const i=n[s];if(i===void 0)break;if(i.constructor===String||i.constructor===Number)t.push(i);else if(i.constructor===Object)break}for(s>0&&e.push(t.join(""));s<n.length;s++){const i=n[s];i instanceof Symbol||e.push(i)}return e},Gi={[gs]:G("font-weight","bold"),[ps]:G("font-weight","normal"),[Vi]:G("color","blue"),[Fi]:G("color","green"),[ji]:G("color","grey"),[ws]:G("color","red"),[Bi]:G("color","purple"),[on]:G("color","orange"),[Ji]:G("color","black")},Hi=n=>{var o;n.length===1&&((o=n[0])==null?void 0:o.constructor)===Function&&(n=n[0]());const t=[],e=[],s=R();let r=[],i=0;for(;i<n.length;i++){const c=n[i],l=Gi[c];if(l!==void 0)s.set(l.left,l.right);else{if(c===void 0)break;if(c.constructor===String||c.constructor===Number){const h=vi(s);i>0||h.length>0?(t.push("%c"+c),e.push(h)):t.push(c)}else break}}for(i>0&&(r=e,r.unshift(t.join("")));i<n.length;i++){const c=n[i];c instanceof Symbol||r.push(c)}return r},ys=ti?Hi:zi,Pi=(...n)=>{console.log(...ys(n)),ms.forEach(t=>t.print(n))},Yi=(...n)=>{console.warn(...ys(n)),n.unshift(on),ms.forEach(t=>t.print(n))},ms=ft(),ks=n=>({[Symbol.iterator](){return this},next:n}),Ki=(n,t)=>ks(()=>{let e;do e=n.next();while(!e.done&&!t(e.value));return e}),ve=(n,t)=>ks(()=>{const{done:e,value:s}=n.next();return{done:e,value:e?void 0:t(s)}});class _e{constructor(t,e){this.clock=t,this.len=e}}class Vt{constructor(){this.clients=new Map}}const bs=(n,t,e)=>t.clients.forEach((s,r)=>{const i=n.doc.store.clients.get(r);if(i!=null){const o=i[i.length-1],c=o.id.clock+o.length;for(let l=0,h=s[l];l<s.length&&h.clock<c;h=s[++l])xs(n,i,h.clock,h.len,e)}}),Wi=(n,t)=>{let e=0,s=n.length-1;for(;e<=s;){const r=F((e+s)/2),i=n[r],o=i.clock;if(o<=t){if(t<o+i.len)return r;e=r+1}else s=r-1}return null},Ss=(n,t)=>{const e=n.clients.get(t.client);return e!==void 0&&Wi(e,t.clock)!==null},cn=n=>{n.clients.forEach(t=>{t.sort((r,i)=>r.clock-i.clock);let e,s;for(e=1,s=1;e<t.length;e++){const r=t[s-1],i=t[e];r.clock+r.len>=i.clock?t[s-1]=new _e(r.clock,st(r.len,i.clock+i.len-r.clock)):(s<e&&(t[s]=i),s++)}t.length=s})},Xi=n=>{const t=new Vt;for(let e=0;e<n.length;e++)n[e].clients.forEach((s,r)=>{if(!t.clients.has(r)){const i=s.slice();for(let o=e+1;o<n.length;o++)sr(i,n[o].clients.get(r)||[]);t.clients.set(r,i)}});return cn(t),t},ne=(n,t,e,s)=>{q(n.clients,t,()=>[]).push(new _e(e,s))},qi=()=>new Vt,Zi=n=>{const t=qi();return n.clients.forEach((e,s)=>{const r=[];for(let i=0;i<e.length;i++){const o=e[i];if(o.deleted){const c=o.id.clock;let l=o.length;if(i+1<e.length)for(let h=e[i+1];i+1<e.length&&h.deleted;h=e[++i+1])l+=h.length;r.push(new _e(c,l))}}r.length>0&&t.clients.set(s,r)}),t},_t=(n,t)=>{m(n.restEncoder,t.clients.size),Q(t.clients.entries()).sort((e,s)=>s[0]-e[0]).forEach(([e,s])=>{n.resetDsCurVal(),m(n.restEncoder,e);const r=s.length;m(n.restEncoder,r);for(let i=0;i<r;i++){const o=s[i];n.writeDsClock(o.clock),n.writeDsLen(o.len)}})},ln=n=>{const t=new Vt,e=p(n.restDecoder);for(let s=0;s<e;s++){n.resetDsCurVal();const r=p(n.restDecoder),i=p(n.restDecoder);if(i>0){const o=q(t.clients,r,()=>[]);for(let c=0;c<i;c++)o.push(new _e(n.readDsClock(),n.readDsLen()))}}return t},Ln=(n,t,e)=>{const s=new Vt,r=p(n.restDecoder);for(let i=0;i<r;i++){n.resetDsCurVal();const o=p(n.restDecoder),c=p(n.restDecoder),l=e.clients.get(o)||[],h=D(e,o);for(let a=0;a<c;a++){const u=n.readDsClock(),d=u+n.readDsLen();if(u<h){h<d&&ne(s,o,h,d-h);let f=J(l,u),g=l[f];for(!g.deleted&&g.id.clock<u&&(l.splice(f+1,0,he(t,g,u-g.id.clock)),f++);f<l.length&&(g=l[f++],g.id.clock<d);)g.deleted||(d<g.id.clock+g.length&&l.splice(f,0,he(t,g,d-g.id.clock)),g.delete(t))}else ne(s,o,u,d-u)}}if(s.clients.size>0){const i=new tt;return m(i.restEncoder,0),_t(i,s),i.toUint8Array()}return null},_s=Yn;class Ct extends ir{constructor({guid:t=Vr(),collectionid:e=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=_s(),this.guid=t,this.collectionid=e,this.share=new Map,this.store=new Os,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=In(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const l=()=>In(h=>{const a=u=>{(u===void 0||u===!0)&&(this.off("sync",a),h())};this.on("sync",a)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const t=this._item;t!==null&&!this.shouldLoad&&b(t.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Q(this.subdocs).map(t=>t.guid))}transact(t,e=null){return b(this,t,e)}get(t,e=I){const s=q(this.share,t,()=>{const i=new e;return i._integrate(this,null),i}),r=s.constructor;if(e!==I&&r!==e)if(r===I){const i=new e;i._map=s._map,s._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=s._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=s._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return s}getArray(t=""){return this.get(t,dt)}getText(t=""){return this.get(t,mt)}getMap(t=""){return this.get(t,yt)}getXmlElement(t=""){return this.get(t,kt)}getXmlFragment(t=""){return this.get(t,et)}toJSON(){const t={};return this.share.forEach((e,s)=>{t[s]=e.toJSON()}),t}destroy(){this.isDestroyed=!0,Q(this.subdocs).forEach(e=>e.destroy());const t=this._item;if(t!==null){this._item=null;const e=t.content;e.doc=new Ct({guid:this.guid,...e.opts,shouldLoad:!1}),e.doc._item=t,b(t.parent.doc,s=>{const r=e.doc;t.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Cs{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return p(this.restDecoder)}readDsLen(){return p(this.restDecoder)}}class Es extends Cs{readLeftID(){return w(p(this.restDecoder),p(this.restDecoder))}readRightID(){return w(p(this.restDecoder),p(this.restDecoder))}readClient(){return p(this.restDecoder)}readInfo(){return gt(this.restDecoder)}readString(){return ht(this.restDecoder)}readParentInfo(){return p(this.restDecoder)===1}readTypeRef(){return p(this.restDecoder)}readLen(){return p(this.restDecoder)}readAny(){return Mt(this.restDecoder)}readBuf(){return ni(L(this.restDecoder))}readJSON(){return JSON.parse(ht(this.restDecoder))}readKey(){return ht(this.restDecoder)}}class Qi{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=p(this.restDecoder),this.dsCurrVal}readDsLen(){const t=p(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class wt extends Qi{constructor(t){super(t),this.keys=[],p(t),this.keyClockDecoder=new xe(L(t)),this.clientDecoder=new Yt(L(t)),this.leftClockDecoder=new xe(L(t)),this.rightClockDecoder=new xe(L(t)),this.infoDecoder=new An(L(t),gt),this.stringDecoder=new Nr(L(t)),this.parentInfoDecoder=new An(L(t),gt),this.typeRefDecoder=new Yt(L(t)),this.lenDecoder=new Yt(L(t))}readLeftID(){return new ut(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ut(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Mt(this.restDecoder)}readBuf(){return L(this.restDecoder)}readJSON(){return Mt(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t<this.keys.length)return this.keys[t];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class to{constructor(){this.restEncoder=fe()}toUint8Array(){return j(this.restEncoder)}resetDsCurVal(){}writeDsClock(t){m(this.restEncoder,t)}writeDsLen(t){m(this.restEncoder,t)}}class jt extends to{writeLeftID(t){m(this.restEncoder,t.client),m(this.restEncoder,t.clock)}writeRightID(t){m(this.restEncoder,t.client),m(this.restEncoder,t.clock)}writeClient(t){m(this.restEncoder,t)}writeInfo(t){Fe(this.restEncoder,t)}writeString(t){lt(this.restEncoder,t)}writeParentInfo(t){m(this.restEncoder,t?1:0)}writeTypeRef(t){m(this.restEncoder,t)}writeLen(t){m(this.restEncoder,t)}writeAny(t){Ot(this.restEncoder,t)}writeBuf(t){x(this.restEncoder,t)}writeJSON(t){lt(this.restEncoder,JSON.stringify(t))}writeKey(t){lt(this.restEncoder,t)}}class eo{constructor(){this.restEncoder=fe(),this.dsCurrVal=0}toUint8Array(){return j(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(t){const e=t-this.dsCurrVal;this.dsCurrVal=t,m(this.restEncoder,e)}writeDsLen(t){t===0&&N(),m(this.restEncoder,t-1),this.dsCurrVal+=t}}class tt extends eo{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Me,this.clientEncoder=new Pt,this.leftClockEncoder=new Me,this.rightClockEncoder=new Me,this.infoEncoder=new Cn(Fe),this.stringEncoder=new Ar,this.parentInfoEncoder=new Cn(Fe),this.typeRefEncoder=new Pt,this.lenEncoder=new Pt}toUint8Array(){const t=fe();return m(t,0),x(t,this.keyClockEncoder.toUint8Array()),x(t,this.clientEncoder.toUint8Array()),x(t,this.leftClockEncoder.toUint8Array()),x(t,this.rightClockEncoder.toUint8Array()),x(t,j(this.infoEncoder)),x(t,this.stringEncoder.toUint8Array()),x(t,j(this.parentInfoEncoder)),x(t,this.typeRefEncoder.toUint8Array()),x(t,this.lenEncoder.toUint8Array()),ge(t,j(this.restEncoder)),j(t)}writeLeftID(t){this.clientEncoder.write(t.client),this.leftClockEncoder.write(t.clock)}writeRightID(t){this.clientEncoder.write(t.client),this.rightClockEncoder.write(t.clock)}writeClient(t){this.clientEncoder.write(t)}writeInfo(t){this.infoEncoder.write(t)}writeString(t){this.stringEncoder.write(t)}writeParentInfo(t){this.parentInfoEncoder.write(t?1:0)}writeTypeRef(t){this.typeRefEncoder.write(t)}writeLen(t){this.lenEncoder.write(t)}writeAny(t){Ot(this.restEncoder,t)}writeBuf(t){x(this.restEncoder,t)}writeJSON(t){Ot(this.restEncoder,t)}writeKey(t){const e=this.keyMap.get(t);e===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(t)):this.keyClockEncoder.write(e)}}const no=(n,t,e,s)=>{s=st(s,t[0].id.clock);const r=J(t,s);m(n.restEncoder,t.length-r),n.writeClient(e),m(n.restEncoder,s);const i=t[r];i.write(n,s-i.id.clock);for(let o=r+1;o<t.length;o++)t[o].write(n,0)},hn=(n,t,e)=>{const s=new Map;e.forEach((r,i)=>{D(t,i)>r&&s.set(i,r)}),an(t).forEach((r,i)=>{e.has(i)||s.set(i,0)}),m(n.restEncoder,s.size),Q(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{no(n,t.clients.get(r),r,i)})},so=(n,t)=>{const e=R(),s=p(n.restDecoder);for(let r=0;r<s;r++){const i=p(n.restDecoder),o=new Array(i),c=n.readClient();let l=p(n.restDecoder);e.set(c,{i:0,refs:o});for(let h=0;h<i;h++){const a=n.readInfo();switch(de&a){case 0:{const u=n.readLen();o[h]=new v(w(c,l),u),l+=u;break}case 10:{const u=p(n.restDecoder);o[h]=new U(w(c,l),u),l+=u;break}default:{const u=(a&(H|T))===0,d=new _(w(c,l),null,(a&T)===T?n.readLeftID():null,null,(a&H)===H?n.readRightID():null,u?n.readParentInfo()?t.get(n.readString()):n.readLeftID():null,u&&(a&At)===At?n.readString():null,Ws(n,a));o[h]=d,l+=d.length}}}}return e},ro=(n,t,e)=>{const s=[];let r=Q(e.keys()).sort((f,g)=>f-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let f=e.get(r[r.length-1]);for(;f.refs.length===f.i;)if(r.pop(),r.length>0)f=e.get(r[r.length-1]);else return null;return f};let o=i();if(o===null)return null;const c=new Os,l=new Map,h=(f,g)=>{const k=l.get(f);(k==null||k>g)&&l.set(f,g)};let a=o.refs[o.i++];const u=new Map,d=()=>{for(const f of s){const g=f.id.client,k=e.get(g);k?(k.i--,c.clients.set(g,k.refs.slice(k.i)),e.delete(g),k.i=0,k.refs=[]):c.clients.set(g,[f]),r=r.filter(it=>it!==g)}s.length=0};for(;;){if(a.constructor!==U){const g=q(u,a.id.client,()=>D(t,a.id.client))-a.id.clock;if(g<0)s.push(a),h(a.id.client,a.id.clock-1),d();else{const k=a.getMissing(n,t);if(k!==null){s.push(a);const it=e.get(k)||{refs:[],i:0};if(it.refs.length===it.i)h(k,D(t,k)),d();else{a=it.refs[it.i++];continue}}else(g===0||g<a.length)&&(a.integrate(n,g),u.set(a.id.client,a.id.clock+a.length))}}if(s.length>0)a=s.pop();else if(o!==null&&o.i<o.refs.length)a=o.refs[o.i++];else{if(o=i(),o===null)break;a=o.refs[o.i++]}}if(c.clients.size>0){const f=new tt;return hn(f,c,new Map),m(f.restEncoder,0),{missing:l,update:f.toUint8Array()}}return null},io=(n,t)=>hn(n,t.doc.store,t.beforeState),oo=(n,t,e,s=new wt(n))=>b(t,r=>{r.local=!1;let i=!1;const o=r.doc,c=o.store,l=so(s,o),h=ro(r,c,l),a=c.pendingStructs;if(a){for(const[d,f]of a.missing)if(f<D(c,d)){i=!0;break}if(h){for(const[d,f]of h.missing){const g=a.missing.get(d);(g==null||g>f)&&a.missing.set(d,f)}a.update=se([a.update,h.update])}}else c.pendingStructs=h;const u=Ln(s,r,c);if(c.pendingDs){const d=new wt(bt(c.pendingDs));p(d.restDecoder);const f=Ln(d,r,c);u&&f?c.pendingDs=se([u,f]):c.pendingDs=u||f}else c.pendingDs=u;if(i){const d=c.pendingStructs.update;c.pendingStructs=null,Ds(r.doc,d)}},e,!1),Ds=(n,t,e,s=wt)=>{const r=bt(t);oo(r,n,e,new s(r))},Ue=(n,t,e)=>Ds(n,t,e,Es),co=(n,t,e=new Map)=>{hn(n,t.store,e),_t(n,Zi(t.store))},lo=(n,t=new Uint8Array([0]),e=new tt)=>{const s=As(t);co(e,n,s);const r=[e.toUint8Array()];if(n.store.pendingDs&&r.push(n.store.pendingDs),n.store.pendingStructs&&r.push(_o(n.store.pendingStructs.update,t)),r.length>1){if(e.constructor===jt)return bo(r.map((i,o)=>o===0?i:Eo(i)));if(e.constructor===tt)return se(r)}return r[0]},ho=(n,t)=>lo(n,t,new jt),ao=n=>{const t=new Map,e=p(n.restDecoder);for(let s=0;s<e;s++){const r=p(n.restDecoder),i=p(n.restDecoder);t.set(r,i)}return t},As=n=>ao(new Cs(bt(n)));class uo{constructor(){this.l=[]}}const Tn=()=>new uo,vn=(n,t)=>n.l.push(t),Un=(n,t)=>{const e=n.l,s=e.length;n.l=e.filter(r=>t!==r),s===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Is=(n,t,e)=>tn(n.l,[t,e]);class ut{constructor(t,e){this.client=t,this.clock=e}}const Jt=(n,t)=>n===t||n!==null&&t!==null&&n.client===t.client&&n.clock===t.clock,w=(n,t)=>new ut(n,t),fo=n=>{for(const[t,e]of n.doc.share.entries())if(e===n)return t;throw N()},ct=(n,t)=>t===void 0?!n.deleted:t.sv.has(n.id.client)&&(t.sv.get(n.id.client)||0)>n.id.clock&&!Ss(t.ds,n.id),Ge=(n,t)=>{const e=q(n.meta,Ge,ft),s=n.doc.store;e.has(t)||(t.sv.forEach((r,i)=>{r<D(s,i)&&X(n,w(i,r))}),bs(n,t.ds,r=>{}),e.add(t))};class Os{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const an=n=>{const t=new Map;return n.clients.forEach((e,s)=>{const r=e[e.length-1];t.set(s,r.id.clock+r.length)}),t},D=(n,t)=>{const e=n.clients.get(t);if(e===void 0)return 0;const s=e[e.length-1];return s.id.clock+s.length},Ms=(n,t)=>{let e=n.clients.get(t.id.client);if(e===void 0)e=[],n.clients.set(t.id.client,e);else{const s=e[e.length-1];if(s.id.clock+s.length!==t.id.clock)throw N()}e.push(t)},J=(n,t)=>{let e=0,s=n.length-1,r=n[s],i=r.id.clock;if(i===t)return s;let o=F(t/(i+r.length-1)*s);for(;e<=s;){if(r=n[o],i=r.id.clock,i<=t){if(t<i+r.length)return o;e=o+1}else s=o-1;o=F((e+s)/2)}throw N()},go=(n,t)=>{const e=n.clients.get(t.client);return e[J(e,t.clock)]},Ne=go,He=(n,t,e)=>{const s=J(t,e),r=t[s];return r.id.clock<e&&r instanceof _?(t.splice(s+1,0,he(n,r,e-r.id.clock)),s+1):s},X=(n,t)=>{const e=n.doc.store.clients.get(t.client);return e[He(n,e,t.clock)]},Nn=(n,t,e)=>{const s=t.clients.get(e.client),r=J(s,e.clock),i=s[r];return e.clock!==i.id.clock+i.length-1&&i.constructor!==v&&s.splice(r+1,0,he(n,i,e.clock-i.id.clock+1)),i},po=(n,t,e)=>{const s=n.clients.get(t.id.client);s[J(s,t.id.clock)]=e},xs=(n,t,e,s,r)=>{if(s===0)return;const i=e+s;let o=He(n,t,e),c;do c=t[o++],i<c.id.clock+c.length&&He(n,t,i),r(c);while(o<t.length&&t[o].id.clock<i)};class wo{constructor(t,e,s){this.doc=t,this.deleteSet=new Vt,this.beforeState=an(t.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=e,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Rn=(n,t)=>t.deleteSet.clients.size===0&&!nr(t.afterState,(e,s)=>t.beforeState.get(s)!==e)?!1:(cn(t.deleteSet),io(n,t),_t(n,t.deleteSet),!0),$n=(n,t,e)=>{const s=t._item;(s===null||s.id.clock<(n.beforeState.get(s.id.client)||0)&&!s.deleted)&&q(n.changed,t,ft).add(e)},Wt=(n,t)=>{let e=n[t],s=n[t-1],r=t;for(;r>0;e=s,s=n[--r-1]){if(s.deleted===e.deleted&&s.constructor===e.constructor&&s.mergeWith(e)){e instanceof _&&e.parentSub!==null&&e.parent._map.get(e.parentSub)===e&&e.parent._map.set(e.parentSub,s);continue}break}const i=t-r;return i&&n.splice(t+1-i,i),i},yo=(n,t,e)=>{for(const[s,r]of n.clients.entries()){const i=t.clients.get(s);for(let o=r.length-1;o>=0;o--){const c=r[o],l=c.clock+c.len;for(let h=J(i,c.clock),a=i[h];h<i.length&&a.id.clock<l;a=i[++h]){const u=i[h];if(c.clock+c.len<=u.id.clock)break;u instanceof _&&u.deleted&&!u.keep&&e(u)&&u.gc(t,!1)}}}},mo=(n,t)=>{n.clients.forEach((e,s)=>{const r=t.clients.get(s);for(let i=e.length-1;i>=0;i--){const o=e[i],c=zn(r.length-1,1+J(r,o.clock+o.len-1));for(let l=c,h=r[l];l>0&&h.id.clock>=o.clock;h=r[l])l-=1+Wt(r,l)}})},Ls=(n,t)=>{if(t<n.length){const e=n[t],s=e.doc,r=s.store,i=e.deleteSet,o=e._mergeStructs;try{cn(i),e.afterState=an(e.doc.store),s.emit("beforeObserverCalls",[e,s]);const c=[];e.changed.forEach((l,h)=>c.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(e,l)})),c.push(()=>{e.changedParentTypes.forEach((l,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(l=l.filter(a=>a.target._item===null||!a.target._item.deleted),l.forEach(a=>{a.currentTarget=h,a._path=null}),l.sort((a,u)=>a.path.length-u.path.length),c.push(()=>{Is(h._dEH,l,e)}))}),c.push(()=>s.emit("afterTransaction",[e,s])),c.push(()=>{e._needFormattingCleanup&&Vo(e)})}),tn(c,[])}finally{s.gc&&yo(i,r,s.gcFilter),mo(i,r),e.afterState.forEach((a,u)=>{const d=e.beforeState.get(u)||0;if(d!==a){const f=r.clients.get(u),g=st(J(f,d),1);for(let k=f.length-1;k>=g;)k-=1+Wt(f,k)}});for(let a=o.length-1;a>=0;a--){const{client:u,clock:d}=o[a].id,f=r.clients.get(u),g=J(f,d);g+1<f.length&&Wt(f,g+1)>1||g>0&&Wt(f,g)}if(!e.local&&e.afterState.get(s.clientID)!==e.beforeState.get(s.clientID)&&(Pi(on,gs,"[yjs] ",ps,ws,"Changed the client-id because another client seems to be using it."),s.clientID=_s()),s.emit("afterTransactionCleanup",[e,s]),s._observers.has("update")){const a=new jt;Rn(a,e)&&s.emit("update",[a.toUint8Array(),e.origin,s,e])}if(s._observers.has("updateV2")){const a=new tt;Rn(a,e)&&s.emit("updateV2",[a.toUint8Array(),e.origin,s,e])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:h}=e;(c.size>0||h.size>0||l.size>0)&&(c.forEach(a=>{a.clientID=s.clientID,a.collectionid==null&&(a.collectionid=s.collectionid),s.subdocs.add(a)}),h.forEach(a=>s.subdocs.delete(a)),s.emit("subdocs",[{loaded:l,added:c,removed:h},s,e]),h.forEach(a=>a.destroy())),n.length<=t+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,n])):Ls(n,t+1)}}},b=(n,t,e=null,s=!0)=>{const r=n._transactionCleanups;let i=!1,o=null;n._transaction===null&&(i=!0,n._transaction=new wo(n,e,s),r.push(n._transaction),r.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=t(n._transaction)}finally{if(i){const c=n._transaction===r[0];n._transaction=null,c&&Ls(r,0)}}return o};function*ko(n){const t=p(n.restDecoder);for(let e=0;e<t;e++){const s=p(n.restDecoder),r=n.readClient();let i=p(n.restDecoder);for(let o=0;o<s;o++){const c=n.readInfo();if(c===10){const l=p(n.restDecoder);yield new U(w(r,i),l),i+=l}else if((de&c)!==0){const l=(c&(H|T))===0,h=new _(w(r,i),null,(c&T)===T?n.readLeftID():null,null,(c&H)===H?n.readRightID():null,l?n.readParentInfo()?n.readString():n.readLeftID():null,l&&(c&At)===At?n.readString():null,Ws(n,c));yield h,i+=h.length}else{const l=n.readLen();yield new v(w(r,i),l),i+=l}}}}class un{constructor(t,e){this.gen=ko(t),this.curr=null,this.done=!1,this.filterSkips=e,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===U);return this.curr}}class dn{constructor(t){this.currClient=0,this.startClock=0,this.written=0,this.encoder=t,this.clientStructs=[]}}const bo=n=>se(n,Es,jt),So=(n,t)=>{if(n.constructor===v){const{client:e,clock:s}=n.id;return new v(w(e,s+t),n.length-t)}else if(n.constructor===U){const{client:e,clock:s}=n.id;return new U(w(e,s+t),n.length-t)}else{const e=n,{client:s,clock:r}=e.id;return new _(w(s,r+t),null,w(s,r+t-1),null,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t))}},se=(n,t=wt,e=tt)=>{if(n.length===1)return n[0];const s=n.map(a=>new t(bt(a)));let r=s.map(a=>new un(a,!0)),i=null;const o=new e,c=new dn(o);for(;r=r.filter(d=>d.curr!==null),r.sort((d,f)=>{if(d.curr.id.client===f.curr.id.client){const g=d.curr.id.clock-f.curr.id.clock;return g===0?d.curr.constructor===f.curr.constructor?0:d.curr.constructor===U?1:-1:g}else return f.curr.id.client-d.curr.id.client}),r.length!==0;){const a=r[0],u=a.curr.id.client;if(i!==null){let d=a.curr,f=!1;for(;d!==null&&d.id.clock+d.length<=i.struct.id.clock+i.struct.length&&d.id.client>=i.struct.id.client;)d=a.next(),f=!0;if(d===null||d.id.client!==u||f&&d.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)K(c,i.struct,i.offset),i={struct:d,offset:0},a.next();else if(i.struct.id.clock+i.struct.length<d.id.clock)if(i.struct.constructor===U)i.struct.length=d.id.clock+d.length-i.struct.id.clock;else{K(c,i.struct,i.offset);const g=d.id.clock-i.struct.id.clock-i.struct.length;i={struct:new U(w(u,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-d.id.clock;g>0&&(i.struct.constructor===U?i.struct.length-=g:d=So(d,g)),i.struct.mergeWith(d)||(K(c,i.struct,i.offset),i={struct:d,offset:0},a.next())}}else i={struct:a.curr,offset:0},a.next();for(let d=a.curr;d!==null&&d.id.client===u&&d.id.clock===i.struct.id.clock+i.struct.length&&d.constructor!==U;d=a.next())K(c,i.struct,i.offset),i={struct:d,offset:0}}i!==null&&(K(c,i.struct,i.offset),i=null),fn(c);const l=s.map(a=>ln(a)),h=Xi(l);return _t(o,h),o.toUint8Array()},_o=(n,t,e=wt,s=tt)=>{const r=As(t),i=new s,o=new dn(i),c=new e(bt(n)),l=new un(c,!1);for(;l.curr;){const a=l.curr,u=a.id.client,d=r.get(u)||0;if(l.curr.constructor===U){l.next();continue}if(a.id.clock+a.length>d)for(K(o,a,st(d-a.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)K(o,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=d;)l.next()}fn(o);const h=ln(c);return _t(i,h),i.toUint8Array()},Ts=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:j(n.encoder.restEncoder)}),n.encoder.restEncoder=fe(),n.written=0)},K=(n,t,e)=>{n.written>0&&n.currClient!==t.id.client&&Ts(n),n.written===0&&(n.currClient=t.id.client,n.encoder.writeClient(t.id.client),m(n.encoder.restEncoder,t.id.clock+e)),t.write(n.encoder,e),n.written++},fn=n=>{Ts(n);const t=n.encoder.restEncoder;m(t,n.clientStructs.length);for(let e=0;e<n.clientStructs.length;e++){const s=n.clientStructs[e];m(t,s.written),ge(t,s.restEncoder)}},Co=(n,t,e,s)=>{const r=new e(bt(n)),i=new un(r,!1),o=new s,c=new dn(o);for(let h=i.curr;h!==null;h=i.next())K(c,t(h),0);fn(c);const l=ln(r);return _t(o,l),o.toUint8Array()},Eo=n=>Co(n,Wr,wt,jt),Vn="You must not compute changes after the event-handler fired.";class Ce{constructor(t,e){this.target=t,this.currentTarget=t,this.transaction=e,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Do(this.currentTarget,this.target))}deletes(t){return Ss(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw B(Vn);const t=new Map,e=this.target;this.transaction.changed.get(e).forEach(r=>{if(r!==null){const i=e._map.get(r);let o,c;if(this.adds(i)){let l=i.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(i))if(l!==null&&this.deletes(l))o="delete",c=Ae(l.content.getContent());else return;else l!==null&&this.deletes(l)?(o="update",c=Ae(l.content.getContent())):(o="add",c=void 0)}else if(this.deletes(i))o="delete",c=Ae(i.content.getContent());else return;t.set(r,{action:o,oldValue:c})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw B(Vn);const e=this.target,s=ft(),r=ft(),i=[];if(t={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(e).has(null)){let c=null;const l=()=>{c&&i.push(c)};for(let h=e._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((c===null||c.delete===void 0)&&(l(),c={delete:0}),c.delete+=h.length,r.add(h)):this.adds(h)?((c===null||c.insert===void 0)&&(l(),c={insert:[]}),c.insert=c.insert.concat(h.content.getContent()),s.add(h)):((c===null||c.retain===void 0)&&(l(),c={retain:0}),c.retain+=h.length);c!==null&&c.retain===void 0&&l()}this._changes=t}return t}}const Do=(n,t)=>{const e=[];for(;t._item!==null&&t!==n;){if(t._item.parentSub!==null)e.unshift(t._item.parentSub);else{let s=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;e.unshift(s)}t=t._item.parent}return e},O=()=>{Yi("Invalid access: Add Yjs type to a document before reading data.")},vs=80;let gn=0;class Ao{constructor(t,e){t.marker=!0,this.p=t,this.index=e,this.timestamp=gn++}}const Io=n=>{n.timestamp=gn++},Us=(n,t,e)=>{n.p.marker=!1,n.p=t,t.marker=!0,n.index=e,n.timestamp=gn++},Oo=(n,t,e)=>{if(n.length>=vs){const s=n.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Us(s,t,e),s}else{const s=new Ao(t,e);return n.push(s),s}},Ee=(n,t)=>{if(n._start===null||t===0||n._searchMarker===null)return null;const e=n._searchMarker.length===0?null:n._searchMarker.reduce((i,o)=>Ht(t-i.index)<Ht(t-o.index)?i:o);let s=n._start,r=0;for(e!==null&&(s=e.p,r=e.index,Io(e));s.right!==null&&r<t;){if(!s.deleted&&s.countable){if(t<r+s.length)break;r+=s.length}s=s.right}for(;s.left!==null&&r>t;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return e!==null&&Ht(e.index-r)<s.parent.length/vs?(Us(e,s,r),e):Oo(n._searchMarker,s,r)},vt=(n,t,e)=>{for(let s=n.length-1;s>=0;s--){const r=n[s];if(e>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){n.splice(s,1);continue}r.p=i,i.marker=!0}(t<r.index||e>0&&t===r.index)&&(r.index=st(t,r.index+e))}},De=(n,t,e)=>{const s=n,r=t.changedParentTypes;for(;q(r,n,()=>[]).push(e),n._item!==null;)n=n._item.parent;Is(s._eH,e,t)};class I{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Tn(),this._dEH=Tn(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,e){this.doc=t,this._item=e}_copy(){throw $()}clone(){throw $()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,e){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){vn(this._eH,t)}observeDeep(t){vn(this._dEH,t)}unobserve(t){Un(this._eH,t)}unobserveDeep(t){Un(this._dEH,t)}toJSON(){}}const Ns=(n,t,e)=>{n.doc??O(),t<0&&(t=n._length+t),e<0&&(e=n._length+e);let s=e-t;const r=[];let i=n._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let c=t;c<o.length&&s>0;c++)r.push(o[c]),s--;t=0}}i=i.right}return r},Rs=n=>{n.doc??O();const t=[];let e=n._start;for(;e!==null;){if(e.countable&&!e.deleted){const s=e.content.getContent();for(let r=0;r<s.length;r++)t.push(s[r])}e=e.right}return t},Ut=(n,t)=>{let e=0,s=n._start;for(n.doc??O();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)t(r[i],e++,n)}s=s.right}},$s=(n,t)=>{const e=[];return Ut(n,(s,r)=>{e.push(t(s,r,n))}),e},Mo=n=>{let t=n._start,e=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(e===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};e=t.content.getContent(),s=0,t=t.right}const r=e[s++];return e.length<=s&&(e=null),{done:!1,value:r}}}},Vs=(n,t)=>{n.doc??O();const e=Ee(n,t);let s=n._start;for(e!==null&&(s=e.p,t-=e.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(t<s.length)return s.content.getContent()[t];t-=s.length}},re=(n,t,e,s)=>{let r=e;const i=n.doc,o=i.clientID,c=i.store,l=e===null?t._start:e.right;let h=[];const a=()=>{h.length>0&&(r=new _(w(o,D(c,o)),r,r&&r.lastId,l,l&&l.id,t,null,new nt(h)),r.integrate(n,0),h=[])};s.forEach(u=>{if(u===null)h.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(u);break;default:switch(a(),u.constructor){case Uint8Array:case ArrayBuffer:r=new _(w(o,D(c,o)),r,r&&r.lastId,l,l&&l.id,t,null,new Ft(new Uint8Array(u))),r.integrate(n,0);break;case Ct:r=new _(w(o,D(c,o)),r,r&&r.lastId,l,l&&l.id,t,null,new Bt(u)),r.integrate(n,0);break;default:if(u instanceof I)r=new _(w(o,D(c,o)),r,r&&r.lastId,l,l&&l.id,t,null,new Y(u)),r.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),a()},js=()=>B("Length exceeded!"),Fs=(n,t,e,s)=>{if(e>t._length)throw js();if(e===0)return t._searchMarker&&vt(t._searchMarker,e,s.length),re(n,t,null,s);const r=e,i=Ee(t,e);let o=t._start;for(i!==null&&(o=i.p,e-=i.index,e===0&&(o=o.prev,e+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(e<=o.length){e<o.length&&X(n,w(o.id.client,o.id.clock+e));break}e-=o.length}return t._searchMarker&&vt(t._searchMarker,r,s.length),re(n,t,o,s)},xo=(n,t,e)=>{let r=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return re(n,t,r,e)},Bs=(n,t,e,s)=>{if(s===0)return;const r=e,i=s,o=Ee(t,e);let c=t._start;for(o!==null&&(c=o.p,e-=o.index);c!==null&&e>0;c=c.right)!c.deleted&&c.countable&&(e<c.length&&X(n,w(c.id.client,c.id.clock+e)),e-=c.length);for(;s>0&&c!==null;)c.deleted||(s<c.length&&X(n,w(c.id.client,c.id.clock+s)),c.delete(n),s-=c.length),c=c.right;if(s>0)throw js();t._searchMarker&&vt(t._searchMarker,r,-i+s)},ie=(n,t,e)=>{const s=t._map.get(e);s!==void 0&&s.delete(n)},pn=(n,t,e,s)=>{const r=t._map.get(e)||null,i=n.doc,o=i.clientID;let c;if(s==null)c=new nt([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new nt([s]);break;case Uint8Array:c=new Ft(s);break;case Ct:c=new Bt(s);break;default:if(s instanceof I)c=new Y(s);else throw new Error("Unexpected content type")}new _(w(o,D(i.store,o)),r,r&&r.lastId,null,null,t,e,c).integrate(n,0)},wn=(n,t)=>{n.doc??O();const e=n._map.get(t);return e!==void 0&&!e.deleted?e.content.getContent()[e.length-1]:void 0},Js=n=>{const t={};return n.doc??O(),n._map.forEach((e,s)=>{e.deleted||(t[s]=e.content.getContent()[e.length-1])}),t},zs=(n,t)=>{n.doc??O();const e=n._map.get(t);return e!==void 0&&!e.deleted},Lo=(n,t)=>{const e={};return n._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&ct(i,t)&&(e[r]=i.content.getContent()[i.length-1])}),e},zt=n=>(n.doc??O(),Ki(n._map.entries(),t=>!t[1].deleted));class To extends Ce{}class dt extends I{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const e=new dt;return e.push(t),e}_integrate(t,e){super._integrate(t,e),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new dt}clone(){const t=new dt;return t.insert(0,this.toArray().map(e=>e instanceof I?e.clone():e)),t}get length(){return this.doc??O(),this._length}_callObserver(t,e){super._callObserver(t,e),De(this,t,new To(this,t))}insert(t,e){this.doc!==null?b(this.doc,s=>{Fs(s,this,t,e)}):this._prelimContent.splice(t,0,...e)}push(t){this.doc!==null?b(this.doc,e=>{xo(e,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,e=1){this.doc!==null?b(this.doc,s=>{Bs(s,this,t,e)}):this._prelimContent.splice(t,e)}get(t){return Vs(this,t)}toArray(){return Rs(this)}slice(t=0,e=this.length){return Ns(this,t,e)}toJSON(){return this.map(t=>t instanceof I?t.toJSON():t)}map(t){return $s(this,t)}forEach(t){Ut(this,t)}[Symbol.iterator](){return Mo(this)}_write(t){t.writeTypeRef(sc)}}const vo=n=>new dt;class Uo extends Ce{constructor(t,e,s){super(t,e),this.keysChanged=s}}class yt extends I{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,e){super._integrate(t,e),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new yt}clone(){const t=new yt;return this.forEach((e,s)=>{t.set(s,e instanceof I?e.clone():e)}),t}_callObserver(t,e){De(this,t,new Uo(this,t,e))}toJSON(){this.doc??O();const t={};return this._map.forEach((e,s)=>{if(!e.deleted){const r=e.content.getContent()[e.length-1];t[s]=r instanceof I?r.toJSON():r}}),t}get size(){return[...zt(this)].length}keys(){return ve(zt(this),t=>t[0])}values(){return ve(zt(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return ve(zt(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??O(),this._map.forEach((e,s)=>{e.deleted||t(e.content.getContent()[e.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?b(this.doc,e=>{ie(e,this,t)}):this._prelimContent.delete(t)}set(t,e){return this.doc!==null?b(this.doc,s=>{pn(s,this,t,e)}):this._prelimContent.set(t,e),e}get(t){return wn(this,t)}has(t){return zs(this,t)}clear(){this.doc!==null?b(this.doc,t=>{this.forEach(function(e,s,r){ie(t,r,s)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(rc)}}const No=n=>new yt,W=(n,t)=>n===t||typeof n=="object"&&typeof t=="object"&&n&&t&&Yr(n,t);class Pe{constructor(t,e,s,r){this.left=t,this.right=e,this.index=s,this.currentAttributes=r}forward(){switch(this.right===null&&N(),this.right.content.constructor){case C:this.right.deleted||Et(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const jn=(n,t,e)=>{for(;t.right!==null&&e>0;){switch(t.right.content.constructor){case C:t.right.deleted||Et(t.currentAttributes,t.right.content);break;default:t.right.deleted||(e<t.right.length&&X(n,w(t.right.id.client,t.right.id.clock+e)),t.index+=t.right.length,e-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Gt=(n,t,e,s)=>{const r=new Map,i=s?Ee(t,e):null;if(i){const o=new Pe(i.p.left,i.p,i.index,r);return jn(n,o,e-i.index)}else{const o=new Pe(null,t._start,0,r);return jn(n,o,e)}},Gs=(n,t,e,s)=>{for(;e.right!==null&&(e.right.deleted===!0||e.right.content.constructor===C&&W(s.get(e.right.content.key),e.right.content.value));)e.right.deleted||s.delete(e.right.content.key),e.forward();const r=n.doc,i=r.clientID;s.forEach((o,c)=>{const l=e.left,h=e.right,a=new _(w(i,D(r.store,i)),l,l&&l.lastId,h,h&&h.id,t,null,new C(c,o));a.integrate(n,0),e.right=a,e.forward()})},Et=(n,t)=>{const{key:e,value:s}=t;s===null?n.delete(e):n.set(e,s)},Hs=(n,t)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===C&&W(t[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},Ps=(n,t,e,s)=>{const r=n.doc,i=r.clientID,o=new Map;for(const c in s){const l=s[c],h=e.currentAttributes.get(c)??null;if(!W(h,l)){o.set(c,h);const{left:a,right:u}=e;e.right=new _(w(i,D(r.store,i)),a,a&&a.lastId,u,u&&u.id,t,null,new C(c,l)),e.right.integrate(n,0),e.forward()}}return o},Re=(n,t,e,s,r)=>{e.currentAttributes.forEach((d,f)=>{r[f]===void 0&&(r[f]=null)});const i=n.doc,o=i.clientID;Hs(e,r);const c=Ps(n,t,e,r),l=s.constructor===String?new z(s):s instanceof I?new Y(s):new rt(s);let{left:h,right:a,index:u}=e;t._searchMarker&&vt(t._searchMarker,e.index,l.getLength()),a=new _(w(o,D(i.store,o)),h,h&&h.lastId,a,a&&a.id,t,null,l),a.integrate(n,0),e.right=a,e.index=u,e.forward(),Gs(n,t,e,c)},Fn=(n,t,e,s,r)=>{const i=n.doc,o=i.clientID;Hs(e,r);const c=Ps(n,t,e,r);t:for(;e.right!==null&&(s>0||c.size>0&&(e.right.deleted||e.right.content.constructor===C));){if(!e.right.deleted)switch(e.right.content.constructor){case C:{const{key:l,value:h}=e.right.content,a=r[l];if(a!==void 0){if(W(a,h))c.delete(l);else{if(s===0)break t;c.set(l,h)}e.right.delete(n)}else e.currentAttributes.set(l,h);break}default:s<e.right.length&&X(n,w(e.right.id.client,e.right.id.clock+s)),s-=e.right.length;break}e.forward()}if(s>0){let l="";for(;s>0;s--)l+=`
4
4
  `;e.right=new _(w(o,D(i.store,o)),e.left,e.left&&e.left.lastId,e.right,e.right&&e.right.id,t,null,new z(l)),e.right.integrate(n,0),e.forward()}Gs(n,t,e,c)},Ys=(n,t,e,s,r)=>{let i=t;const o=R();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===C){const h=i.content;o.set(h.key,h)}i=i.right}let c=0,l=!1;for(;t!==i;){if(e===t&&(l=!0),!t.deleted){const h=t.content;switch(h.constructor){case C:{const{key:a,value:u}=h,d=s.get(a)??null;(o.get(a)!==h||d===u)&&(t.delete(n),c++,!l&&(r.get(a)??null)===u&&d!==u&&(d===null?r.delete(a):r.set(a,d))),!l&&!t.deleted&&Et(r,h);break}}}t=t.right}return c},Ro=(n,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const e=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===C){const s=t.content.key;e.has(s)?t.delete(n):e.add(s)}t=t.left}},$o=n=>{let t=0;return b(n.doc,e=>{let s=n._start,r=n._start,i=R();const o=Ve(i);for(;r;){if(r.deleted===!1)switch(r.content.constructor){case C:Et(o,r.content);break;default:t+=Ys(e,s,r,i,o),i=Ve(o),s=r;break}r=r.right}}),t},Vo=n=>{const t=new Set,e=n.doc;for(const[s,r]of n.afterState.entries()){const i=n.beforeState.get(s)||0;r!==i&&xs(n,e.store.clients.get(s),i,r,o=>{!o.deleted&&o.content.constructor===C&&o.constructor!==v&&t.add(o.parent)})}b(e,s=>{bs(n,n.deleteSet,r=>{if(r instanceof v||!r.parent._hasFormatting||t.has(r.parent))return;const i=r.parent;r.content.constructor===C?t.add(i):Ro(s,r)});for(const r of t)$o(r)})},Bn=(n,t,e)=>{const s=e,r=Ve(t.currentAttributes),i=t.right;for(;e>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Y:case rt:case z:e<t.right.length&&X(n,w(t.right.id.client,t.right.id.clock+e)),e-=t.right.length,t.right.delete(n);break}t.forward()}i&&Ys(n,i,t.right,r,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&vt(o._searchMarker,t.index,-s+e),t};class jo extends Ce{constructor(t,e,s){super(t,e),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(r=>{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,e=[];b(t,s=>{const r=new Map,i=new Map;let o=this.target._start,c=null;const l={};let h="",a=0,u=0;const d=()=>{if(c!==null){let f=null;switch(c){case"delete":u>0&&(f={delete:u}),u=0;break;case"insert":(typeof h=="object"||h.length>0)&&(f={insert:h},r.size>0&&(f.attributes={},r.forEach((g,k)=>{g!==null&&(f.attributes[k]=g)}))),h="";break;case"retain":a>0&&(f={retain:a},Pr(l)||(f.attributes=zr({},l))),a=0;break}f&&e.push(f),c=null}};for(;o!==null;){switch(o.content.constructor){case Y:case rt:this.adds(o)?this.deletes(o)||(d(),c="insert",h=o.content.getContent()[0],d()):this.deletes(o)?(c!=="delete"&&(d(),c="delete"),u+=1):o.deleted||(c!=="retain"&&(d(),c="retain"),a+=1);break;case z:this.adds(o)?this.deletes(o)||(c!=="insert"&&(d(),c="insert"),h+=o.content.str):this.deletes(o)?(c!=="delete"&&(d(),c="delete"),u+=o.length):o.deleted||(c!=="retain"&&(d(),c="retain"),a+=o.length);break;case C:{const{key:f,value:g}=o.content;if(this.adds(o)){if(!this.deletes(o)){const k=r.get(f)??null;W(k,g)?g!==null&&o.delete(s):(c==="retain"&&d(),W(g,i.get(f)??null)?delete l[f]:l[f]=g)}}else if(this.deletes(o)){i.set(f,g);const k=r.get(f)??null;W(k,g)||(c==="retain"&&d(),l[f]=k)}else if(!o.deleted){i.set(f,g);const k=l[f];k!==void 0&&(W(k,g)?k!==null&&o.delete(s):(c==="retain"&&d(),g===null?delete l[f]:l[f]=g))}o.deleted||(c==="insert"&&d(),Et(r,o.content));break}}o=o.right}for(d();e.length>0;){const f=e[e.length-1];if(f.retain!==void 0&&f.attributes===void 0)e.pop();else break}}),this._delta=e}return this._delta}}class mt extends I{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??O(),this._length}_integrate(t,e){super._integrate(t,e);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new mt}clone(){const t=new mt;return t.applyDelta(this.toDelta()),t}_callObserver(t,e){super._callObserver(t,e);const s=new jo(this,t,e);De(this,t,s),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??O();let t="",e=this._start;for(;e!==null;)!e.deleted&&e.countable&&e.content.constructor===z&&(t+=e.content.str),e=e.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:e=!0}={}){this.doc!==null?b(this.doc,s=>{const r=new Pe(null,this._start,0,new Map);for(let i=0;i<t.length;i++){const o=t[i];if(o.insert!==void 0){const c=!e&&typeof o.insert=="string"&&i===t.length-1&&r.right===null&&o.insert.slice(-1)===`
5
- `?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&Re(s,this,r,c,o.attributes||{})}else o.retain!==void 0?Fn(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Bn(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,e,s){this.doc??O();const r=[],i=new Map,o=this.doc;let c="",l=this._start;function h(){if(c.length>0){const u={};let d=!1;i.forEach((g,k)=>{d=!0,u[k]=g});const f={insert:c};d&&(f.attributes=u),r.push(f),c=""}}const a=()=>{for(;l!==null;){if(ct(l,t)||e!==void 0&&ct(l,e))switch(l.content.constructor){case z:{const u=i.get("ychange");t!==void 0&&!ct(l,t)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",l.id):{type:"removed"})):e!==void 0&&!ct(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",l.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),c+=l.content.str;break}case Y:case rt:{h();const u={insert:l.content.getContent()[0]};if(i.size>0){const d={};u.attributes=d,i.forEach((f,g)=>{d[g]=f})}r.push(u);break}case C:ct(l,t)&&(h(),Et(i,l.content));break}l=l.right}h()};return t||e?b(o,u=>{t&&Ge(u,t),e&&Ge(u,e),a()},"cleanup"):a(),r}insert(t,e,s){if(e.length<=0)return;const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!s);s||(s={},o.currentAttributes.forEach((c,l)=>{s[l]=c})),Re(i,this,o,e,s)}):this._pending.push(()=>this.insert(t,e,s))}insertEmbed(t,e,s){const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!s);Re(i,this,o,e,s||{})}):this._pending.push(()=>this.insertEmbed(t,e,s||{}))}delete(t,e){if(e===0)return;const s=this.doc;s!==null?b(s,r=>{Bn(r,Gt(r,this,t,!0),e)}):this._pending.push(()=>this.delete(t,e))}format(t,e,s){if(e===0)return;const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!1);o.right!==null&&Fn(i,this,o,e,s)}):this._pending.push(()=>this.format(t,e,s))}removeAttribute(t){this.doc!==null?b(this.doc,e=>{ie(e,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,e){this.doc!==null?b(this.doc,s=>{pn(s,this,t,e)}):this._pending.push(()=>this.setAttribute(t,e))}getAttribute(t){return wn(this,t)}getAttributes(){return Js(this)}_write(t){t.writeTypeRef(ic)}}const Fo=n=>new mt;class $e{constructor(t,e=()=>!0){this._filter=e,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??O()}[Symbol.iterator](){return this}next(){let t=this._currentNode,e=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(e)))do if(e=t.content.type,!t.deleted&&(e.constructor===kt||e.constructor===et)&&e._start!==null)t=e._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class et extends I{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,e){super._integrate(t,e),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new et}clone(){const t=new et;return t.insert(0,this.toArray().map(e=>e instanceof I?e.clone():e)),t}get length(){return this.doc??O(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new $e(this,t)}querySelector(t){t=t.toUpperCase();const s=new $e(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Q(new $e(this,e=>e.nodeName&&e.nodeName.toUpperCase()===t))}_callObserver(t,e){De(this,t,new zo(this,e,t))}toString(){return $s(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,e={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),Ut(this,i=>{r.insertBefore(i.toDOM(t,e,s),null)}),r}insert(t,e){this.doc!==null?b(this.doc,s=>{Fs(s,this,t,e)}):this._prelimContent.splice(t,0,...e)}insertAfter(t,e){if(this.doc!==null)b(this.doc,s=>{const r=t&&t instanceof I?t._item:t;re(s,this,r,e)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw B("Reference item not found");s.splice(r,0,...e)}}delete(t,e=1){this.doc!==null?b(this.doc,s=>{Bs(s,this,t,e)}):this._prelimContent.splice(t,e)}toArray(){return Rs(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Vs(this,t)}slice(t=0,e=this.length){return Ns(this,t,e)}forEach(t){Ut(this,t)}_write(t){t.writeTypeRef(cc)}}const Bo=n=>new et;class kt extends et{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,e){super._integrate(t,e),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new kt(this.nodeName)}clone(){const t=new kt(this.nodeName),e=this.getAttributes();return Hr(e,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof I?s.clone():s)),t}toString(){const t=this.getAttributes(),e=[],s=[];for(const c in t)s.push(c);s.sort();const r=s.length;for(let c=0;c<r;c++){const l=s[c];e.push(l+'="'+t[l]+'"')}const i=this.nodeName.toLocaleLowerCase(),o=e.length>0?" "+e.join(" "):"";return`<${i}${o}>${super.toString()}</${i}>`}removeAttribute(t){this.doc!==null?b(this.doc,e=>{ie(e,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,e){this.doc!==null?b(this.doc,s=>{pn(s,this,t,e)}):this._prelimAttrs.set(t,e)}getAttribute(t){return wn(this,t)}hasAttribute(t){return zs(this,t)}getAttributes(t){return t?Lo(this,t):Js(this)}toDOM(t=document,e={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const c=i[o];typeof c=="string"&&r.setAttribute(o,c)}return Ut(this,o=>{r.appendChild(o.toDOM(t,e,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(oc),t.writeKey(this.nodeName)}}const Jo=n=>new kt(n.readKey());class zo extends Ce{constructor(t,e,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,e.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class oe extends yt{constructor(t){super(),this.hookName=t}_copy(){return new oe(this.hookName)}clone(){const t=new oe(this.hookName);return this.forEach((e,s)=>{t.set(s,e)}),t}toDOM(t=document,e={},s){const r=e[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(lc),t.writeKey(this.hookName)}}const Go=n=>new oe(n.readKey());class ce extends mt{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new ce}clone(){const t=new ce;return t.applyDelta(this.toDelta()),t}toDOM(t=document,e,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const e=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,c)=>o.key<c.key?-1:1),e.push({nodeName:r,attrs:i})}e.sort((r,i)=>r.nodeName<i.nodeName?-1:1);let s="";for(let r=0;r<e.length;r++){const i=e[r];s+=`<${i.nodeName}`;for(let o=0;o<i.attrs.length;o++){const c=i.attrs[o];s+=` ${c.key}="${c.value}"`}s+=">"}s+=t.insert;for(let r=e.length-1;r>=0;r--)s+=`</${e[r].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(hc)}}const Ho=n=>new ce;class yn{constructor(t,e){this.id=t,this.length=e}get deleted(){throw $()}mergeWith(t){return!1}write(t,e,s){throw $()}integrate(t,e){throw $()}}const Po=0;class v extends yn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,e){e>0&&(this.id.clock+=e,this.length-=e),Ms(t.doc.store,this)}write(t,e){t.writeInfo(Po),t.writeLen(this.length-e)}getMissing(t,e){return null}}class Ft{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ft(this.content)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeBuf(this.content)}getRef(){return 3}}const Yo=n=>new Ft(n.readBuf());class Nt{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Nt(this.len)}splice(t){const e=new Nt(this.len-t);return this.len=t,e}mergeWith(t){return this.len+=t.len,!0}integrate(t,e){ne(t.deleteSet,e.id.client,e.id.clock,this.len),e.markDeleted()}delete(t){}gc(t){}write(t,e){t.writeLen(this.len-e)}getRef(){return 1}}const Ko=n=>new Nt(n.readLen()),Ks=(n,t)=>new Ct({guid:n,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Bt{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const e={};this.opts=e,t.gc||(e.gc=!1),t.autoLoad&&(e.autoLoad=!0),t.meta!==null&&(e.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Bt(Ks(this.doc.guid,this.opts))}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){this.doc._item=e,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,e){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const Wo=n=>new Bt(Ks(n.readString(),n.readAny()));class rt{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new rt(this.embed)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeJSON(this.embed)}getRef(){return 5}}const Xo=n=>new rt(n.readJSON());class C{constructor(t,e){this.key=t,this.value=e}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new C(this.key,this.value)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){const s=e.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,e){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const qo=n=>new C(n.readKey(),n.readJSON());class le{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new le(this.arr)}splice(t){const e=new le(this.arr.slice(t));return this.arr=this.arr.slice(0,t),e}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){const s=this.arr.length;t.writeLen(s-e);for(let r=e;r<s;r++){const i=this.arr[r];t.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const Zo=n=>{const t=n.readLen(),e=[];for(let s=0;s<t;s++){const r=n.readString();r==="undefined"?e.push(void 0):e.push(JSON.parse(r))}return new le(e)},Qo=Zt("node_env")==="development";class nt{constructor(t){this.arr=t,Qo&&Xn(t)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new nt(this.arr)}splice(t){const e=new nt(this.arr.slice(t));return this.arr=this.arr.slice(0,t),e}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){const s=this.arr.length;t.writeLen(s-e);for(let r=e;r<s;r++){const i=this.arr[r];t.writeAny(i)}}getRef(){return 8}}const tc=n=>{const t=n.readLen(),e=[];for(let s=0;s<t;s++)e.push(n.readAny());return new nt(e)};class z{constructor(t){this.str=t}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new z(this.str)}splice(t){const e=new z(this.str.slice(t));this.str=this.str.slice(0,t);const s=this.str.charCodeAt(t-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",e.str="�"+e.str.slice(1)),e}mergeWith(t){return this.str+=t.str,!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeString(e===0?this.str:this.str.slice(e))}getRef(){return 4}}const ec=n=>new z(n.readString()),nc=[vo,No,Fo,Jo,Bo,Go,Ho],sc=0,rc=1,ic=2,oc=3,cc=4,lc=5,hc=6;class Y{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Y(this.type._copy())}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){this.type._integrate(t.doc,e)}delete(t){let e=this.type._start;for(;e!==null;)e.deleted?e.id.clock<(t.beforeState.get(e.id.client)||0)&&t._mergeStructs.push(e):e.delete(t),e=e.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let e=this.type._start;for(;e!==null;)e.gc(t,!0),e=e.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,e){this.type._write(t)}getRef(){return 7}}const ac=n=>new Y(nc[n.readTypeRef()](n)),he=(n,t,e)=>{const{client:s,clock:r}=t.id,i=new _(w(s,r+e),t,w(s,r+e-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=w(t.redone.client,t.redone.clock+e)),t.right=i,i.right!==null&&(i.right.left=i),n._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=e,i};class _ extends yn{constructor(t,e,s,r,i,o,c,l){super(t,l.getLength()),this.origin=s,this.left=e,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?kn:0}set marker(t){(this.info&Oe)>0!==t&&(this.info^=Oe)}get marker(){return(this.info&Oe)>0}get keep(){return(this.info&mn)>0}set keep(t){this.keep!==t&&(this.info^=mn)}get countable(){return(this.info&kn)>0}get deleted(){return(this.info&Ie)>0}set deleted(t){this.deleted!==t&&(this.info^=Ie)}markDeleted(){this.info|=Ie}getMissing(t,e){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=D(e,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=D(e,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ut&&this.id.client!==this.parent.client&&this.parent.clock>=D(e,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Nn(t,e,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=X(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===v||this.right&&this.right.constructor===v)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===_?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===_&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ut){const s=Ne(e,this.parent);s.constructor===v?this.parent=null:this.parent=s.content.type}return null}integrate(t,e){if(e>0&&(this.id.clock+=e,this.left=Nn(t,t.doc.store,w(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(e),this.length-=e),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),Jt(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Jt(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&o.has(Ne(t.doc.store,r.origin)))i.has(Ne(t.doc.store,r.origin))||(s=r,i.clear());else break;r=r.right}this.left=s}if(this.left!==null){const s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(t)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ms(t.doc.store,this),this.content.integrate(t,this),$n(t,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(t)}else new v(this.id,this.length).integrate(t,0)}get next(){let t=this.right;for(;t!==null&&t.deleted;)t=t.right;return t}get prev(){let t=this.left;for(;t!==null&&t.deleted;)t=t.left;return t}get lastId(){return this.length===1?this.id:w(this.id.client,this.id.clock+this.length-1)}mergeWith(t){if(this.constructor===t.constructor&&Jt(t.origin,this.lastId)&&this.right===t&&Jt(this.rightOrigin,t.rightOrigin)&&this.id.client===t.id.client&&this.id.clock+this.length===t.id.clock&&this.deleted===t.deleted&&this.redone===null&&t.redone===null&&this.content.constructor===t.content.constructor&&this.content.mergeWith(t.content)){const e=this.parent._searchMarker;return e&&e.forEach(s=>{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const e=this.parent;this.countable&&this.parentSub===null&&(e._length-=this.length),this.markDeleted(),ne(t.deleteSet,this.id.client,this.id.clock,this.length),$n(t,e,this.parentSub),this.content.delete(t)}}gc(t,e){if(!this.deleted)throw N();this.content.gc(t),e?po(t,this,new v(this.id,this.length)):this.content=new Nt(this.length)}write(t,e){const s=e>0?w(this.id.client,this.id.clock+e-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&de|(s===null?0:T)|(r===null?0:H)|(i===null?0:At);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const h=fo(c);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(l.id)}else c.constructor===String?(t.writeParentInfo(!0),t.writeString(c)):c.constructor===ut?(t.writeParentInfo(!1),t.writeLeftID(c)):N();i!==null&&t.writeString(i)}this.content.write(t,e)}}const Ws=(n,t)=>uc[t&de](n),uc=[()=>{N()},Ko,Zo,Yo,ec,Xo,qo,ac,tc,Wo,()=>{N()}],dc=10;class U extends yn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,e){N()}write(t,e){t.writeInfo(dc),m(t.restEncoder,this.length-e)}getMissing(t,e){return null}}const Xs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},qs="__ $YJS$ __";Xs[qs]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Xs[qs]=!0;class fc extends Ye.Emitter{constructor(e){super();y(this,"doc");y(this,"config");y(this,"transport","websocket");y(this,"persistTimer",null);y(this,"dirty",!1);y(this,"sharedObjectCount",0);y(this,"destroyed",!1);this.config=e,this.doc=new Ct,this.doc.on("update",(s,r)=>{r!=="remote"&&(this.dirty=!0,this.broadcastUpdate(s))}),this.persistTimer=setInterval(()=>{this.dirty&&this.persist()},e.persistIntervalMs)}get currentTransport(){return this.transport}setTransport(e){this.transport!==e&&(this.transport=e,this.emit("transport:change",e))}checkSharedObjectLimit(){if(this.sharedObjectCount>=this.config.maxSharedObjects)throw new Error(`Max shared objects limit reached (${this.config.maxSharedObjects}). Cannot create more shared data structures in this room.`);this.sharedObjectCount++}applyP2PUpdate(e){Ue(this.doc,e,"remote")}applyWSUpdate(e){const s=atob(e),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);Ue(this.doc,r,"remote")}async bootstrap(){try{const e=await fetch(`${this.config.baseUrl}/api/v1/rooms/${this.config.roomId}/p2p/state`,{headers:{Authorization:`Bearer ${this.config.authToken}`}});if(e.ok){const{state:s}=await e.json();if(s){const r=atob(s),i=new Uint8Array(r.length);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);Ue(this.doc,i,"remote")}}}catch(e){console.warn("P2P state bootstrap failed:",e)}}async persist(){if(!this.destroyed)try{const e=ho(this.doc);let s="";for(let i=0;i<e.length;i++)s+=String.fromCharCode(e[i]);const r=btoa(s);await fetch(`${this.config.baseUrl}/api/v1/rooms/${this.config.roomId}/p2p/state`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.authToken}`},body:JSON.stringify({state:r})}),this.dirty=!1}catch(e){console.warn("P2P state persist failed:",e)}}destroy(){this.destroyed=!0,this.persistTimer&&(clearInterval(this.persistTimer),this.persistTimer=null),this.dirty&&this.persist(),this.doc.destroy(),this.removeAll()}broadcastUpdate(e){if(this.transport==="p2p")this.config.sendP2P(e);else{let s="";for(let r=0;r<e.length;r++)s+=String.fromCharCode(e[r]);this.config.sendWS(btoa(s))}}}class gc{constructor(t){y(this,"ymap");y(this,"listeners",new Set);y(this,"observer");this.ymap=t,this.observer=e=>{const s=[];if(e.changes.keys.forEach((r,i)=>{r.action==="add"?s.push({action:"add",key:i,value:this.ymap.get(i)}):r.action==="update"?s.push({action:"update",key:i,value:this.ymap.get(i),oldValue:r.oldValue}):r.action==="delete"&&s.push({action:"delete",key:i,oldValue:r.oldValue})}),s.length>0)for(const r of this.listeners)r(s)},this.ymap.observe(this.observer)}get(t){return this.ymap.get(t)}set(t,e){this.ymap.set(t,e)}delete(t){return this.ymap.has(t)?(this.ymap.delete(t),!0):!1}has(t){return this.ymap.has(t)}keys(){return Array.from(this.ymap.keys())}values(){return Array.from(this.ymap.values())}entries(){return Array.from(this.ymap.entries())}forEach(t){this.ymap.forEach(t)}get size(){return this.ymap.size}toJSON(){return this.ymap.toJSON()}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.ymap.unobserve(this.observer),this.listeners.clear()}}class pc{constructor(t){y(this,"yarray");y(this,"listeners",new Set);y(this,"observer");this.yarray=t,this.observer=e=>{const s=[];let r=0;for(const i of e.changes.delta)if(i.retain)r+=i.retain;else if(i.insert){const o=i.insert;s.push({action:"insert",index:r,values:o}),r+=o.length}else i.delete&&s.push({action:"delete",index:r});if(s.length>0)for(const i of this.listeners)i(s)},this.yarray.observe(this.observer)}get(t){return this.yarray.get(t)}push(...t){this.yarray.push(t)}insert(t,e){this.yarray.insert(t,[e])}delete(t,e=1){this.yarray.delete(t,e)}move(t,e){const s=this.yarray.get(t);this.yarray.doc.transact(()=>{this.yarray.delete(t);const r=t<e?e-1:e;this.yarray.insert(r,[s])})}indexOf(t){const e=this.yarray.toArray(),s=JSON.stringify(t);return e.findIndex(r=>JSON.stringify(r)===s)}toArray(){return this.yarray.toArray()}get length(){return this.yarray.length}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.yarray.unobserve(this.observer),this.listeners.clear()}}class wc{constructor(t,e){y(this,"ymap");y(this,"clientKey");y(this,"listeners",new Set);y(this,"observer");this.ymap=t,this.clientKey=e,this.observer=()=>{const s=this.value;for(const r of this.listeners)r(s)},this.ymap.observe(this.observer)}get value(){let t=0;return this.ymap.forEach(e=>{t+=e}),t}increment(t=1){const e=this.ymap.get(this.clientKey)??0;this.ymap.set(this.clientKey,e+t)}decrement(t=1){this.increment(-t)}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.ymap.unobserve(this.observer),this.listeners.clear()}}class yc extends Ye.Emitter{constructor(e){super();y(this,"peerManager");y(this,"syncEngine");y(this,"config");y(this,"sharedMaps",new Map);y(this,"sharedLists",new Map);y(this,"sharedCounters",new Map);y(this,"destroyed",!1);this.config=e,this.peerManager=new tr(e.iceServers,e.p2pConfig.meshLimit,e.userId,s=>e.sendWS(s)),this.syncEngine=new fc({roomId:e.roomId,baseUrl:e.baseUrl,authToken:e.authToken,persistIntervalMs:e.p2pConfig.persistIntervalMs,maxSharedObjects:e.p2pConfig.maxSharedObjects,sendP2P:s=>this.peerManager.sendCrdt(s),sendWS:s=>e.sendWS({type:"p2p:sync",update:s})}),this.peerManager.on("crdt:message",s=>{this.syncEngine.applyP2PUpdate(s.data)}),this.peerManager.on("raw:message",s=>{try{const r=JSON.parse(s.data);this.emit("message",{data:r,fromUserId:s.fromUserId})}catch{this.emit("message",{data:s.data,fromUserId:s.fromUserId})}}),this.peerManager.on("peer:connected",s=>{this.peerManager.activePeerCount>0&&this.syncEngine.setTransport("p2p"),this.emit("peer:connected",s)}),this.peerManager.on("peer:disconnected",s=>{this.peerManager.activePeerCount===0&&this.syncEngine.setTransport("websocket"),this.emit("peer:disconnected",s)}),this.peerManager.on("peer:fallback",()=>{this.syncEngine.setTransport("websocket"),this.emit("transport:change","websocket")}),this.syncEngine.on("transport:change",s=>{this.emit("transport:change",s)})}async initialize(){await this.syncEngine.bootstrap()}async handleSignalOffer(e,s){await this.peerManager.handleOffer(e,s)}async handleSignalAnswer(e,s){await this.peerManager.handleAnswer(e,s)}async handleIceCandidate(e,s){await this.peerManager.handleIceCandidate(e,s)}handleP2PSync(e,s){this.syncEngine.applyWSUpdate(s)}async onPeerJoined(e){this.peerManager.shouldUseMesh()&&await this.peerManager.createOffer(e)}onPeerLeft(e){this.peerManager.removePeer(e)}sharedMap(e){if(this.sharedMaps.has(e))return this.sharedMaps.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getMap(e),r=new gc(s);return this.sharedMaps.set(e,r),r}sharedList(e){if(this.sharedLists.has(e))return this.sharedLists.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getArray(e),r=new pc(s);return this.sharedLists.set(e,r),r}sharedCounter(e){if(this.sharedCounters.has(e))return this.sharedCounters.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getMap(`__counter_${e}`),r=new wc(s,this.config.userId);return this.sharedCounters.set(e,r),r}send(e){const s=typeof e=="string"?e:JSON.stringify(e);this.peerManager.sendRaw(s)}sendTo(e,s){const r=typeof s=="string"?s:JSON.stringify(s);this.peerManager.sendRaw(r,e)}get peers(){return this.peerManager.peerStates}get transport(){return this.syncEngine.currentTransport}destroy(){if(!this.destroyed){this.destroyed=!0;for(const[,e]of this.sharedMaps)e.destroy();for(const[,e]of this.sharedLists)e.destroy();for(const[,e]of this.sharedCounters)e.destroy();this.sharedMaps.clear(),this.sharedLists.clear(),this.sharedCounters.clear(),this.peerManager.destroy(),this.syncEngine.destroy(),this.removeAll()}}}exports.P2PManager=yc;
5
+ `?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&Re(s,this,r,c,o.attributes||{})}else o.retain!==void 0?Fn(s,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Bn(s,r,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,e,s){this.doc??O();const r=[],i=new Map,o=this.doc;let c="",l=this._start;function h(){if(c.length>0){const u={};let d=!1;i.forEach((g,k)=>{d=!0,u[k]=g});const f={insert:c};d&&(f.attributes=u),r.push(f),c=""}}const a=()=>{for(;l!==null;){if(ct(l,t)||e!==void 0&&ct(l,e))switch(l.content.constructor){case z:{const u=i.get("ychange");t!==void 0&&!ct(l,t)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(h(),i.set("ychange",s?s("removed",l.id):{type:"removed"})):e!==void 0&&!ct(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(h(),i.set("ychange",s?s("added",l.id):{type:"added"})):u!==void 0&&(h(),i.delete("ychange")),c+=l.content.str;break}case Y:case rt:{h();const u={insert:l.content.getContent()[0]};if(i.size>0){const d={};u.attributes=d,i.forEach((f,g)=>{d[g]=f})}r.push(u);break}case C:ct(l,t)&&(h(),Et(i,l.content));break}l=l.right}h()};return t||e?b(o,u=>{t&&Ge(u,t),e&&Ge(u,e),a()},"cleanup"):a(),r}insert(t,e,s){if(e.length<=0)return;const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!s);s||(s={},o.currentAttributes.forEach((c,l)=>{s[l]=c})),Re(i,this,o,e,s)}):this._pending.push(()=>this.insert(t,e,s))}insertEmbed(t,e,s){const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!s);Re(i,this,o,e,s||{})}):this._pending.push(()=>this.insertEmbed(t,e,s||{}))}delete(t,e){if(e===0)return;const s=this.doc;s!==null?b(s,r=>{Bn(r,Gt(r,this,t,!0),e)}):this._pending.push(()=>this.delete(t,e))}format(t,e,s){if(e===0)return;const r=this.doc;r!==null?b(r,i=>{const o=Gt(i,this,t,!1);o.right!==null&&Fn(i,this,o,e,s)}):this._pending.push(()=>this.format(t,e,s))}removeAttribute(t){this.doc!==null?b(this.doc,e=>{ie(e,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,e){this.doc!==null?b(this.doc,s=>{pn(s,this,t,e)}):this._pending.push(()=>this.setAttribute(t,e))}getAttribute(t){return wn(this,t)}getAttributes(){return Js(this)}_write(t){t.writeTypeRef(ic)}}const Fo=n=>new mt;class $e{constructor(t,e=()=>!0){this._filter=e,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??O()}[Symbol.iterator](){return this}next(){let t=this._currentNode,e=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(e)))do if(e=t.content.type,!t.deleted&&(e.constructor===kt||e.constructor===et)&&e._start!==null)t=e._start;else for(;t!==null;){const s=t.next;if(s!==null){t=s;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class et extends I{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,e){super._integrate(t,e),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new et}clone(){const t=new et;return t.insert(0,this.toArray().map(e=>e instanceof I?e.clone():e)),t}get length(){return this.doc??O(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new $e(this,t)}querySelector(t){t=t.toUpperCase();const s=new $e(this,r=>r.nodeName&&r.nodeName.toUpperCase()===t).next();return s.done?null:s.value}querySelectorAll(t){return t=t.toUpperCase(),Q(new $e(this,e=>e.nodeName&&e.nodeName.toUpperCase()===t))}_callObserver(t,e){De(this,t,new zo(this,e,t))}toString(){return $s(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,e={},s){const r=t.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),Ut(this,i=>{r.insertBefore(i.toDOM(t,e,s),null)}),r}insert(t,e){this.doc!==null?b(this.doc,s=>{Fs(s,this,t,e)}):this._prelimContent.splice(t,0,...e)}insertAfter(t,e){if(this.doc!==null)b(this.doc,s=>{const r=t&&t instanceof I?t._item:t;re(s,this,r,e)});else{const s=this._prelimContent,r=t===null?0:s.findIndex(i=>i===t)+1;if(r===0&&t!==null)throw B("Reference item not found");s.splice(r,0,...e)}}delete(t,e=1){this.doc!==null?b(this.doc,s=>{Bs(s,this,t,e)}):this._prelimContent.splice(t,e)}toArray(){return Rs(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Vs(this,t)}slice(t=0,e=this.length){return Ns(this,t,e)}forEach(t){Ut(this,t)}_write(t){t.writeTypeRef(cc)}}const Bo=n=>new et;class kt extends et{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,e){super._integrate(t,e),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new kt(this.nodeName)}clone(){const t=new kt(this.nodeName),e=this.getAttributes();return Hr(e,(s,r)=>{t.setAttribute(r,s)}),t.insert(0,this.toArray().map(s=>s instanceof I?s.clone():s)),t}toString(){const t=this.getAttributes(),e=[],s=[];for(const c in t)s.push(c);s.sort();const r=s.length;for(let c=0;c<r;c++){const l=s[c];e.push(l+'="'+t[l]+'"')}const i=this.nodeName.toLocaleLowerCase(),o=e.length>0?" "+e.join(" "):"";return`<${i}${o}>${super.toString()}</${i}>`}removeAttribute(t){this.doc!==null?b(this.doc,e=>{ie(e,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,e){this.doc!==null?b(this.doc,s=>{pn(s,this,t,e)}):this._prelimAttrs.set(t,e)}getAttribute(t){return wn(this,t)}hasAttribute(t){return zs(this,t)}getAttributes(t){return t?Lo(this,t):Js(this)}toDOM(t=document,e={},s){const r=t.createElement(this.nodeName),i=this.getAttributes();for(const o in i){const c=i[o];typeof c=="string"&&r.setAttribute(o,c)}return Ut(this,o=>{r.appendChild(o.toDOM(t,e,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(t){t.writeTypeRef(oc),t.writeKey(this.nodeName)}}const Jo=n=>new kt(n.readKey());class zo extends Ce{constructor(t,e,s){super(t,s),this.childListChanged=!1,this.attributesChanged=new Set,e.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class oe extends yt{constructor(t){super(),this.hookName=t}_copy(){return new oe(this.hookName)}clone(){const t=new oe(this.hookName);return this.forEach((e,s)=>{t.set(s,e)}),t}toDOM(t=document,e={},s){const r=e[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(t){t.writeTypeRef(lc),t.writeKey(this.hookName)}}const Go=n=>new oe(n.readKey());class ce extends mt{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new ce}clone(){const t=new ce;return t.applyDelta(this.toDelta()),t}toDOM(t=document,e,s){const r=t.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(t=>{const e=[];for(const r in t.attributes){const i=[];for(const o in t.attributes[r])i.push({key:o,value:t.attributes[r][o]});i.sort((o,c)=>o.key<c.key?-1:1),e.push({nodeName:r,attrs:i})}e.sort((r,i)=>r.nodeName<i.nodeName?-1:1);let s="";for(let r=0;r<e.length;r++){const i=e[r];s+=`<${i.nodeName}`;for(let o=0;o<i.attrs.length;o++){const c=i.attrs[o];s+=` ${c.key}="${c.value}"`}s+=">"}s+=t.insert;for(let r=e.length-1;r>=0;r--)s+=`</${e[r].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(hc)}}const Ho=n=>new ce;class yn{constructor(t,e){this.id=t,this.length=e}get deleted(){throw $()}mergeWith(t){return!1}write(t,e,s){throw $()}integrate(t,e){throw $()}}const Po=0;class v extends yn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,e){e>0&&(this.id.clock+=e,this.length-=e),Ms(t.doc.store,this)}write(t,e){t.writeInfo(Po),t.writeLen(this.length-e)}getMissing(t,e){return null}}class Ft{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ft(this.content)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeBuf(this.content)}getRef(){return 3}}const Yo=n=>new Ft(n.readBuf());class Nt{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Nt(this.len)}splice(t){const e=new Nt(this.len-t);return this.len=t,e}mergeWith(t){return this.len+=t.len,!0}integrate(t,e){ne(t.deleteSet,e.id.client,e.id.clock,this.len),e.markDeleted()}delete(t){}gc(t){}write(t,e){t.writeLen(this.len-e)}getRef(){return 1}}const Ko=n=>new Nt(n.readLen()),Ks=(n,t)=>new Ct({guid:n,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Bt{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const e={};this.opts=e,t.gc||(e.gc=!1),t.autoLoad&&(e.autoLoad=!0),t.meta!==null&&(e.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Bt(Ks(this.doc.guid,this.opts))}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){this.doc._item=e,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,e){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const Wo=n=>new Bt(Ks(n.readString(),n.readAny()));class rt{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new rt(this.embed)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeJSON(this.embed)}getRef(){return 5}}const Xo=n=>new rt(n.readJSON());class C{constructor(t,e){this.key=t,this.value=e}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new C(this.key,this.value)}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){const s=e.parent;s._searchMarker=null,s._hasFormatting=!0}delete(t){}gc(t){}write(t,e){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const qo=n=>new C(n.readKey(),n.readJSON());class le{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new le(this.arr)}splice(t){const e=new le(this.arr.slice(t));return this.arr=this.arr.slice(0,t),e}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){const s=this.arr.length;t.writeLen(s-e);for(let r=e;r<s;r++){const i=this.arr[r];t.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const Zo=n=>{const t=n.readLen(),e=[];for(let s=0;s<t;s++){const r=n.readString();r==="undefined"?e.push(void 0):e.push(JSON.parse(r))}return new le(e)},Qo=Zt("node_env")==="development";class nt{constructor(t){this.arr=t,Qo&&Xn(t)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new nt(this.arr)}splice(t){const e=new nt(this.arr.slice(t));return this.arr=this.arr.slice(0,t),e}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){const s=this.arr.length;t.writeLen(s-e);for(let r=e;r<s;r++){const i=this.arr[r];t.writeAny(i)}}getRef(){return 8}}const tc=n=>{const t=n.readLen(),e=[];for(let s=0;s<t;s++)e.push(n.readAny());return new nt(e)};class z{constructor(t){this.str=t}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new z(this.str)}splice(t){const e=new z(this.str.slice(t));this.str=this.str.slice(0,t);const s=this.str.charCodeAt(t-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,t-1)+"�",e.str="�"+e.str.slice(1)),e}mergeWith(t){return this.str+=t.str,!0}integrate(t,e){}delete(t){}gc(t){}write(t,e){t.writeString(e===0?this.str:this.str.slice(e))}getRef(){return 4}}const ec=n=>new z(n.readString()),nc=[vo,No,Fo,Jo,Bo,Go,Ho],sc=0,rc=1,ic=2,oc=3,cc=4,lc=5,hc=6;class Y{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Y(this.type._copy())}splice(t){throw $()}mergeWith(t){return!1}integrate(t,e){this.type._integrate(t.doc,e)}delete(t){let e=this.type._start;for(;e!==null;)e.deleted?e.id.clock<(t.beforeState.get(e.id.client)||0)&&t._mergeStructs.push(e):e.delete(t),e=e.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(t.beforeState.get(s.id.client)||0)&&t._mergeStructs.push(s):s.delete(t)}),t.changed.delete(this.type)}gc(t){let e=this.type._start;for(;e!==null;)e.gc(t,!0),e=e.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(t,!0),s=s.left}),this.type._map=new Map}write(t,e){this.type._write(t)}getRef(){return 7}}const ac=n=>new Y(nc[n.readTypeRef()](n)),he=(n,t,e)=>{const{client:s,clock:r}=t.id,i=new _(w(s,r+e),t,w(s,r+e-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=w(t.redone.client,t.redone.clock+e)),t.right=i,i.right!==null&&(i.right.left=i),n._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=e,i};class _ extends yn{constructor(t,e,s,r,i,o,c,l){super(t,l.getLength()),this.origin=s,this.left=e,this.right=r,this.rightOrigin=i,this.parent=o,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?kn:0}set marker(t){(this.info&Oe)>0!==t&&(this.info^=Oe)}get marker(){return(this.info&Oe)>0}get keep(){return(this.info&mn)>0}set keep(t){this.keep!==t&&(this.info^=mn)}get countable(){return(this.info&kn)>0}get deleted(){return(this.info&Ie)>0}set deleted(t){this.deleted!==t&&(this.info^=Ie)}markDeleted(){this.info|=Ie}getMissing(t,e){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=D(e,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=D(e,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ut&&this.id.client!==this.parent.client&&this.parent.clock>=D(e,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Nn(t,e,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=X(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===v||this.right&&this.right.constructor===v)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===_?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===_&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ut){const s=Ne(e,this.parent);s.constructor===v?this.parent=null:this.parent=s.content.type}return null}integrate(t,e){if(e>0&&(this.id.clock+=e,this.left=Nn(t,t.doc.store,w(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(e),this.length-=e),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),i.add(r),Jt(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Jt(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&o.has(Ne(t.doc.store,r.origin)))i.has(Ne(t.doc.store,r.origin))||(s=r,i.clear());else break;r=r.right}this.left=s}if(this.left!==null){const s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(t)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ms(t.doc.store,this),this.content.integrate(t,this),$n(t,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(t)}else new v(this.id,this.length).integrate(t,0)}get next(){let t=this.right;for(;t!==null&&t.deleted;)t=t.right;return t}get prev(){let t=this.left;for(;t!==null&&t.deleted;)t=t.left;return t}get lastId(){return this.length===1?this.id:w(this.id.client,this.id.clock+this.length-1)}mergeWith(t){if(this.constructor===t.constructor&&Jt(t.origin,this.lastId)&&this.right===t&&Jt(this.rightOrigin,t.rightOrigin)&&this.id.client===t.id.client&&this.id.clock+this.length===t.id.clock&&this.deleted===t.deleted&&this.redone===null&&t.redone===null&&this.content.constructor===t.content.constructor&&this.content.mergeWith(t.content)){const e=this.parent._searchMarker;return e&&e.forEach(s=>{s.p===t&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const e=this.parent;this.countable&&this.parentSub===null&&(e._length-=this.length),this.markDeleted(),ne(t.deleteSet,this.id.client,this.id.clock,this.length),$n(t,e,this.parentSub),this.content.delete(t)}}gc(t,e){if(!this.deleted)throw N();this.content.gc(t),e?po(t,this,new v(this.id,this.length)):this.content=new Nt(this.length)}write(t,e){const s=e>0?w(this.id.client,this.id.clock+e-1):this.origin,r=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&de|(s===null?0:T)|(r===null?0:H)|(i===null?0:At);if(t.writeInfo(o),s!==null&&t.writeLeftID(s),r!==null&&t.writeRightID(r),s===null&&r===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const h=fo(c);t.writeParentInfo(!0),t.writeString(h)}else t.writeParentInfo(!1),t.writeLeftID(l.id)}else c.constructor===String?(t.writeParentInfo(!0),t.writeString(c)):c.constructor===ut?(t.writeParentInfo(!1),t.writeLeftID(c)):N();i!==null&&t.writeString(i)}this.content.write(t,e)}}const Ws=(n,t)=>uc[t&de](n),uc=[()=>{N()},Ko,Zo,Yo,ec,Xo,qo,ac,tc,Wo,()=>{N()}],dc=10;class U extends yn{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,e){N()}write(t,e){t.writeInfo(dc),m(t.restEncoder,this.length-e)}getMissing(t,e){return null}}const Xs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},qs="__ $YJS$ __";Xs[qs]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Xs[qs]=!0;class fc extends Ye.Emitter{constructor(e){super();y(this,"doc");y(this,"config");y(this,"transport","websocket");y(this,"persistTimer",null);y(this,"dirty",!1);y(this,"sharedObjectCount",0);y(this,"destroyed",!1);this.config=e,this.doc=new Ct,this.doc.on("update",(s,r)=>{r!=="remote"&&(this.dirty=!0,this.broadcastUpdate(s))}),this.persistTimer=setInterval(()=>{this.dirty&&this.persist()},e.persistIntervalMs)}get currentTransport(){return this.transport}setTransport(e){this.transport!==e&&(this.transport=e,this.emit("transport:change",e))}checkSharedObjectLimit(){if(this.sharedObjectCount>=this.config.maxSharedObjects)throw new Error(`Max shared objects limit reached (${this.config.maxSharedObjects}). Cannot create more shared data structures in this room.`);this.sharedObjectCount++}applyP2PUpdate(e){Ue(this.doc,e,"remote")}applyWSUpdate(e){const s=atob(e),r=new Uint8Array(s.length);for(let i=0;i<s.length;i++)r[i]=s.charCodeAt(i);Ue(this.doc,r,"remote")}async bootstrap(){try{const e=await fetch(`${this.config.baseUrl}/api/v1/rooms/${this.config.roomId}/p2p/state`,{headers:{Authorization:`Bearer ${this.config.authToken}`}});if(e.ok){const{state:s}=await e.json();if(s){const r=atob(s),i=new Uint8Array(r.length);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);Ue(this.doc,i,"remote")}}}catch(e){console.warn("P2P state bootstrap failed:",e)}}async persist(){if(!this.destroyed)try{const e=ho(this.doc);let s="";for(let i=0;i<e.length;i++)s+=String.fromCharCode(e[i]);const r=btoa(s);await fetch(`${this.config.baseUrl}/api/v1/rooms/${this.config.roomId}/p2p/state`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.authToken}`},body:JSON.stringify({state:r})}),this.dirty=!1}catch(e){console.warn("P2P state persist failed:",e)}}destroy(){this.destroyed=!0,this.persistTimer&&(clearInterval(this.persistTimer),this.persistTimer=null),this.dirty&&this.persist(),this.doc.destroy(),this.removeAll()}broadcastUpdate(e){let s="";for(let r=0;r<e.length;r++)s+=String.fromCharCode(e[r]);this.config.sendWS(btoa(s)),this.transport==="p2p"&&this.config.sendP2P(e)}}class gc{constructor(t){y(this,"ymap");y(this,"listeners",new Set);y(this,"observer");this.ymap=t,this.observer=e=>{const s=[];if(e.changes.keys.forEach((r,i)=>{r.action==="add"?s.push({action:"add",key:i,value:this.get(i)}):r.action==="update"?s.push({action:"update",key:i,value:this.get(i),oldValue:r.oldValue}):r.action==="delete"&&s.push({action:"delete",key:i,oldValue:r.oldValue})}),s.length>0)for(const r of this.listeners)r(s)},this.ymap.observe(this.observer)}get(t){const e=this.ymap.get(t);if(e!==void 0)return e&&typeof e=="object"&&typeof e.toJSON=="function"?e.toJSON():e}set(t,e){this.ymap.set(t,e)}delete(t){return this.ymap.has(t)?(this.ymap.delete(t),!0):!1}has(t){return this.ymap.has(t)}keys(){return Array.from(this.ymap.keys())}values(){return this.keys().map(t=>this.get(t))}entries(){return this.keys().map(t=>[t,this.get(t)])}forEach(t){for(const e of this.keys())t(this.get(e),e)}get size(){return this.ymap.size}toJSON(){const t={};for(const e of this.keys())t[e]=this.get(e);return t}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.ymap.unobserve(this.observer),this.listeners.clear()}}class pc{constructor(t){y(this,"yarray");y(this,"listeners",new Set);y(this,"observer");this.yarray=t,this.observer=e=>{const s=[];let r=0;for(const i of e.changes.delta)if(i.retain)r+=i.retain;else if(i.insert){const o=i.insert;s.push({action:"insert",index:r,values:o}),r+=o.length}else i.delete&&s.push({action:"delete",index:r});if(s.length>0)for(const i of this.listeners)i(s)},this.yarray.observe(this.observer)}get(t){return this.yarray.get(t)}push(...t){this.yarray.push(t)}insert(t,e){this.yarray.insert(t,[e])}delete(t,e=1){this.yarray.delete(t,e)}move(t,e){const s=this.yarray.get(t);this.yarray.doc.transact(()=>{this.yarray.delete(t);const r=t<e?e-1:e;this.yarray.insert(r,[s])})}indexOf(t){const e=this.yarray.toArray(),s=JSON.stringify(t);return e.findIndex(r=>JSON.stringify(r)===s)}toArray(){return this.yarray.toArray()}get length(){return this.yarray.length}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.yarray.unobserve(this.observer),this.listeners.clear()}}class wc{constructor(t,e){y(this,"ymap");y(this,"clientKey");y(this,"listeners",new Set);y(this,"observer");this.ymap=t,this.clientKey=e,this.observer=()=>{const s=this.value;for(const r of this.listeners)r(s)},this.ymap.observe(this.observer)}get value(){let t=0;return this.ymap.forEach(e=>{t+=e}),t}increment(t=1){const e=this.ymap.get(this.clientKey)??0;this.ymap.set(this.clientKey,e+t)}decrement(t=1){this.increment(-t)}on(t,e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.ymap.unobserve(this.observer),this.listeners.clear()}}class yc extends Ye.Emitter{constructor(e){super();y(this,"peerManager");y(this,"syncEngine");y(this,"config");y(this,"sharedMaps",new Map);y(this,"sharedLists",new Map);y(this,"sharedCounters",new Map);y(this,"destroyed",!1);this.config=e,this.peerManager=new tr(e.iceServers,e.p2pConfig.meshLimit,e.userId,s=>e.sendWS(s)),this.syncEngine=new fc({roomId:e.roomId,baseUrl:e.baseUrl,authToken:e.authToken,persistIntervalMs:e.p2pConfig.persistIntervalMs,maxSharedObjects:e.p2pConfig.maxSharedObjects,sendP2P:s=>this.peerManager.sendCrdt(s),sendWS:s=>e.sendWS({type:"p2p:sync",update:s})}),this.peerManager.on("crdt:message",s=>{this.syncEngine.applyP2PUpdate(s.data)}),this.peerManager.on("raw:message",s=>{try{const r=JSON.parse(s.data);this.emit("message",{data:r,fromUserId:s.fromUserId})}catch{this.emit("message",{data:s.data,fromUserId:s.fromUserId})}}),this.peerManager.on("peer:connected",s=>{this.peerManager.activePeerCount>0&&this.syncEngine.setTransport("p2p"),this.emit("peer:connected",s)}),this.peerManager.on("peer:disconnected",s=>{this.peerManager.activePeerCount===0&&this.syncEngine.setTransport("websocket"),this.emit("peer:disconnected",s)}),this.peerManager.on("peer:fallback",()=>{this.syncEngine.setTransport("websocket"),this.emit("transport:change","websocket")}),this.syncEngine.on("transport:change",s=>{this.emit("transport:change",s)})}async initialize(){await this.syncEngine.bootstrap()}async handleSignalOffer(e,s){await this.peerManager.handleOffer(e,s)}async handleSignalAnswer(e,s){await this.peerManager.handleAnswer(e,s)}async handleIceCandidate(e,s){await this.peerManager.handleIceCandidate(e,s)}handleP2PSync(e,s){this.syncEngine.applyWSUpdate(s)}async onPeerJoined(e){this.peerManager.shouldUseMesh()&&await this.peerManager.createOffer(e)}onPeerLeft(e){this.peerManager.removePeer(e)}sharedMap(e){if(this.sharedMaps.has(e))return this.sharedMaps.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getMap(e),r=new gc(s);return this.sharedMaps.set(e,r),r}sharedList(e){if(this.sharedLists.has(e))return this.sharedLists.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getArray(e),r=new pc(s);return this.sharedLists.set(e,r),r}sharedCounter(e){if(this.sharedCounters.has(e))return this.sharedCounters.get(e);this.syncEngine.checkSharedObjectLimit();const s=this.syncEngine.doc.getMap(`__counter_${e}`),r=new wc(s,this.config.userId);return this.sharedCounters.set(e,r),r}send(e){const s=typeof e=="string"?e:JSON.stringify(e);this.peerManager.sendRaw(s)}sendTo(e,s){const r=typeof s=="string"?s:JSON.stringify(s);this.peerManager.sendRaw(r,e)}get peers(){return this.peerManager.peerStates}get transport(){return this.syncEngine.currentTransport}destroy(){if(!this.destroyed){this.destroyed=!0;for(const[,e]of this.sharedMaps)e.destroy();for(const[,e]of this.sharedLists)e.destroy();for(const[,e]of this.sharedCounters)e.destroy();this.sharedMaps.clear(),this.sharedLists.clear(),this.sharedCounters.clear(),this.peerManager.destroy(),this.syncEngine.destroy(),this.removeAll()}}}exports.P2PManager=yc;
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var _=(h,a,e)=>a in h?f(h,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):h[a]=e;var r=(h,a,e)=>_(h,typeof a!="symbol"?a+"":a,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@gamention/pulse-shared");class d{constructor(){r(this,"handlers",new Map)}on(a,e){this.handlers.has(a)||this.handlers.set(a,new Set);const t=this.handlers.get(a);return t.add(e),()=>t.delete(e)}off(a,e){var t;(t=this.handlers.get(a))==null||t.delete(e)}emit(a,e){var t;(t=this.handlers.get(a))==null||t.forEach(s=>s(e))}removeAll(){this.handlers.clear()}}class p extends d{constructor(e){super();r(this,"ws",null);r(this,"endpoint");r(this,"reconnectAttempt",0);r(this,"reconnectTimer",null);r(this,"_state","disconnected");r(this,"permanentlyClosed",!1);r(this,"handleOpen",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)});r(this,"handleMessage",e=>{try{const t=JSON.parse(e.data);this.emit("message",t)}catch{}});r(this,"handleClose",()=>{this.cleanupWs(),this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()});r(this,"handleError",()=>{var e;(e=this.ws)==null||e.close()});this.endpoint=e??c.DEFAULT_ENDPOINT}get state(){return this._state}connect(){this.ws||this.permanentlyClosed||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",this.handleOpen),this.ws.addEventListener("message",this.handleMessage),this.ws.addEventListener("close",this.handleClose),this.ws.addEventListener("error",this.handleError))}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.cleanupWs(),this._state="disconnected",this.emit("state",this._state)}send(e){var t;((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}permanentDisconnect(){this.permanentlyClosed=!0,this.disconnect()}cleanupWs(){this.ws&&(this.ws.removeEventListener("open",this.handleOpen),this.ws.removeEventListener("message",this.handleMessage),this.ws.removeEventListener("close",this.handleClose),this.ws.removeEventListener("error",this.handleError),this.ws.close(),this.ws=null)}scheduleReconnect(){if(this.permanentlyClosed)return;const e=Math.min(c.RECONNECT_BASE_DELAY_MS*2**this.reconnectAttempt,c.RECONNECT_MAX_DELAY_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}}class u extends d{constructor(){super(...arguments);r(this,"baseUrl","");r(this,"_user",null);r(this,"_config",{...c.DEFAULT_ENV_CONFIG});r(this,"_p2pConfig",null);r(this,"_users",new Map);r(this,"_presence",new Map);r(this,"_threads",new Map);r(this,"_reactions",new Map);r(this,"_notifications",[]);r(this,"_activityLogs",[]);r(this,"_typing",new Map);r(this,"_viewports",new Map);r(this,"_selections",new Map)}get user(){return this._user}get p2pConfig(){return this._p2pConfig}get config(){return this._config}removeComment(e){for(const[t,s]of this._threads){const i=s.comments.findIndex(n=>n.id===e);if(i!==-1){s.comments.splice(i,1),s.comments.length===0&&this._threads.delete(t),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(e=>!e.read).length}markNotificationRead(e){const t=this._notifications.find(s=>s.id===e);t&&!t.read&&(t.read=!0,this.emit("notifications",this._notifications))}markAllNotificationsRead(){let e=!1;for(const t of this._notifications)t.read||(t.read=!0,e=!0);e&&this.emit("notifications",this._notifications)}get activityLogs(){return this._activityLogs}getUser(e){return this._users.get(e)}get users(){return[...this._users.values()]}getReactions(e){return this._reactions.get(e)??[]}getTypingUsers(e){const t=this._typing.get(e);if(!t)return[];const s=Date.now(),i=[];for(const[n,o]of t)s-o<3e3&&i.push(n);return i}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}resolveUrl(e){return!this.baseUrl||!e||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}${e}`}resolveAttachments(e){return e.map(t=>({...t,url:this.resolveUrl(t.url),thumbnailUrl:t.thumbnailUrl?this.resolveUrl(t.thumbnailUrl):void 0}))}resolveComment(e){return!e.attachments||e.attachments.length===0?e:{...e,attachments:this.resolveAttachments(e.attachments)}}resolveThread(e){return{...e,comments:e.comments.map(t=>this.resolveComment(t))}}handleMessage(e){switch(e.type){case"auth:ok":this._config=e.config??{...c.DEFAULT_ENV_CONFIG},this._p2pConfig=e.p2pConfig??null,this._user=e.user,this._users.clear();for(const t of e.users)this._users.set(t.id,t);this._presence.clear();for(const t of e.presence)this._presence.set(t.user.id,t),this._users.set(t.user.id,t.user);this._users.set(e.user.id,e.user),this._threads.clear();for(const t of e.threads)this._threads.set(t.id,this.resolveThread(t));this._notifications=e.notifications,this._reactions.clear();for(const t of e.reactions){const s=this._reactions.get(t.targetId)??[];s.push(t),this._reactions.set(t.targetId,s)}this._activityLogs=[...e.activityLogs],this.emit("auth",e.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(e.user.user.id,e.user),this._users.set(e.user.user.id,e.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(e.userId),this._viewports.delete(e.userId),this._selections.delete(e.userId);for(const t of this._typing.values())t.delete(e.userId);this.emit("presence",this.presence);break;case"presence:update":{const t=this._presence.get(e.userId);t&&(t.status=e.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:e.userId,position:e.position});break;case"click:perform":this.emit("click",{userId:e.userId,position:e.position});break;case"thread:created":this._threads.set(e.thread.id,this.resolveThread(e.thread)),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(this.resolveComment(e.comment)),t.updatedAt=e.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const t=this._threads.get(e.threadId);if(t){const s=t.comments.findIndex(i=>i.id===e.comment.id);s!==-1&&(t.comments[s]=this.resolveComment(e.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const t=this._threads.get(e.threadId);t&&(t.comments=t.comments.filter(s=>s.id!==e.commentId),t.comments.length===0&&this._threads.delete(e.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const t=this._threads.get(e.threadId);t&&(t.resolved=e.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(e.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const t=this._reactions.get(e.reaction.targetId)??[];t.push(e.reaction),this._reactions.set(e.reaction.targetId,t),this.emit("reactions",{targetId:e.reaction.targetId,reactions:t});break}case"reaction:removed":{const t=this._reactions.get(e.targetId);if(t){const s=t.filter(i=>i.id!==e.reactionId);this._reactions.set(e.targetId,s),this.emit("reactions",{targetId:e.targetId,reactions:s})}break}case"notification":this._notifications.unshift(e.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(e.threadId)||this._typing.set(e.threadId,new Map),this._typing.get(e.threadId).set(e.userId,Date.now()),this.emit("typing",{threadId:e.threadId,userId:e.userId});break}case"viewport:update":{this._viewports.set(e.userId,{scrollX:e.scrollX,scrollY:e.scrollY,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,pageWidth:e.pageWidth,pageHeight:e.pageHeight}),this.emit("viewport",{userId:e.userId});break}case"selection:update":this._selections.set(e.userId,e.selection),this.emit("selection",{userId:e.userId,selection:e.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:e.userId,emoji:e.emoji,position:e.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:e.userId,points:e.points,color:e.color,width:e.width});break;case"draw:clear":this.emit("draw-clear",{userId:e.userId});break;case"activity:logged":this._activityLogs.unshift(e.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"auth:error":this.emit("auth:error",e);break;case"error":this.emit("error",e);break}}reset(){this._user=null,this._config={...c.DEFAULT_ENV_CONFIG},this._p2pConfig=null,this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}}class m extends d{constructor(e){var s;super();r(this,"state");r(this,"connection");r(this,"config");r(this,"heartbeatTimer",null);r(this,"lastCursorSend",0);r(this,"pendingCursor",null);r(this,"cursorTimer",null);r(this,"_p2p",null);r(this,"_p2pInstance",null);r(this,"p2pEnabled");r(this,"iceServers");r(this,"signalingQueue",[]);this.config=e,this.state=new u,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const t=((s=e.endpoint)==null?void 0:s.replace(/^http/,"ws"))??void 0;this.connection=new p(t),this.p2pEnabled=e.p2p??!1,this.iceServers=e.iceServers??[{urls:"stun:stun.l.google.com:19302"}],this.connection.on("message",i=>{this.state.handleMessage(i),this.emit(i.type,i),i.type==="auth:error"&&this.connection.permanentDisconnect(),i.type==="signal:offer"||i.type==="signal:answer"||i.type==="signal:ice"||i.type==="p2p:sync"?this._p2pInstance?this.routeP2PMessage(i):this.p2pEnabled&&this.signalingQueue.push(i):this._p2pInstance&&(i.type==="presence:join"?this._p2pInstance.onPeerJoined(i.user.user.id):i.type==="presence:leave"&&this._p2pInstance.onPeerLeft(i.userId))}),this.connection.on("state",i=>{this.emit("connection",i),i==="connected"?(this.authenticate(),this.startHeartbeat()):i==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null),this.connection.disconnect(),this.state.reset()}destroy(){var e;(e=this._p2pInstance)==null||e.destroy(),this._p2pInstance=null,this._p2p=null,this.disconnect(),this.removeAll(),this.state.removeAll(),this.connection.removeAll()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(e){this.connection.send(e)}moveCursor(e){const t=Date.now();this.pendingCursor=e,t-this.lastCursorSend>=c.CURSOR_THROTTLE_MS?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},c.CURSOR_THROTTLE_MS))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(e){this.send({type:"presence:update",status:e})}startHeartbeat(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},c.PRESENCE_HEARTBEAT_MS))}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(e,t={}){const s=crypto.randomUUID();return this.send({type:"thread:create",id:s,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),s}reply(e,t,s=[],i){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:s,attachmentIds:i}),n}editComment(e,t,s=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:s})}deleteComment(e){this.state.removeComment(e),this.send({type:"comment:delete",commentId:e})}resolveThread(e,t=!0){this.send({type:"thread:resolve",threadId:e,resolved:t})}addReaction(e,t,s){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:s})}removeReaction(e){this.send({type:"reaction:remove",reactionId:e})}markRead(e){this.state.markNotificationRead(e),this.send({type:"notification:read",notificationId:e})}markAllRead(){this.state.markAllNotificationsRead(),this.send({type:"notification:read-all"})}performClick(e){this.send({type:"click:perform",position:e})}sendTyping(e){this.send({type:"typing:start",threadId:e})}updateViewport(e){this.send({type:"viewport:update",...e})}updateSelection(e){this.send({type:"selection:update",selection:e})}dropEmoji(e,t){this.send({type:"emoji:drop",emoji:e,position:t})}drawStroke(e,t,s){this.send({type:"draw:stroke",points:e,color:t,width:s})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=typeof window<"u"?window.location.origin:"",s=(this.config.endpoint??t).replace(/^ws(s?):/,"http$1:"),i=new FormData;i.append("file",e);const n=await fetch(`${s}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:i});if(!n.ok){const l=await n.json().catch(()=>({error:"Upload failed"}));throw new Error(l.error??"Upload failed")}const o=await n.json();return o.url&&!o.url.startsWith("http")&&(o.url=`${s}${o.url}`),o.thumbnailUrl&&!o.thumbnailUrl.startsWith("http")&&(o.thumbnailUrl=`${s}${o.thumbnailUrl}`),o}setAppearOffline(e){e?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}get p2p(){return this.p2pEnabled?(this._p2p||(this._p2p=this.initP2P()),this._p2p):Promise.reject(new Error("P2P is not enabled. Pass { p2p: true } in PulseConfig."))}async initP2P(){const e=await new Promise((n,o)=>{if(this.state.user&&this.state.p2pConfig){n({userId:this.state.user.id,p2pConfig:this.state.p2pConfig});return}const l=this.state.on("auth",()=>{if(l(),!this.state.p2pConfig){o(new Error("P2P is not enabled for this environment."));return}n({userId:this.state.user.id,p2pConfig:this.state.p2pConfig})})});let t=this.iceServers;try{const n=await fetch(`${this.state.baseUrl}/api/v1/turn-credentials`,{headers:{Authorization:`Bearer ${this.config.token}`}});n.ok&&(t=(await n.json()).iceServers)}catch{}const{P2PManager:s}=await Promise.resolve().then(()=>require("./P2PManager-e4ShL60A.cjs")),i=new s({roomId:this.config.room,userId:e.userId,baseUrl:this.state.baseUrl,authToken:this.config.token,p2pConfig:e.p2pConfig,iceServers:t,sendWS:n=>this.send(n)});this._p2pInstance=i,await i.initialize();for(const n of this.state.presence)n.user.id!==e.userId&&i.onPeerJoined(n.user.id);for(const n of this.signalingQueue)this.routeP2PMessage(n);return this.signalingQueue=[],i}routeP2PMessage(e){this._p2pInstance&&(e.type==="signal:offer"?this._p2pInstance.handleSignalOffer(e.fromUserId,e.sdp):e.type==="signal:answer"?this._p2pInstance.handleSignalAnswer(e.fromUserId,e.sdp):e.type==="signal:ice"?this._p2pInstance.handleIceCandidate(e.fromUserId,e.candidate):e.type==="p2p:sync"&&this._p2pInstance.handleP2PSync(e.fromUserId,e.update))}}exports.Connection=p;exports.Emitter=d;exports.PulseClient=m;exports.StateManager=u;
1
+ "use strict";var f=Object.defineProperty;var _=(h,a,e)=>a in h?f(h,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):h[a]=e;var r=(h,a,e)=>_(h,typeof a!="symbol"?a+"":a,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@gamention/pulse-shared");class d{constructor(){r(this,"handlers",new Map)}on(a,e){this.handlers.has(a)||this.handlers.set(a,new Set);const t=this.handlers.get(a);return t.add(e),()=>t.delete(e)}off(a,e){var t;(t=this.handlers.get(a))==null||t.delete(e)}emit(a,e){var t;(t=this.handlers.get(a))==null||t.forEach(s=>s(e))}removeAll(){this.handlers.clear()}}class p extends d{constructor(e){super();r(this,"ws",null);r(this,"endpoint");r(this,"reconnectAttempt",0);r(this,"reconnectTimer",null);r(this,"_state","disconnected");r(this,"permanentlyClosed",!1);r(this,"handleOpen",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)});r(this,"handleMessage",e=>{try{const t=JSON.parse(e.data);this.emit("message",t)}catch{}});r(this,"handleClose",()=>{this.cleanupWs(),this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()});r(this,"handleError",()=>{var e;(e=this.ws)==null||e.close()});this.endpoint=e??c.DEFAULT_ENDPOINT}get state(){return this._state}connect(){this.ws||this.permanentlyClosed||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",this.handleOpen),this.ws.addEventListener("message",this.handleMessage),this.ws.addEventListener("close",this.handleClose),this.ws.addEventListener("error",this.handleError))}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.cleanupWs(),this._state="disconnected",this.emit("state",this._state)}send(e){var t;((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}permanentDisconnect(){this.permanentlyClosed=!0,this.disconnect()}cleanupWs(){this.ws&&(this.ws.removeEventListener("open",this.handleOpen),this.ws.removeEventListener("message",this.handleMessage),this.ws.removeEventListener("close",this.handleClose),this.ws.removeEventListener("error",this.handleError),this.ws.close(),this.ws=null)}scheduleReconnect(){if(this.permanentlyClosed)return;const e=Math.min(c.RECONNECT_BASE_DELAY_MS*2**this.reconnectAttempt,c.RECONNECT_MAX_DELAY_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}}class u extends d{constructor(){super(...arguments);r(this,"baseUrl","");r(this,"_user",null);r(this,"_config",{...c.DEFAULT_ENV_CONFIG});r(this,"_p2pConfig",null);r(this,"_users",new Map);r(this,"_presence",new Map);r(this,"_threads",new Map);r(this,"_reactions",new Map);r(this,"_notifications",[]);r(this,"_activityLogs",[]);r(this,"_typing",new Map);r(this,"_viewports",new Map);r(this,"_selections",new Map)}get user(){return this._user}get p2pConfig(){return this._p2pConfig}get config(){return this._config}removeComment(e){for(const[t,s]of this._threads){const i=s.comments.findIndex(n=>n.id===e);if(i!==-1){s.comments.splice(i,1),s.comments.length===0&&this._threads.delete(t),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(e=>!e.read).length}markNotificationRead(e){const t=this._notifications.find(s=>s.id===e);t&&!t.read&&(t.read=!0,this.emit("notifications",this._notifications))}markAllNotificationsRead(){let e=!1;for(const t of this._notifications)t.read||(t.read=!0,e=!0);e&&this.emit("notifications",this._notifications)}get activityLogs(){return this._activityLogs}getUser(e){return this._users.get(e)}get users(){return[...this._users.values()]}getReactions(e){return this._reactions.get(e)??[]}getTypingUsers(e){const t=this._typing.get(e);if(!t)return[];const s=Date.now(),i=[];for(const[n,o]of t)s-o<3e3&&i.push(n);return i}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}resolveUrl(e){return!this.baseUrl||!e||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}${e}`}resolveAttachments(e){return e.map(t=>({...t,url:this.resolveUrl(t.url),thumbnailUrl:t.thumbnailUrl?this.resolveUrl(t.thumbnailUrl):void 0}))}resolveComment(e){return!e.attachments||e.attachments.length===0?e:{...e,attachments:this.resolveAttachments(e.attachments)}}resolveThread(e){return{...e,comments:e.comments.map(t=>this.resolveComment(t))}}handleMessage(e){switch(e.type){case"auth:ok":this._config=e.config??{...c.DEFAULT_ENV_CONFIG},this._p2pConfig=e.p2pConfig??null,this._user=e.user,this._users.clear();for(const t of e.users)this._users.set(t.id,t);this._presence.clear();for(const t of e.presence)this._presence.set(t.user.id,t),this._users.set(t.user.id,t.user);this._users.set(e.user.id,e.user),this._threads.clear();for(const t of e.threads)this._threads.set(t.id,this.resolveThread(t));this._notifications=e.notifications,this._reactions.clear();for(const t of e.reactions){const s=this._reactions.get(t.targetId)??[];s.push(t),this._reactions.set(t.targetId,s)}this._activityLogs=[...e.activityLogs],this.emit("auth",e.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(e.user.user.id,e.user),this._users.set(e.user.user.id,e.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(e.userId),this._viewports.delete(e.userId),this._selections.delete(e.userId);for(const t of this._typing.values())t.delete(e.userId);this.emit("presence",this.presence);break;case"presence:update":{const t=this._presence.get(e.userId);t&&(t.status=e.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:e.userId,position:e.position});break;case"click:perform":this.emit("click",{userId:e.userId,position:e.position});break;case"thread:created":this._threads.set(e.thread.id,this.resolveThread(e.thread)),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(this.resolveComment(e.comment)),t.updatedAt=e.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const t=this._threads.get(e.threadId);if(t){const s=t.comments.findIndex(i=>i.id===e.comment.id);s!==-1&&(t.comments[s]=this.resolveComment(e.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const t=this._threads.get(e.threadId);t&&(t.comments=t.comments.filter(s=>s.id!==e.commentId),t.comments.length===0&&this._threads.delete(e.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const t=this._threads.get(e.threadId);t&&(t.resolved=e.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(e.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const t=this._reactions.get(e.reaction.targetId)??[];t.push(e.reaction),this._reactions.set(e.reaction.targetId,t),this.emit("reactions",{targetId:e.reaction.targetId,reactions:t});break}case"reaction:removed":{const t=this._reactions.get(e.targetId);if(t){const s=t.filter(i=>i.id!==e.reactionId);this._reactions.set(e.targetId,s),this.emit("reactions",{targetId:e.targetId,reactions:s})}break}case"notification":this._notifications.unshift(e.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(e.threadId)||this._typing.set(e.threadId,new Map),this._typing.get(e.threadId).set(e.userId,Date.now()),this.emit("typing",{threadId:e.threadId,userId:e.userId});break}case"viewport:update":{this._viewports.set(e.userId,{scrollX:e.scrollX,scrollY:e.scrollY,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,pageWidth:e.pageWidth,pageHeight:e.pageHeight}),this.emit("viewport",{userId:e.userId});break}case"selection:update":this._selections.set(e.userId,e.selection),this.emit("selection",{userId:e.userId,selection:e.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:e.userId,emoji:e.emoji,position:e.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:e.userId,points:e.points,color:e.color,width:e.width});break;case"draw:clear":this.emit("draw-clear",{userId:e.userId});break;case"activity:logged":this._activityLogs.unshift(e.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"auth:error":this.emit("auth:error",e);break;case"error":this.emit("error",e);break}}reset(){this._user=null,this._config={...c.DEFAULT_ENV_CONFIG},this._p2pConfig=null,this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}}class m extends d{constructor(e){var s;super();r(this,"state");r(this,"connection");r(this,"config");r(this,"heartbeatTimer",null);r(this,"lastCursorSend",0);r(this,"pendingCursor",null);r(this,"cursorTimer",null);r(this,"_p2p",null);r(this,"_p2pInstance",null);r(this,"p2pEnabled");r(this,"iceServers");r(this,"signalingQueue",[]);this.config=e,this.state=new u,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const t=((s=e.endpoint)==null?void 0:s.replace(/^http/,"ws"))??void 0;this.connection=new p(t),this.p2pEnabled=e.p2p??!1,this.iceServers=e.iceServers??[{urls:"stun:stun.l.google.com:19302"}],this.connection.on("message",i=>{this.state.handleMessage(i),this.emit(i.type,i),i.type==="auth:error"&&this.connection.permanentDisconnect(),i.type==="signal:offer"||i.type==="signal:answer"||i.type==="signal:ice"||i.type==="p2p:sync"?this._p2pInstance?this.routeP2PMessage(i):this.p2pEnabled&&this.signalingQueue.push(i):this._p2pInstance&&(i.type==="presence:join"?this._p2pInstance.onPeerJoined(i.user.user.id):i.type==="presence:leave"&&this._p2pInstance.onPeerLeft(i.userId))}),this.connection.on("state",i=>{this.emit("connection",i),i==="connected"?(this.authenticate(),this.startHeartbeat()):i==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null),this.connection.disconnect(),this.state.reset()}destroy(){var e;(e=this._p2pInstance)==null||e.destroy(),this._p2pInstance=null,this._p2p=null,this.disconnect(),this.removeAll(),this.state.removeAll(),this.connection.removeAll()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(e){this.connection.send(e)}moveCursor(e){const t=Date.now();this.pendingCursor=e,t-this.lastCursorSend>=c.CURSOR_THROTTLE_MS?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},c.CURSOR_THROTTLE_MS))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(e){this.send({type:"presence:update",status:e})}startHeartbeat(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},c.PRESENCE_HEARTBEAT_MS))}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(e,t={}){const s=crypto.randomUUID();return this.send({type:"thread:create",id:s,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),s}reply(e,t,s=[],i){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:s,attachmentIds:i}),n}editComment(e,t,s=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:s})}deleteComment(e){this.state.removeComment(e),this.send({type:"comment:delete",commentId:e})}resolveThread(e,t=!0){this.send({type:"thread:resolve",threadId:e,resolved:t})}addReaction(e,t,s){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:s})}removeReaction(e){this.send({type:"reaction:remove",reactionId:e})}markRead(e){this.state.markNotificationRead(e),this.send({type:"notification:read",notificationId:e})}markAllRead(){this.state.markAllNotificationsRead(),this.send({type:"notification:read-all"})}performClick(e){this.send({type:"click:perform",position:e})}sendTyping(e){this.send({type:"typing:start",threadId:e})}updateViewport(e){this.send({type:"viewport:update",...e})}updateSelection(e){this.send({type:"selection:update",selection:e})}dropEmoji(e,t){this.send({type:"emoji:drop",emoji:e,position:t})}drawStroke(e,t,s){this.send({type:"draw:stroke",points:e,color:t,width:s})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=typeof window<"u"?window.location.origin:"",s=(this.config.endpoint??t).replace(/^ws(s?):/,"http$1:"),i=new FormData;i.append("file",e);const n=await fetch(`${s}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:i});if(!n.ok){const l=await n.json().catch(()=>({error:"Upload failed"}));throw new Error(l.error??"Upload failed")}const o=await n.json();return o.url&&!o.url.startsWith("http")&&(o.url=`${s}${o.url}`),o.thumbnailUrl&&!o.thumbnailUrl.startsWith("http")&&(o.thumbnailUrl=`${s}${o.thumbnailUrl}`),o}setAppearOffline(e){e?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}get p2p(){return this.p2pEnabled?(this._p2p||(this._p2p=this.initP2P()),this._p2p):Promise.reject(new Error("P2P is not enabled. Pass { p2p: true } in PulseConfig."))}async initP2P(){const e=await new Promise((n,o)=>{if(this.state.user&&this.state.p2pConfig){n({userId:this.state.user.id,p2pConfig:this.state.p2pConfig});return}const l=this.state.on("auth",()=>{if(l(),!this.state.p2pConfig){o(new Error("P2P is not enabled for this environment."));return}n({userId:this.state.user.id,p2pConfig:this.state.p2pConfig})})});let t=this.iceServers;try{const n=await fetch(`${this.state.baseUrl}/api/v1/turn-credentials`,{headers:{Authorization:`Bearer ${this.config.token}`}});n.ok&&(t=(await n.json()).iceServers)}catch{}const{P2PManager:s}=await Promise.resolve().then(()=>require("./P2PManager-DvcbFu7Y.cjs")),i=new s({roomId:this.config.room,userId:e.userId,baseUrl:this.state.baseUrl,authToken:this.config.token,p2pConfig:e.p2pConfig,iceServers:t,sendWS:n=>this.send(n)});this._p2pInstance=i,await i.initialize();for(const n of this.state.presence)n.user.id!==e.userId&&i.onPeerJoined(n.user.id);for(const n of this.signalingQueue)this.routeP2PMessage(n);return this.signalingQueue=[],i}routeP2PMessage(e){this._p2pInstance&&(e.type==="signal:offer"?this._p2pInstance.handleSignalOffer(e.fromUserId,e.sdp):e.type==="signal:answer"?this._p2pInstance.handleSignalAnswer(e.fromUserId,e.sdp):e.type==="signal:ice"?this._p2pInstance.handleIceCandidate(e.fromUserId,e.candidate):e.type==="p2p:sync"&&this._p2pInstance.handleP2PSync(e.fromUserId,e.update))}}exports.Connection=p;exports.Emitter=d;exports.PulseClient=m;exports.StateManager=u;
@@ -527,7 +527,7 @@ class C extends l {
527
527
  n.ok && (t = (await n.json()).iceServers);
528
528
  } catch {
529
529
  }
530
- const { P2PManager: s } = await import("./P2PManager-CwR8sbb_.js"), i = new s({
530
+ const { P2PManager: s } = await import("./P2PManager-D6Mx1Ibo.js"), i = new s({
531
531
  roomId: this.config.room,
532
532
  userId: e.userId,
533
533
  baseUrl: this.state.baseUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamention/pulse-core",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "Core client SDK for Pulse — WebSocket connection, state management, and API for real-time collaboration",
5
5
  "type": "module",
6
6
  "main": "./dist/pulse-core.cjs",