@gamention/pulse-core 0.3.2 → 0.3.3

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.
@@ -1,15 +1,16 @@
1
1
  var Zs = Object.defineProperty;
2
2
  var Qs = (n, t, e) => t in n ? Zs(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var k = (n, t, e) => Qs(n, typeof t != "symbol" ? t + "" : t, e);
3
+ var y = (n, t, e) => Qs(n, typeof t != "symbol" ? t + "" : t, e);
4
4
  import { Emitter as Ye } from "./pulse-core.js";
5
5
  class tr extends Ye {
6
- constructor(e, s, r) {
6
+ constructor(e, s, r, i) {
7
7
  super();
8
- k(this, "peers", /* @__PURE__ */ new Map());
9
- k(this, "iceServers");
10
- k(this, "meshLimit");
11
- k(this, "sendSignal");
12
- this.iceServers = e, this.meshLimit = s, this.sendSignal = r;
8
+ y(this, "peers", /* @__PURE__ */ new Map());
9
+ y(this, "iceServers");
10
+ y(this, "meshLimit");
11
+ y(this, "localUserId");
12
+ y(this, "sendSignal");
13
+ this.iceServers = e, this.meshLimit = s, this.localUserId = r, this.sendSignal = i;
13
14
  }
14
15
  get peerStates() {
15
16
  var s;
@@ -33,6 +34,8 @@ class tr extends Ye {
33
34
  this.emit("peer:fallback", e);
34
35
  return;
35
36
  }
37
+ if (this.localUserId > e)
38
+ return;
36
39
  const s = this.createPeerConnection(e), r = this.peers.get(e);
37
40
  r.crdtChannel = s.createDataChannel("crdt", { ordered: !0 }), r.rawChannel = s.createDataChannel("raw", { ordered: !1 }), this.setupDataChannelHandlers(e, r.crdtChannel, "crdt"), this.setupDataChannelHandlers(e, r.rawChannel, "raw");
38
41
  const i = await s.createOffer();
@@ -256,7 +259,7 @@ const fe = () => new Rt(), yr = (n) => {
256
259
  }, E = (n, t) => {
257
260
  const e = n.cbuf.length;
258
261
  n.cpos === e && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(e * 2), n.cpos = 0), n.cbuf[n.cpos++] = t;
259
- }, Fe = E, y = (n, t) => {
262
+ }, Fe = E, m = (n, t) => {
260
263
  for (; t > Z; )
261
264
  E(n, T | Z & t), t = F(t / 128);
262
265
  E(n, Z & t);
@@ -267,14 +270,14 @@ const fe = () => new Rt(), yr = (n) => {
267
270
  }, Be = new Uint8Array(3e4), kr = Be.length / 3, br = (n, t) => {
268
271
  if (t.length < kr) {
269
272
  const e = It.encodeInto(t, Be).written || 0;
270
- y(n, e);
273
+ m(n, e);
271
274
  for (let s = 0; s < e; s++)
272
275
  E(n, Be[s]);
273
276
  } else
274
277
  x(n, pr(t));
275
278
  }, Sr = (n, t) => {
276
279
  const e = unescape(encodeURIComponent(t)), s = e.length;
277
- y(n, s);
280
+ m(n, s);
278
281
  for (let r = 0; r < s; r++)
279
282
  E(
280
283
  n,
@@ -286,7 +289,7 @@ It.encodeInto ? br : Sr, ge = (n, t) => {
286
289
  const e = n.cbuf.length, s = n.cpos, r = zn(e - s, t.length), i = t.length - r;
287
290
  n.cbuf.set(t.subarray(0, r), s), n.cpos += r, i > 0 && (n.bufs.push(n.cbuf), n.cbuf = new Uint8Array(st(e * 2, i)), n.cbuf.set(t.subarray(r)), n.cpos = i);
288
291
  }, x = (n, t) => {
289
- y(n, t.byteLength), ge(n, t);
292
+ m(n, t.byteLength), ge(n, t);
290
293
  }, Xe = (n, t) => {
291
294
  mr(n, t);
292
295
  const e = new DataView(n.cbuf.buffer, n.cpos, t);
@@ -309,7 +312,7 @@ It.encodeInto ? br : Sr, ge = (n, t) => {
309
312
  if (t === null)
310
313
  E(n, 126);
311
314
  else if (ue(t)) {
312
- E(n, 117), y(n, t.length);
315
+ E(n, 117), m(n, t.length);
313
316
  for (let e = 0; e < t.length; e++)
314
317
  Ot(n, t[e]);
315
318
  } else if (t instanceof Uint8Array)
@@ -317,7 +320,7 @@ It.encodeInto ? br : Sr, ge = (n, t) => {
317
320
  else {
318
321
  E(n, 118);
319
322
  const e = Object.keys(t);
320
- y(n, e.length);
323
+ m(n, e.length);
321
324
  for (let s = 0; s < e.length; s++) {
322
325
  const r = e[s];
323
326
  lt(n, r), Ot(n, t[r]);
@@ -342,11 +345,11 @@ class Cn extends Rt {
342
345
  * @param {T} v
343
346
  */
344
347
  write(t) {
345
- this.s === t ? this.count++ : (this.count > 0 && y(this, this.count - 1), this.count = 1, this.w(this, t), this.s = t);
348
+ this.s === t ? this.count++ : (this.count > 0 && m(this, this.count - 1), this.count = 1, this.w(this, t), this.s = t);
346
349
  }
347
350
  }
348
351
  const En = (n) => {
349
- n.count > 0 && (We(n.encoder, n.count === 1 ? n.s : -n.s), n.count > 1 && y(n.encoder, n.count - 2));
352
+ n.count > 0 && (We(n.encoder, n.count === 1 ? n.s : -n.s), n.count > 1 && m(n.encoder, n.count - 2));
350
353
  };
351
354
  class Pt {
352
355
  constructor() {
@@ -370,7 +373,7 @@ class Pt {
370
373
  const Dn = (n) => {
371
374
  if (n.count > 0) {
372
375
  const t = n.diff * 2 + (n.count === 1 ? 0 : 1);
373
- We(n.encoder, t), n.count > 1 && y(n.encoder, n.count - 2);
376
+ We(n.encoder, t), n.count > 1 && m(n.encoder, n.count - 2);
374
377
  }
375
378
  };
376
379
  class Me {
@@ -881,7 +884,7 @@ class M {
881
884
  * union). By default, the more objects are added, the the fewer objects this schema will accept.
882
885
  * @protected
883
886
  */
884
- k(M, "_dilutes", !1);
887
+ y(M, "_dilutes", !1);
885
888
  class nn extends M {
886
889
  /**
887
890
  * @param {C} c
@@ -1036,7 +1039,7 @@ const ae = class ae extends M {
1036
1039
  });
1037
1040
  }
1038
1041
  };
1039
- k(ae, "_dilutes", !0);
1042
+ y(ae, "_dilutes", !0);
1040
1043
  let Qt = ae;
1041
1044
  const fi = (n) => (
1042
1045
  /** @type {any} */
@@ -1182,7 +1185,7 @@ class me extends M {
1182
1185
  return e == null || e.extend(null, "Union", typeof t), s;
1183
1186
  }
1184
1187
  }
1185
- k(me, "_dilutes", !0);
1188
+ y(me, "_dilutes", !0);
1186
1189
  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 = (
1187
1190
  /** @type {Schema<$Union<any>>} */
1188
1191
  S(me)
@@ -1531,10 +1534,10 @@ const bs = (n, t, e) => t.clients.forEach((s, r) => {
1531
1534
  r.length > 0 && t.clients.set(s, r);
1532
1535
  }), t;
1533
1536
  }, _t = (n, t) => {
1534
- y(n.restEncoder, t.clients.size), Q(t.clients.entries()).sort((e, s) => s[0] - e[0]).forEach(([e, s]) => {
1535
- n.resetDsCurVal(), y(n.restEncoder, e);
1537
+ m(n.restEncoder, t.clients.size), Q(t.clients.entries()).sort((e, s) => s[0] - e[0]).forEach(([e, s]) => {
1538
+ n.resetDsCurVal(), m(n.restEncoder, e);
1536
1539
  const r = s.length;
1537
- y(n.restEncoder, r);
1540
+ m(n.restEncoder, r);
1538
1541
  for (let i = 0; i < r; i++) {
1539
1542
  const o = s[i];
1540
1543
  n.writeDsClock(o.clock), n.writeDsLen(o.len);
@@ -1573,7 +1576,7 @@ const bs = (n, t, e) => t.clients.forEach((s, r) => {
1573
1576
  }
1574
1577
  if (s.clients.size > 0) {
1575
1578
  const i = new tt();
1576
- return y(i.restEncoder, 0), _t(i, s), i.toUint8Array();
1579
+ return m(i.restEncoder, 0), _t(i, s), i.toUint8Array();
1577
1580
  }
1578
1581
  return null;
1579
1582
  }, _s = Yn;
@@ -2024,13 +2027,13 @@ class to {
2024
2027
  * @param {number} clock
2025
2028
  */
2026
2029
  writeDsClock(t) {
2027
- y(this.restEncoder, t);
2030
+ m(this.restEncoder, t);
2028
2031
  }
2029
2032
  /**
2030
2033
  * @param {number} len
2031
2034
  */
2032
2035
  writeDsLen(t) {
2033
- y(this.restEncoder, t);
2036
+ m(this.restEncoder, t);
2034
2037
  }
2035
2038
  }
2036
2039
  class jt extends to {
@@ -2038,20 +2041,20 @@ class jt extends to {
2038
2041
  * @param {ID} id
2039
2042
  */
2040
2043
  writeLeftID(t) {
2041
- y(this.restEncoder, t.client), y(this.restEncoder, t.clock);
2044
+ m(this.restEncoder, t.client), m(this.restEncoder, t.clock);
2042
2045
  }
2043
2046
  /**
2044
2047
  * @param {ID} id
2045
2048
  */
2046
2049
  writeRightID(t) {
2047
- y(this.restEncoder, t.client), y(this.restEncoder, t.clock);
2050
+ m(this.restEncoder, t.client), m(this.restEncoder, t.clock);
2048
2051
  }
2049
2052
  /**
2050
2053
  * Use writeClient and writeClock instead of writeID if possible.
2051
2054
  * @param {number} client
2052
2055
  */
2053
2056
  writeClient(t) {
2054
- y(this.restEncoder, t);
2057
+ m(this.restEncoder, t);
2055
2058
  }
2056
2059
  /**
2057
2060
  * @param {number} info An unsigned 8-bit integer
@@ -2069,13 +2072,13 @@ class jt extends to {
2069
2072
  * @param {boolean} isYKey
2070
2073
  */
2071
2074
  writeParentInfo(t) {
2072
- y(this.restEncoder, t ? 1 : 0);
2075
+ m(this.restEncoder, t ? 1 : 0);
2073
2076
  }
2074
2077
  /**
2075
2078
  * @param {number} info An unsigned 8-bit integer
2076
2079
  */
2077
2080
  writeTypeRef(t) {
2078
- y(this.restEncoder, t);
2081
+ m(this.restEncoder, t);
2079
2082
  }
2080
2083
  /**
2081
2084
  * Write len of a struct - well suited for Opt RLE encoder.
@@ -2083,7 +2086,7 @@ class jt extends to {
2083
2086
  * @param {number} len
2084
2087
  */
2085
2088
  writeLen(t) {
2086
- y(this.restEncoder, t);
2089
+ m(this.restEncoder, t);
2087
2090
  }
2088
2091
  /**
2089
2092
  * @param {any} any
@@ -2125,13 +2128,13 @@ class eo {
2125
2128
  */
2126
2129
  writeDsClock(t) {
2127
2130
  const e = t - this.dsCurrVal;
2128
- this.dsCurrVal = t, y(this.restEncoder, e);
2131
+ this.dsCurrVal = t, m(this.restEncoder, e);
2129
2132
  }
2130
2133
  /**
2131
2134
  * @param {number} len
2132
2135
  */
2133
2136
  writeDsLen(t) {
2134
- t === 0 && N(), y(this.restEncoder, t - 1), this.dsCurrVal += t;
2137
+ t === 0 && N(), m(this.restEncoder, t - 1), this.dsCurrVal += t;
2135
2138
  }
2136
2139
  }
2137
2140
  class tt extends eo {
@@ -2140,7 +2143,7 @@ class tt extends eo {
2140
2143
  }
2141
2144
  toUint8Array() {
2142
2145
  const t = fe();
2143
- return y(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);
2146
+ 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);
2144
2147
  }
2145
2148
  /**
2146
2149
  * @param {ID} id
@@ -2230,7 +2233,7 @@ class tt extends eo {
2230
2233
  const no = (n, t, e, s) => {
2231
2234
  s = st(s, t[0].id.clock);
2232
2235
  const r = J(t, s);
2233
- y(n.restEncoder, t.length - r), n.writeClient(e), y(n.restEncoder, s);
2236
+ m(n.restEncoder, t.length - r), n.writeClient(e), m(n.restEncoder, s);
2234
2237
  const i = t[r];
2235
2238
  i.write(n, s - i.id.clock);
2236
2239
  for (let o = r + 1; o < t.length; o++)
@@ -2241,7 +2244,7 @@ const no = (n, t, e, s) => {
2241
2244
  D(t, i) > r && s.set(i, r);
2242
2245
  }), an(t).forEach((r, i) => {
2243
2246
  e.has(i) || s.set(i, 0);
2244
- }), y(n.restEncoder, s.size), Q(s.entries()).sort((r, i) => i[0] - r[0]).forEach(([r, i]) => {
2247
+ }), m(n.restEncoder, s.size), Q(s.entries()).sort((r, i) => i[0] - r[0]).forEach(([r, i]) => {
2245
2248
  no(
2246
2249
  n,
2247
2250
  /** @type {Array<GC|Item>} */
@@ -2317,8 +2320,8 @@ const no = (n, t, e, s) => {
2317
2320
  if (o === null)
2318
2321
  return null;
2319
2322
  const c = new Os(), l = /* @__PURE__ */ new Map(), h = (f, g) => {
2320
- const m = l.get(f);
2321
- (m == null || m > g) && l.set(f, g);
2323
+ const k = l.get(f);
2324
+ (k == null || k > g) && l.set(f, g);
2322
2325
  };
2323
2326
  let a = (
2324
2327
  /** @type {any} */
@@ -2329,8 +2332,8 @@ const no = (n, t, e, s) => {
2329
2332
  );
2330
2333
  const u = /* @__PURE__ */ new Map(), d = () => {
2331
2334
  for (const f of s) {
2332
- const g = f.id.client, m = e.get(g);
2333
- m ? (m.i--, c.clients.set(g, m.refs.slice(m.i)), e.delete(g), m.i = 0, m.refs = []) : c.clients.set(g, [f]), r = r.filter((it) => it !== g);
2335
+ const g = f.id.client, k = e.get(g);
2336
+ 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);
2334
2337
  }
2335
2338
  s.length = 0;
2336
2339
  };
@@ -2340,18 +2343,18 @@ const no = (n, t, e, s) => {
2340
2343
  if (g < 0)
2341
2344
  s.push(a), h(a.id.client, a.id.clock - 1), d();
2342
2345
  else {
2343
- const m = a.getMissing(n, t);
2344
- if (m !== null) {
2346
+ const k = a.getMissing(n, t);
2347
+ if (k !== null) {
2345
2348
  s.push(a);
2346
2349
  const it = e.get(
2347
2350
  /** @type {number} */
2348
- m
2351
+ k
2349
2352
  ) || { refs: [], i: 0 };
2350
2353
  if (it.refs.length === it.i)
2351
2354
  h(
2352
2355
  /** @type {number} */
2353
- m,
2354
- D(t, m)
2356
+ k,
2357
+ D(t, k)
2355
2358
  ), d();
2356
2359
  else {
2357
2360
  a = it.refs[it.i++];
@@ -2375,7 +2378,7 @@ const no = (n, t, e, s) => {
2375
2378
  }
2376
2379
  if (c.clients.size > 0) {
2377
2380
  const f = new tt();
2378
- return hn(f, c, /* @__PURE__ */ new Map()), y(f.restEncoder, 0), { missing: l, update: f.toUint8Array() };
2381
+ return hn(f, c, /* @__PURE__ */ new Map()), m(f.restEncoder, 0), { missing: l, update: f.toUint8Array() };
2379
2382
  }
2380
2383
  return null;
2381
2384
  }, io = (n, t) => hn(n, t.doc.store, t.beforeState), oo = (n, t, e, s = new wt(n)) => b(t, (r) => {
@@ -2629,8 +2632,8 @@ const Rn = (n, t) => t.deleteSet.clients.size === 0 && !nr(t.afterState, (e, s)
2629
2632
  /** @type {Array<GC|Item>} */
2630
2633
  r.clients.get(u)
2631
2634
  ), g = st(J(f, d), 1);
2632
- for (let m = f.length - 1; m >= g; )
2633
- m -= 1 + Wt(f, m);
2635
+ for (let k = f.length - 1; k >= g; )
2636
+ k -= 1 + Wt(f, k);
2634
2637
  }
2635
2638
  });
2636
2639
  for (let a = o.length - 1; a >= 0; a--) {
@@ -2834,14 +2837,14 @@ const bo = (n) => se(n, Es, jt), So = (n, t) => {
2834
2837
  }, Ts = (n) => {
2835
2838
  n.written > 0 && (n.clientStructs.push({ written: n.written, restEncoder: j(n.encoder.restEncoder) }), n.encoder.restEncoder = fe(), n.written = 0);
2836
2839
  }, K = (n, t, e) => {
2837
- n.written > 0 && n.currClient !== t.id.client && Ts(n), n.written === 0 && (n.currClient = t.id.client, n.encoder.writeClient(t.id.client), y(n.encoder.restEncoder, t.id.clock + e)), t.write(n.encoder, e), n.written++;
2840
+ 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++;
2838
2841
  }, fn = (n) => {
2839
2842
  Ts(n);
2840
2843
  const t = n.encoder.restEncoder;
2841
- y(t, n.clientStructs.length);
2844
+ m(t, n.clientStructs.length);
2842
2845
  for (let e = 0; e < n.clientStructs.length; e++) {
2843
2846
  const s = n.clientStructs[e];
2844
- y(t, s.written), ge(t, s.restEncoder);
2847
+ m(t, s.written), ge(t, s.restEncoder);
2845
2848
  }
2846
2849
  }, Co = (n, t, e, s) => {
2847
2850
  const r = new e(bt(n)), i = new un(r, !1), o = new s(), c = new dn(o);
@@ -4158,8 +4161,8 @@ class jo extends Ce {
4158
4161
  u > 0 && (f = { delete: u }), u = 0;
4159
4162
  break;
4160
4163
  case "insert":
4161
- (typeof h == "object" || h.length > 0) && (f = { insert: h }, r.size > 0 && (f.attributes = {}, r.forEach((g, m) => {
4162
- g !== null && (f.attributes[m] = g);
4164
+ (typeof h == "object" || h.length > 0) && (f = { insert: h }, r.size > 0 && (f.attributes = {}, r.forEach((g, k) => {
4165
+ g !== null && (f.attributes[k] = g);
4163
4166
  }))), h = "";
4164
4167
  break;
4165
4168
  case "retain":
@@ -4186,17 +4189,17 @@ class jo extends Ce {
4186
4189
  );
4187
4190
  if (this.adds(o)) {
4188
4191
  if (!this.deletes(o)) {
4189
- const m = r.get(f) ?? null;
4190
- W(m, g) ? g !== null && o.delete(s) : (c === "retain" && d(), W(g, i.get(f) ?? null) ? delete l[f] : l[f] = g);
4192
+ const k = r.get(f) ?? null;
4193
+ W(k, g) ? g !== null && o.delete(s) : (c === "retain" && d(), W(g, i.get(f) ?? null) ? delete l[f] : l[f] = g);
4191
4194
  }
4192
4195
  } else if (this.deletes(o)) {
4193
4196
  i.set(f, g);
4194
- const m = r.get(f) ?? null;
4195
- W(m, g) || (c === "retain" && d(), l[f] = m);
4197
+ const k = r.get(f) ?? null;
4198
+ W(k, g) || (c === "retain" && d(), l[f] = k);
4196
4199
  } else if (!o.deleted) {
4197
4200
  i.set(f, g);
4198
- const m = l[f];
4199
- m !== void 0 && (W(m, g) ? m !== null && o.delete(s) : (c === "retain" && d(), g === null ? delete l[f] : l[f] = g));
4201
+ const k = l[f];
4202
+ k !== void 0 && (W(k, g) ? k !== null && o.delete(s) : (c === "retain" && d(), g === null ? delete l[f] : l[f] = g));
4200
4203
  }
4201
4204
  o.deleted || (c === "insert" && d(), Et(
4202
4205
  r,
@@ -4342,8 +4345,8 @@ class mt extends I {
4342
4345
  if (c.length > 0) {
4343
4346
  const u = {};
4344
4347
  let d = !1;
4345
- i.forEach((g, m) => {
4346
- d = !0, u[m] = g;
4348
+ i.forEach((g, k) => {
4349
+ d = !0, u[k] = g;
4347
4350
  });
4348
4351
  const f = { insert: c };
4349
4352
  d && (f.attributes = u), r.push(f), c = "";
@@ -6324,7 +6327,7 @@ class U extends yn {
6324
6327
  * @param {number} offset
6325
6328
  */
6326
6329
  write(t, e) {
6327
- t.writeInfo(dc), y(t.restEncoder, this.length - e);
6330
+ t.writeInfo(dc), m(t.restEncoder, this.length - e);
6328
6331
  }
6329
6332
  /**
6330
6333
  * @param {Transaction} transaction
@@ -6344,13 +6347,13 @@ Xs[qs] = !0;
6344
6347
  class fc extends Ye {
6345
6348
  constructor(e) {
6346
6349
  super();
6347
- k(this, "doc");
6348
- k(this, "config");
6349
- k(this, "transport", "websocket");
6350
- k(this, "persistTimer", null);
6351
- k(this, "dirty", !1);
6352
- k(this, "sharedObjectCount", 0);
6353
- k(this, "destroyed", !1);
6350
+ y(this, "doc");
6351
+ y(this, "config");
6352
+ y(this, "transport", "websocket");
6353
+ y(this, "persistTimer", null);
6354
+ y(this, "dirty", !1);
6355
+ y(this, "sharedObjectCount", 0);
6356
+ y(this, "destroyed", !1);
6354
6357
  this.config = e, this.doc = new Ct(), this.doc.on("update", (s, r) => {
6355
6358
  r !== "remote" && (this.dirty = !0, this.broadcastUpdate(s));
6356
6359
  }), this.persistTimer = setInterval(() => {
@@ -6445,9 +6448,9 @@ class fc extends Ye {
6445
6448
  }
6446
6449
  class gc {
6447
6450
  constructor(t) {
6448
- k(this, "ymap");
6449
- k(this, "listeners", /* @__PURE__ */ new Set());
6450
- k(this, "observer");
6451
+ y(this, "ymap");
6452
+ y(this, "listeners", /* @__PURE__ */ new Set());
6453
+ y(this, "observer");
6451
6454
  this.ymap = t, this.observer = (e) => {
6452
6455
  const s = [];
6453
6456
  if (e.changes.keys.forEach((r, i) => {
@@ -6505,9 +6508,9 @@ class gc {
6505
6508
  }
6506
6509
  class pc {
6507
6510
  constructor(t) {
6508
- k(this, "yarray");
6509
- k(this, "listeners", /* @__PURE__ */ new Set());
6510
- k(this, "observer");
6511
+ y(this, "yarray");
6512
+ y(this, "listeners", /* @__PURE__ */ new Set());
6513
+ y(this, "observer");
6511
6514
  this.yarray = t, this.observer = (e) => {
6512
6515
  const s = [];
6513
6516
  let r = 0;
@@ -6562,10 +6565,10 @@ class pc {
6562
6565
  }
6563
6566
  class wc {
6564
6567
  constructor(t, e) {
6565
- k(this, "ymap");
6566
- k(this, "clientKey");
6567
- k(this, "listeners", /* @__PURE__ */ new Set());
6568
- k(this, "observer");
6568
+ y(this, "ymap");
6569
+ y(this, "clientKey");
6570
+ y(this, "listeners", /* @__PURE__ */ new Set());
6571
+ y(this, "observer");
6569
6572
  this.ymap = t, this.clientKey = e, this.observer = () => {
6570
6573
  const s = this.value;
6571
6574
  for (const r of this.listeners)
@@ -6595,16 +6598,17 @@ class wc {
6595
6598
  class kc extends Ye {
6596
6599
  constructor(e) {
6597
6600
  super();
6598
- k(this, "peerManager");
6599
- k(this, "syncEngine");
6600
- k(this, "config");
6601
- k(this, "sharedMaps", /* @__PURE__ */ new Map());
6602
- k(this, "sharedLists", /* @__PURE__ */ new Map());
6603
- k(this, "sharedCounters", /* @__PURE__ */ new Map());
6604
- k(this, "destroyed", !1);
6601
+ y(this, "peerManager");
6602
+ y(this, "syncEngine");
6603
+ y(this, "config");
6604
+ y(this, "sharedMaps", /* @__PURE__ */ new Map());
6605
+ y(this, "sharedLists", /* @__PURE__ */ new Map());
6606
+ y(this, "sharedCounters", /* @__PURE__ */ new Map());
6607
+ y(this, "destroyed", !1);
6605
6608
  this.config = e, this.peerManager = new tr(
6606
6609
  e.iceServers,
6607
6610
  e.p2pConfig.meshLimit,
6611
+ e.userId,
6608
6612
  (s) => e.sendWS(s)
6609
6613
  ), this.syncEngine = new fc({
6610
6614
  roomId: e.roomId,
@@ -1,5 +1,5 @@
1
- "use strict";var Zs=Object.defineProperty;var Qs=(n,t,e)=>t in n?Zs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var k=(n,t,e)=>Qs(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("./pulse-core.cjs");class tr extends Ye.Emitter{constructor(e,s,r){super();k(this,"peers",new Map);k(this,"iceServers");k(this,"meshLimit");k(this,"sendSignal");this.iceServers=e,this.meshLimit=s,this.sendSignal=r}get peerStates(){var s;const e=new Map;for(const[r,i]of this.peers)e.set(r,{userId:r,state:i.state,dataChannelOpen:((s=i.crdtChannel)==null?void 0:s.readyState)==="open"});return e}get activePeerCount(){return this.peers.size}shouldUseMesh(){return this.peers.size<this.meshLimit}async createOffer(e){if(!this.shouldUseMesh()){this.emit("peer:fallback",e);return}const s=this.createPeerConnection(e),r=this.peers.get(e);r.crdtChannel=s.createDataChannel("crdt",{ordered:!0}),r.rawChannel=s.createDataChannel("raw",{ordered:!1}),this.setupDataChannelHandlers(e,r.crdtChannel,"crdt"),this.setupDataChannelHandlers(e,r.rawChannel,"raw");const i=await s.createOffer();await s.setLocalDescription(i),this.sendSignal({type:"signal:offer",targetUserId:e,sdp:s.localDescription})}async handleOffer(e,s){const r=this.createPeerConnection(e);r.ondatachannel=o=>{const c=this.peers.get(e);c&&(o.channel.label==="crdt"?(c.crdtChannel=o.channel,this.setupDataChannelHandlers(e,o.channel,"crdt")):o.channel.label==="raw"&&(c.rawChannel=o.channel,this.setupDataChannelHandlers(e,o.channel,"raw")))},await r.setRemoteDescription(s);const i=await r.createAnswer();await r.setLocalDescription(i),this.sendSignal({type:"signal:answer",targetUserId:e,sdp:r.localDescription})}async handleAnswer(e,s){const r=this.peers.get(e);r&&await r.pc.setRemoteDescription(s)}async handleIceCandidate(e,s){const r=this.peers.get(e);r&&await r.pc.addIceCandidate(s)}sendCrdt(e){var r;const s=e instanceof Uint8Array?e:new Uint8Array(e);for(const[,i]of this.peers)((r=i.crdtChannel)==null?void 0:r.readyState)==="open"&&i.crdtChannel.send(s)}sendRaw(e,s){var r,i;if(s){const o=this.peers.get(s);((r=o==null?void 0:o.rawChannel)==null?void 0:r.readyState)==="open"&&o.rawChannel.send(e);return}for(const[,o]of this.peers)((i=o==null?void 0:o.rawChannel)==null?void 0:i.readyState)==="open"&&o.rawChannel.send(e)}removePeer(e){var r,i;const s=this.peers.get(e);s&&((r=s.crdtChannel)==null||r.close(),(i=s.rawChannel)==null||i.close(),s.pc.close(),this.peers.delete(e),this.emit("peer:disconnected",e))}destroy(){for(const e of[...this.peers.keys()])this.removePeer(e);this.removeAll()}createPeerConnection(e){this.peers.has(e)&&this.removePeer(e);const s=new RTCPeerConnection({iceServers:this.iceServers}),r={pc:s,crdtChannel:null,rawChannel:null,state:"connecting"};return this.peers.set(e,r),s.onicecandidate=i=>{i.candidate&&this.sendSignal({type:"signal:ice",targetUserId:e,candidate:i.candidate})},s.onconnectionstatechange=()=>{const i=s.connectionState;i==="connected"?(r.state="connected",this.emit("peer:connected",e)):(i==="disconnected"||i==="failed"||i==="closed")&&(r.state="disconnected",this.removePeer(e))},s}setupDataChannelHandlers(e,s,r){s.binaryType="arraybuffer",s.onmessage=i=>{r==="crdt"?this.emit("crdt:message",{fromUserId:e,data:new Uint8Array(i.data)}):this.emit("raw:message",{fromUserId:e,data:i.data})}}}const R=()=>new Map,Ve=n=>{const t=R();return n.forEach((e,s)=>{t.set(s,e)}),t},q=(n,t,e)=>{let s=n.get(t);return s===void 0&&n.set(t,s=e()),s},er=(n,t)=>{const e=[];for(const[s,r]of n)e.push(t(r,s));return e},nr=(n,t)=>{for(const[e,s]of n)if(t(s,e))return!0;return!1},ft=()=>new Set,Ae=n=>n[n.length-1],sr=(n,t)=>{for(let e=0;e<t.length;e++)n.push(t[e])},Q=Array.from,Ke=(n,t)=>{for(let e=0;e<n.length;e++)if(!t(n[e],e,n))return!1;return!0},Jn=(n,t)=>{for(let e=0;e<n.length;e++)if(t(n[e],e,n))return!0;return!1},rr=(n,t)=>{const e=new Array(n);for(let s=0;s<n;s++)e[s]=t(s,e);return e},ue=Array.isArray;class ir{constructor(){this._observers=R()}on(t,e){return q(this._observers,t,ft).add(e),e}once(t,e){const s=(...r)=>{this.off(t,s),e(...r)};this.on(t,s)}off(t,e){const s=this._observers.get(t);s!==void 0&&(s.delete(e),s.size===0&&this._observers.delete(t))}emit(t,e){return Q((this._observers.get(t)||R()).values()).forEach(s=>s(...e))}destroy(){this._observers=R()}}const F=Math.floor,Ht=Math.abs,zn=(n,t)=>n<t?n:t,st=(n,t)=>n>t?n:t,Gn=n=>n!==0?n<0:1/n<0,mn=1,kn=2,Ie=4,Oe=8,At=32,H=64,T=128,de=31,je=63,Z=127,or=2147483647,Xt=Number.MAX_SAFE_INTEGER,bn=Number.MIN_SAFE_INTEGER,cr=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&F(n)===n),lr=String.fromCharCode,hr=n=>n.toLowerCase(),ar=/^\s*/g,ur=n=>n.replace(ar,""),dr=/([A-Z])/g,Sn=(n,t)=>ur(n.replace(dr,e=>`${t}${hr(e)}`)),fr=n=>{const t=unescape(encodeURIComponent(n)),e=t.length,s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t.codePointAt(r);return s},It=typeof TextEncoder<"u"?new TextEncoder:null,gr=n=>It.encode(n),pr=It?gr:fr;let Dt=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Dt&&Dt.decode(new Uint8Array).length===1&&(Dt=null);const wr=(n,t)=>rr(t,()=>n).join("");class Rt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const fe=()=>new Rt,yr=n=>{let t=n.cpos;for(let e=0;e<n.bufs.length;e++)t+=n.bufs[e].length;return t},j=n=>{const t=new Uint8Array(yr(n));let e=0;for(let s=0;s<n.bufs.length;s++){const r=n.bufs[s];t.set(r,e),e+=r.length}return t.set(new Uint8Array(n.cbuf.buffer,0,n.cpos),e),t},mr=(n,t)=>{const e=n.cbuf.length;e-n.cpos<t&&(n.bufs.push(new Uint8Array(n.cbuf.buffer,0,n.cpos)),n.cbuf=new Uint8Array(st(e,t)*2),n.cpos=0)},E=(n,t)=>{const e=n.cbuf.length;n.cpos===e&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(e*2),n.cpos=0),n.cbuf[n.cpos++]=t},Fe=E,y=(n,t)=>{for(;t>Z;)E(n,T|Z&t),t=F(t/128);E(n,Z&t)},We=(n,t)=>{const e=Gn(t);for(e&&(t=-t),E(n,(t>je?T:0)|(e?H:0)|je&t),t=F(t/64);t>0;)E(n,(t>Z?T:0)|Z&t),t=F(t/128)},Be=new Uint8Array(3e4),kr=Be.length/3,br=(n,t)=>{if(t.length<kr){const e=It.encodeInto(t,Be).written||0;y(n,e);for(let s=0;s<e;s++)E(n,Be[s])}else x(n,pr(t))},Sr=(n,t)=>{const e=unescape(encodeURIComponent(t)),s=e.length;y(n,s);for(let r=0;r<s;r++)E(n,e.codePointAt(r))},lt=It&&It.encodeInto?br:Sr,ge=(n,t)=>{const e=n.cbuf.length,s=n.cpos,r=zn(e-s,t.length),i=t.length-r;n.cbuf.set(t.subarray(0,r),s),n.cpos+=r,i>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(st(e*2,i)),n.cbuf.set(t.subarray(r)),n.cpos=i)},x=(n,t)=>{y(n,t.byteLength),ge(n,t)},Xe=(n,t)=>{mr(n,t);const e=new DataView(n.cbuf.buffer,n.cpos,t);return n.cpos+=t,e},_r=(n,t)=>Xe(n,4).setFloat32(0,t,!1),Cr=(n,t)=>Xe(n,8).setFloat64(0,t,!1),Er=(n,t)=>Xe(n,8).setBigInt64(0,t,!1),_n=new DataView(new ArrayBuffer(4)),Dr=n=>(_n.setFloat32(0,n),_n.getFloat32(0)===n),Ot=(n,t)=>{switch(typeof t){case"string":E(n,119),lt(n,t);break;case"number":cr(t)&&Ht(t)<=or?(E(n,125),We(n,t)):Dr(t)?(E(n,124),_r(n,t)):(E(n,123),Cr(n,t));break;case"bigint":E(n,122),Er(n,t);break;case"object":if(t===null)E(n,126);else if(ue(t)){E(n,117),y(n,t.length);for(let e=0;e<t.length;e++)Ot(n,t[e])}else if(t instanceof Uint8Array)E(n,116),x(n,t);else{E(n,118);const e=Object.keys(t);y(n,e.length);for(let s=0;s<e.length;s++){const r=e[s];lt(n,r),Ot(n,t[r])}}break;case"boolean":E(n,t?120:121);break;default:E(n,127)}};class Cn extends Rt{constructor(t){super(),this.w=t,this.s=null,this.count=0}write(t){this.s===t?this.count++:(this.count>0&&y(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const En=n=>{n.count>0&&(We(n.encoder,n.count===1?n.s:-n.s),n.count>1&&y(n.encoder,n.count-2))};class Pt{constructor(){this.encoder=new Rt,this.s=0,this.count=0}write(t){this.s===t?this.count++:(En(this),this.count=1,this.s=t)}toUint8Array(){return En(this),j(this.encoder)}}const Dn=n=>{if(n.count>0){const t=n.diff*2+(n.count===1?0:1);We(n.encoder,t),n.count>1&&y(n.encoder,n.count-2)}};class Me{constructor(){this.encoder=new Rt,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Dn(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Dn(this),j(this.encoder)}}class Ar{constructor(){this.sarr=[],this.s="",this.lensE=new Pt}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Rt;return this.sarr.push(this.s),this.s="",lt(t,this.sarr.join("")),ge(t,this.lensE.toUint8Array()),j(t)}}const B=n=>new Error(n),$=()=>{throw B("Method unimplemented")},N=()=>{throw B("Unexpected case")},Hn=B("Unexpected end of array"),Pn=B("Integer out of Range");class pe{constructor(t){this.arr=t,this.pos=0}}const bt=n=>new pe(n),Ir=n=>n.pos!==n.arr.length,Or=(n,t)=>{const e=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,e},L=n=>Or(n,p(n)),gt=n=>n.arr[n.pos++],p=n=>{let t=0,e=1;const s=n.arr.length;for(;n.pos<s;){const r=n.arr[n.pos++];if(t=t+(r&Z)*e,e*=128,r<T)return t;if(t>Xt)throw Pn}throw Hn},qe=n=>{let t=n.arr[n.pos++],e=t&je,s=64;const r=(t&H)>0?-1:1;if((t&T)===0)return r*e;const i=n.arr.length;for(;n.pos<i;){if(t=n.arr[n.pos++],e=e+(t&Z)*s,s*=128,t<T)return r*e;if(e>Xt)throw Pn}throw Hn},Mr=n=>{let t=p(n);if(t===0)return"";{let e=String.fromCodePoint(gt(n));if(--t<100)for(;t--;)e+=String.fromCodePoint(gt(n));else for(;t>0;){const s=t<1e4?t:1e4,r=n.arr.subarray(n.pos,n.pos+s);n.pos+=s,e+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(e))}},xr=n=>Dt.decode(L(n)),ht=Dt?xr:Mr,Ze=(n,t)=>{const e=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,t);return n.pos+=t,e},Lr=n=>Ze(n,4).getFloat32(0,!1),Tr=n=>Ze(n,8).getFloat64(0,!1),vr=n=>Ze(n,8).getBigInt64(0,!1),Ur=[n=>{},n=>null,qe,Lr,Tr,vr,n=>!1,n=>!0,ht,n=>{const t=p(n),e={};for(let s=0;s<t;s++){const r=ht(n);e[r]=Mt(n)}return e},n=>{const t=p(n),e=[];for(let s=0;s<t;s++)e.push(Mt(n));return e},L],Mt=n=>Ur[127-gt(n)](n);class An extends pe{constructor(t,e){super(t),this.reader=e,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ir(this)?this.count=p(this)+1:this.count=-1),this.count--,this.s}}class Yt extends pe{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qe(this);const t=Gn(this.s);this.count=1,t&&(this.s=-this.s,this.count=p(this)+2)}return this.count--,this.s}}class xe extends pe{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qe(this),e=t&1;this.diff=F(t/2),this.count=1,e&&(this.count=p(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Nr{constructor(t){this.decoder=new Yt(t),this.str=ht(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),e=this.str.slice(this.spos,t);return this.spos=t,e}}const Rr=crypto.getRandomValues.bind(crypto),Yn=()=>Rr(new Uint32Array(1))[0],$r="10000000-1000-4000-8000"+-1e11,Vr=()=>$r.replace(/[018]/g,n=>(n^Yn()&15>>n/4).toString(16)),In=n=>new Promise(n);Promise.all.bind(Promise);const On=n=>n===void 0?null:n;class jr{constructor(){this.map=new Map}setItem(t,e){this.map.set(t,e)}getItem(t){return this.map.get(t)}}let Kn=new jr,Fr=!0;try{typeof localStorage<"u"&&localStorage&&(Kn=localStorage,Fr=!1)}catch{}const Br=Kn,xt=Symbol("Equality"),Wn=(n,t)=>{var e;return n===t||!!((e=n==null?void 0:n[xt])!=null&&e.call(n,t))||!1},Jr=n=>typeof n=="object",zr=Object.assign,Gr=Object.keys,Hr=(n,t)=>{for(const e in n)t(n[e],e)},qt=n=>Gr(n).length,Pr=n=>{for(const t in n)return!1;return!0},$t=(n,t)=>{for(const e in n)if(!t(n[e],e))return!1;return!0},Qe=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),Yr=(n,t)=>n===t||qt(n)===qt(t)&&$t(n,(e,s)=>(e!==void 0||Qe(t,s))&&Wn(t[s],e)),Kr=Object.freeze,Xn=n=>{for(const t in n){const e=n[t];(typeof e=="object"||typeof e=="function")&&Xn(n[t])}return Kr(n)},tn=(n,t,e=0)=>{try{for(;e<n.length;e++)n[e](...t)}finally{e<n.length&&tn(n,t,e+1)}},Wr=n=>n,Kt=(n,t)=>{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[xt]!=null)return n[xt](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;break}case Set:{if(n.size!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;break}case Map:{if(n.size!==t.size)return!1;for(const e of n.keys())if(!t.has(e)||!Kt(n.get(e),t.get(e)))return!1;break}case void 0:case Object:if(qt(n)!==qt(t))return!1;for(const e in n)if(!Qe(n,e)||!Kt(n[e],t[e]))return!1;break;case Array:if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(!Kt(n[e],t[e]))return!1;break;default:return!1}return!0},Xr=(n,t)=>t.includes(n),Lt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let V;const qr=()=>{if(V===void 0)if(Lt){V=R();const n=process.argv;let t=null;for(let e=0;e<n.length;e++){const s=n[e];s[0]==="-"?(t!==null&&V.set(t,""),t=s):t!==null&&(V.set(t,s),t=null)}t!==null&&V.set(t,"")}else typeof location=="object"?(V=R(),(location.search||"?").slice(1).split("&").forEach(n=>{if(n.length!==0){const[t,e]=n.split("=");V.set(`--${Sn(t,"-")}`,e),V.set(`-${Sn(t,"-")}`,e)}})):V=R();return V},Je=n=>qr().has(n),Zt=n=>On(Lt?process.env[n.toUpperCase().replaceAll("-","_")]:Br.getItem(n)),qn=n=>Je("--"+n)||Zt(n)!==null,Zr=qn("production"),Qr=Lt&&Xr(process.env.FORCE_COLOR,["true","1","2"]),ti=Qr||!Je("--no-colors")&&!qn("no-color")&&(!Lt||process.stdout.isTTY)&&(!Lt||Je("--color")||Zt("COLORTERM")!==null||(Zt("TERM")||"").includes("color")),ei=n=>new Uint8Array(n),ni=n=>{const t=ei(n.byteLength);return t.set(n),t};class si{constructor(t,e){this.left=t,this.right=e}}const G=(n,t)=>new si(n,t),Mn=n=>n.next()>=.5,Le=(n,t,e)=>F(n.next()*(e+1-t)+t),Zn=(n,t,e)=>F(n.next()*(e+1-t)+t),en=(n,t,e)=>Zn(n,t,e),ri=n=>lr(en(n,97,122)),ii=(n,t=0,e=20)=>{const s=en(n,t,e);let r="";for(let i=0;i<s;i++)r+=ri(n);return r},Te=(n,t)=>t[en(n,0,t.length-1)],oi=Symbol("0schema");class ci{constructor(){this._rerrs=[]}extend(t,e,s,r=null){this._rerrs.push({path:t,expected:e,has:s,message:r})}toString(){const t=[];for(let e=this._rerrs.length-1;e>0;e--){const s=this._rerrs[e];t.push(wr(" ",(this._rerrs.length-e)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
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}}k(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})}};k(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}}k(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
- ${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)=>{y(n.restEncoder,t.clients.size),Q(t.clients.entries()).sort((e,s)=>s[0]-e[0]).forEach(([e,s])=>{n.resetDsCurVal(),y(n.restEncoder,e);const r=s.length;y(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 y(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){y(this.restEncoder,t)}writeDsLen(t){y(this.restEncoder,t)}}class jt extends to{writeLeftID(t){y(this.restEncoder,t.client),y(this.restEncoder,t.clock)}writeRightID(t){y(this.restEncoder,t.client),y(this.restEncoder,t.clock)}writeClient(t){y(this.restEncoder,t)}writeInfo(t){Fe(this.restEncoder,t)}writeString(t){lt(this.restEncoder,t)}writeParentInfo(t){y(this.restEncoder,t?1:0)}writeTypeRef(t){y(this.restEncoder,t)}writeLen(t){y(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,y(this.restEncoder,e)}writeDsLen(t){t===0&&N(),y(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 y(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);y(n.restEncoder,t.length-r),n.writeClient(e),y(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)}),y(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 m=l.get(f);(m==null||m>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,m=e.get(g);m?(m.i--,c.clients.set(g,m.refs.slice(m.i)),e.delete(g),m.i=0,m.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 m=a.getMissing(n,t);if(m!==null){s.push(a);const it=e.get(m)||{refs:[],i:0};if(it.refs.length===it.i)h(m,D(t,m)),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),y(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 m=f.length-1;m>=g;)m-=1+Wt(f,m)}});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),y(n.encoder.restEncoder,t.id.clock+e)),t.write(n.encoder,e),n.written++},fn=n=>{Ts(n);const t=n.encoder.restEncoder;y(t,n.clientStructs.length);for(let e=0;e<n.clientStructs.length;e++){const s=n.clientStructs[e];y(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
- `;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,m)=>{g!==null&&(f.attributes[m]=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 m=r.get(f)??null;W(m,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 m=r.get(f)??null;W(m,g)||(c==="retain"&&d(),l[f]=m)}else if(!o.deleted){i.set(f,g);const m=l[f];m!==void 0&&(W(m,g)?m!==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,m)=>{d=!0,u[m]=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),y(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();k(this,"doc");k(this,"config");k(this,"transport","websocket");k(this,"persistTimer",null);k(this,"dirty",!1);k(this,"sharedObjectCount",0);k(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){k(this,"ymap");k(this,"listeners",new Set);k(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){k(this,"yarray");k(this,"listeners",new Set);k(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){k(this,"ymap");k(this,"clientKey");k(this,"listeners",new Set);k(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();k(this,"peerManager");k(this,"syncEngine");k(this,"config");k(this,"sharedMaps",new Map);k(this,"sharedLists",new Map);k(this,"sharedCounters",new Map);k(this,"destroyed",!1);this.config=e,this.peerManager=new tr(e.iceServers,e.p2pConfig.meshLimit,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
+ "use strict";var Zs=Object.defineProperty;var Qs=(n,t,e)=>t in n?Zs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var y=(n,t,e)=>Qs(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ye=require("./pulse-core.cjs");class tr extends Ye.Emitter{constructor(e,s,r,i){super();y(this,"peers",new Map);y(this,"iceServers");y(this,"meshLimit");y(this,"localUserId");y(this,"sendSignal");this.iceServers=e,this.meshLimit=s,this.localUserId=r,this.sendSignal=i}get peerStates(){var s;const e=new Map;for(const[r,i]of this.peers)e.set(r,{userId:r,state:i.state,dataChannelOpen:((s=i.crdtChannel)==null?void 0:s.readyState)==="open"});return e}get activePeerCount(){return this.peers.size}shouldUseMesh(){return this.peers.size<this.meshLimit}async createOffer(e){if(!this.shouldUseMesh()){this.emit("peer:fallback",e);return}if(this.localUserId>e)return;const s=this.createPeerConnection(e),r=this.peers.get(e);r.crdtChannel=s.createDataChannel("crdt",{ordered:!0}),r.rawChannel=s.createDataChannel("raw",{ordered:!1}),this.setupDataChannelHandlers(e,r.crdtChannel,"crdt"),this.setupDataChannelHandlers(e,r.rawChannel,"raw");const i=await s.createOffer();await s.setLocalDescription(i),this.sendSignal({type:"signal:offer",targetUserId:e,sdp:s.localDescription})}async handleOffer(e,s){const r=this.createPeerConnection(e);r.ondatachannel=o=>{const c=this.peers.get(e);c&&(o.channel.label==="crdt"?(c.crdtChannel=o.channel,this.setupDataChannelHandlers(e,o.channel,"crdt")):o.channel.label==="raw"&&(c.rawChannel=o.channel,this.setupDataChannelHandlers(e,o.channel,"raw")))},await r.setRemoteDescription(s);const i=await r.createAnswer();await r.setLocalDescription(i),this.sendSignal({type:"signal:answer",targetUserId:e,sdp:r.localDescription})}async handleAnswer(e,s){const r=this.peers.get(e);r&&await r.pc.setRemoteDescription(s)}async handleIceCandidate(e,s){const r=this.peers.get(e);r&&await r.pc.addIceCandidate(s)}sendCrdt(e){var r;const s=e instanceof Uint8Array?e:new Uint8Array(e);for(const[,i]of this.peers)((r=i.crdtChannel)==null?void 0:r.readyState)==="open"&&i.crdtChannel.send(s)}sendRaw(e,s){var r,i;if(s){const o=this.peers.get(s);((r=o==null?void 0:o.rawChannel)==null?void 0:r.readyState)==="open"&&o.rawChannel.send(e);return}for(const[,o]of this.peers)((i=o==null?void 0:o.rawChannel)==null?void 0:i.readyState)==="open"&&o.rawChannel.send(e)}removePeer(e){var r,i;const s=this.peers.get(e);s&&((r=s.crdtChannel)==null||r.close(),(i=s.rawChannel)==null||i.close(),s.pc.close(),this.peers.delete(e),this.emit("peer:disconnected",e))}destroy(){for(const e of[...this.peers.keys()])this.removePeer(e);this.removeAll()}createPeerConnection(e){this.peers.has(e)&&this.removePeer(e);const s=new RTCPeerConnection({iceServers:this.iceServers}),r={pc:s,crdtChannel:null,rawChannel:null,state:"connecting"};return this.peers.set(e,r),s.onicecandidate=i=>{i.candidate&&this.sendSignal({type:"signal:ice",targetUserId:e,candidate:i.candidate})},s.onconnectionstatechange=()=>{const i=s.connectionState;i==="connected"?(r.state="connected",this.emit("peer:connected",e)):(i==="disconnected"||i==="failed"||i==="closed")&&(r.state="disconnected",this.removePeer(e))},s}setupDataChannelHandlers(e,s,r){s.binaryType="arraybuffer",s.onmessage=i=>{r==="crdt"?this.emit("crdt:message",{fromUserId:e,data:new Uint8Array(i.data)}):this.emit("raw:message",{fromUserId:e,data:i.data})}}}const R=()=>new Map,Ve=n=>{const t=R();return n.forEach((e,s)=>{t.set(s,e)}),t},q=(n,t,e)=>{let s=n.get(t);return s===void 0&&n.set(t,s=e()),s},er=(n,t)=>{const e=[];for(const[s,r]of n)e.push(t(r,s));return e},nr=(n,t)=>{for(const[e,s]of n)if(t(s,e))return!0;return!1},ft=()=>new Set,Ae=n=>n[n.length-1],sr=(n,t)=>{for(let e=0;e<t.length;e++)n.push(t[e])},Q=Array.from,Ke=(n,t)=>{for(let e=0;e<n.length;e++)if(!t(n[e],e,n))return!1;return!0},Jn=(n,t)=>{for(let e=0;e<n.length;e++)if(t(n[e],e,n))return!0;return!1},rr=(n,t)=>{const e=new Array(n);for(let s=0;s<n;s++)e[s]=t(s,e);return e},ue=Array.isArray;class ir{constructor(){this._observers=R()}on(t,e){return q(this._observers,t,ft).add(e),e}once(t,e){const s=(...r)=>{this.off(t,s),e(...r)};this.on(t,s)}off(t,e){const s=this._observers.get(t);s!==void 0&&(s.delete(e),s.size===0&&this._observers.delete(t))}emit(t,e){return Q((this._observers.get(t)||R()).values()).forEach(s=>s(...e))}destroy(){this._observers=R()}}const F=Math.floor,Ht=Math.abs,zn=(n,t)=>n<t?n:t,st=(n,t)=>n>t?n:t,Gn=n=>n!==0?n<0:1/n<0,mn=1,kn=2,Ie=4,Oe=8,At=32,H=64,T=128,de=31,je=63,Z=127,or=2147483647,Xt=Number.MAX_SAFE_INTEGER,bn=Number.MIN_SAFE_INTEGER,cr=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&F(n)===n),lr=String.fromCharCode,hr=n=>n.toLowerCase(),ar=/^\s*/g,ur=n=>n.replace(ar,""),dr=/([A-Z])/g,Sn=(n,t)=>ur(n.replace(dr,e=>`${t}${hr(e)}`)),fr=n=>{const t=unescape(encodeURIComponent(n)),e=t.length,s=new Uint8Array(e);for(let r=0;r<e;r++)s[r]=t.codePointAt(r);return s},It=typeof TextEncoder<"u"?new TextEncoder:null,gr=n=>It.encode(n),pr=It?gr:fr;let Dt=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Dt&&Dt.decode(new Uint8Array).length===1&&(Dt=null);const wr=(n,t)=>rr(t,()=>n).join("");class Rt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const fe=()=>new Rt,yr=n=>{let t=n.cpos;for(let e=0;e<n.bufs.length;e++)t+=n.bufs[e].length;return t},j=n=>{const t=new Uint8Array(yr(n));let e=0;for(let s=0;s<n.bufs.length;s++){const r=n.bufs[s];t.set(r,e),e+=r.length}return t.set(new Uint8Array(n.cbuf.buffer,0,n.cpos),e),t},mr=(n,t)=>{const e=n.cbuf.length;e-n.cpos<t&&(n.bufs.push(new Uint8Array(n.cbuf.buffer,0,n.cpos)),n.cbuf=new Uint8Array(st(e,t)*2),n.cpos=0)},E=(n,t)=>{const e=n.cbuf.length;n.cpos===e&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(e*2),n.cpos=0),n.cbuf[n.cpos++]=t},Fe=E,m=(n,t)=>{for(;t>Z;)E(n,T|Z&t),t=F(t/128);E(n,Z&t)},We=(n,t)=>{const e=Gn(t);for(e&&(t=-t),E(n,(t>je?T:0)|(e?H:0)|je&t),t=F(t/64);t>0;)E(n,(t>Z?T:0)|Z&t),t=F(t/128)},Be=new Uint8Array(3e4),kr=Be.length/3,br=(n,t)=>{if(t.length<kr){const e=It.encodeInto(t,Be).written||0;m(n,e);for(let s=0;s<e;s++)E(n,Be[s])}else x(n,pr(t))},Sr=(n,t)=>{const e=unescape(encodeURIComponent(t)),s=e.length;m(n,s);for(let r=0;r<s;r++)E(n,e.codePointAt(r))},lt=It&&It.encodeInto?br:Sr,ge=(n,t)=>{const e=n.cbuf.length,s=n.cpos,r=zn(e-s,t.length),i=t.length-r;n.cbuf.set(t.subarray(0,r),s),n.cpos+=r,i>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(st(e*2,i)),n.cbuf.set(t.subarray(r)),n.cpos=i)},x=(n,t)=>{m(n,t.byteLength),ge(n,t)},Xe=(n,t)=>{mr(n,t);const e=new DataView(n.cbuf.buffer,n.cpos,t);return n.cpos+=t,e},_r=(n,t)=>Xe(n,4).setFloat32(0,t,!1),Cr=(n,t)=>Xe(n,8).setFloat64(0,t,!1),Er=(n,t)=>Xe(n,8).setBigInt64(0,t,!1),_n=new DataView(new ArrayBuffer(4)),Dr=n=>(_n.setFloat32(0,n),_n.getFloat32(0)===n),Ot=(n,t)=>{switch(typeof t){case"string":E(n,119),lt(n,t);break;case"number":cr(t)&&Ht(t)<=or?(E(n,125),We(n,t)):Dr(t)?(E(n,124),_r(n,t)):(E(n,123),Cr(n,t));break;case"bigint":E(n,122),Er(n,t);break;case"object":if(t===null)E(n,126);else if(ue(t)){E(n,117),m(n,t.length);for(let e=0;e<t.length;e++)Ot(n,t[e])}else if(t instanceof Uint8Array)E(n,116),x(n,t);else{E(n,118);const e=Object.keys(t);m(n,e.length);for(let s=0;s<e.length;s++){const r=e[s];lt(n,r),Ot(n,t[r])}}break;case"boolean":E(n,t?120:121);break;default:E(n,127)}};class Cn extends Rt{constructor(t){super(),this.w=t,this.s=null,this.count=0}write(t){this.s===t?this.count++:(this.count>0&&m(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const En=n=>{n.count>0&&(We(n.encoder,n.count===1?n.s:-n.s),n.count>1&&m(n.encoder,n.count-2))};class Pt{constructor(){this.encoder=new Rt,this.s=0,this.count=0}write(t){this.s===t?this.count++:(En(this),this.count=1,this.s=t)}toUint8Array(){return En(this),j(this.encoder)}}const Dn=n=>{if(n.count>0){const t=n.diff*2+(n.count===1?0:1);We(n.encoder,t),n.count>1&&m(n.encoder,n.count-2)}};class Me{constructor(){this.encoder=new Rt,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Dn(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Dn(this),j(this.encoder)}}class Ar{constructor(){this.sarr=[],this.s="",this.lensE=new Pt}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Rt;return this.sarr.push(this.s),this.s="",lt(t,this.sarr.join("")),ge(t,this.lensE.toUint8Array()),j(t)}}const B=n=>new Error(n),$=()=>{throw B("Method unimplemented")},N=()=>{throw B("Unexpected case")},Hn=B("Unexpected end of array"),Pn=B("Integer out of Range");class pe{constructor(t){this.arr=t,this.pos=0}}const bt=n=>new pe(n),Ir=n=>n.pos!==n.arr.length,Or=(n,t)=>{const e=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,e},L=n=>Or(n,p(n)),gt=n=>n.arr[n.pos++],p=n=>{let t=0,e=1;const s=n.arr.length;for(;n.pos<s;){const r=n.arr[n.pos++];if(t=t+(r&Z)*e,e*=128,r<T)return t;if(t>Xt)throw Pn}throw Hn},qe=n=>{let t=n.arr[n.pos++],e=t&je,s=64;const r=(t&H)>0?-1:1;if((t&T)===0)return r*e;const i=n.arr.length;for(;n.pos<i;){if(t=n.arr[n.pos++],e=e+(t&Z)*s,s*=128,t<T)return r*e;if(e>Xt)throw Pn}throw Hn},Mr=n=>{let t=p(n);if(t===0)return"";{let e=String.fromCodePoint(gt(n));if(--t<100)for(;t--;)e+=String.fromCodePoint(gt(n));else for(;t>0;){const s=t<1e4?t:1e4,r=n.arr.subarray(n.pos,n.pos+s);n.pos+=s,e+=String.fromCodePoint.apply(null,r),t-=s}return decodeURIComponent(escape(e))}},xr=n=>Dt.decode(L(n)),ht=Dt?xr:Mr,Ze=(n,t)=>{const e=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,t);return n.pos+=t,e},Lr=n=>Ze(n,4).getFloat32(0,!1),Tr=n=>Ze(n,8).getFloat64(0,!1),vr=n=>Ze(n,8).getBigInt64(0,!1),Ur=[n=>{},n=>null,qe,Lr,Tr,vr,n=>!1,n=>!0,ht,n=>{const t=p(n),e={};for(let s=0;s<t;s++){const r=ht(n);e[r]=Mt(n)}return e},n=>{const t=p(n),e=[];for(let s=0;s<t;s++)e.push(Mt(n));return e},L],Mt=n=>Ur[127-gt(n)](n);class An extends pe{constructor(t,e){super(t),this.reader=e,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ir(this)?this.count=p(this)+1:this.count=-1),this.count--,this.s}}class Yt extends pe{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=qe(this);const t=Gn(this.s);this.count=1,t&&(this.s=-this.s,this.count=p(this)+2)}return this.count--,this.s}}class xe extends pe{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=qe(this),e=t&1;this.diff=F(t/2),this.count=1,e&&(this.count=p(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Nr{constructor(t){this.decoder=new Yt(t),this.str=ht(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),e=this.str.slice(this.spos,t);return this.spos=t,e}}const Rr=crypto.getRandomValues.bind(crypto),Yn=()=>Rr(new Uint32Array(1))[0],$r="10000000-1000-4000-8000"+-1e11,Vr=()=>$r.replace(/[018]/g,n=>(n^Yn()&15>>n/4).toString(16)),In=n=>new Promise(n);Promise.all.bind(Promise);const On=n=>n===void 0?null:n;class jr{constructor(){this.map=new Map}setItem(t,e){this.map.set(t,e)}getItem(t){return this.map.get(t)}}let Kn=new jr,Fr=!0;try{typeof localStorage<"u"&&localStorage&&(Kn=localStorage,Fr=!1)}catch{}const Br=Kn,xt=Symbol("Equality"),Wn=(n,t)=>{var e;return n===t||!!((e=n==null?void 0:n[xt])!=null&&e.call(n,t))||!1},Jr=n=>typeof n=="object",zr=Object.assign,Gr=Object.keys,Hr=(n,t)=>{for(const e in n)t(n[e],e)},qt=n=>Gr(n).length,Pr=n=>{for(const t in n)return!1;return!0},$t=(n,t)=>{for(const e in n)if(!t(n[e],e))return!1;return!0},Qe=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),Yr=(n,t)=>n===t||qt(n)===qt(t)&&$t(n,(e,s)=>(e!==void 0||Qe(t,s))&&Wn(t[s],e)),Kr=Object.freeze,Xn=n=>{for(const t in n){const e=n[t];(typeof e=="object"||typeof e=="function")&&Xn(n[t])}return Kr(n)},tn=(n,t,e=0)=>{try{for(;e<n.length;e++)n[e](...t)}finally{e<n.length&&tn(n,t,e+1)}},Wr=n=>n,Kt=(n,t)=>{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[xt]!=null)return n[xt](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;break}case Set:{if(n.size!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;break}case Map:{if(n.size!==t.size)return!1;for(const e of n.keys())if(!t.has(e)||!Kt(n.get(e),t.get(e)))return!1;break}case void 0:case Object:if(qt(n)!==qt(t))return!1;for(const e in n)if(!Qe(n,e)||!Kt(n[e],t[e]))return!1;break;case Array:if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(!Kt(n[e],t[e]))return!1;break;default:return!1}return!0},Xr=(n,t)=>t.includes(n),Lt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";let V;const qr=()=>{if(V===void 0)if(Lt){V=R();const n=process.argv;let t=null;for(let e=0;e<n.length;e++){const s=n[e];s[0]==="-"?(t!==null&&V.set(t,""),t=s):t!==null&&(V.set(t,s),t=null)}t!==null&&V.set(t,"")}else typeof location=="object"?(V=R(),(location.search||"?").slice(1).split("&").forEach(n=>{if(n.length!==0){const[t,e]=n.split("=");V.set(`--${Sn(t,"-")}`,e),V.set(`-${Sn(t,"-")}`,e)}})):V=R();return V},Je=n=>qr().has(n),Zt=n=>On(Lt?process.env[n.toUpperCase().replaceAll("-","_")]:Br.getItem(n)),qn=n=>Je("--"+n)||Zt(n)!==null,Zr=qn("production"),Qr=Lt&&Xr(process.env.FORCE_COLOR,["true","1","2"]),ti=Qr||!Je("--no-colors")&&!qn("no-color")&&(!Lt||process.stdout.isTTY)&&(!Lt||Je("--color")||Zt("COLORTERM")!==null||(Zt("TERM")||"").includes("color")),ei=n=>new Uint8Array(n),ni=n=>{const t=ei(n.byteLength);return t.set(n),t};class si{constructor(t,e){this.left=t,this.right=e}}const G=(n,t)=>new si(n,t),Mn=n=>n.next()>=.5,Le=(n,t,e)=>F(n.next()*(e+1-t)+t),Zn=(n,t,e)=>F(n.next()*(e+1-t)+t),en=(n,t,e)=>Zn(n,t,e),ri=n=>lr(en(n,97,122)),ii=(n,t=0,e=20)=>{const s=en(n,t,e);let r="";for(let i=0;i<s;i++)r+=ri(n);return r},Te=(n,t)=>t[en(n,0,t.length-1)],oi=Symbol("0schema");class ci{constructor(){this._rerrs=[]}extend(t,e,s,r=null){this._rerrs.push({path:t,expected:e,has:s,message:r})}toString(){const t=[];for(let e=this._rerrs.length-1;e>0;e--){const s=this._rerrs[e];t.push(wr(" ",(this._rerrs.length-e)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return t.join(`
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
+ ${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
+ `;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;
@@ -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(i=>i(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);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._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",e=>{try{const t=JSON.parse(e.data);this.emit("message",t)}catch{}}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var e;(e=this.ws)==null||e.close()}))}disconnect(){var e;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(e=this.ws)==null||e.close(),this.ws=null,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()}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,i]of this._threads){const s=i.comments.findIndex(n=>n.id===e);if(s!==-1){i.comments.splice(s,1),i.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(i=>i.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 i=Date.now(),s=[];for(const[n,o]of t)i-o<3e3&&s.push(n);return s}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 i=this._reactions.get(t.targetId)??[];i.push(t),this._reactions.set(t.targetId,i)}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 i=t.comments.findIndex(s=>s.id===e.comment.id);i!==-1&&(t.comments[i]=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(i=>i.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 i=t.filter(s=>s.id!==e.reactionId);this._reactions.set(e.targetId,i),this.emit("reactions",{targetId:e.targetId,reactions:i})}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 i;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");this.config=e,this.state=new u,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const t=((i=e.endpoint)==null?void 0:i.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",s=>{this.state.handleMessage(s),this.emit(s.type,s),s.type==="auth:error"&&this.connection.permanentDisconnect(),this._p2pInstance&&(s.type==="signal:offer"?this._p2pInstance.handleSignalOffer(s.fromUserId,s.sdp):s.type==="signal:answer"?this._p2pInstance.handleSignalAnswer(s.fromUserId,s.sdp):s.type==="signal:ice"?this._p2pInstance.handleIceCandidate(s.fromUserId,s.candidate):s.type==="p2p:sync"?this._p2pInstance.handleP2PSync(s.fromUserId,s.update):s.type==="presence:join"?this._p2pInstance.onPeerJoined(s.user.user.id):s.type==="presence:leave"&&this._p2pInstance.onPeerLeft(s.userId))}),this.connection.on("state",s=>{this.emit("connection",s),s==="connected"?(this.authenticate(),this.startHeartbeat()):s==="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 i=crypto.randomUUID();return this.send({type:"thread:create",id:i,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),i}reply(e,t,i=[],s){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:i,attachmentIds:s}),n}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}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,i){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:i})}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,i){this.send({type:"draw:stroke",points:e,color:t,width:i})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=typeof window<"u"?window.location.origin:"",i=(this.config.endpoint??t).replace(/^ws(s?):/,"http$1:"),s=new FormData;s.append("file",e);const n=await fetch(`${i}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:s});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=`${i}${o.url}`),o.thumbnailUrl&&!o.thumbnailUrl.startsWith("http")&&(o.thumbnailUrl=`${i}${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:i}=await Promise.resolve().then(()=>require("./P2PManager-CcuTidGn.cjs")),s=new i({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=s,await s.initialize();for(const n of this.state.presence)n.user.id!==e.userId&&s.onPeerJoined(n.user.id);return s}}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(i=>i(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);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._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",e=>{try{const t=JSON.parse(e.data);this.emit("message",t)}catch{}}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var e;(e=this.ws)==null||e.close()}))}disconnect(){var e;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(e=this.ws)==null||e.close(),this.ws=null,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()}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,i]of this._threads){const s=i.comments.findIndex(n=>n.id===e);if(s!==-1){i.comments.splice(s,1),i.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(i=>i.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 i=Date.now(),s=[];for(const[n,o]of t)i-o<3e3&&s.push(n);return s}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 i=this._reactions.get(t.targetId)??[];i.push(t),this._reactions.set(t.targetId,i)}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 i=t.comments.findIndex(s=>s.id===e.comment.id);i!==-1&&(t.comments[i]=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(i=>i.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 i=t.filter(s=>s.id!==e.reactionId);this._reactions.set(e.targetId,i),this.emit("reactions",{targetId:e.targetId,reactions:i})}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 i;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");this.config=e,this.state=new u,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const t=((i=e.endpoint)==null?void 0:i.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",s=>{this.state.handleMessage(s),this.emit(s.type,s),s.type==="auth:error"&&this.connection.permanentDisconnect(),this._p2pInstance&&(s.type==="signal:offer"?this._p2pInstance.handleSignalOffer(s.fromUserId,s.sdp):s.type==="signal:answer"?this._p2pInstance.handleSignalAnswer(s.fromUserId,s.sdp):s.type==="signal:ice"?this._p2pInstance.handleIceCandidate(s.fromUserId,s.candidate):s.type==="p2p:sync"?this._p2pInstance.handleP2PSync(s.fromUserId,s.update):s.type==="presence:join"?this._p2pInstance.onPeerJoined(s.user.user.id):s.type==="presence:leave"&&this._p2pInstance.onPeerLeft(s.userId))}),this.connection.on("state",s=>{this.emit("connection",s),s==="connected"?(this.authenticate(),this.startHeartbeat()):s==="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 i=crypto.randomUUID();return this.send({type:"thread:create",id:i,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),i}reply(e,t,i=[],s){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:i,attachmentIds:s}),n}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}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,i){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:i})}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,i){this.send({type:"draw:stroke",points:e,color:t,width:i})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=typeof window<"u"?window.location.origin:"",i=(this.config.endpoint??t).replace(/^ws(s?):/,"http$1:"),s=new FormData;s.append("file",e);const n=await fetch(`${i}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:s});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=`${i}${o.url}`),o.thumbnailUrl&&!o.thumbnailUrl.startsWith("http")&&(o.thumbnailUrl=`${i}${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:i}=await Promise.resolve().then(()=>require("./P2PManager-e4ShL60A.cjs")),s=new i({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=s,await s.initialize();for(const n of this.state.presence)n.user.id!==e.userId&&s.onPeerJoined(n.user.id);return s}}exports.Connection=p;exports.Emitter=d;exports.PulseClient=m;exports.StateManager=u;
@@ -519,7 +519,7 @@ class k extends p {
519
519
  n.ok && (t = (await n.json()).iceServers);
520
520
  } catch {
521
521
  }
522
- const { P2PManager: i } = await import("./P2PManager-B21XQVk_.js"), s = new i({
522
+ const { P2PManager: i } = await import("./P2PManager-CwR8sbb_.js"), s = new i({
523
523
  roomId: this.config.room,
524
524
  userId: e.userId,
525
525
  baseUrl: this.state.baseUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamention/pulse-core",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
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",