@inditextech/weave-store-websockets 0.1.1 → 0.2.0

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.
package/dist/server.js CHANGED
@@ -1,352 +1,1619 @@
1
- var G = Object.defineProperty;
2
- var H = (e, n, t) => n in e ? G(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
- var d = (e, n, t) => (H(e, typeof n != "symbol" ? n + "" : n, t), t);
4
- import { WebSocketServer as q } from "ws";
5
- import * as g from "yjs";
6
- import { D as Y, s as Q, w as A, e as Z, t as T, h as N, j as V, p as E, q as ee, r as te, z as ne, B as se, x as re, l as ae, k as oe, A as ie, g as ce } from "./awareness-C8fdGy2v.js";
7
- import { W as st, C as rt } from "./awareness-C8fdGy2v.js";
8
- import le from "http";
9
- var b = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
10
- function fe(e) {
11
- return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
12
- }
13
- var pe = "Expected a function", K = NaN, de = "[object Symbol]", ue = /^\s+|\s+$/g, ye = /^[-+]0x[0-9a-f]+$/i, ge = /^0b[01]+$/i, he = /^0o[0-7]+$/i, me = parseInt, we = typeof b == "object" && b && b.Object === Object && b, Se = typeof self == "object" && self && self.Object === Object && self, Ce = we || Se || Function("return this")(), Ae = Object.prototype, Te = Ae.toString, Ee = Math.max, ve = Math.min, B = function() {
14
- return Ce.Date.now();
15
- };
16
- function Le(e, n, t) {
17
- var r, s, i, a, o, p, l = 0, h = !1, f = !1, u = !0;
18
- if (typeof e != "function")
19
- throw new TypeError(pe);
20
- n = D(n) || 0, R(t) && (h = !!t.leading, f = "maxWait" in t, i = f ? Ee(D(t.maxWait) || 0, n) : i, u = "trailing" in t ? !!t.trailing : u);
21
- function O(c) {
22
- var y = r, S = s;
23
- return r = s = void 0, l = c, a = e.apply(S, y), a;
24
- }
25
- function X(c) {
26
- return l = c, o = setTimeout(L, n), h ? O(c) : a;
27
- }
28
- function J(c) {
29
- var y = c - p, S = c - l, x = n - y;
30
- return f ? ve(x, i - S) : x;
31
- }
32
- function W(c) {
33
- var y = c - p, S = c - l;
34
- return p === void 0 || y >= n || y < 0 || f && S >= i;
35
- }
36
- function L() {
37
- var c = B();
38
- if (W(c))
39
- return j(c);
40
- o = setTimeout(L, J(c));
41
- }
42
- function j(c) {
43
- return o = void 0, u && r ? O(c) : (r = s = void 0, a);
44
- }
45
- function $() {
46
- o !== void 0 && clearTimeout(o), l = 0, r = p = s = o = void 0;
47
- }
48
- function z() {
49
- return o === void 0 ? a : j(B());
50
- }
51
- function U() {
52
- var c = B(), y = W(c);
53
- if (r = arguments, s = this, p = c, y) {
54
- if (o === void 0)
55
- return X(p);
56
- if (f)
57
- return o = setTimeout(L, n), O(p);
58
- }
59
- return o === void 0 && (o = setTimeout(L, n)), a;
60
- }
61
- return U.cancel = $, U.flush = z, U;
62
- }
63
- function R(e) {
64
- var n = typeof e;
65
- return !!e && (n == "object" || n == "function");
66
- }
67
- function be(e) {
68
- return !!e && typeof e == "object";
69
- }
70
- function Ie(e) {
71
- return typeof e == "symbol" || be(e) && Te.call(e) == de;
72
- }
73
- function D(e) {
74
- if (typeof e == "number")
75
- return e;
76
- if (Ie(e))
77
- return K;
78
- if (R(e)) {
79
- var n = typeof e.valueOf == "function" ? e.valueOf() : e;
80
- e = R(n) ? n + "" : n;
81
- }
82
- if (typeof e != "string")
83
- return e === 0 ? e : +e;
84
- e = e.replace(ue, "");
85
- var t = ge.test(e);
86
- return t || he.test(e) ? me(e.slice(2), t ? 2 : 8) : ye.test(e) ? K : +e;
87
- }
88
- var _e = Le;
89
- const Oe = /* @__PURE__ */ fe(_e), M = process.env.CALLBACK_URL ? new URL(process.env.CALLBACK_URL) : null, Ue = Y(
90
- process.env.CALLBACK_TIMEOUT || "5000"
91
- ), P = process.env.CALLBACK_OBJECTS ? JSON.parse(process.env.CALLBACK_OBJECTS) : {}, Be = !!M, Re = (e, n, t) => {
92
- const s = {
93
- room: t.name,
94
- data: {}
95
- };
96
- Object.keys(P).forEach((a) => {
97
- const o = P[a];
98
- s.data[a] = {
99
- type: o,
100
- content: ke(a, o, t).toJSON()
101
- };
102
- }), M && Me(M, Ue, s);
103
- }, Me = (e, n, t) => {
104
- t = JSON.stringify(t);
105
- const r = {
106
- hostname: e.hostname,
107
- port: e.port,
108
- path: e.pathname,
109
- timeout: n,
110
- method: "POST",
111
- headers: {
112
- "Content-Type": "application/json",
113
- "Content-Length": Buffer.byteLength(t)
114
- }
115
- }, s = le.request(r);
116
- s.on("timeout", () => {
117
- console.warn("Callback request timed out."), s.abort();
118
- }), s.on("error", (i) => {
119
- console.error("Callback request error.", i), s.abort();
120
- }), s.write(t), s.end();
121
- }, ke = (e, n, t) => {
122
- switch (n) {
123
- case "Array":
124
- return t.getArray(e);
125
- case "Map":
126
- return t.getMap(e);
127
- case "Text":
128
- return t.getText(e);
129
- case "XmlFragment":
130
- return t.getXmlFragment(e);
131
- case "XmlElement":
132
- return t.getXmlElement(e);
133
- default:
134
- return {};
135
- }
136
- };
137
- let m;
138
- const We = parseInt(
139
- process.env.CALLBACK_DEBOUNCE_WAIT || "2000"
140
- ), je = parseInt(
141
- process.env.CALLBACK_DEBOUNCE_MAXWAIT || "10000"
142
- ), xe = 0, Ke = 1, De = process.env.GC !== "false" && process.env.GC !== "0", F = /* @__PURE__ */ new Map(), I = /* @__PURE__ */ new Map(), _ = 0, k = 1, Pe = (e, n, t) => {
143
- const r = E();
144
- A(r, _), ce(r, e);
145
- const s = T(r);
146
- t.conns.forEach((i, a) => v(t, a, s));
147
- };
148
- let Fe = () => Promise.resolve();
149
- class Ne extends g.Doc {
150
- constructor(t) {
151
- super({ gc: De });
152
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
153
- d(this, "name");
154
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
- d(this, "conns");
156
- d(this, "awareness");
157
- d(this, "whenInitialized");
158
- this.name = t, this.conns = /* @__PURE__ */ new Map(), this.awareness = new ie(this), this.awareness.setLocalState(null);
159
- const r = ({
160
- added: s,
161
- updated: i,
162
- removed: a
163
- }, o) => {
164
- const p = s.concat(i, a);
165
- if (o !== null) {
166
- const f = (
167
- /** @type {Set<number>} */
168
- this.conns.get(o)
169
- );
170
- f !== void 0 && (s.forEach((u) => {
171
- f.add(u);
172
- }), a.forEach((u) => {
173
- f.delete(u);
174
- }));
175
- }
176
- const l = E();
177
- A(l, k), N(
178
- l,
179
- V(this.awareness, p)
180
- );
181
- const h = T(l);
182
- this.conns.forEach((f, u) => {
183
- v(this, u, h);
184
- });
185
- };
186
- this.awareness.on("update", r), this.on("update", Pe), Be && this.on(
187
- "update",
188
- Oe(Re, We, {
189
- maxWait: je
190
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
191
- })
192
- ), this.whenInitialized = Fe();
193
- }
194
- }
195
- const Ve = (e, n, t = !0) => Q(F, e, async () => {
196
- let r;
197
- m && m.fetchRoom && (r = await m.fetchRoom(e));
198
- const s = new Ne(e);
199
- return s.gc = t, F.set(e, s), r ? g.applyUpdate(s, r) : n(s), await Ge(e, s), s;
200
- }), Xe = (e, n, t) => {
201
- try {
202
- const r = E(), s = ee(t);
203
- switch (te(s)) {
204
- case _:
205
- A(r, _), re(s, r, n, e), ae(r) > 1 && v(n, e, T(r));
206
- break;
207
- case k: {
208
- ne(
209
- n.awareness,
210
- se(s),
211
- e
212
- );
213
- break;
214
- }
215
- }
216
- } catch (r) {
217
- console.error(r);
218
- }
219
- }, w = (e, n) => {
220
- if (e.conns.has(n)) {
221
- const t = e.conns.get(n);
222
- e.conns.delete(n), I.has(e.name) && clearInterval(I.get(e.name)), oe(
223
- e.awareness,
224
- Array.from(t),
225
- null
226
- );
227
- }
228
- n.close();
229
- }, v = (e, n, t) => {
230
- n.readyState !== xe && n.readyState !== Ke && w(e, n);
231
- try {
232
- n.send(t, {}, (r) => {
233
- r != null && w(e, n);
234
- });
235
- } catch {
236
- w(e, n);
237
- }
238
- }, Je = 3e4, $e = (e) => {
239
- m = e;
240
- }, ze = (e, n) => async (t, r, { gc: s = !0 } = {}) => {
241
- const i = e(r);
242
- if (!i)
243
- return;
244
- t.binaryType = "arraybuffer";
245
- const a = await Ve(i, n, s);
246
- a.conns.set(t, /* @__PURE__ */ new Set()), t.on(
247
- "message",
248
- (l) => Xe(t, a, new Uint8Array(l))
249
- );
250
- let o = !0;
251
- const p = setInterval(() => {
252
- if (!o)
253
- a.conns.has(t) && w(a, t), clearInterval(p);
254
- else if (a.conns.has(t)) {
255
- o = !1;
256
- try {
257
- t.ping();
258
- } catch {
259
- w(a, t), clearInterval(p);
260
- }
261
- }
262
- }, Je);
263
- t.on("close", () => {
264
- w(a, t), clearInterval(p);
265
- }), t.on("pong", () => {
266
- o = !0;
267
- });
268
- {
269
- const l = E();
270
- A(l, _), Z(l, a), v(a, t, T(l));
271
- const h = a.awareness.getStates();
272
- if (h.size > 0) {
273
- const f = E();
274
- A(f, k), N(
275
- f,
276
- V(
277
- a.awareness,
278
- Array.from(h.keys())
279
- )
280
- ), v(a, t, T(f));
281
- }
282
- }
283
- };
284
- async function Ge(e, n) {
285
- if (!I.has(e)) {
286
- const t = async () => {
287
- const s = g.encodeStateAsUpdate(n);
288
- if (m && m.persistRoom)
289
- try {
290
- await m.persistRoom(e, s);
291
- } catch (i) {
292
- console.error(i);
293
- }
294
- };
295
- t();
296
- const r = setInterval(
297
- t,
298
- parseInt(process.env.WEAVE_WEBSOCKETS_STATE_SYNC_FREQUENCY_SEG ?? "10") * 1e3
299
- );
300
- I.set(e, r);
301
- }
302
- }
303
- const C = function(e) {
304
- const n = new g.Map();
305
- n.set("key", e), n.set("type", "layer");
306
- const t = new g.Map();
307
- return t.set("id", e), t.set("nodeType", "layer"), t.set("children", new g.Array()), n.set("props", t), n;
308
- };
309
- function He(e) {
310
- const n = new g.Array();
311
- n.insert(0, [
312
- C("gridLayer"),
313
- C("mainLayer"),
314
- C("selectionLayer"),
315
- C("usersPointersLayer"),
316
- C("utilityLayer")
317
- ]);
318
- const t = new g.Map();
319
- t.set("id", "stage"), t.set("children", n), e.getMap("weave").set("key", "stage"), e.getMap("weave").set("type", "stage"), e.getMap("weave").set("props", t);
1
+ import { WEAVE_STORE_WEBSOCKETS, WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS } from "./types-Cq7de9Ah.js";
2
+ import http from "http";
3
+ import https from "https";
4
+ import { WebSocketServer } from "ws";
5
+ import * as Y$2 from "yjs";
6
+ import * as Y$1 from "yjs";
7
+ import * as Y from "yjs";
8
+ import "node:http";
9
+
10
+ //#region rolldown:runtime
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJS = (cb, mod) => function() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps = (to, from$1, except, desc) => {
21
+ if (from$1 && typeof from$1 === "object" || typeof from$1 === "function") for (var keys$1 = __getOwnPropNames(from$1), i = 0, n = keys$1.length, key; i < n; i++) {
22
+ key = keys$1[i];
23
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
24
+ get: ((k) => from$1[k]).bind(null, key),
25
+ enumerable: !(desc = __getOwnPropDesc(from$1, key)) || desc.enumerable
26
+ });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
31
+ value: mod,
32
+ enumerable: true
33
+ }) : target, mod));
34
+
35
+ //#endregion
36
+ //#region ../../node_modules/lib0/math.js
37
+ /**
38
+ * Common Math expressions.
39
+ *
40
+ * @module math
41
+ */
42
+ const floor = Math.floor;
43
+ /**
44
+ * @function
45
+ * @param {number} a
46
+ * @param {number} b
47
+ * @return {number} The smaller element of a and b
48
+ */
49
+ const min = (a, b) => a < b ? a : b;
50
+ /**
51
+ * @function
52
+ * @param {number} a
53
+ * @param {number} b
54
+ * @return {number} The bigger element of a and b
55
+ */
56
+ const max = (a, b) => a > b ? a : b;
57
+ const isNaN$1 = Number.isNaN;
58
+
59
+ //#endregion
60
+ //#region ../../node_modules/lib0/binary.js
61
+ const BIT8 = 128;
62
+ const BIT18 = 1 << 17;
63
+ const BIT19 = 1 << 18;
64
+ const BIT20 = 1 << 19;
65
+ const BIT21 = 1 << 20;
66
+ const BIT22 = 1 << 21;
67
+ const BIT23 = 1 << 22;
68
+ const BIT24 = 1 << 23;
69
+ const BIT25 = 1 << 24;
70
+ const BIT26 = 1 << 25;
71
+ const BIT27 = 1 << 26;
72
+ const BIT28 = 1 << 27;
73
+ const BIT29 = 1 << 28;
74
+ const BIT30 = 1 << 29;
75
+ const BIT31 = 1 << 30;
76
+ const BIT32 = 1 << 31;
77
+ const BITS7 = 127;
78
+ const BITS17 = BIT18 - 1;
79
+ const BITS18 = BIT19 - 1;
80
+ const BITS19 = BIT20 - 1;
81
+ const BITS20 = BIT21 - 1;
82
+ const BITS21 = BIT22 - 1;
83
+ const BITS22 = BIT23 - 1;
84
+ const BITS23 = BIT24 - 1;
85
+ const BITS24 = BIT25 - 1;
86
+ const BITS25 = BIT26 - 1;
87
+ const BITS26 = BIT27 - 1;
88
+ const BITS27 = BIT28 - 1;
89
+ const BITS28 = BIT29 - 1;
90
+ const BITS29 = BIT30 - 1;
91
+ const BITS30 = BIT31 - 1;
92
+ /**
93
+ * @type {number}
94
+ */
95
+ const BITS31 = 2147483647;
96
+ /**
97
+ * @type {number}
98
+ */
99
+ const BITS32 = 4294967295;
100
+
101
+ //#endregion
102
+ //#region ../../node_modules/lib0/number.js
103
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
104
+ const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
105
+ const LOWEST_INT32 = 1 << 31;
106
+ const HIGHEST_INT32 = BITS31;
107
+ const HIGHEST_UINT32 = BITS32;
108
+ /* c8 ignore next */
109
+ const isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
110
+ const isNaN = Number.isNaN;
111
+ const parseInt$1 = Number.parseInt;
112
+
113
+ //#endregion
114
+ //#region ../../node_modules/lib0/set.js
115
+ /**
116
+ * Utility module to work with sets.
117
+ *
118
+ * @module set
119
+ */
120
+ const create$2 = () => new Set();
121
+
122
+ //#endregion
123
+ //#region ../../node_modules/lib0/array.js
124
+ /**
125
+ * Transforms something array-like to an actual Array.
126
+ *
127
+ * @function
128
+ * @template T
129
+ * @param {ArrayLike<T>|Iterable<T>} arraylike
130
+ * @return {T}
131
+ */
132
+ const from = Array.from;
133
+ const isArray$1 = Array.isArray;
134
+
135
+ //#endregion
136
+ //#region ../../node_modules/lib0/string.js
137
+ /**
138
+ * Utility module to work with strings.
139
+ *
140
+ * @module string
141
+ */
142
+ const fromCharCode = String.fromCharCode;
143
+ const fromCodePoint = String.fromCodePoint;
144
+ /**
145
+ * The largest utf16 character.
146
+ * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)
147
+ */
148
+ const MAX_UTF16_CHARACTER = fromCharCode(65535);
149
+ /**
150
+ * @param {string} str
151
+ * @return {Uint8Array}
152
+ */
153
+ const _encodeUtf8Polyfill = (str) => {
154
+ const encodedString = unescape(encodeURIComponent(str));
155
+ const len = encodedString.length;
156
+ const buf = new Uint8Array(len);
157
+ for (let i = 0; i < len; i++) buf[i] = encodedString.codePointAt(i);
158
+ return buf;
159
+ };
160
+ /* c8 ignore next */
161
+ const utf8TextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
162
+ /**
163
+ * @param {string} str
164
+ * @return {Uint8Array}
165
+ */
166
+ const _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
167
+ /**
168
+ * @param {string} str
169
+ * @return {Uint8Array}
170
+ */
171
+ /* c8 ignore next */
172
+ const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
173
+ /* c8 ignore next */
174
+ let utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", {
175
+ fatal: true,
176
+ ignoreBOM: true
177
+ });
178
+ /* c8 ignore start */
179
+ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1)
180
+ /* c8 ignore next */
181
+ utf8TextDecoder = null;
182
+
183
+ //#endregion
184
+ //#region ../../node_modules/lib0/encoding.js
185
+ /**
186
+ * A BinaryEncoder handles the encoding to an Uint8Array.
187
+ */
188
+ var Encoder = class {
189
+ constructor() {
190
+ this.cpos = 0;
191
+ this.cbuf = new Uint8Array(100);
192
+ /**
193
+ * @type {Array<Uint8Array>}
194
+ */
195
+ this.bufs = [];
196
+ }
197
+ };
198
+ /**
199
+ * @function
200
+ * @return {Encoder}
201
+ */
202
+ const createEncoder = () => new Encoder();
203
+ /**
204
+ * The current length of the encoded data.
205
+ *
206
+ * @function
207
+ * @param {Encoder} encoder
208
+ * @return {number}
209
+ */
210
+ const length$1 = (encoder) => {
211
+ let len = encoder.cpos;
212
+ for (let i = 0; i < encoder.bufs.length; i++) len += encoder.bufs[i].length;
213
+ return len;
214
+ };
215
+ /**
216
+ * Transform to Uint8Array.
217
+ *
218
+ * @function
219
+ * @param {Encoder} encoder
220
+ * @return {Uint8Array} The created ArrayBuffer.
221
+ */
222
+ const toUint8Array = (encoder) => {
223
+ const uint8arr = new Uint8Array(length$1(encoder));
224
+ let curPos = 0;
225
+ for (let i = 0; i < encoder.bufs.length; i++) {
226
+ const d = encoder.bufs[i];
227
+ uint8arr.set(d, curPos);
228
+ curPos += d.length;
229
+ }
230
+ uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
231
+ return uint8arr;
232
+ };
233
+ /**
234
+ * Write one byte to the encoder.
235
+ *
236
+ * @function
237
+ * @param {Encoder} encoder
238
+ * @param {number} num The byte that is to be encoded.
239
+ */
240
+ const write = (encoder, num) => {
241
+ const bufferLen = encoder.cbuf.length;
242
+ if (encoder.cpos === bufferLen) {
243
+ encoder.bufs.push(encoder.cbuf);
244
+ encoder.cbuf = new Uint8Array(bufferLen * 2);
245
+ encoder.cpos = 0;
246
+ }
247
+ encoder.cbuf[encoder.cpos++] = num;
248
+ };
249
+ /**
250
+ * Write a variable length unsigned integer. Max encodable integer is 2^53.
251
+ *
252
+ * @function
253
+ * @param {Encoder} encoder
254
+ * @param {number} num The number that is to be encoded.
255
+ */
256
+ const writeVarUint = (encoder, num) => {
257
+ while (num > BITS7) {
258
+ write(encoder, BIT8 | BITS7 & num);
259
+ num = floor(num / 128);
260
+ }
261
+ write(encoder, BITS7 & num);
262
+ };
263
+ /**
264
+ * A cache to store strings temporarily
265
+ */
266
+ const _strBuffer = new Uint8Array(3e4);
267
+ const _maxStrBSize = _strBuffer.length / 3;
268
+ /**
269
+ * Write a variable length string.
270
+ *
271
+ * @function
272
+ * @param {Encoder} encoder
273
+ * @param {String} str The string that is to be encoded.
274
+ */
275
+ const _writeVarStringNative = (encoder, str) => {
276
+ if (str.length < _maxStrBSize) {
277
+ /* c8 ignore next */
278
+ const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
279
+ writeVarUint(encoder, written);
280
+ for (let i = 0; i < written; i++) write(encoder, _strBuffer[i]);
281
+ } else writeVarUint8Array(encoder, encodeUtf8(str));
282
+ };
283
+ /**
284
+ * Write a variable length string.
285
+ *
286
+ * @function
287
+ * @param {Encoder} encoder
288
+ * @param {String} str The string that is to be encoded.
289
+ */
290
+ const _writeVarStringPolyfill = (encoder, str) => {
291
+ const encodedString = unescape(encodeURIComponent(str));
292
+ const len = encodedString.length;
293
+ writeVarUint(encoder, len);
294
+ for (let i = 0; i < len; i++) write(
295
+ encoder,
296
+ /** @type {number} */
297
+ encodedString.codePointAt(i)
298
+ );
299
+ };
300
+ /**
301
+ * Write a variable length string.
302
+ *
303
+ * @function
304
+ * @param {Encoder} encoder
305
+ * @param {String} str The string that is to be encoded.
306
+ */
307
+ /* c8 ignore next */
308
+ const writeVarString = utf8TextEncoder && utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
309
+ /**
310
+ * Append fixed-length Uint8Array to the encoder.
311
+ *
312
+ * @function
313
+ * @param {Encoder} encoder
314
+ * @param {Uint8Array} uint8Array
315
+ */
316
+ const writeUint8Array = (encoder, uint8Array) => {
317
+ const bufferLen = encoder.cbuf.length;
318
+ const cpos = encoder.cpos;
319
+ const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
320
+ const rightCopyLen = uint8Array.length - leftCopyLen;
321
+ encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
322
+ encoder.cpos += leftCopyLen;
323
+ if (rightCopyLen > 0) {
324
+ encoder.bufs.push(encoder.cbuf);
325
+ encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
326
+ encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
327
+ encoder.cpos = rightCopyLen;
328
+ }
329
+ };
330
+ /**
331
+ * Append an Uint8Array to Encoder.
332
+ *
333
+ * @function
334
+ * @param {Encoder} encoder
335
+ * @param {Uint8Array} uint8Array
336
+ */
337
+ const writeVarUint8Array = (encoder, uint8Array) => {
338
+ writeVarUint(encoder, uint8Array.byteLength);
339
+ writeUint8Array(encoder, uint8Array);
340
+ };
341
+ const floatTestBed = new DataView(new ArrayBuffer(4));
342
+
343
+ //#endregion
344
+ //#region ../../node_modules/lib0/error.js
345
+ /**
346
+ * Error helpers.
347
+ *
348
+ * @module error
349
+ */
350
+ /**
351
+ * @param {string} s
352
+ * @return {Error}
353
+ */
354
+ /* c8 ignore next */
355
+ const create$1 = (s) => new Error(s);
356
+
357
+ //#endregion
358
+ //#region ../../node_modules/lib0/decoding.js
359
+ const errorUnexpectedEndOfArray = create$1("Unexpected end of array");
360
+ const errorIntegerOutOfRange = create$1("Integer out of Range");
361
+ /**
362
+ * A Decoder handles the decoding of an Uint8Array.
363
+ */
364
+ var Decoder = class {
365
+ /**
366
+ * @param {Uint8Array} uint8Array Binary data to decode
367
+ */
368
+ constructor(uint8Array) {
369
+ /**
370
+ * Decoding target.
371
+ *
372
+ * @type {Uint8Array}
373
+ */
374
+ this.arr = uint8Array;
375
+ /**
376
+ * Current decoding position.
377
+ *
378
+ * @type {number}
379
+ */
380
+ this.pos = 0;
381
+ }
382
+ };
383
+ /**
384
+ * @function
385
+ * @param {Uint8Array} uint8Array
386
+ * @return {Decoder}
387
+ */
388
+ const createDecoder = (uint8Array) => new Decoder(uint8Array);
389
+ /**
390
+ * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
391
+ *
392
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
393
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
394
+ *
395
+ * @function
396
+ * @param {Decoder} decoder The decoder instance
397
+ * @param {number} len The length of bytes to read
398
+ * @return {Uint8Array}
399
+ */
400
+ const readUint8Array = (decoder, len) => {
401
+ const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
402
+ decoder.pos += len;
403
+ return view;
404
+ };
405
+ /**
406
+ * Read variable length Uint8Array.
407
+ *
408
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
409
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
410
+ *
411
+ * @function
412
+ * @param {Decoder} decoder
413
+ * @return {Uint8Array}
414
+ */
415
+ const readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
416
+ /**
417
+ * Read one byte as unsigned integer.
418
+ * @function
419
+ * @param {Decoder} decoder The decoder instance
420
+ * @return {number} Unsigned 8-bit integer
421
+ */
422
+ const readUint8 = (decoder) => decoder.arr[decoder.pos++];
423
+ /**
424
+ * Read unsigned integer (32bit) with variable length.
425
+ * 1/8th of the storage is used as encoding overhead.
426
+ * * numbers < 2^7 is stored in one bytlength
427
+ * * numbers < 2^14 is stored in two bylength
428
+ *
429
+ * @function
430
+ * @param {Decoder} decoder
431
+ * @return {number} An unsigned integer.length
432
+ */
433
+ const readVarUint = (decoder) => {
434
+ let num = 0;
435
+ let mult = 1;
436
+ const len = decoder.arr.length;
437
+ while (decoder.pos < len) {
438
+ const r = decoder.arr[decoder.pos++];
439
+ num = num + (r & BITS7) * mult;
440
+ mult *= 128;
441
+ if (r < BIT8) return num;
442
+ /* c8 ignore start */
443
+ if (num > MAX_SAFE_INTEGER) throw errorIntegerOutOfRange;
444
+ }
445
+ throw errorUnexpectedEndOfArray;
446
+ };
447
+ /**
448
+ * We don't test this function anymore as we use native decoding/encoding by default now.
449
+ * Better not modify this anymore..
450
+ *
451
+ * Transforming utf8 to a string is pretty expensive. The code performs 10x better
452
+ * when String.fromCodePoint is fed with all characters as arguments.
453
+ * But most environments have a maximum number of arguments per functions.
454
+ * For effiency reasons we apply a maximum of 10000 characters at once.
455
+ *
456
+ * @function
457
+ * @param {Decoder} decoder
458
+ * @return {String} The read String.
459
+ */
460
+ /* c8 ignore start */
461
+ const _readVarStringPolyfill = (decoder) => {
462
+ let remainingLen = readVarUint(decoder);
463
+ if (remainingLen === 0) return "";
464
+ else {
465
+ let encodedString = String.fromCodePoint(readUint8(decoder));
466
+ if (--remainingLen < 100) while (remainingLen--) encodedString += String.fromCodePoint(readUint8(decoder));
467
+ else while (remainingLen > 0) {
468
+ const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
469
+ const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
470
+ decoder.pos += nextLen;
471
+ encodedString += String.fromCodePoint.apply(
472
+ null,
473
+ /** @type {any} */
474
+ bytes
475
+ );
476
+ remainingLen -= nextLen;
477
+ }
478
+ return decodeURIComponent(escape(encodedString));
479
+ }
480
+ };
481
+ /* c8 ignore stop */
482
+ /**
483
+ * @function
484
+ * @param {Decoder} decoder
485
+ * @return {String} The read String
486
+ */
487
+ const _readVarStringNative = (decoder) => utf8TextDecoder.decode(readVarUint8Array(decoder));
488
+ /**
489
+ * Read string of variable length
490
+ * * varUint is used to store the length of the string
491
+ *
492
+ * @function
493
+ * @param {Decoder} decoder
494
+ * @return {String} The read String
495
+ *
496
+ */
497
+ /* c8 ignore next */
498
+ const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
499
+
500
+ //#endregion
501
+ //#region ../../node_modules/y-protocols/sync.js
502
+ /**
503
+ * @typedef {Map<number, number>} StateMap
504
+ */
505
+ /**
506
+ * Core Yjs defines two message types:
507
+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.
508
+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it
509
+ * received all information from the remote client.
510
+ *
511
+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection
512
+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both
513
+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.
514
+ *
515
+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.
516
+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies
517
+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the
518
+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can
519
+ * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.
520
+ * Therefore it is necessary that the client initiates the sync.
521
+ *
522
+ * Construction of a message:
523
+ * [messageType : varUint, message definition..]
524
+ *
525
+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!
526
+ *
527
+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)
528
+ */
529
+ const messageYjsSyncStep1 = 0;
530
+ const messageYjsSyncStep2 = 1;
531
+ const messageYjsUpdate = 2;
532
+ /**
533
+ * Create a sync step 1 message based on the state of the current shared document.
534
+ *
535
+ * @param {encoding.Encoder} encoder
536
+ * @param {Y.Doc} doc
537
+ */
538
+ const writeSyncStep1 = (encoder, doc) => {
539
+ writeVarUint(encoder, messageYjsSyncStep1);
540
+ const sv = Y$2.encodeStateVector(doc);
541
+ writeVarUint8Array(encoder, sv);
542
+ };
543
+ /**
544
+ * @param {encoding.Encoder} encoder
545
+ * @param {Y.Doc} doc
546
+ * @param {Uint8Array} [encodedStateVector]
547
+ */
548
+ const writeSyncStep2 = (encoder, doc, encodedStateVector) => {
549
+ writeVarUint(encoder, messageYjsSyncStep2);
550
+ writeVarUint8Array(encoder, Y$2.encodeStateAsUpdate(doc, encodedStateVector));
551
+ };
552
+ /**
553
+ * Read SyncStep1 message and reply with SyncStep2.
554
+ *
555
+ * @param {decoding.Decoder} decoder The reply to the received message
556
+ * @param {encoding.Encoder} encoder The received message
557
+ * @param {Y.Doc} doc
558
+ */
559
+ const readSyncStep1 = (decoder, encoder, doc) => writeSyncStep2(encoder, doc, readVarUint8Array(decoder));
560
+ /**
561
+ * Read and apply Structs and then DeleteStore to a y instance.
562
+ *
563
+ * @param {decoding.Decoder} decoder
564
+ * @param {Y.Doc} doc
565
+ * @param {any} transactionOrigin
566
+ */
567
+ const readSyncStep2 = (decoder, doc, transactionOrigin) => {
568
+ try {
569
+ Y$2.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin);
570
+ } catch (error) {
571
+ console.error("Caught error while handling a Yjs update", error);
572
+ }
573
+ };
574
+ /**
575
+ * @param {encoding.Encoder} encoder
576
+ * @param {Uint8Array} update
577
+ */
578
+ const writeUpdate = (encoder, update) => {
579
+ writeVarUint(encoder, messageYjsUpdate);
580
+ writeVarUint8Array(encoder, update);
581
+ };
582
+ /**
583
+ * Read and apply Structs and then DeleteStore to a y instance.
584
+ *
585
+ * @param {decoding.Decoder} decoder
586
+ * @param {Y.Doc} doc
587
+ * @param {any} transactionOrigin
588
+ */
589
+ const readUpdate = readSyncStep2;
590
+ /**
591
+ * @param {decoding.Decoder} decoder A message received from another client
592
+ * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.
593
+ * @param {Y.Doc} doc
594
+ * @param {any} transactionOrigin
595
+ */
596
+ const readSyncMessage = (decoder, encoder, doc, transactionOrigin) => {
597
+ const messageType = readVarUint(decoder);
598
+ switch (messageType) {
599
+ case messageYjsSyncStep1:
600
+ readSyncStep1(decoder, encoder, doc);
601
+ break;
602
+ case messageYjsSyncStep2:
603
+ readSyncStep2(decoder, doc, transactionOrigin);
604
+ break;
605
+ case messageYjsUpdate:
606
+ readUpdate(decoder, doc, transactionOrigin);
607
+ break;
608
+ default: throw new Error("Unknown message type");
609
+ }
610
+ return messageType;
611
+ };
612
+
613
+ //#endregion
614
+ //#region ../../node_modules/lib0/time.js
615
+ /**
616
+ * Return current unix time.
617
+ *
618
+ * @return {number}
619
+ */
620
+ const getUnixTime = Date.now;
621
+
622
+ //#endregion
623
+ //#region ../../node_modules/lib0/map.js
624
+ /**
625
+ * Utility module to work with key-value stores.
626
+ *
627
+ * @module map
628
+ */
629
+ /**
630
+ * Creates a new Map instance.
631
+ *
632
+ * @function
633
+ * @return {Map<any, any>}
634
+ *
635
+ * @function
636
+ */
637
+ const create = () => new Map();
638
+ /**
639
+ * Get map property. Create T if property is undefined and set T on map.
640
+ *
641
+ * ```js
642
+ * const listeners = map.setIfUndefined(events, 'eventName', set.create)
643
+ * listeners.add(listener)
644
+ * ```
645
+ *
646
+ * @function
647
+ * @template {Map<any, any>} MAP
648
+ * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF
649
+ * @param {MAP} map
650
+ * @param {MAP extends Map<infer K,any> ? K : unknown} key
651
+ * @param {CF} createT
652
+ * @return {ReturnType<CF>}
653
+ */
654
+ const setIfUndefined = (map, key, createT) => {
655
+ let set = map.get(key);
656
+ if (set === void 0) map.set(key, set = createT());
657
+ return set;
658
+ };
659
+
660
+ //#endregion
661
+ //#region ../../node_modules/lib0/observable.js
662
+ /* c8 ignore start */
663
+ /**
664
+ * Handles named events.
665
+ *
666
+ * @deprecated
667
+ * @template N
668
+ */
669
+ var Observable = class {
670
+ constructor() {
671
+ /**
672
+ * Some desc.
673
+ * @type {Map<N, any>}
674
+ */
675
+ this._observers = create();
676
+ }
677
+ /**
678
+ * @param {N} name
679
+ * @param {function} f
680
+ */
681
+ on(name, f) {
682
+ setIfUndefined(this._observers, name, create$2).add(f);
683
+ }
684
+ /**
685
+ * @param {N} name
686
+ * @param {function} f
687
+ */
688
+ once(name, f) {
689
+ /**
690
+ * @param {...any} args
691
+ */
692
+ const _f = (...args) => {
693
+ this.off(name, _f);
694
+ f(...args);
695
+ };
696
+ this.on(name, _f);
697
+ }
698
+ /**
699
+ * @param {N} name
700
+ * @param {function} f
701
+ */
702
+ off(name, f) {
703
+ const observers = this._observers.get(name);
704
+ if (observers !== void 0) {
705
+ observers.delete(f);
706
+ if (observers.size === 0) this._observers.delete(name);
707
+ }
708
+ }
709
+ /**
710
+ * Emit a named event. All registered event listeners that listen to the
711
+ * specified name will receive the event.
712
+ *
713
+ * @todo This should catch exceptions
714
+ *
715
+ * @param {N} name The event name.
716
+ * @param {Array<any>} args The arguments that are applied to the event listener.
717
+ */
718
+ emit(name, args) {
719
+ return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args));
720
+ }
721
+ destroy() {
722
+ this._observers = create();
723
+ }
724
+ };
725
+ /* c8 ignore end */
726
+
727
+ //#endregion
728
+ //#region ../../node_modules/lib0/object.js
729
+ /**
730
+ * @param {Object<string,any>} obj
731
+ */
732
+ const keys = Object.keys;
733
+ /**
734
+ * @deprecated use object.size instead
735
+ * @param {Object<string,any>} obj
736
+ * @return {number}
737
+ */
738
+ const length = (obj) => keys(obj).length;
739
+ /**
740
+ * Calls `Object.prototype.hasOwnProperty`.
741
+ *
742
+ * @param {any} obj
743
+ * @param {string|symbol} key
744
+ * @return {boolean}
745
+ */
746
+ const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
747
+
748
+ //#endregion
749
+ //#region ../../node_modules/lib0/traits.js
750
+ const EqualityTraitSymbol = Symbol("Equality");
751
+ /**
752
+ * @typedef {{ [EqualityTraitSymbol]:(other:EqualityTrait)=>boolean }} EqualityTrait
753
+ */
754
+
755
+ //#endregion
756
+ //#region ../../node_modules/lib0/function.js
757
+ /* c8 ignore start */
758
+ /**
759
+ * @param {any} a
760
+ * @param {any} b
761
+ * @return {boolean}
762
+ */
763
+ const equalityDeep = (a, b) => {
764
+ if (a === b) return true;
765
+ if (a == null || b == null || a.constructor !== b.constructor) return false;
766
+ if (a[EqualityTraitSymbol] != null) return a[EqualityTraitSymbol](b);
767
+ switch (a.constructor) {
768
+ case ArrayBuffer:
769
+ a = new Uint8Array(a);
770
+ b = new Uint8Array(b);
771
+ case Uint8Array: {
772
+ if (a.byteLength !== b.byteLength) return false;
773
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
774
+ break;
775
+ }
776
+ case Set: {
777
+ if (a.size !== b.size) return false;
778
+ for (const value of a) if (!b.has(value)) return false;
779
+ break;
780
+ }
781
+ case Map: {
782
+ if (a.size !== b.size) return false;
783
+ for (const key of a.keys()) if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) return false;
784
+ break;
785
+ }
786
+ case Object:
787
+ if (length(a) !== length(b)) return false;
788
+ for (const key in a) if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) return false;
789
+ break;
790
+ case Array:
791
+ if (a.length !== b.length) return false;
792
+ for (let i = 0; i < a.length; i++) if (!equalityDeep(a[i], b[i])) return false;
793
+ break;
794
+ default: return false;
795
+ }
796
+ return true;
797
+ };
798
+ /* c8 ignore stop */
799
+ const isArray = isArray$1;
800
+
801
+ //#endregion
802
+ //#region ../../node_modules/y-protocols/awareness.js
803
+ const outdatedTimeout = 3e4;
804
+ /**
805
+ * @typedef {Object} MetaClientState
806
+ * @property {number} MetaClientState.clock
807
+ * @property {number} MetaClientState.lastUpdated unix timestamp
808
+ */
809
+ /**
810
+ * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information
811
+ * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of
812
+ * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.
813
+ *
814
+ * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override
815
+ * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is
816
+ * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that
817
+ * a remote client is offline, it may propagate a message with
818
+ * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a
819
+ * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.
820
+ *
821
+ * Before a client disconnects, it should propagate a `null` state with an updated clock.
822
+ *
823
+ * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.
824
+ *
825
+ * @extends {Observable<string>}
826
+ */
827
+ var Awareness = class extends Observable {
828
+ /**
829
+ * @param {Y.Doc} doc
830
+ */
831
+ constructor(doc) {
832
+ super();
833
+ this.doc = doc;
834
+ /**
835
+ * @type {number}
836
+ */
837
+ this.clientID = doc.clientID;
838
+ /**
839
+ * Maps from client id to client state
840
+ * @type {Map<number, Object<string, any>>}
841
+ */
842
+ this.states = new Map();
843
+ /**
844
+ * @type {Map<number, MetaClientState>}
845
+ */
846
+ this.meta = new Map();
847
+ this._checkInterval = setInterval(() => {
848
+ const now$1 = getUnixTime();
849
+ if (this.getLocalState() !== null && outdatedTimeout / 2 <= now$1 - this.meta.get(this.clientID).lastUpdated) this.setLocalState(this.getLocalState());
850
+ /**
851
+ * @type {Array<number>}
852
+ */
853
+ const remove = [];
854
+ this.meta.forEach((meta, clientid) => {
855
+ if (clientid !== this.clientID && outdatedTimeout <= now$1 - meta.lastUpdated && this.states.has(clientid)) remove.push(clientid);
856
+ });
857
+ if (remove.length > 0) removeAwarenessStates(this, remove, "timeout");
858
+ }, floor(outdatedTimeout / 10));
859
+ doc.on("destroy", () => {
860
+ this.destroy();
861
+ });
862
+ this.setLocalState({});
863
+ }
864
+ destroy() {
865
+ this.emit("destroy", [this]);
866
+ this.setLocalState(null);
867
+ super.destroy();
868
+ clearInterval(this._checkInterval);
869
+ }
870
+ /**
871
+ * @return {Object<string,any>|null}
872
+ */
873
+ getLocalState() {
874
+ return this.states.get(this.clientID) || null;
875
+ }
876
+ /**
877
+ * @param {Object<string,any>|null} state
878
+ */
879
+ setLocalState(state) {
880
+ const clientID = this.clientID;
881
+ const currLocalMeta = this.meta.get(clientID);
882
+ const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1;
883
+ const prevState = this.states.get(clientID);
884
+ if (state === null) this.states.delete(clientID);
885
+ else this.states.set(clientID, state);
886
+ this.meta.set(clientID, {
887
+ clock,
888
+ lastUpdated: getUnixTime()
889
+ });
890
+ const added = [];
891
+ const updated = [];
892
+ const filteredUpdated = [];
893
+ const removed = [];
894
+ if (state === null) removed.push(clientID);
895
+ else if (prevState == null) {
896
+ if (state != null) added.push(clientID);
897
+ } else {
898
+ updated.push(clientID);
899
+ if (!equalityDeep(prevState, state)) filteredUpdated.push(clientID);
900
+ }
901
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) this.emit("change", [{
902
+ added,
903
+ updated: filteredUpdated,
904
+ removed
905
+ }, "local"]);
906
+ this.emit("update", [{
907
+ added,
908
+ updated,
909
+ removed
910
+ }, "local"]);
911
+ }
912
+ /**
913
+ * @param {string} field
914
+ * @param {any} value
915
+ */
916
+ setLocalStateField(field, value) {
917
+ const state = this.getLocalState();
918
+ if (state !== null) this.setLocalState({
919
+ ...state,
920
+ [field]: value
921
+ });
922
+ }
923
+ /**
924
+ * @return {Map<number,Object<string,any>>}
925
+ */
926
+ getStates() {
927
+ return this.states;
928
+ }
929
+ };
930
+ /**
931
+ * Mark (remote) clients as inactive and remove them from the list of active peers.
932
+ * This change will be propagated to remote clients.
933
+ *
934
+ * @param {Awareness} awareness
935
+ * @param {Array<number>} clients
936
+ * @param {any} origin
937
+ */
938
+ const removeAwarenessStates = (awareness, clients, origin) => {
939
+ const removed = [];
940
+ for (let i = 0; i < clients.length; i++) {
941
+ const clientID = clients[i];
942
+ if (awareness.states.has(clientID)) {
943
+ awareness.states.delete(clientID);
944
+ if (clientID === awareness.clientID) {
945
+ const curMeta = awareness.meta.get(clientID);
946
+ awareness.meta.set(clientID, {
947
+ clock: curMeta.clock + 1,
948
+ lastUpdated: getUnixTime()
949
+ });
950
+ }
951
+ removed.push(clientID);
952
+ }
953
+ }
954
+ if (removed.length > 0) {
955
+ awareness.emit("change", [{
956
+ added: [],
957
+ updated: [],
958
+ removed
959
+ }, origin]);
960
+ awareness.emit("update", [{
961
+ added: [],
962
+ updated: [],
963
+ removed
964
+ }, origin]);
965
+ }
966
+ };
967
+ /**
968
+ * @param {Awareness} awareness
969
+ * @param {Array<number>} clients
970
+ * @return {Uint8Array}
971
+ */
972
+ const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
973
+ const len = clients.length;
974
+ const encoder = createEncoder();
975
+ writeVarUint(encoder, len);
976
+ for (let i = 0; i < len; i++) {
977
+ const clientID = clients[i];
978
+ const state = states.get(clientID) || null;
979
+ const clock = awareness.meta.get(clientID).clock;
980
+ writeVarUint(encoder, clientID);
981
+ writeVarUint(encoder, clock);
982
+ writeVarString(encoder, JSON.stringify(state));
983
+ }
984
+ return toUint8Array(encoder);
985
+ };
986
+ /**
987
+ * @param {Awareness} awareness
988
+ * @param {Uint8Array} update
989
+ * @param {any} origin This will be added to the emitted change event
990
+ */
991
+ const applyAwarenessUpdate = (awareness, update, origin) => {
992
+ const decoder = createDecoder(update);
993
+ const timestamp = getUnixTime();
994
+ const added = [];
995
+ const updated = [];
996
+ const filteredUpdated = [];
997
+ const removed = [];
998
+ const len = readVarUint(decoder);
999
+ for (let i = 0; i < len; i++) {
1000
+ const clientID = readVarUint(decoder);
1001
+ let clock = readVarUint(decoder);
1002
+ const state = JSON.parse(readVarString(decoder));
1003
+ const clientMeta = awareness.meta.get(clientID);
1004
+ const prevState = awareness.states.get(clientID);
1005
+ const currClock = clientMeta === void 0 ? 0 : clientMeta.clock;
1006
+ if (currClock < clock || currClock === clock && state === null && awareness.states.has(clientID)) {
1007
+ if (state === null) if (clientID === awareness.clientID && awareness.getLocalState() != null) clock++;
1008
+ else awareness.states.delete(clientID);
1009
+ else awareness.states.set(clientID, state);
1010
+ awareness.meta.set(clientID, {
1011
+ clock,
1012
+ lastUpdated: timestamp
1013
+ });
1014
+ if (clientMeta === void 0 && state !== null) added.push(clientID);
1015
+ else if (clientMeta !== void 0 && state === null) removed.push(clientID);
1016
+ else if (state !== null) {
1017
+ if (!equalityDeep(state, prevState)) filteredUpdated.push(clientID);
1018
+ updated.push(clientID);
1019
+ }
1020
+ }
1021
+ }
1022
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) awareness.emit("change", [{
1023
+ added,
1024
+ updated: filteredUpdated,
1025
+ removed
1026
+ }, origin]);
1027
+ if (added.length > 0 || updated.length > 0 || removed.length > 0) awareness.emit("update", [{
1028
+ added,
1029
+ updated,
1030
+ removed
1031
+ }, origin]);
1032
+ };
1033
+
1034
+ //#endregion
1035
+ //#region ../../node_modules/lodash.debounce/index.js
1036
+ var require_lodash = __commonJS({ "../../node_modules/lodash.debounce/index.js"(exports, module) {
1037
+ /**
1038
+ * lodash (Custom Build) <https://lodash.com/>
1039
+ * Build: `lodash modularize exports="npm" -o ./`
1040
+ * Copyright jQuery Foundation and other contributors <https://jquery.org/>
1041
+ * Released under MIT license <https://lodash.com/license>
1042
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
1043
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
1044
+ */
1045
+ /** Used as the `TypeError` message for "Functions" methods. */
1046
+ var FUNC_ERROR_TEXT = "Expected a function";
1047
+ /** Used as references for various `Number` constants. */
1048
+ var NAN = NaN;
1049
+ /** `Object#toString` result references. */
1050
+ var symbolTag = "[object Symbol]";
1051
+ /** Used to match leading and trailing whitespace. */
1052
+ var reTrim = /^\s+|\s+$/g;
1053
+ /** Used to detect bad signed hexadecimal string values. */
1054
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
1055
+ /** Used to detect binary string values. */
1056
+ var reIsBinary = /^0b[01]+$/i;
1057
+ /** Used to detect octal string values. */
1058
+ var reIsOctal = /^0o[0-7]+$/i;
1059
+ /** Built-in method references without a dependency on `root`. */
1060
+ var freeParseInt = parseInt;
1061
+ /** Detect free variable `global` from Node.js. */
1062
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
1063
+ /** Detect free variable `self`. */
1064
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
1065
+ /** Used as a reference to the global object. */
1066
+ var root = freeGlobal || freeSelf || Function("return this")();
1067
+ /** Used for built-in method references. */
1068
+ var objectProto = Object.prototype;
1069
+ /**
1070
+ * Used to resolve the
1071
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
1072
+ * of values.
1073
+ */
1074
+ var objectToString = objectProto.toString;
1075
+ var nativeMax = Math.max, nativeMin = Math.min;
1076
+ /**
1077
+ * Gets the timestamp of the number of milliseconds that have elapsed since
1078
+ * the Unix epoch (1 January 1970 00:00:00 UTC).
1079
+ *
1080
+ * @static
1081
+ * @memberOf _
1082
+ * @since 2.4.0
1083
+ * @category Date
1084
+ * @returns {number} Returns the timestamp.
1085
+ * @example
1086
+ *
1087
+ * _.defer(function(stamp) {
1088
+ * console.log(_.now() - stamp);
1089
+ * }, _.now());
1090
+ * // => Logs the number of milliseconds it took for the deferred invocation.
1091
+ */
1092
+ var now = function() {
1093
+ return root.Date.now();
1094
+ };
1095
+ /**
1096
+ * Creates a debounced function that delays invoking `func` until after `wait`
1097
+ * milliseconds have elapsed since the last time the debounced function was
1098
+ * invoked. The debounced function comes with a `cancel` method to cancel
1099
+ * delayed `func` invocations and a `flush` method to immediately invoke them.
1100
+ * Provide `options` to indicate whether `func` should be invoked on the
1101
+ * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
1102
+ * with the last arguments provided to the debounced function. Subsequent
1103
+ * calls to the debounced function return the result of the last `func`
1104
+ * invocation.
1105
+ *
1106
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
1107
+ * invoked on the trailing edge of the timeout only if the debounced function
1108
+ * is invoked more than once during the `wait` timeout.
1109
+ *
1110
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
1111
+ * until to the next tick, similar to `setTimeout` with a timeout of `0`.
1112
+ *
1113
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
1114
+ * for details over the differences between `_.debounce` and `_.throttle`.
1115
+ *
1116
+ * @static
1117
+ * @memberOf _
1118
+ * @since 0.1.0
1119
+ * @category Function
1120
+ * @param {Function} func The function to debounce.
1121
+ * @param {number} [wait=0] The number of milliseconds to delay.
1122
+ * @param {Object} [options={}] The options object.
1123
+ * @param {boolean} [options.leading=false]
1124
+ * Specify invoking on the leading edge of the timeout.
1125
+ * @param {number} [options.maxWait]
1126
+ * The maximum time `func` is allowed to be delayed before it's invoked.
1127
+ * @param {boolean} [options.trailing=true]
1128
+ * Specify invoking on the trailing edge of the timeout.
1129
+ * @returns {Function} Returns the new debounced function.
1130
+ * @example
1131
+ *
1132
+ * // Avoid costly calculations while the window size is in flux.
1133
+ * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
1134
+ *
1135
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
1136
+ * jQuery(element).on('click', _.debounce(sendMail, 300, {
1137
+ * 'leading': true,
1138
+ * 'trailing': false
1139
+ * }));
1140
+ *
1141
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
1142
+ * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
1143
+ * var source = new EventSource('/stream');
1144
+ * jQuery(source).on('message', debounced);
1145
+ *
1146
+ * // Cancel the trailing debounced invocation.
1147
+ * jQuery(window).on('popstate', debounced.cancel);
1148
+ */
1149
+ function debounce(func, wait, options) {
1150
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
1151
+ if (typeof func != "function") throw new TypeError(FUNC_ERROR_TEXT);
1152
+ wait = toNumber(wait) || 0;
1153
+ if (isObject(options)) {
1154
+ leading = !!options.leading;
1155
+ maxing = "maxWait" in options;
1156
+ maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
1157
+ trailing = "trailing" in options ? !!options.trailing : trailing;
1158
+ }
1159
+ function invokeFunc(time) {
1160
+ var args = lastArgs, thisArg = lastThis;
1161
+ lastArgs = lastThis = void 0;
1162
+ lastInvokeTime = time;
1163
+ result = func.apply(thisArg, args);
1164
+ return result;
1165
+ }
1166
+ function leadingEdge(time) {
1167
+ lastInvokeTime = time;
1168
+ timerId = setTimeout(timerExpired, wait);
1169
+ return leading ? invokeFunc(time) : result;
1170
+ }
1171
+ function remainingWait(time) {
1172
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result$1 = wait - timeSinceLastCall;
1173
+ return maxing ? nativeMin(result$1, maxWait - timeSinceLastInvoke) : result$1;
1174
+ }
1175
+ function shouldInvoke(time) {
1176
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
1177
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
1178
+ }
1179
+ function timerExpired() {
1180
+ var time = now();
1181
+ if (shouldInvoke(time)) return trailingEdge(time);
1182
+ timerId = setTimeout(timerExpired, remainingWait(time));
1183
+ }
1184
+ function trailingEdge(time) {
1185
+ timerId = void 0;
1186
+ if (trailing && lastArgs) return invokeFunc(time);
1187
+ lastArgs = lastThis = void 0;
1188
+ return result;
1189
+ }
1190
+ function cancel() {
1191
+ if (timerId !== void 0) clearTimeout(timerId);
1192
+ lastInvokeTime = 0;
1193
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
1194
+ }
1195
+ function flush() {
1196
+ return timerId === void 0 ? result : trailingEdge(now());
1197
+ }
1198
+ function debounced() {
1199
+ var time = now(), isInvoking = shouldInvoke(time);
1200
+ lastArgs = arguments;
1201
+ lastThis = this;
1202
+ lastCallTime = time;
1203
+ if (isInvoking) {
1204
+ if (timerId === void 0) return leadingEdge(lastCallTime);
1205
+ if (maxing) {
1206
+ timerId = setTimeout(timerExpired, wait);
1207
+ return invokeFunc(lastCallTime);
1208
+ }
1209
+ }
1210
+ if (timerId === void 0) timerId = setTimeout(timerExpired, wait);
1211
+ return result;
1212
+ }
1213
+ debounced.cancel = cancel;
1214
+ debounced.flush = flush;
1215
+ return debounced;
1216
+ }
1217
+ /**
1218
+ * Checks if `value` is the
1219
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
1220
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
1221
+ *
1222
+ * @static
1223
+ * @memberOf _
1224
+ * @since 0.1.0
1225
+ * @category Lang
1226
+ * @param {*} value The value to check.
1227
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
1228
+ * @example
1229
+ *
1230
+ * _.isObject({});
1231
+ * // => true
1232
+ *
1233
+ * _.isObject([1, 2, 3]);
1234
+ * // => true
1235
+ *
1236
+ * _.isObject(_.noop);
1237
+ * // => true
1238
+ *
1239
+ * _.isObject(null);
1240
+ * // => false
1241
+ */
1242
+ function isObject(value) {
1243
+ var type = typeof value;
1244
+ return !!value && (type == "object" || type == "function");
1245
+ }
1246
+ /**
1247
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
1248
+ * and has a `typeof` result of "object".
1249
+ *
1250
+ * @static
1251
+ * @memberOf _
1252
+ * @since 4.0.0
1253
+ * @category Lang
1254
+ * @param {*} value The value to check.
1255
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
1256
+ * @example
1257
+ *
1258
+ * _.isObjectLike({});
1259
+ * // => true
1260
+ *
1261
+ * _.isObjectLike([1, 2, 3]);
1262
+ * // => true
1263
+ *
1264
+ * _.isObjectLike(_.noop);
1265
+ * // => false
1266
+ *
1267
+ * _.isObjectLike(null);
1268
+ * // => false
1269
+ */
1270
+ function isObjectLike(value) {
1271
+ return !!value && typeof value == "object";
1272
+ }
1273
+ /**
1274
+ * Checks if `value` is classified as a `Symbol` primitive or object.
1275
+ *
1276
+ * @static
1277
+ * @memberOf _
1278
+ * @since 4.0.0
1279
+ * @category Lang
1280
+ * @param {*} value The value to check.
1281
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
1282
+ * @example
1283
+ *
1284
+ * _.isSymbol(Symbol.iterator);
1285
+ * // => true
1286
+ *
1287
+ * _.isSymbol('abc');
1288
+ * // => false
1289
+ */
1290
+ function isSymbol(value) {
1291
+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
1292
+ }
1293
+ /**
1294
+ * Converts `value` to a number.
1295
+ *
1296
+ * @static
1297
+ * @memberOf _
1298
+ * @since 4.0.0
1299
+ * @category Lang
1300
+ * @param {*} value The value to process.
1301
+ * @returns {number} Returns the number.
1302
+ * @example
1303
+ *
1304
+ * _.toNumber(3.2);
1305
+ * // => 3.2
1306
+ *
1307
+ * _.toNumber(Number.MIN_VALUE);
1308
+ * // => 5e-324
1309
+ *
1310
+ * _.toNumber(Infinity);
1311
+ * // => Infinity
1312
+ *
1313
+ * _.toNumber('3.2');
1314
+ * // => 3.2
1315
+ */
1316
+ function toNumber(value) {
1317
+ if (typeof value == "number") return value;
1318
+ if (isSymbol(value)) return NAN;
1319
+ if (isObject(value)) {
1320
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
1321
+ value = isObject(other) ? other + "" : other;
1322
+ }
1323
+ if (typeof value != "string") return value === 0 ? value : +value;
1324
+ value = value.replace(reTrim, "");
1325
+ var isBinary = reIsBinary.test(value);
1326
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
1327
+ }
1328
+ module.exports = debounce;
1329
+ } });
1330
+ var import_lodash = __toESM(require_lodash(), 1);
1331
+
1332
+ //#endregion
1333
+ //#region src/server/websockets-callbacks.ts
1334
+ const CALLBACK_URL = process.env.CALLBACK_URL ? new URL(process.env.CALLBACK_URL) : null;
1335
+ const CALLBACK_TIMEOUT = parseInt$1(process.env.CALLBACK_TIMEOUT || "5000");
1336
+ const CALLBACK_OBJECTS = process.env.CALLBACK_OBJECTS ? JSON.parse(process.env.CALLBACK_OBJECTS) : {};
1337
+ const isCallbackSet = !!CALLBACK_URL;
1338
+ const callbackHandler = (_update, _origin, doc) => {
1339
+ const room = doc.name;
1340
+ const dataToSend = {
1341
+ room,
1342
+ data: {}
1343
+ };
1344
+ const sharedObjectList = Object.keys(CALLBACK_OBJECTS);
1345
+ sharedObjectList.forEach((sharedObjectName) => {
1346
+ const sharedObjectType = CALLBACK_OBJECTS[sharedObjectName];
1347
+ dataToSend.data[sharedObjectName] = {
1348
+ type: sharedObjectType,
1349
+ content: getContent(sharedObjectName, sharedObjectType, doc).toJSON()
1350
+ };
1351
+ });
1352
+ if (CALLBACK_URL) callbackRequest(CALLBACK_URL, CALLBACK_TIMEOUT, dataToSend);
1353
+ };
1354
+ const callbackRequest = (url, timeout, data) => {
1355
+ data = JSON.stringify(data);
1356
+ const options = {
1357
+ hostname: url.hostname,
1358
+ port: url.port,
1359
+ path: url.pathname,
1360
+ timeout,
1361
+ method: "POST",
1362
+ headers: {
1363
+ "Content-Type": "application/json",
1364
+ "Content-Length": Buffer.byteLength(data)
1365
+ }
1366
+ };
1367
+ const req = http.request(options);
1368
+ req.on("timeout", () => {
1369
+ console.warn("Callback request timed out.");
1370
+ req.abort();
1371
+ });
1372
+ req.on("error", (e) => {
1373
+ console.error("Callback request error.", e);
1374
+ req.abort();
1375
+ });
1376
+ req.write(data);
1377
+ req.end();
1378
+ };
1379
+ const getContent = (objName, objType, doc) => {
1380
+ switch (objType) {
1381
+ case "Array": return doc.getArray(objName);
1382
+ case "Map": return doc.getMap(objName);
1383
+ case "Text": return doc.getText(objName);
1384
+ case "XmlFragment": return doc.getXmlFragment(objName);
1385
+ case "XmlElement": return doc.getXmlElement(objName);
1386
+ default: return {};
1387
+ }
1388
+ };
1389
+
1390
+ //#endregion
1391
+ //#region src/server/websockets-utils.ts
1392
+ let actualServer = void 0;
1393
+ const CALLBACK_DEBOUNCE_WAIT = parseInt(process.env.CALLBACK_DEBOUNCE_WAIT || "2000");
1394
+ const CALLBACK_DEBOUNCE_MAXWAIT = parseInt(process.env.CALLBACK_DEBOUNCE_MAXWAIT || "10000");
1395
+ const wsReadyStateConnecting = 0;
1396
+ const wsReadyStateOpen = 1;
1397
+ const gcEnabled = process.env.GC !== "false" && process.env.GC !== "0";
1398
+ const docs = new Map();
1399
+ const persistenceMap = new Map();
1400
+ const messageSync = 0;
1401
+ const messageAwareness = 1;
1402
+ const updateHandler = (update, _origin, doc) => {
1403
+ const encoder = createEncoder();
1404
+ writeVarUint(encoder, messageSync);
1405
+ writeUpdate(encoder, update);
1406
+ const message = toUint8Array(encoder);
1407
+ doc.conns.forEach((_, conn) => send(doc, conn, message));
1408
+ };
1409
+ let contentInitializor = () => Promise.resolve();
1410
+ var WSSharedDoc = class extends Y$1.Doc {
1411
+ constructor(name) {
1412
+ super({ gc: gcEnabled });
1413
+ this.name = name;
1414
+ this.conns = new Map();
1415
+ this.awareness = new Awareness(this);
1416
+ this.awareness.setLocalState(null);
1417
+ const awarenessChangeHandler = ({ added, updated, removed }, conn) => {
1418
+ const changedClients = added.concat(updated, removed);
1419
+ if (conn !== null) {
1420
+ const connControlledIDs = this.conns.get(conn);
1421
+ if (connControlledIDs !== void 0) {
1422
+ added.forEach((clientID) => {
1423
+ connControlledIDs.add(clientID);
1424
+ });
1425
+ removed.forEach((clientID) => {
1426
+ connControlledIDs.delete(clientID);
1427
+ });
1428
+ }
1429
+ }
1430
+ const encoder = createEncoder();
1431
+ writeVarUint(encoder, messageAwareness);
1432
+ writeVarUint8Array(encoder, encodeAwarenessUpdate(this.awareness, changedClients));
1433
+ const buff = toUint8Array(encoder);
1434
+ this.conns.forEach((_, c) => {
1435
+ send(this, c, buff);
1436
+ });
1437
+ };
1438
+ this.awareness.on("update", awarenessChangeHandler);
1439
+ this.on("update", updateHandler);
1440
+ if (isCallbackSet) this.on("update", (0, import_lodash.default)(callbackHandler, CALLBACK_DEBOUNCE_WAIT, { maxWait: CALLBACK_DEBOUNCE_MAXWAIT }));
1441
+ this.whenInitialized = contentInitializor();
1442
+ }
1443
+ };
1444
+ const getYDoc = (docName, initialState, gc = true) => setIfUndefined(docs, docName, async () => {
1445
+ let documentData = void 0;
1446
+ if (actualServer && actualServer.fetchRoom) documentData = await actualServer.fetchRoom(docName);
1447
+ const doc = new WSSharedDoc(docName);
1448
+ doc.gc = gc;
1449
+ docs.set(docName, doc);
1450
+ if (documentData) Y$1.applyUpdate(doc, documentData);
1451
+ else initialState(doc);
1452
+ await setupRoomPersistence(docName, doc);
1453
+ return doc;
1454
+ });
1455
+ const messageListener = (conn, doc, message) => {
1456
+ try {
1457
+ const encoder = createEncoder();
1458
+ const decoder = createDecoder(message);
1459
+ const messageType = readVarUint(decoder);
1460
+ switch (messageType) {
1461
+ case messageSync:
1462
+ writeVarUint(encoder, messageSync);
1463
+ readSyncMessage(decoder, encoder, doc, conn);
1464
+ if (length$1(encoder) > 1) send(doc, conn, toUint8Array(encoder));
1465
+ break;
1466
+ case messageAwareness: {
1467
+ applyAwarenessUpdate(doc.awareness, readVarUint8Array(decoder), conn);
1468
+ break;
1469
+ }
1470
+ }
1471
+ } catch (err) {
1472
+ console.error(err);
1473
+ }
1474
+ };
1475
+ const closeConn = (doc, conn) => {
1476
+ if (doc.conns.has(conn)) {
1477
+ /**
1478
+ * @type {Set<number>}
1479
+ */
1480
+ const controlledIds = doc.conns.get(conn);
1481
+ doc.conns.delete(conn);
1482
+ if (persistenceMap.has(doc.name)) clearInterval(persistenceMap.get(doc.name));
1483
+ removeAwarenessStates(doc.awareness, Array.from(controlledIds), null);
1484
+ }
1485
+ conn.close();
1486
+ };
1487
+ const send = (doc, conn, m) => {
1488
+ if (conn.readyState !== wsReadyStateConnecting && conn.readyState !== wsReadyStateOpen) closeConn(doc, conn);
1489
+ try {
1490
+ conn.send(m, {}, (err) => {
1491
+ if (err != null) closeConn(doc, conn);
1492
+ });
1493
+ } catch (e) {
1494
+ closeConn(doc, conn);
1495
+ }
1496
+ };
1497
+ const pingTimeout = 3e4;
1498
+ const setServer = (server) => {
1499
+ actualServer = server;
1500
+ };
1501
+ const setupWSConnection = (getDocName, initialState) => {
1502
+ return async (conn, req, { gc = true } = {}) => {
1503
+ const docName = getDocName(req);
1504
+ if (!docName) return;
1505
+ conn.binaryType = "arraybuffer";
1506
+ const doc = await getYDoc(docName, initialState, gc);
1507
+ doc.conns.set(conn, new Set());
1508
+ conn.on("message", (message) => messageListener(conn, doc, new Uint8Array(message)));
1509
+ let pongReceived = true;
1510
+ const pingInterval = setInterval(() => {
1511
+ if (!pongReceived) {
1512
+ if (doc.conns.has(conn)) closeConn(doc, conn);
1513
+ clearInterval(pingInterval);
1514
+ } else if (doc.conns.has(conn)) {
1515
+ pongReceived = false;
1516
+ try {
1517
+ conn.ping();
1518
+ } catch (e) {
1519
+ closeConn(doc, conn);
1520
+ clearInterval(pingInterval);
1521
+ }
1522
+ }
1523
+ }, pingTimeout);
1524
+ conn.on("close", () => {
1525
+ closeConn(doc, conn);
1526
+ clearInterval(pingInterval);
1527
+ });
1528
+ conn.on("pong", () => {
1529
+ pongReceived = true;
1530
+ });
1531
+ {
1532
+ const encoder = createEncoder();
1533
+ writeVarUint(encoder, messageSync);
1534
+ writeSyncStep1(encoder, doc);
1535
+ send(doc, conn, toUint8Array(encoder));
1536
+ const awarenessStates = doc.awareness.getStates();
1537
+ if (awarenessStates.size > 0) {
1538
+ const encoder$1 = createEncoder();
1539
+ writeVarUint(encoder$1, messageAwareness);
1540
+ writeVarUint8Array(encoder$1, encodeAwarenessUpdate(doc.awareness, Array.from(awarenessStates.keys())));
1541
+ send(doc, conn, toUint8Array(encoder$1));
1542
+ }
1543
+ }
1544
+ };
1545
+ };
1546
+ async function setupRoomPersistence(roomId, doc) {
1547
+ if (!persistenceMap.has(roomId)) {
1548
+ const persistHandler = async () => {
1549
+ const actualState = Y$1.encodeStateAsUpdate(doc);
1550
+ if (actualServer && actualServer.persistRoom) try {
1551
+ await actualServer.persistRoom(roomId, actualState);
1552
+ } catch (ex) {
1553
+ console.error(ex);
1554
+ }
1555
+ };
1556
+ persistHandler();
1557
+ const intervalId = setInterval(persistHandler, parseInt(process.env.WEAVE_WEBSOCKETS_STATE_SYNC_FREQUENCY_SEG ?? "10") * 1e3);
1558
+ persistenceMap.set(roomId, intervalId);
1559
+ }
320
1560
  }
321
- class et {
322
- constructor({
323
- initialState: n = He,
324
- performUpgrade: t,
325
- extractRoomId: r,
326
- persistRoom: s,
327
- fetchRoom: i
328
- }) {
329
- d(this, "initialState");
330
- d(this, "performUpgrade");
331
- d(this, "extractRoomId");
332
- d(this, "wss");
333
- d(this, "persistRoom");
334
- d(this, "fetchRoom");
335
- this.initialState = n, this.performUpgrade = t, this.extractRoomId = r, this.persistRoom = s, this.fetchRoom = i, this.wss = new q({ noServer: !0 }), $e(this), this.wss.on(
336
- "connection",
337
- ze(this.extractRoomId, this.initialState)
338
- );
339
- }
340
- handleUpgrade(n) {
341
- n.on("upgrade", async (t, r, s) => {
342
- await this.performUpgrade(t) && this.wss.handleUpgrade(t, r, s, (a) => {
343
- this.wss.emit("connection", a, t);
344
- });
345
- });
346
- }
1561
+
1562
+ //#endregion
1563
+ //#region src/server/default-initial-state.ts
1564
+ const yjsLayer = function(id) {
1565
+ const newLayerMap = new Y.Map();
1566
+ newLayerMap.set("key", id);
1567
+ newLayerMap.set("type", "layer");
1568
+ const newLayerMapProps = new Y.Map();
1569
+ newLayerMapProps.set("id", id);
1570
+ newLayerMapProps.set("nodeType", "layer");
1571
+ newLayerMapProps.set("children", new Y.Array());
1572
+ newLayerMap.set("props", newLayerMapProps);
1573
+ return newLayerMap;
1574
+ };
1575
+ function defaultInitialState(doc) {
1576
+ const children = new Y.Array();
1577
+ children.insert(0, [
1578
+ yjsLayer("gridLayer"),
1579
+ yjsLayer("mainLayer"),
1580
+ yjsLayer("selectionLayer"),
1581
+ yjsLayer("usersPointersLayer"),
1582
+ yjsLayer("utilityLayer")
1583
+ ]);
1584
+ const stageProps = new Y.Map();
1585
+ stageProps.set("id", "stage");
1586
+ stageProps.set("children", children);
1587
+ doc.getMap("weave").set("key", "stage");
1588
+ doc.getMap("weave").set("type", "stage");
1589
+ doc.getMap("weave").set("props", stageProps);
347
1590
  }
348
- export {
349
- st as WEAVE_STORE_WEBSOCKETS,
350
- rt as WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS,
351
- et as WeaveWebsocketsServer
1591
+
1592
+ //#endregion
1593
+ //#region src/server/websockets-server.ts
1594
+ var WeaveWebsocketsServer = class {
1595
+ persistRoom = void 0;
1596
+ fetchRoom = void 0;
1597
+ constructor({ initialState = defaultInitialState, performUpgrade, extractRoomId, persistRoom, fetchRoom }) {
1598
+ this.initialState = initialState;
1599
+ this.performUpgrade = performUpgrade;
1600
+ this.extractRoomId = extractRoomId;
1601
+ this.persistRoom = persistRoom;
1602
+ this.fetchRoom = fetchRoom;
1603
+ this.wss = new WebSocketServer({ noServer: true });
1604
+ setServer(this);
1605
+ this.wss.on("connection", setupWSConnection(this.extractRoomId, this.initialState));
1606
+ }
1607
+ handleUpgrade(server) {
1608
+ server.on("upgrade", async (request, socket, head) => {
1609
+ const continueToUpgrade = await this.performUpgrade(request);
1610
+ if (!continueToUpgrade) return;
1611
+ this.wss.handleUpgrade(request, socket, head, (ws) => {
1612
+ this.wss.emit("connection", ws, request);
1613
+ });
1614
+ });
1615
+ }
352
1616
  };
1617
+
1618
+ //#endregion
1619
+ export { WEAVE_STORE_WEBSOCKETS, WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS, WeaveWebsocketsServer };