@inditextech/weave-store-websockets 0.1.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/client.js ADDED
@@ -0,0 +1,377 @@
1
+ var Z = Object.defineProperty;
2
+ var v = (e, s, t) => s in e ? Z(e, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[s] = t;
3
+ var m = (e, s, t) => (v(e, typeof s != "symbol" ? s + "" : s, t), t);
4
+ import { WeaveStore as ee } from "@inditextech/weave-sdk";
5
+ import { i as se, c as A, f as L, a as te, s as ne, b as ce, r as x, d as ae, m as oe, O as ie, A as re, w as i, e as I, t as o, l as P, g as le, h as p, j as S, k as V, n as U, o as he, p as r, q as de, u as ue, v as fe, x as we, y as me, z as ge, B as ye, W as be } from "./awareness-C8fdGy2v.js";
6
+ import { C as Xe } from "./awareness-C8fdGy2v.js";
7
+ import "yjs";
8
+ const W = (e) => e === void 0 ? null : e;
9
+ class pe {
10
+ constructor() {
11
+ this.map = /* @__PURE__ */ new Map();
12
+ }
13
+ /**
14
+ * @param {string} key
15
+ * @param {any} newValue
16
+ */
17
+ setItem(s, t) {
18
+ this.map.set(s, t);
19
+ }
20
+ /**
21
+ * @param {string} key
22
+ */
23
+ getItem(s) {
24
+ return this.map.get(s);
25
+ }
26
+ }
27
+ let D = new pe(), k = !0;
28
+ try {
29
+ typeof localStorage < "u" && localStorage && (D = localStorage, k = !1);
30
+ } catch {
31
+ }
32
+ const N = D, Se = (e) => k || addEventListener(
33
+ "storage",
34
+ /** @type {any} */
35
+ e
36
+ ), _e = (e) => k || removeEventListener(
37
+ "storage",
38
+ /** @type {any} */
39
+ e
40
+ ), u = typeof process < "u" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process < "u" ? process : 0) === "[object process]", j = typeof window < "u" && typeof document < "u" && !u;
41
+ let l;
42
+ const Ce = () => {
43
+ if (l === void 0)
44
+ if (u) {
45
+ l = A();
46
+ const e = process.argv;
47
+ let s = null;
48
+ for (let t = 0; t < e.length; t++) {
49
+ const n = e[t];
50
+ n[0] === "-" ? (s !== null && l.set(s, ""), s = n) : s !== null && (l.set(s, n), s = null);
51
+ }
52
+ s !== null && l.set(s, "");
53
+ } else
54
+ typeof location == "object" ? (l = A(), (location.search || "?").slice(1).split("&").forEach((e) => {
55
+ if (e.length !== 0) {
56
+ const [s, t] = e.split("=");
57
+ l.set(`--${L(s, "-")}`, t), l.set(`-${L(s, "-")}`, t);
58
+ }
59
+ })) : l = A();
60
+ return l;
61
+ }, O = (e) => Ce().has(e), T = (e) => W(u ? process.env[e.toUpperCase().replaceAll("-", "_")] : N.getItem(e)), $ = (e) => O("--" + e) || T(e) !== null;
62
+ $("production");
63
+ const Ae = u && se(process.env.FORCE_COLOR, ["true", "1", "2"]);
64
+ Ae || !O("--no-colors") && // @todo deprecate --no-colors
65
+ !$("no-color") && (!u || process.stdout.isTTY) && (!u || O("--color") || T("COLORTERM") !== null || (T("TERM") || "").includes("color"));
66
+ const Be = (e) => new Uint8Array(e), Ie = (e, s, t) => new Uint8Array(e, s, t), Ue = (e) => new Uint8Array(e), Oe = (e) => {
67
+ let s = "";
68
+ for (let t = 0; t < e.byteLength; t++)
69
+ s += te(e[t]);
70
+ return btoa(s);
71
+ }, Te = (e) => Buffer.from(e.buffer, e.byteOffset, e.byteLength).toString("base64"), Ee = (e) => {
72
+ const s = atob(e), t = Be(s.length);
73
+ for (let n = 0; n < s.length; n++)
74
+ t[n] = s.charCodeAt(n);
75
+ return t;
76
+ }, ke = (e) => {
77
+ const s = Buffer.from(e, "base64");
78
+ return Ie(s.buffer, s.byteOffset, s.byteLength);
79
+ }, Re = j ? Oe : Te, Me = j ? Ee : ke, F = /* @__PURE__ */ new Map();
80
+ class Le {
81
+ /**
82
+ * @param {string} room
83
+ */
84
+ constructor(s) {
85
+ this.room = s, this.onmessage = null, this._onChange = (t) => t.key === s && this.onmessage !== null && this.onmessage({ data: Me(t.newValue || "") }), Se(this._onChange);
86
+ }
87
+ /**
88
+ * @param {ArrayBuffer} buf
89
+ */
90
+ postMessage(s) {
91
+ N.setItem(this.room, Re(Ue(s)));
92
+ }
93
+ close() {
94
+ _e(this._onChange);
95
+ }
96
+ }
97
+ const We = typeof BroadcastChannel > "u" ? Le : BroadcastChannel, R = (e) => ne(F, e, () => {
98
+ const s = ce(), t = new We(e);
99
+ return t.onmessage = (n) => s.forEach((c) => c(n.data, "broadcastchannel")), {
100
+ bc: t,
101
+ subs: s
102
+ };
103
+ }), He = (e, s) => (R(e).subs.add(s), s), xe = (e, s) => {
104
+ const t = R(e), n = t.subs.delete(s);
105
+ return n && t.subs.size === 0 && (t.bc.close(), F.delete(e)), n;
106
+ }, g = (e, s, t = null) => {
107
+ const n = R(e);
108
+ n.bc.postMessage(s), n.subs.forEach((c) => c(s, t));
109
+ }, Pe = 0, Ve = (e, s, t) => {
110
+ switch (x(e)) {
111
+ case Pe:
112
+ t(s, ae(e));
113
+ }
114
+ }, De = (e) => oe(e, (s, t) => `${encodeURIComponent(t)}=${encodeURIComponent(s)}`).join("&"), f = 0, Q = 3, y = 1, Ne = 2, _ = [];
115
+ _[f] = (e, s, t, n, c) => {
116
+ i(e, f);
117
+ const a = we(
118
+ s,
119
+ e,
120
+ t.doc,
121
+ t
122
+ );
123
+ n && a === me && !t.synced && (t.synced = !0);
124
+ };
125
+ _[Q] = (e, s, t, n, c) => {
126
+ i(e, y), p(
127
+ e,
128
+ S(
129
+ t.awareness,
130
+ Array.from(t.awareness.getStates().keys())
131
+ )
132
+ );
133
+ };
134
+ _[y] = (e, s, t, n, c) => {
135
+ ge(
136
+ t.awareness,
137
+ ye(s),
138
+ t
139
+ );
140
+ };
141
+ _[Ne] = (e, s, t, n, c) => {
142
+ Ve(
143
+ s,
144
+ t.doc,
145
+ (a, w) => je(t, w)
146
+ );
147
+ };
148
+ const H = 3e4, je = (e, s) => console.warn(`Permission denied to access ${e.url}.
149
+ ${s}`), z = (e, s, t) => {
150
+ const n = de(s), c = r(), a = x(n), w = e.messageHandlers[a];
151
+ return /** @type {any} */ w ? w(c, n, e, t, a) : console.error("Unable to compute message"), c;
152
+ }, E = (e, s, t) => {
153
+ s === e.ws && (e.emit("connection-close", [t, e]), e.ws = null, s.close(), e.wsconnecting = !1, e.wsconnected ? (e.wsconnected = !1, e.synced = !1, V(
154
+ e.awareness,
155
+ Array.from(e.awareness.getStates().keys()).filter(
156
+ (n) => n !== e.doc.clientID
157
+ ),
158
+ e
159
+ ), e.emit("status", [{
160
+ status: "disconnected"
161
+ }])) : e.wsUnsuccessfulReconnects++, setTimeout(
162
+ K,
163
+ ue(
164
+ fe(2, e.wsUnsuccessfulReconnects) * 100,
165
+ e.maxBackoffTime
166
+ ),
167
+ e
168
+ ));
169
+ }, K = (e) => {
170
+ if (e.shouldConnect && e.ws === null) {
171
+ const s = new e._WS(e.url, e.protocols);
172
+ s.binaryType = "arraybuffer", e.ws = s, e.wsconnecting = !0, e.wsconnected = !1, e.synced = !1, s.onmessage = (t) => {
173
+ e.wsLastMessageReceived = U();
174
+ const n = z(e, new Uint8Array(t.data), !0);
175
+ P(n) > 1 && s.send(o(n));
176
+ }, s.onerror = (t) => {
177
+ e.emit("connection-error", [t, e]);
178
+ }, s.onclose = (t) => {
179
+ E(e, s, t);
180
+ }, s.onopen = () => {
181
+ e.wsLastMessageReceived = U(), e.wsconnecting = !1, e.wsconnected = !0, e.wsUnsuccessfulReconnects = 0, e.emit("status", [{
182
+ status: "connected"
183
+ }]);
184
+ const t = r();
185
+ if (i(t, f), I(t, e.doc), s.send(o(t)), e.awareness.getLocalState() !== null) {
186
+ const n = r();
187
+ i(n, y), p(
188
+ n,
189
+ S(e.awareness, [
190
+ e.doc.clientID
191
+ ])
192
+ ), s.send(o(n));
193
+ }
194
+ }, e.emit("status", [{
195
+ status: "connecting"
196
+ }]);
197
+ }
198
+ }, B = (e, s) => {
199
+ const t = e.ws;
200
+ e.wsconnected && t && t.readyState === t.OPEN && t.send(s), e.bcconnected && g(e.bcChannel, s, e);
201
+ };
202
+ class $e extends ie {
203
+ /**
204
+ * @param {string} serverUrl
205
+ * @param {string} roomname
206
+ * @param {Y.Doc} doc
207
+ * @param {object} opts
208
+ * @param {boolean} [opts.connect]
209
+ * @param {awarenessProtocol.Awareness} [opts.awareness]
210
+ * @param {Object<string,string>} [opts.params] specify url parameters
211
+ * @param {Array<string>} [opts.protocols] specify websocket protocols
212
+ * @param {typeof WebSocket} [opts.WebSocketPolyfill] Optionall provide a WebSocket polyfill
213
+ * @param {number} [opts.resyncInterval] Request server state every `resyncInterval` milliseconds
214
+ * @param {number} [opts.maxBackoffTime] Maximum amount of time to wait before trying to reconnect (we try to reconnect using exponential backoff)
215
+ * @param {boolean} [opts.disableBc] Disable cross-tab BroadcastChannel communication
216
+ */
217
+ constructor(s, t, n, {
218
+ connect: c = !0,
219
+ awareness: a = new re(n),
220
+ params: w = {},
221
+ protocols: Y = [],
222
+ WebSocketPolyfill: q = WebSocket,
223
+ resyncInterval: M = -1,
224
+ maxBackoffTime: G = 2500,
225
+ disableBc: J = !1
226
+ } = {}) {
227
+ for (super(); s[s.length - 1] === "/"; )
228
+ s = s.slice(0, s.length - 1);
229
+ this.serverUrl = s, this.bcChannel = s + "/" + t, this.maxBackoffTime = G, this.params = w, this.protocols = Y, this.roomname = t, this.doc = n, this._WS = q, this.awareness = a, this.wsconnected = !1, this.wsconnecting = !1, this.bcconnected = !1, this.disableBc = J, this.wsUnsuccessfulReconnects = 0, this.messageHandlers = _.slice(), this._synced = !1, this.ws = null, this.wsLastMessageReceived = 0, this.shouldConnect = c, this._resyncInterval = 0, M > 0 && (this._resyncInterval = /** @type {any} */
230
+ setInterval(() => {
231
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
232
+ const h = r();
233
+ i(h, f), I(h, n), this.ws.send(o(h));
234
+ }
235
+ }, M)), this._bcSubscriber = (h, b) => {
236
+ if (b !== this) {
237
+ const d = z(this, new Uint8Array(h), !1);
238
+ P(d) > 1 && g(this.bcChannel, o(d), this);
239
+ }
240
+ }, this._updateHandler = (h, b) => {
241
+ if (b !== this) {
242
+ const d = r();
243
+ i(d, f), le(d, h), B(this, o(d));
244
+ }
245
+ }, this.doc.on("update", this._updateHandler), this._awarenessUpdateHandler = ({ added: h, updated: b, removed: d }, Fe) => {
246
+ const X = h.concat(b).concat(d), C = r();
247
+ i(C, y), p(
248
+ C,
249
+ S(a, X)
250
+ ), B(this, o(C));
251
+ }, this._exitHandler = () => {
252
+ V(
253
+ this.awareness,
254
+ [n.clientID],
255
+ "app closed"
256
+ );
257
+ }, u && typeof process < "u" && process.on("exit", this._exitHandler), a.on("update", this._awarenessUpdateHandler), this._checkInterval = /** @type {any} */
258
+ setInterval(() => {
259
+ this.wsconnected && H < U() - this.wsLastMessageReceived && E(
260
+ this,
261
+ /** @type {WebSocket} */
262
+ this.ws,
263
+ null
264
+ );
265
+ }, H / 10), c && this.connect();
266
+ }
267
+ get url() {
268
+ const s = De(this.params);
269
+ return this.serverUrl + "/" + this.roomname + (s.length === 0 ? "" : "?" + s);
270
+ }
271
+ /**
272
+ * @type {boolean}
273
+ */
274
+ get synced() {
275
+ return this._synced;
276
+ }
277
+ set synced(s) {
278
+ this._synced !== s && (this._synced = s, this.emit("synced", [s]), this.emit("sync", [s]));
279
+ }
280
+ destroy() {
281
+ this._resyncInterval !== 0 && clearInterval(this._resyncInterval), clearInterval(this._checkInterval), this.disconnect(), u && typeof process < "u" && process.off("exit", this._exitHandler), this.awareness.off("update", this._awarenessUpdateHandler), this.doc.off("update", this._updateHandler), super.destroy();
282
+ }
283
+ connectBc() {
284
+ if (this.disableBc)
285
+ return;
286
+ this.bcconnected || (He(this.bcChannel, this._bcSubscriber), this.bcconnected = !0);
287
+ const s = r();
288
+ i(s, f), I(s, this.doc), g(this.bcChannel, o(s), this);
289
+ const t = r();
290
+ i(t, f), he(t, this.doc), g(this.bcChannel, o(t), this);
291
+ const n = r();
292
+ i(n, Q), g(
293
+ this.bcChannel,
294
+ o(n),
295
+ this
296
+ );
297
+ const c = r();
298
+ i(c, y), p(
299
+ c,
300
+ S(this.awareness, [
301
+ this.doc.clientID
302
+ ])
303
+ ), g(
304
+ this.bcChannel,
305
+ o(c),
306
+ this
307
+ );
308
+ }
309
+ disconnectBc() {
310
+ const s = r();
311
+ i(s, y), p(
312
+ s,
313
+ S(this.awareness, [
314
+ this.doc.clientID
315
+ ], /* @__PURE__ */ new Map())
316
+ ), B(this, o(s)), this.bcconnected && (xe(this.bcChannel, this._bcSubscriber), this.bcconnected = !1);
317
+ }
318
+ disconnect() {
319
+ this.shouldConnect = !1, this.disconnectBc(), this.ws !== null && E(this, this.ws, null);
320
+ }
321
+ connect() {
322
+ this.shouldConnect = !0, !this.wsconnected && this.ws === null && (K(this), this.connectBc());
323
+ }
324
+ }
325
+ class qe extends ee {
326
+ constructor(t, n) {
327
+ super(t);
328
+ m(this, "websocketOptions");
329
+ m(this, "roomId");
330
+ m(this, "provider");
331
+ m(this, "name", be);
332
+ m(this, "supportsUndoManager", !0);
333
+ const { roomId: c } = n;
334
+ this.websocketOptions = n, this.roomId = c, this.init();
335
+ }
336
+ init() {
337
+ const {
338
+ wsOptions: { serverUrl: t }
339
+ } = this.websocketOptions;
340
+ this.provider = new $e(
341
+ t,
342
+ this.roomId,
343
+ this.getDocument(),
344
+ {
345
+ connect: !1,
346
+ disableBc: !0
347
+ }
348
+ ), this.provider.on(
349
+ "status",
350
+ ({ status: n }) => {
351
+ var c, a;
352
+ (a = (c = this.websocketOptions.callbacks) == null ? void 0 : c.onConnectionStatusChange) == null || a.call(c, n), this.instance.emitEvent("onConnectionStatusChange", n);
353
+ }
354
+ );
355
+ }
356
+ connect() {
357
+ this.provider.connect();
358
+ }
359
+ disconnect() {
360
+ this.provider.connect();
361
+ }
362
+ setAwarenessInfo(t, n) {
363
+ this.provider.awareness.setLocalStateField(t, n);
364
+ }
365
+ onAwarenessChange(t) {
366
+ const n = this.provider.awareness;
367
+ n.on("change", () => {
368
+ const c = Array.from(n.getStates().values());
369
+ c.splice(n.clientID, 1), t(c);
370
+ });
371
+ }
372
+ }
373
+ export {
374
+ be as WEAVE_STORE_WEBSOCKETS,
375
+ Xe as WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS,
376
+ qe as WeaveStoreWebsockets
377
+ };
Binary file
@@ -0,0 +1 @@
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;
Binary file
@@ -0,0 +1,59 @@
1
+ import { default as default_2 } from 'http';
2
+ import { default as default_3 } from 'https';
3
+ import { IncomingMessage } from 'http';
4
+ import * as Y from 'yjs';
5
+
6
+ export declare type ExtractRoomId = (req: IncomingMessage) => string | undefined;
7
+
8
+ export declare type FetchInitialState = (doc: Y.Doc) => void;
9
+
10
+ export declare type FetchRoom = (roomId: string) => Promise<Uint8Array | null>;
11
+
12
+ export declare type PerformUpgrade = (req: IncomingMessage) => Promise<boolean>;
13
+
14
+ export declare type PersistRoom = (roomId: string, actualState: Uint8Array<ArrayBufferLike>) => Promise<void>;
15
+
16
+ export declare const WEAVE_STORE_WEBSOCKETS = "store-websockets";
17
+
18
+ export declare const WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS: {
19
+ readonly CONNECTING: "connecting";
20
+ readonly CONNECTED: "connected";
21
+ readonly DISCONNECTED: "disconnected";
22
+ };
23
+
24
+ export declare type WeaveStoreWebsocketsCallbacks = {
25
+ onConnectionStatusChange?: (status: WeaveStoreWebsocketsConnectionStatus) => void;
26
+ };
27
+
28
+ export declare type WeaveStoreWebsocketsConnectionStatus = (typeof WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS)[WeaveStoreWebsocketsConnectionStatusKeys];
29
+
30
+ export declare type WeaveStoreWebsocketsConnectionStatusKeys = keyof typeof WEAVE_STORE_WEBSOCKETS_CONNECTION_STATUS;
31
+
32
+ export declare type WeaveStoreWebsocketsOptions = {
33
+ roomId: string;
34
+ wsOptions: {
35
+ serverUrl: string;
36
+ };
37
+ callbacks?: WeaveStoreWebsocketsCallbacks;
38
+ };
39
+
40
+ export declare class WeaveWebsocketsServer {
41
+ private initialState;
42
+ private performUpgrade;
43
+ private extractRoomId;
44
+ private wss;
45
+ persistRoom: PersistRoom | undefined;
46
+ fetchRoom: FetchRoom | undefined;
47
+ constructor({ initialState, performUpgrade, extractRoomId, persistRoom, fetchRoom, }: WeaveWebsocketsServerParams);
48
+ handleUpgrade(server: default_2.Server | default_3.Server): void;
49
+ }
50
+
51
+ declare type WeaveWebsocketsServerParams = {
52
+ initialState?: FetchInitialState;
53
+ performUpgrade: PerformUpgrade;
54
+ extractRoomId: ExtractRoomId;
55
+ persistRoom?: PersistRoom;
56
+ fetchRoom?: FetchRoom;
57
+ };
58
+
59
+ export { }