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