@hcikn/colibri 1.2.0 → 2.0.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/index.js CHANGED
@@ -1,974 +1,1562 @@
1
- // src/Colibri.ts
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_without_holes(arr) {
8
- if (Array.isArray(arr)) return _array_like_to_array(arr);
9
- }
10
- function _assert_this_initialized(self) {
11
- if (self === void 0) {
12
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
11
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
12
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
13
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
14
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
15
+ var __runInitializers = (array, flags, self, value) => {
16
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
17
+ return value;
18
+ };
19
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
20
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
21
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
22
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
23
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
24
+ return __privateGet(this, extra);
25
+ }, set [name](x) {
26
+ return __privateSet(this, extra, x);
27
+ } }, name));
28
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
29
+ for (var i = decorators.length - 1; i >= 0; i--) {
30
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
31
+ if (k) {
32
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
33
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
34
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
13
35
  }
14
- return self;
15
- }
16
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
36
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
37
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
38
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
39
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
40
+ }
41
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
42
+ };
43
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
44
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
45
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
46
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
47
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
48
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
49
+
50
+ // src/Colibri.ts
51
+ import { Subject } from "rxjs";
52
+ import { connect } from "socket.io-client";
53
+
54
+ // src/ColibriError.ts
55
+ import { CustomError } from "ts-custom-error";
56
+ var ColibriError = class extends CustomError {
57
+ };
58
+ var ProtocolMismatchError = class extends ColibriError {
59
+ constructor(message, serverVersion, clientVersion, fatal = true) {
60
+ super(message);
61
+ this.serverVersion = serverVersion;
62
+ this.clientVersion = clientVersion;
63
+ this.fatal = fatal;
64
+ }
65
+ };
66
+
67
+ // src/lifecycle.ts
68
+ var awaitingInstance = [];
69
+ var whenColibriCreated = (action) => {
70
+ awaitingInstance.push(action);
71
+ return () => {
72
+ const index = awaitingInstance.indexOf(action);
73
+ if (index >= 0) awaitingInstance.splice(index, 1);
74
+ };
75
+ };
76
+ var colibriCreated = (colibri) => {
77
+ for (const action of awaitingInstance.splice(0)) {
17
78
  try {
18
- var info = gen[key](arg);
19
- var value = info.value;
79
+ action(colibri);
20
80
  } catch (error) {
21
- reject(error);
22
- return;
81
+ console.error("Colibri: a registration made before new Colibri() failed to attach.", error);
23
82
  }
24
- if (info.done) {
25
- resolve(value);
26
- } else {
27
- Promise.resolve(value).then(_next, _throw);
83
+ }
84
+ };
85
+ var reconnectActions = /* @__PURE__ */ new WeakMap();
86
+ var disconnectActions = /* @__PURE__ */ new WeakMap();
87
+ var addAction = (actions, colibri, action) => {
88
+ const forInstance = actions.get(colibri);
89
+ if (forInstance) forInstance.push(action);
90
+ else actions.set(colibri, [action]);
91
+ };
92
+ var runActions = (actions, colibri, failure) => {
93
+ for (const action of actions.get(colibri) ?? []) {
94
+ try {
95
+ action(colibri);
96
+ } catch (error) {
97
+ console.error(failure, error);
28
98
  }
29
- }
30
- function _async_to_generator(fn) {
31
- return function() {
32
- var self = this, args = arguments;
33
- return new Promise(function(resolve, reject) {
34
- var gen = fn.apply(self, args);
35
- function _next(value) {
36
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
37
- }
38
- function _throw(err) {
39
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
40
- }
41
- _next(undefined);
42
- });
43
- };
44
- }
45
- function _class_call_check(instance, Constructor) {
46
- if (!(instance instanceof Constructor)) {
47
- throw new TypeError("Cannot call a class as a function");
99
+ }
100
+ };
101
+ var onColibriReconnected = (colibri, action) => {
102
+ addAction(reconnectActions, colibri, action);
103
+ };
104
+ var colibriReconnected = (colibri) => {
105
+ runActions(reconnectActions, colibri, "Colibri: catching up after a reconnect failed.");
106
+ };
107
+ var onColibriDisconnected = (colibri, action) => {
108
+ addAction(disconnectActions, colibri, action);
109
+ };
110
+ var colibriDisconnected = (colibri) => {
111
+ runActions(disconnectActions, colibri, "Colibri: handling a disconnect failed.");
112
+ };
113
+ var lastHeard = /* @__PURE__ */ new WeakMap();
114
+ var colibriHeardFrom = (colibri) => {
115
+ lastHeard.set(colibri, Date.now());
116
+ };
117
+ var lastHeardFrom = (colibri) => lastHeard.get(colibri);
118
+
119
+ // src/Colibri.ts
120
+ var PROTOCOL_VERSION = "2";
121
+ var REST_MEDIA_TYPE = `application/vnd.colibri.v${PROTOCOL_VERSION}+json`;
122
+ var COLIBRI_CHANNEL = "colibri";
123
+ var ADMIN_APP = "colibri";
124
+ var PROTOCOL_REJECTED_COMMAND = "protocol::rejected";
125
+ var PROTOCOL_ACCEPTED_COMMAND = "protocol::accepted";
126
+ var LATENCY_COMMAND = "latency";
127
+ var OLD_SERVER_TIMEOUT_MS = 5e3;
128
+ var OLD_SERVER_PROTOCOL_VERSION = "1";
129
+ var pageHostname = () => typeof window !== "undefined" ? window.location?.hostname ?? "" : "";
130
+ var SCHEMES = {
131
+ ws: { socket: "ws", rest: "http" },
132
+ http: { socket: "ws", rest: "http" },
133
+ wss: { socket: "wss", rest: "https" },
134
+ https: { socket: "wss", rest: "https" }
135
+ };
136
+ var parseServerAddress = (server) => {
137
+ const address = server.trim();
138
+ const match = /^([a-z][a-z0-9+.-]*):\/\/(.*)$/i.exec(address);
139
+ const schemes = match ? SCHEMES[match[1].toLowerCase()] : SCHEMES.ws;
140
+ if (!schemes) {
141
+ throw new ColibriError(
142
+ `Unsupported scheme in server address '${server}' - use ws://, wss://, http://, https:// or none.`
143
+ );
144
+ }
145
+ const authority = (match ? match[2] : address).replace(/\/+$/, "");
146
+ if (authority.length === 0) {
147
+ throw new ColibriError("Server Address missing or empty!");
148
+ }
149
+ if (/[/?#]/.test(authority)) {
150
+ throw new ColibriError(
151
+ `Server address '${server}' has a path or query after the host - pass only the host and, optionally, the port, e.g. 'http://example.com:9211'.`
152
+ );
153
+ }
154
+ const hostAndPort = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(authority);
155
+ if (!hostAndPort) {
156
+ throw new ColibriError(
157
+ `Server address '${server}' is not a host, or a host and a numeric port - an IPv6 address goes in brackets.`
158
+ );
159
+ }
160
+ const portText = hostAndPort.at(2);
161
+ return { ...schemes, host: hostAndPort[1], port: portText === void 0 ? void 0 : Number(portText) };
162
+ };
163
+ var DEFAULT_PORT = 9211;
164
+ var checkPort = (port) => {
165
+ if (!Number.isInteger(port)) {
166
+ throw new ColibriError(`Port must be a whole number (1 - 65535): ${port}`);
167
+ }
168
+ if (port < 1 || port > 65535) {
169
+ throw new ColibriError(`Port out of allowed range (1 - 65535): ${port}`);
170
+ }
171
+ };
172
+ var coercePort = (port) => typeof port === "string" && /^\s*\d+\s*$/.test(port) ? Number(port) : port;
173
+ var resolvePort = (server, fromAddress, given) => {
174
+ if (given !== void 0) checkPort(given);
175
+ if (fromAddress === void 0) return given ?? DEFAULT_PORT;
176
+ checkPort(fromAddress);
177
+ if (given !== void 0 && given !== fromAddress) {
178
+ throw new ColibriError(
179
+ `Server address '${server}' has port ${fromAddress}, but port ${given} was passed as well - give the port once.`
180
+ );
181
+ }
182
+ return fromAddress;
183
+ };
184
+ var pendingRegistrations = [];
185
+ var Colibri = class _Colibri {
186
+ /**
187
+ * Connects to a Colibri server. Only one instance may exist.
188
+ * @param app the application name; clients only see each other's messages within one app
189
+ * @param server the host, optionally after `ws://`, `wss://`, `http://` or `https://` (the
190
+ * secure ones mean `wss` for the socket and `https` for REST) and optionally with a port,
191
+ * as in `'http://example.com:9211'`; no path. Defaults to the host that served the page,
192
+ * and is required outside a browser.
193
+ * @param port the server port, if the address has none; 9211 if neither does. When both have
194
+ * one, they must agree.
195
+ * @throws ColibriError for an address or port this client cannot connect to, or when an
196
+ * instance already exists
197
+ */
198
+ constructor(app, server = pageHostname(), port) {
199
+ this.app = app;
200
+ this.server = server;
201
+ if (server.trim().length <= 0) {
202
+ throw new ColibriError(
203
+ typeof window === "undefined" ? "Server Address missing or empty! Outside a browser there is no page to take it from, so pass it as the second argument." : "Server Address missing or empty!"
204
+ );
48
205
  }
49
- }
50
- function _defineProperties(target, props) {
51
- for(var i = 0; i < props.length; i++){
52
- var descriptor = props[i];
53
- descriptor.enumerable = descriptor.enumerable || false;
54
- descriptor.configurable = true;
55
- if ("value" in descriptor) descriptor.writable = true;
56
- Object.defineProperty(target, descriptor.key, descriptor);
206
+ const address = parseServerAddress(server);
207
+ this.port = resolvePort(server, address.port, coercePort(port));
208
+ this.uri = `${address.socket}://${address.host}:${this.port}`;
209
+ this.uriRestApi = `${address.rest}://${address.host}:${this.port}/api/store/${encodeURIComponent(app)}/`;
210
+ if (_Colibri.instance) throw new ColibriError("A Colibri instance already exists!");
211
+ else _Colibri.instance = this;
212
+ if (app === ADMIN_APP) {
213
+ console.warn(
214
+ `Colibri: the app name '${ADMIN_APP}' is reserved for the server's admin UI, and the server treats this client as one: it sends it the server's log as it is written and every client's connects and disconnects, shares its messages with every open admin UI, and skips the protocol version check. Give your app a name of its own.`
215
+ );
57
216
  }
58
- }
59
- function _create_class(Constructor, protoProps, staticProps) {
60
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
61
- if (staticProps) _defineProperties(Constructor, staticProps);
62
- return Constructor;
63
- }
64
- function _get_prototype_of(o) {
65
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
66
- return o.__proto__ || Object.getPrototypeOf(o);
67
- };
68
- return _get_prototype_of(o);
69
- }
70
- function _inherits(subClass, superClass) {
71
- if (typeof superClass !== "function" && superClass !== null) {
72
- throw new TypeError("Super expression must either be null or a function");
73
- }
74
- subClass.prototype = Object.create(superClass && superClass.prototype, {
75
- constructor: {
76
- value: subClass,
77
- writable: true,
78
- configurable: true
79
- }
217
+ this.socket = connect(this.uri, {
218
+ query: { app, version: PROTOCOL_VERSION },
219
+ transports: ["websocket"]
80
220
  });
81
- if (superClass) _set_prototype_of(subClass, superClass);
82
- }
83
- function _instanceof(left, right) {
84
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
85
- return !!right[Symbol.hasInstance](left);
86
- } else {
87
- return left instanceof right;
221
+ this.socket.on("connect", this.onSocketConnect.bind(this));
222
+ this.socket.on("disconnect", this.onSocketDisconnect.bind(this));
223
+ this.socket.on("connect_error", this.onSocketConnectError.bind(this));
224
+ this.socket.onAny(this.onSocketAny.bind(this));
225
+ this.registerChannel(COLIBRI_CHANNEL, (msg) => {
226
+ if (msg.command === LATENCY_COMMAND) {
227
+ SendMessage(COLIBRI_CHANNEL, LATENCY_COMMAND, msg.payload);
228
+ }
229
+ });
230
+ for (const { channel, handler, once } of pendingRegistrations.splice(0)) {
231
+ if (once) this.registerOnce(channel, handler);
232
+ else this.registerChannel(channel, handler);
88
233
  }
89
- }
90
- function _iterable_to_array(iter) {
91
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
92
- }
93
- function _non_iterable_spread() {
94
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
95
- }
96
- function _possible_constructor_return(self, call) {
97
- if (call && (_type_of(call) === "object" || typeof call === "function")) {
98
- return call;
234
+ colibriCreated(this);
235
+ }
236
+ static instance = null;
237
+ socket;
238
+ messageSubject = new Subject();
239
+ messages = this.messageSubject.asObservable();
240
+ protocolMismatchSubject = new Subject();
241
+ /**
242
+ * Reports that this client and the server do not speak the same wire protocol. Two kinds,
243
+ * told apart by {@link ProtocolMismatchError.fatal `fatal`}, each emitted at most once per
244
+ * instance:
245
+ *
246
+ * - `fatal: true`: the server refused this client. The connection is closed and not retried.
247
+ * - `fatal: false`: the server did not announce itself within 5s of connecting, so it is
248
+ * suspected to predate colibri-server 2.0.0. The connection stays up.
249
+ *
250
+ * A suspicion can be followed by a refusal, never the other way round. Nothing is replayed to
251
+ * a late subscriber, so subscribe right after construction. Both kinds are also logged.
252
+ */
253
+ protocolMismatch = this.protocolMismatchSubject.asObservable();
254
+ uri;
255
+ uriRestApi;
256
+ /** The port connected to: the one in the server address, else the one passed, else 9211. */
257
+ port;
258
+ oldServerTimer;
259
+ // Once per instance, not per connection, so a reconnect does not repeat the warning.
260
+ hasReportedOldServer = false;
261
+ // Once per instance, not once per `protocol::rejected` received.
262
+ hasReportedRefusal = false;
263
+ hasConnected = false;
264
+ // An outage runs from a failed connection attempt to the next connect.
265
+ hasReportedOutage = false;
266
+ onSocketConnect() {
267
+ console.debug(`Connected to colibri server on ${this.server}`);
268
+ this.hasReportedOutage = false;
269
+ this.waitForServerHello();
270
+ if (this.hasConnected) colibriReconnected(this);
271
+ this.hasConnected = true;
272
+ }
273
+ // Until the next connect, sends wait in Socket.IO's buffer and go out ahead of anything a
274
+ // catch-up sends, which is the wrong order for some of them.
275
+ onSocketDisconnect() {
276
+ colibriDisconnected(this);
277
+ }
278
+ // Socket.IO retries silently, so a mistyped address, a server that is down and a firewall all
279
+ // look like a slow connection. Reported once per outage, on its first failed attempt, not on
280
+ // every retry.
281
+ onSocketConnectError(error) {
282
+ if (this.hasReportedOutage) return;
283
+ this.hasReportedOutage = true;
284
+ const cause = error.description?.message;
285
+ const reason = typeof cause === "string" && cause.length > 0 ? `${error.message}: ${cause}` : error.message;
286
+ console.warn(
287
+ `Colibri: could not connect to ${this.uri} (${reason}). ` + (this.socket.active ? "Retrying until it answers - check the server address and that the server is running." : "Not retrying.")
288
+ );
289
+ }
290
+ /*
291
+ * Detecting a server that predates the protocol version check.
292
+ *
293
+ * Such a server neither refuses this client nor says what it speaks, so a current one
294
+ * announces itself unprompted and the missing announcement is the signal. The timer only
295
+ * observes; it does not gate message delivery.
296
+ */
297
+ waitForServerHello() {
298
+ if (this.hasReportedOldServer) return;
299
+ clearTimeout(this.oldServerTimer);
300
+ this.oldServerTimer = setTimeout(() => {
301
+ this.onServerHelloMissing();
302
+ }, OLD_SERVER_TIMEOUT_MS);
303
+ }
304
+ stopWaitingForServerHello() {
305
+ clearTimeout(this.oldServerTimer);
306
+ this.oldServerTimer = void 0;
307
+ }
308
+ onServerHelloMissing() {
309
+ if (!this.socket.connected) return;
310
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
311
+ this.waitForServerHello();
312
+ return;
99
313
  }
100
- return _assert_this_initialized(self);
101
- }
102
- function _set_prototype_of(o, p) {
103
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
104
- o.__proto__ = p;
105
- return o;
106
- };
107
- return _set_prototype_of(o, p);
108
- }
109
- function _to_consumable_array(arr) {
110
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
111
- }
112
- function _type_of(obj) {
113
- "@swc/helpers - typeof";
114
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
115
- }
116
- function _unsupported_iterable_to_array(o, minLen) {
117
- if (!o) return;
118
- if (typeof o === "string") return _array_like_to_array(o, minLen);
119
- var n = Object.prototype.toString.call(o).slice(8, -1);
120
- if (n === "Object" && o.constructor) n = o.constructor.name;
121
- if (n === "Map" || n === "Set") return Array.from(n);
122
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
123
- }
124
- function _is_native_reflect_construct() {
125
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
126
- if (Reflect.construct.sham) return false;
127
- if (typeof Proxy === "function") return true;
128
- try {
129
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
130
- return true;
131
- } catch (e) {
132
- return false;
314
+ this.hasReportedOldServer = true;
315
+ this.stopWaitingForServerHello();
316
+ const error = new ProtocolMismatchError(
317
+ `The server did not identify itself within ${OLD_SERVER_TIMEOUT_MS / 1e3}s, so it predates colibri-server 2.0.0 and speaks protocol v1; this client speaks v${PROTOCOL_VERSION}.`,
318
+ // A protocol version, as in the refusal. Inferred, not received: every 2.0.0+ server
319
+ // announces itself, and everything older speaks v1.
320
+ OLD_SERVER_PROTOCOL_VERSION,
321
+ PROTOCOL_VERSION,
322
+ false
323
+ );
324
+ console.warn(`Colibri: ${error.message} The connection still works; upgrade the server when you can.`);
325
+ this.protocolMismatchSubject.next(error);
326
+ }
327
+ onSocketAny(channel, msg) {
328
+ colibriHeardFrom(this);
329
+ const { command, payload } = msg;
330
+ if (channel === COLIBRI_CHANNEL && command === PROTOCOL_REJECTED_COMMAND) {
331
+ this.onProtocolRejected(payload);
332
+ return;
133
333
  }
134
- }
135
- function _create_super(Derived) {
136
- var hasNativeReflectConstruct = _is_native_reflect_construct();
137
- return function _createSuperInternal() {
138
- var Super = _get_prototype_of(Derived), result;
139
- if (hasNativeReflectConstruct) {
140
- var NewTarget = _get_prototype_of(this).constructor;
141
- result = Reflect.construct(Super, arguments, NewTarget);
142
- } else {
143
- result = Super.apply(this, arguments);
144
- }
145
- return _possible_constructor_return(this, result);
146
- };
147
- }
148
- function _ts_generator(thisArg, body) {
149
- var f, y, t, g, _ = {
150
- label: 0,
151
- sent: function() {
152
- if (t[0] & 1) throw t[1];
153
- return t[1];
154
- },
155
- trys: [],
156
- ops: []
157
- };
158
- return g = {
159
- next: verb(0),
160
- "throw": verb(1),
161
- "return": verb(2)
162
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
163
- return this;
164
- }), g;
165
- function verb(n) {
166
- return function(v) {
167
- return step([
168
- n,
169
- v
170
- ]);
171
- };
172
- }
173
- function step(op) {
174
- if (f) throw new TypeError("Generator is already executing.");
175
- while(_)try {
176
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
177
- if (y = 0, t) op = [
178
- op[0] & 2,
179
- t.value
180
- ];
181
- switch(op[0]){
182
- case 0:
183
- case 1:
184
- t = op;
185
- break;
186
- case 4:
187
- _.label++;
188
- return {
189
- value: op[1],
190
- done: false
191
- };
192
- case 5:
193
- _.label++;
194
- y = op[1];
195
- op = [
196
- 0
197
- ];
198
- continue;
199
- case 7:
200
- op = _.ops.pop();
201
- _.trys.pop();
202
- continue;
203
- default:
204
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
205
- _ = 0;
206
- continue;
207
- }
208
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
209
- _.label = op[1];
210
- break;
211
- }
212
- if (op[0] === 6 && _.label < t[1]) {
213
- _.label = t[1];
214
- t = op;
215
- break;
216
- }
217
- if (t && _.label < t[2]) {
218
- _.label = t[2];
219
- _.ops.push(op);
220
- break;
221
- }
222
- if (t[2]) _.ops.pop();
223
- _.trys.pop();
224
- continue;
225
- }
226
- op = body.call(thisArg, _);
227
- } catch (e) {
228
- op = [
229
- 6,
230
- e
231
- ];
232
- y = 0;
233
- } finally{
234
- f = t = 0;
235
- }
236
- if (op[0] & 5) throw op[1];
237
- return {
238
- value: op[0] ? op[1] : void 0,
239
- done: true
240
- };
334
+ if (channel === COLIBRI_CHANNEL && command === PROTOCOL_ACCEPTED_COMMAND) {
335
+ this.stopWaitingForServerHello();
336
+ return;
241
337
  }
242
- }
243
- import { connect } from "socket.io-client";
244
- // src/ColibriError.ts
245
- import { CustomError } from "ts-custom-error";
246
- var ColibriError = /*#__PURE__*/ function(CustomError) {
247
- "use strict";
248
- _inherits(ColibriError, CustomError);
249
- var _super = _create_super(ColibriError);
250
- function ColibriError(message) {
251
- _class_call_check(this, ColibriError);
252
- return _super.call(this, message);
253
- }
254
- return ColibriError;
255
- }(CustomError);
256
- // src/Colibri.ts
257
- import { Subject } from "rxjs";
258
- var _window_location_hostname;
259
- var _Colibri = /*#__PURE__*/ function() {
260
- "use strict";
261
- function _Colibri(app) {
262
- var server = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : function() {
263
- var _window_location, _window;
264
- return (_window_location_hostname = (_window = window) === null || _window === void 0 ? void 0 : (_window_location = _window.location) === null || _window_location === void 0 ? void 0 : _window_location.hostname) !== null && _window_location_hostname !== void 0 ? _window_location_hostname : "";
265
- }(), port = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 9011;
266
- _class_call_check(this, _Colibri);
267
- this.app = app;
268
- this.server = server;
269
- this.port = port;
270
- this.messageSubject = new Subject();
271
- this.messages = this.messageSubject.asObservable();
272
- if (server.trim().length <= 0) {
273
- throw new ColibriError("Server Address missing or empty!");
274
- }
275
- if (port < 1 || port > 65535) {
276
- throw new ColibriError("Port out of allowed range (0 - 65535)");
277
- }
278
- this.uri = "".concat(server, ":").concat(port);
279
- if (!new RegExp("wss?://", "i").test(this.uri)) {
280
- this.uri = "ws://".concat(this.uri);
281
- }
282
- this.uriRestApi = "".concat(this.uri, "/api/store/").concat(app, "/");
283
- if (_Colibri.instance) throw new ColibriError("A Colibri instance already exists!");
284
- else _Colibri.instance = this;
285
- this.socket = connect(this.uri, {
286
- query: {
287
- app: app,
288
- version: "1"
289
- },
290
- transports: [
291
- "websocket"
292
- ]
293
- });
294
- this.socket.on("connect", this.onSocketConnect.bind(this));
295
- this.socket.onAny(this.onSocketAny.bind(this));
296
- this.registerChannel("colibri", function(msg) {
297
- if (msg.command === "latency") {
298
- SendMessage("colibri", "latency", msg.payload);
299
- }
300
- });
338
+ this.messageSubject.next({ channel, command, payload });
339
+ }
340
+ // `rejection` is optional because it comes off the wire, and a bare `protocol::rejected` must
341
+ // still give a usable error rather than a TypeError.
342
+ onProtocolRejected(rejection) {
343
+ this.stopWaitingForServerHello();
344
+ this.hasReportedOldServer = true;
345
+ this.socket.io.reconnection(false);
346
+ this.socket.disconnect();
347
+ if (this.hasReportedRefusal) return;
348
+ this.hasReportedRefusal = true;
349
+ const serverVersion = rejection?.serverVersion ?? "unknown";
350
+ const error = new ProtocolMismatchError(
351
+ rejection?.reason ?? `Server refused the connection: it speaks protocol v${serverVersion}, this client speaks v${PROTOCOL_VERSION}.`,
352
+ serverVersion,
353
+ rejection?.clientVersion ?? PROTOCOL_VERSION
354
+ );
355
+ console.error(
356
+ `Colibri: ${error.message} Update colibri-web and colibri-server to matching versions. Not reconnecting.`
357
+ );
358
+ this.protocolMismatchSubject.next(error);
359
+ }
360
+ /**
361
+ * Returns the existing Colibri instance or null if there's none yet
362
+ * @param warnIfNotInitialized true => print Log message if Colibri has not been initialized yet
363
+ * @returns
364
+ */
365
+ static getInstance(warnIfNotInitialized = true) {
366
+ if (warnIfNotInitialized && !_Colibri.instance) {
367
+ console.warn("Colibri not initialized yet! (Instance is null)");
301
368
  }
302
- _create_class(_Colibri, [
303
- {
304
- key: "onSocketConnect",
305
- value: function onSocketConnect() {
306
- console.debug("Connected to colibri server on ".concat(this.server));
307
- }
308
- },
309
- {
310
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
311
- key: "onSocketAny",
312
- value: function onSocketAny(channel, msg) {
313
- this.messageSubject.next({
314
- channel: channel,
315
- command: msg.command,
316
- payload: msg.payload
317
- });
318
- }
319
- },
320
- {
321
- /**
369
+ return _Colibri.instance;
370
+ }
371
+ /**
322
372
  * Sends a single message in the given `channel`.
323
373
  * @param channel message channel
324
374
  * @param command message command
325
375
  * @param payload message payload
326
- */ key: "sendMessage",
327
- value: function sendMessage(channel, command) {
328
- var payload = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
329
- this.socket.emit(channel, {
330
- command: command,
331
- payload: payload
332
- });
333
- }
334
- },
335
- {
336
- //#region Socket Events
337
- /**
376
+ */
377
+ sendMessage(channel, command, payload = {}) {
378
+ this.socket.emit(channel, {
379
+ command,
380
+ payload
381
+ });
382
+ }
383
+ // #region Socket Events
384
+ /**
338
385
  * Adds a `handler` function listening for messages in `channel`.
339
386
  * @param channel message channel
340
387
  * @param handler handler to be executed when a message is received
341
- */ key: "registerChannel",
342
- value: function registerChannel(channel, handler) {
343
- this.socket.on(channel, handler);
344
- }
345
- },
346
- {
347
- /**
388
+ */
389
+ registerChannel(channel, handler) {
390
+ this.socket.on(channel, handler);
391
+ }
392
+ /**
348
393
  * Removes the `handler` function listening for messages in `channel`.
349
394
  * @param channel message channel
350
395
  * @param handler handler to be executed when a message is received
351
- */ key: "unregisterChannel",
352
- value: function unregisterChannel(channel, handler) {
353
- this.socket.off(channel, handler);
354
- }
355
- },
356
- {
357
- /**
396
+ */
397
+ unregisterChannel(channel, handler) {
398
+ this.socket.off(channel, handler);
399
+ }
400
+ /**
358
401
  * Adds a one-time `handler` function listening for the next message in `channel`.
359
402
  * @param channel message channel
360
403
  * @param handler handler to be executed when a message is received
361
- */ key: "registerOnce",
362
- value: function registerOnce(channel, handler) {
363
- this.socket.once(channel, handler);
364
- }
365
- },
366
- {
367
- //#endregion
368
- //#region Rest API
369
- /**
370
- * Returns the REST API Endpoint for a given `key` or null of the key is empty.
404
+ */
405
+ registerOnce(channel, handler) {
406
+ this.socket.once(channel, handler);
407
+ }
408
+ // #endregion
409
+ // #region Rest API
410
+ /**
411
+ * Returns the REST API Endpoint for a given `key`, or null if the key is empty, `.` or `..`.
412
+ * Any other key is stored under exactly that name (`#`, `?`, `/`, `%` and spaces included)
413
+ * after surrounding whitespace and leading slashes are stripped.
371
414
  * @param key REST API storage key
372
415
  * @returns
373
- */ key: "getRestUri",
374
- value: function getRestUri(key) {
375
- key = key.trim();
376
- while(key.startsWith("/"))key = key.substring(1);
377
- return key.length === 0 ? null : this.uriRestApi + key;
378
- }
379
- },
380
- {
381
- key: "getRestObject",
382
- value: /**
416
+ */
417
+ getRestUri(key) {
418
+ key = key.trim();
419
+ while (key.startsWith("/")) key = key.substring(1);
420
+ if (key.length === 0 || key === "." || key === "..") return null;
421
+ return this.uriRestApi + encodeURIComponent(key);
422
+ }
423
+ /**
383
424
  * Queries an object from the REST API identified by `key`.
425
+ *
426
+ * Rejects when the server cannot be reached (wrong address, server down, no network) or an
427
+ * answer with a success status is not JSON.
384
428
  * @param key REST API storage key
385
- * @returns JSON object with data or null if object does not exist or any other error occurrs
386
- */ // eslint-disable-next-line @typescript-eslint/no-explicit-any
387
- function getRestObject(key) {
388
- var _this = this;
389
- return _async_to_generator(function() {
390
- var uri, response;
391
- return _ts_generator(this, function(_state) {
392
- switch(_state.label){
393
- case 0:
394
- uri = _this.getRestUri(key);
395
- if (!uri) return [
396
- 2,
397
- null
398
- ];
399
- return [
400
- 4,
401
- fetch(uri, {
402
- method: "GET",
403
- headers: {
404
- "Content-Type": "application/json"
405
- }
406
- })
407
- ];
408
- case 1:
409
- response = _state.sent();
410
- if (response.status >= 400) return [
411
- 2,
412
- null
413
- ];
414
- else return [
415
- 2,
416
- response.json()
417
- ];
418
- return [
419
- 2
420
- ];
421
- }
422
- });
423
- })();
424
- }
425
- },
426
- {
427
- key: "setRestObject",
428
- value: /**
429
- * Sets or updatees an object in the REST API identified by `key`.
429
+ * @returns the stored value; or null if `key` is empty or the server answered with an error
430
+ * status, such as 404 for a key that was never stored. A stored `null` looks the same.
431
+ */
432
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
433
+ async getRestObject(key) {
434
+ const uri = this.getRestUri(key);
435
+ if (!uri) return null;
436
+ const response = await fetch(uri, {
437
+ method: "GET",
438
+ headers: {
439
+ Accept: REST_MEDIA_TYPE
440
+ }
441
+ });
442
+ if (response.status >= 400) return null;
443
+ else return response.json();
444
+ }
445
+ /**
446
+ * Sets or updates an object in the REST API identified by `key`.
447
+ *
448
+ * Rejects when the server cannot be reached (wrong address, server down, no network) or
449
+ * `data` cannot be serialized to JSON (circular structure, BigInt).
430
450
  * @param key REST API storage key
431
451
  * @param data JSON data to write
432
- * @returns true if data was written to REST API
433
- */ function setRestObject(key, data) {
434
- var _this = this;
435
- return _async_to_generator(function() {
436
- var uri, response;
437
- return _ts_generator(this, function(_state) {
438
- switch(_state.label){
439
- case 0:
440
- uri = _this.getRestUri(key);
441
- if (!uri) return [
442
- 2,
443
- false
444
- ];
445
- return [
446
- 4,
447
- fetch(uri, {
448
- method: "PUT",
449
- headers: {
450
- "Content-Type": "application/json"
451
- },
452
- body: JSON.stringify(data)
453
- })
454
- ];
455
- case 1:
456
- response = _state.sent();
457
- return [
458
- 2,
459
- response.status >= 200 && response.status < 300
460
- ];
461
- }
462
- });
463
- })();
464
- }
465
- }
466
- ], [
467
- {
468
- key: "getInstance",
469
- value: /**
470
- * Returns the existing Colibri instance or null if there's none yet
471
- * @param warnIfNotInitialized true => print Log message if Colibri has not been initialized yet
472
- * @returns
473
- */ function getInstance() {
474
- var warnIfNotInitialized = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
475
- if (warnIfNotInitialized && !_Colibri.instance) {
476
- console.warn("Colibri not initialized yet! (Instance is null)");
477
- }
478
- return _Colibri.instance;
479
- }
480
- }
481
- ]);
482
- return _Colibri;
483
- }();
484
- _Colibri.instance = null;
485
- var Colibri = _Colibri;
486
- var SendMessage = function(channel, command) {
487
- var payload = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
488
- var _Colibri_getInstance;
489
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.sendMessage(channel, command, payload);
490
- };
491
- var RegisterChannel = function(channel, handler) {
492
- var _Colibri_getInstance;
493
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.registerChannel(channel, handler);
494
- };
495
- var UnregisterChannel = function(channel, handler) {
496
- var _Colibri_getInstance;
497
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.unregisterChannel(channel, handler);
498
- };
499
- var RegisterOnce = function(channel, handler) {
500
- var _Colibri_getInstance;
501
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.registerOnce(channel, handler);
502
- };
503
- var GetRestApi = function(key) {
504
- var _Colibri_getInstance;
505
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.getRestObject(key);
506
- };
507
- var PutRestApi = function(key, data) {
508
- var _Colibri_getInstance;
509
- return (_Colibri_getInstance = Colibri.getInstance()) === null || _Colibri_getInstance === void 0 ? void 0 : _Colibri_getInstance.setRestObject(key, data);
452
+ * @returns true if the server stored the data; false if `key` is empty or the server answered
453
+ * with any other status
454
+ */
455
+ async setRestObject(key, data) {
456
+ const uri = this.getRestUri(key);
457
+ if (!uri) return false;
458
+ const response = await fetch(uri, {
459
+ method: "PUT",
460
+ headers: {
461
+ Accept: REST_MEDIA_TYPE,
462
+ "Content-Type": REST_MEDIA_TYPE
463
+ },
464
+ body: JSON.stringify(data)
465
+ });
466
+ return response.status >= 200 && response.status < 300;
467
+ }
468
+ /**
469
+ * Deletes the object identified by `key` from the REST API.
470
+ *
471
+ * Rejects when the server cannot be reached (wrong address, server down, no network).
472
+ * @param key REST API storage key
473
+ * @returns true if the server deleted the value; false if `key` is empty or the server answered
474
+ * with any other status, such as 404 for a key that holds no value
475
+ */
476
+ async deleteRestObject(key) {
477
+ const uri = this.getRestUri(key);
478
+ if (!uri) return false;
479
+ const response = await fetch(uri, {
480
+ method: "DELETE",
481
+ headers: {
482
+ Accept: REST_MEDIA_TYPE
483
+ }
484
+ });
485
+ return response.status >= 200 && response.status < 300;
486
+ }
487
+ // #endregion
488
+ };
489
+ var SendMessage = (channel, command, payload = {}) => Colibri.getInstance()?.sendMessage(channel, command, payload);
490
+ var RegisterChannel = (channel, handler) => {
491
+ const colibri = Colibri.getInstance(false);
492
+ if (colibri) colibri.registerChannel(channel, handler);
493
+ else pendingRegistrations.push({ channel, handler, once: false });
510
494
  };
495
+ var UnregisterChannel = (channel, handler) => {
496
+ const colibri = Colibri.getInstance(false);
497
+ if (colibri) {
498
+ colibri.unregisterChannel(channel, handler);
499
+ return;
500
+ }
501
+ const index = pendingRegistrations.findIndex((p) => p.channel === channel && p.handler === handler);
502
+ if (index >= 0) pendingRegistrations.splice(index, 1);
503
+ };
504
+ var RegisterOnce = (channel, handler) => {
505
+ const colibri = Colibri.getInstance(false);
506
+ if (colibri) colibri.registerOnce(channel, handler);
507
+ else pendingRegistrations.push({ channel, handler, once: true });
508
+ };
509
+ var GetRestApi = (key) => Colibri.getInstance()?.getRestObject(key);
510
+ var PutRestApi = (key, data) => Colibri.getInstance()?.setRestObject(key, data);
511
+ var DeleteRestApi = (key) => Colibri.getInstance()?.deleteRestObject(key);
512
+
511
513
  // src/Broadcasting.ts
512
- var sendBool = function(channel, val) {
513
- SendMessage(channel, "broadcast::bool", val);
514
+ var sendBool = (channel, val) => {
515
+ SendMessage(channel, "broadcast::bool", val);
516
+ };
517
+ var sendBoolArray = (channel, val) => {
518
+ SendMessage(channel, "broadcast::bool[]", val);
514
519
  };
515
- var sendBoolArray = function(channel, val) {
516
- SendMessage(channel, "broadcast::bool[]", val);
520
+ var sendNumber = (channel, val) => {
521
+ SendMessage(channel, "broadcast::float", val);
517
522
  };
518
- var sendNumber = function(channel, val) {
519
- SendMessage(channel, "broadcast::float", val);
523
+ var sendNumberArray = (channel, val) => {
524
+ SendMessage(channel, "broadcast::float[]", val);
520
525
  };
521
- var sendNumberArray = function(channel, val) {
522
- SendMessage(channel, "broadcast::float[]", val);
526
+ var sendString = (channel, val) => {
527
+ SendMessage(channel, "broadcast::string", val);
523
528
  };
524
- var sendString = function(channel, val) {
525
- SendMessage(channel, "broadcast::string", val);
529
+ var sendStringArray = (channel, val) => {
530
+ SendMessage(channel, "broadcast::string[]", val);
526
531
  };
527
- var sendStringArray = function(channel, val) {
528
- SendMessage(channel, "broadcast::string[]", val);
532
+ var sendVector2 = (channel, val) => {
533
+ SendMessage(channel, "broadcast::vector2", val);
529
534
  };
530
- var sendVector3 = function(channel, val) {
531
- SendMessage(channel, "broadcast::vector3", val);
535
+ var sendVector2Array = (channel, val) => {
536
+ SendMessage(channel, "broadcast::vector2[]", val);
532
537
  };
533
- var sendVector3Array = function(channel, val) {
534
- SendMessage(channel, "broadcast::vector3[]", val);
538
+ var sendVector3 = (channel, val) => {
539
+ SendMessage(channel, "broadcast::vector3", val);
535
540
  };
536
- var sendQuaternion = function(channel, val) {
537
- SendMessage(channel, "broadcast::quaternion", val);
541
+ var sendVector3Array = (channel, val) => {
542
+ SendMessage(channel, "broadcast::vector3[]", val);
538
543
  };
539
- var sendQuaternionArray = function(channel, val) {
540
- SendMessage(channel, "broadcast::quaternion[]", val);
544
+ var sendQuaternion = (channel, val) => {
545
+ SendMessage(channel, "broadcast::quaternion", val);
541
546
  };
542
- var sendColor = function(channel, val) {
543
- SendMessage(channel, "broadcast::color", val);
547
+ var sendQuaternionArray = (channel, val) => {
548
+ SendMessage(channel, "broadcast::quaternion[]", val);
544
549
  };
545
- var sendColorArray = function(channel, val) {
546
- SendMessage(channel, "broadcast::color[]", val);
550
+ var sendColor = (channel, val) => {
551
+ SendMessage(channel, "broadcast::color", val);
547
552
  };
548
- var sendJson = function(channel, val) {
549
- SendMessage(channel, "broadcast::json", val);
553
+ var sendColorArray = (channel, val) => {
554
+ SendMessage(channel, "broadcast::color[]", val);
555
+ };
556
+ var sendJson = (channel, val) => {
557
+ SendMessage(channel, "broadcast::json", val);
550
558
  };
551
559
  var listeners = {};
552
- var registerListener = function(channel, type, callback) {
553
- if (listeners[channel] === void 0) {
554
- listeners[channel] = {};
555
- RegisterChannel(channel, function(msg) {
556
- if (msg.command in listeners[channel]) {
557
- listeners[channel][msg.command].forEach(function(cb) {
558
- return cb(msg.payload);
559
- });
560
- }
560
+ var channelHandlers = {};
561
+ var registerListener = (channel, type, callback) => {
562
+ let channelListeners = listeners[channel];
563
+ if (channelListeners === void 0) {
564
+ const newChannelListeners = {};
565
+ channelListeners = newChannelListeners;
566
+ listeners[channel] = newChannelListeners;
567
+ const handler = (msg) => {
568
+ const commandListeners = newChannelListeners[msg.command];
569
+ if (commandListeners !== void 0) {
570
+ commandListeners.forEach((cb) => {
571
+ cb(msg.payload);
561
572
  });
562
- }
563
- if (listeners[channel][type] === void 0) {
564
- listeners[channel][type] = [];
565
- }
566
- listeners[channel][type].push(callback);
573
+ }
574
+ };
575
+ channelHandlers[channel] = handler;
576
+ RegisterChannel(channel, handler);
577
+ }
578
+ let typeListeners = channelListeners[type];
579
+ if (typeListeners === void 0) {
580
+ typeListeners = [];
581
+ channelListeners[type] = typeListeners;
582
+ }
583
+ typeListeners.push(callback);
567
584
  };
568
- var receiveBool = function(channel, callback) {
569
- registerListener(channel, "broadcast::bool", callback);
585
+ var receiveBool = (channel, callback) => {
586
+ registerListener(channel, "broadcast::bool", callback);
570
587
  };
571
- var receiveBoolArray = function(channel, callback) {
572
- registerListener(channel, "broadcast::bool[]", callback);
588
+ var receiveBoolArray = (channel, callback) => {
589
+ registerListener(channel, "broadcast::bool[]", callback);
573
590
  };
574
- var receiveNumber = function(channel, callback) {
575
- registerListener(channel, "broadcast::float", callback);
591
+ var receiveNumber = (channel, callback) => {
592
+ registerListener(channel, "broadcast::float", callback);
593
+ registerListener(channel, "broadcast::int", callback);
576
594
  };
577
- var receiveNumberArray = function(channel, callback) {
578
- registerListener(channel, "broadcast::float[]", callback);
595
+ var receiveNumberArray = (channel, callback) => {
596
+ registerListener(channel, "broadcast::float[]", callback);
597
+ registerListener(channel, "broadcast::int[]", callback);
579
598
  };
580
- var receiveString = function(channel, callback) {
581
- registerListener(channel, "broadcast::string", callback);
599
+ var receiveString = (channel, callback) => {
600
+ registerListener(channel, "broadcast::string", callback);
582
601
  };
583
- var receiveStringArray = function(channel, callback) {
584
- registerListener(channel, "broadcast::string[]", callback);
602
+ var receiveStringArray = (channel, callback) => {
603
+ registerListener(channel, "broadcast::string[]", callback);
585
604
  };
586
- var receiveVector3 = function(channel, callback) {
587
- registerListener(channel, "broadcast::vector3", callback);
605
+ var receiveVector2 = (channel, callback) => {
606
+ registerListener(channel, "broadcast::vector2", callback);
588
607
  };
589
- var receiveVector3Array = function(channel, callback) {
590
- registerListener(channel, "broadcast::vector3[]", callback);
608
+ var receiveVector2Array = (channel, callback) => {
609
+ registerListener(channel, "broadcast::vector2[]", callback);
591
610
  };
592
- var receiveQuaternion = function(channel, callback) {
593
- registerListener(channel, "broadcast::quaternion", callback);
611
+ var receiveVector3 = (channel, callback) => {
612
+ registerListener(channel, "broadcast::vector3", callback);
594
613
  };
595
- var receiveQuaternionArray = function(channel, callback) {
596
- registerListener(channel, "broadcast::quaternion[]", callback);
614
+ var receiveVector3Array = (channel, callback) => {
615
+ registerListener(channel, "broadcast::vector3[]", callback);
597
616
  };
598
- var receiveColor = function(channel, callback) {
599
- registerListener(channel, "broadcast::color", callback);
617
+ var receiveQuaternion = (channel, callback) => {
618
+ registerListener(channel, "broadcast::quaternion", callback);
600
619
  };
601
- var receiveColorArray = function(channel, callback) {
602
- registerListener(channel, "broadcast::color[]", callback);
620
+ var receiveQuaternionArray = (channel, callback) => {
621
+ registerListener(channel, "broadcast::quaternion[]", callback);
603
622
  };
604
- var receiveJson = function(channel, callback) {
605
- registerListener(channel, "broadcast::json", callback);
623
+ var receiveColor = (channel, callback) => {
624
+ registerListener(channel, "broadcast::color", callback);
606
625
  };
607
- var unregister = function(channel, callback) {
608
- for(var command in listeners[channel]){
609
- var index = listeners[channel][command].indexOf(callback);
610
- if (index >= 0) {
611
- listeners[channel][command].splice(index, 1);
612
- }
626
+ var receiveColorArray = (channel, callback) => {
627
+ registerListener(channel, "broadcast::color[]", callback);
628
+ };
629
+ var receiveJson = (channel, callback) => {
630
+ registerListener(channel, "broadcast::json", callback);
631
+ };
632
+ var clamp01 = (n) => Math.min(1, Math.max(0, n));
633
+ var hexPair = (n) => Math.round(clamp01(n) * 255).toString(16).padStart(2, "0");
634
+ var warnNotAColor = (val) => {
635
+ console.warn(`Colibri: '${JSON.stringify(val)}' is not a colour - expected "#RRGGBBAA" or [r,g,b,a]. Using black.`);
636
+ };
637
+ var asComponents = (val) => {
638
+ if (!Array.isArray(val) || val.length < 3) return null;
639
+ const numbers = val;
640
+ if (!numbers.every((c) => typeof c === "number" && !Number.isNaN(c))) return null;
641
+ return numbers;
642
+ };
643
+ var toHexColor = (val) => {
644
+ const rgba = toRgbaColor(val);
645
+ return `#${hexPair(rgba[0])}${hexPair(rgba[1])}${hexPair(rgba[2])}${hexPair(rgba[3])}`;
646
+ };
647
+ var toRgbaColor = (val) => {
648
+ const components = asComponents(val);
649
+ if (components !== null) {
650
+ return [
651
+ clamp01(components[0]),
652
+ clamp01(components[1]),
653
+ clamp01(components[2]),
654
+ components.length > 3 ? clamp01(components[3]) : 1
655
+ ];
656
+ }
657
+ if (typeof val === "string") {
658
+ const hex = val.startsWith("#") ? val.slice(1) : val;
659
+ const digits = hex.length === 3 || hex.length === 4 ? hex.replace(/./g, (c) => c + c) : hex;
660
+ if ((digits.length === 6 || digits.length === 8) && /^[0-9a-f]+$/i.test(digits)) {
661
+ const byteAt = (i) => parseInt(digits.slice(i, i + 2), 16) / 255;
662
+ return [byteAt(0), byteAt(2), byteAt(4), digits.length === 8 ? byteAt(6) : 1];
613
663
  }
664
+ }
665
+ warnNotAColor(val);
666
+ return [0, 0, 0, 1];
667
+ };
668
+ var unregister = (channel, callback) => {
669
+ const channelListeners = listeners[channel];
670
+ if (channelListeners === void 0) return;
671
+ let hasRemainingListeners = false;
672
+ for (const command in channelListeners) {
673
+ const commandListeners = channelListeners[command];
674
+ const index = commandListeners?.indexOf(callback) ?? -1;
675
+ if (index >= 0) {
676
+ commandListeners?.splice(index, 1);
677
+ }
678
+ if ((commandListeners?.length ?? 0) > 0) {
679
+ hasRemainingListeners = true;
680
+ }
681
+ }
682
+ if (!hasRemainingListeners) {
683
+ const handler = channelHandlers[channel];
684
+ if (handler !== void 0) {
685
+ UnregisterChannel(channel, handler);
686
+ }
687
+ Reflect.deleteProperty(listeners, channel);
688
+ Reflect.deleteProperty(channelHandlers, channel);
689
+ }
614
690
  };
615
691
  var Sync = {
616
- sendBool: sendBool,
617
- sendBoolArray: sendBoolArray,
618
- sendNumber: sendNumber,
619
- sendNumberArray: sendNumberArray,
620
- sendString: sendString,
621
- sendStringArray: sendStringArray,
622
- sendVector3: sendVector3,
623
- sendVector3Array: sendVector3Array,
624
- sendQuaternion: sendQuaternion,
625
- sendQuaternionArray: sendQuaternionArray,
626
- sendColor: sendColor,
627
- sendColorArray: sendColorArray,
628
- sendJson: sendJson,
629
- receiveBool: receiveBool,
630
- receiveBoolArray: receiveBoolArray,
631
- receiveNumber: receiveNumber,
632
- receiveNumberArray: receiveNumberArray,
633
- receiveString: receiveString,
634
- receiveStringArray: receiveStringArray,
635
- receiveVector3: receiveVector3,
636
- receiveVector3Array: receiveVector3Array,
637
- receiveQuaternion: receiveQuaternion,
638
- receiveQuaternionArray: receiveQuaternionArray,
639
- receiveColor: receiveColor,
640
- receiveColorArray: receiveColorArray,
641
- receiveJson: receiveJson,
642
- unregister: unregister,
643
- // for better compatibility with Unity Colibri
644
- sendFloat: sendNumber,
645
- sendInt: sendNumber,
646
- sendFloatArray: sendNumberArray,
647
- sendIntArray: sendNumberArray
692
+ sendBool,
693
+ sendBoolArray,
694
+ sendNumber,
695
+ sendNumberArray,
696
+ sendString,
697
+ sendStringArray,
698
+ sendVector2,
699
+ sendVector2Array,
700
+ sendVector3,
701
+ sendVector3Array,
702
+ sendQuaternion,
703
+ sendQuaternionArray,
704
+ sendColor,
705
+ sendColorArray,
706
+ sendJson,
707
+ receiveBool,
708
+ receiveBoolArray,
709
+ receiveNumber,
710
+ receiveNumberArray,
711
+ receiveString,
712
+ receiveStringArray,
713
+ receiveVector2,
714
+ receiveVector2Array,
715
+ receiveVector3,
716
+ receiveVector3Array,
717
+ receiveQuaternion,
718
+ receiveQuaternionArray,
719
+ receiveColor,
720
+ receiveColorArray,
721
+ receiveJson,
722
+ unregister,
723
+ // for better compatibility with Unity Colibri
724
+ // sendInt and sendIntArray still send the float commands (JS cannot tell 5 from 5.0), so a
725
+ // Unity client has to listen for float, not int.
726
+ sendFloat: sendNumber,
727
+ sendInt: sendNumber,
728
+ sendFloatArray: sendNumberArray,
729
+ sendIntArray: sendNumberArray
648
730
  };
731
+
649
732
  // src/RemoteLogger.ts
650
- var RemoteLogger = /*#__PURE__*/ function() {
651
- "use strict";
652
- function _RemoteLogger() {
653
- var enabled = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
654
- var _this = this;
655
- _class_call_check(this, _RemoteLogger);
656
- this.enabled = enabled;
657
- this.consoleDebug = console.debug;
658
- this.consoleLog = console.log;
659
- this.consoleInfo = console.info;
660
- this.consoleWarn = console.warn;
661
- this.consoleError = console.error;
662
- console.debug = function() {
663
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
664
- args[_key] = arguments[_key];
665
- }
666
- _this.consoleDebug.apply(_this, _to_consumable_array(args));
667
- _this.sendMessage("debug", args);
668
- };
669
- console.log = function() {
670
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
671
- args[_key] = arguments[_key];
672
- }
673
- _this.consoleLog.apply(_this, _to_consumable_array(args));
674
- _this.sendMessage("info", args);
675
- };
676
- console.info = function() {
677
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
678
- args[_key] = arguments[_key];
679
- }
680
- _this.consoleInfo.apply(_this, _to_consumable_array(args));
681
- _this.sendMessage("info", args);
682
- };
683
- console.warn = function() {
684
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
685
- args[_key] = arguments[_key];
686
- }
687
- _this.consoleWarn.apply(_this, _to_consumable_array(args));
688
- _this.sendMessage("warn", args);
689
- };
690
- console.error = function() {
691
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
692
- args[_key] = arguments[_key];
693
- }
694
- _this.consoleError.apply(_this, _to_consumable_array(args));
695
- _this.sendMessage("error", args);
696
- };
697
- }
698
- _create_class(_RemoteLogger, [
699
- {
700
- key: "sendMessage",
701
- value: function sendMessage(level, args) {
702
- if (!this.enabled) return;
703
- SendMessage("log", level, _to_consumable_array(args).map(stringify).join().trim());
704
- }
705
- },
706
- {
707
- key: "enable",
708
- value: function enable() {
709
- this.enabled = true;
710
- }
711
- },
712
- {
713
- key: "disable",
714
- value: function disable() {
715
- this.enabled = false;
716
- }
717
- }
718
- ], [
719
- {
720
- key: "init",
721
- value: /**
733
+ var MAX_EARLY_LINES = 100;
734
+ var RemoteLogger = class _RemoteLogger {
735
+ /**
736
+ * Forwards everything logged through `console` to the server's log. Create one, at startup.
737
+ * A further instance warns once and does not patch again; its `enabled` argument, `enable()` and
738
+ * `disable()` act on the first one.
739
+ * @param enabled whether to forward from the start
740
+ */
741
+ constructor(enabled = true) {
742
+ this.enabled = enabled;
743
+ const patched = _RemoteLogger.patched;
744
+ if (patched) {
745
+ this.forwarder = patched;
746
+ patched.enabled = enabled;
747
+ if (!patched.hasWarnedOfAnotherInstance) {
748
+ patched.hasWarnedOfAnotherInstance = true;
749
+ console.warn(
750
+ "RemoteLogger: the console is already forwarded by an earlier new RemoteLogger(), so this one controls that instead of forwarding every line a second time. Create one, at startup."
751
+ );
752
+ }
753
+ return;
754
+ }
755
+ _RemoteLogger.patched = this;
756
+ this.forwarder = this;
757
+ console.debug = (...args) => {
758
+ this.consoleDebug(...args);
759
+ this.sendMessage("debug", args);
760
+ };
761
+ console.log = (...args) => {
762
+ this.consoleLog(...args);
763
+ this.sendMessage("info", args);
764
+ };
765
+ console.info = (...args) => {
766
+ this.consoleInfo(...args);
767
+ this.sendMessage("info", args);
768
+ };
769
+ console.warn = (...args) => {
770
+ this.consoleWarn(...args);
771
+ this.sendMessage("warn", args);
772
+ };
773
+ console.error = (...args) => {
774
+ this.consoleError(...args);
775
+ this.sendMessage("error", args);
776
+ };
777
+ }
778
+ // The instance that patched the console. Later instances delegate to it, since patching again
779
+ // would forward every line once per instance (StrictMode and hot reload create extras).
780
+ static patched = null;
781
+ // Itself, or the instance that patched the console.
782
+ forwarder;
783
+ hasWarnedOfAnotherInstance = false;
784
+ consoleDebug = console.debug;
785
+ consoleLog = console.log;
786
+ consoleInfo = console.info;
787
+ consoleWarn = console.warn;
788
+ consoleError = console.error;
789
+ // Recursion guard: lines logged while forwarding (by Colibri, or by a getter that JSON.stringify
790
+ // runs) go to the console only.
791
+ forwarding = false;
792
+ // Lines logged before `new Colibri()`.
793
+ earlyLines = [];
794
+ droppedEarlyLines = 0;
795
+ waitingForColibri = false;
796
+ /**
722
797
  * @deprecated use new class constructor directly
723
- */ function init() {
724
- var enabled = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
725
- return new _RemoteLogger(enabled);
726
- }
727
- }
728
- ]);
729
- return _RemoteLogger;
730
- }();
731
- var stringify = function(obj) {
732
- if (_instanceof(obj, Error)) {
733
- return obj.message + "\n" + obj.stack;
734
- }
735
- if (typeof obj === "string") return obj;
736
- var cache = [];
737
- var str = JSON.stringify(obj, function(_, value) {
798
+ */
799
+ static init(enabled = true) {
800
+ return new _RemoteLogger(enabled);
801
+ }
802
+ sendMessage(level, args) {
803
+ if (!this.enabled || this.forwarding) return;
804
+ this.forwarding = true;
805
+ try {
806
+ const message = [...args].map(stringify).join().trim();
807
+ const colibri = Colibri.getInstance(false);
808
+ if (colibri) colibri.sendMessage("log", level, message);
809
+ else this.keepUntilColibriExists(level, message);
810
+ } catch (error) {
811
+ this.consoleError("RemoteLogger: could not forward a log line.", error);
812
+ } finally {
813
+ this.forwarding = false;
814
+ }
815
+ }
816
+ keepUntilColibriExists(level, message) {
817
+ if (this.earlyLines.length >= MAX_EARLY_LINES) {
818
+ this.droppedEarlyLines++;
819
+ return;
820
+ }
821
+ this.earlyLines.push({ level, message });
822
+ if (!this.waitingForColibri) {
823
+ this.waitingForColibri = true;
824
+ whenColibriCreated((colibri) => {
825
+ this.sendEarlyLines(colibri);
826
+ });
827
+ }
828
+ }
829
+ // Socket.IO buffers emits until connected, so there is no need to wait for the connection.
830
+ sendEarlyLines(colibri) {
831
+ this.waitingForColibri = false;
832
+ for (const { level, message } of this.earlyLines.splice(0)) {
833
+ colibri.sendMessage("log", level, message);
834
+ }
835
+ if (this.droppedEarlyLines > 0) {
836
+ colibri.sendMessage(
837
+ "log",
838
+ "warn",
839
+ `RemoteLogger: ${this.droppedEarlyLines} more line(s) logged before new Colibri() were not kept, only the first ${MAX_EARLY_LINES}.`
840
+ );
841
+ this.droppedEarlyLines = 0;
842
+ }
843
+ }
844
+ /** Starts forwarding console output to the server's log. */
845
+ enable() {
846
+ this.forwarder.enabled = true;
847
+ }
848
+ /** Stops forwarding to the server's log; the console still prints. */
849
+ disable() {
850
+ this.forwarder.enabled = false;
851
+ }
852
+ };
853
+ var stringify = (obj) => {
854
+ if (obj instanceof Error) {
855
+ return obj.message + "\n" + (obj.stack ?? "");
856
+ }
857
+ if (typeof obj === "string") return obj;
858
+ const cache = [];
859
+ let str;
860
+ try {
861
+ str = JSON.stringify(
862
+ obj,
863
+ (_, value) => {
864
+ if (typeof value === "bigint") return value.toString();
738
865
  if (typeof value === "object" && value !== null) {
739
- if (cache.indexOf(value) !== -1) {
740
- return;
741
- }
742
- cache.push(value);
866
+ if (cache.indexOf(value) !== -1) {
867
+ return;
868
+ }
869
+ cache.push(value);
743
870
  }
744
871
  return value;
745
- }, 2);
746
- return str;
872
+ },
873
+ 2
874
+ );
875
+ } catch {
876
+ str = String(obj);
877
+ }
878
+ return str;
747
879
  };
880
+
748
881
  // src/ModelSynchronization.ts
749
882
  import { BehaviorSubject } from "rxjs";
750
- var RegisterModelSync = function(registration) {
751
- var name = registration.name || registration.type.name.toLowerCase();
752
- SendMessage(name, "model::request");
753
- console.log("Registering model '".concat(name, "'"));
754
- RegisterChannel("".concat(name), function(payload) {
755
- var msg = payload;
756
- if (msg.command === "model::update") {
757
- onUpdate(msg.payload);
758
- } else if (msg.command === "model::delete") {
759
- onDelete(msg.payload.id);
760
- } else {
761
- console.error("Unknown model command: ".concat(msg.command));
883
+
884
+ // src/SyncModel.ts
885
+ import { Subject as Subject2, auditTime, buffer, filter, map, share } from "rxjs";
886
+ var SyncModel = class _SyncModel {
887
+ id;
888
+ // True while update() applies a remote update, so the setters do not echo it.
889
+ applyingRemoteUpdate = false;
890
+ modelChanges = new Subject2();
891
+ modelChanges$ = this.modelChanges.pipe(
892
+ // auditTime arms its timer on the first change only; bufferTime keeps an interval running while idle.
893
+ buffer(this.modelChanges.pipe(auditTime(1))),
894
+ map((changes) => changes.filter(this.uniq)),
895
+ filter((changes) => changes.length > 0),
896
+ share()
897
+ );
898
+ // Emits once on delete(), which RegisterModelSync sends on as model::delete. Public only for RegisterModelSync.
899
+ deletions = new Subject2();
900
+ // ES private: a subclass may have a `deleted` of its own.
901
+ #deleted = false;
902
+ constructor(id) {
903
+ this.id = id;
904
+ }
905
+ uniq(value, index, array) {
906
+ return array.indexOf(value) === index;
907
+ }
908
+ onModelChanges(prop) {
909
+ this.modelChanges.next(prop);
910
+ }
911
+ /**
912
+ * Deletes the model for every client of the app (Unity destroys its GameObject) and removes it
913
+ * from this client's list. The model stops syncing.
914
+ */
915
+ delete() {
916
+ if (this.#deleted) return;
917
+ this.#deleted = true;
918
+ if (!this.deletions.observed) {
919
+ console.warn(
920
+ `Colibri: delete() of '${this.id}', which no RegisterModelSync lists. Register it, or take it from the list RegisterModelSync gives, to delete it for every client.`
921
+ );
922
+ }
923
+ _SyncModel.prototype.detach.call(this);
924
+ this.deletions.next();
925
+ this.deletions.complete();
926
+ }
927
+ /**
928
+ * Stops syncing the model on this client only; every other client keeps it. RegisterModelSync
929
+ * calls it on a remote delete and when registerModel replaces a listed copy.
930
+ */
931
+ detach() {
932
+ this.modelChanges.complete();
933
+ }
934
+ registerSyncedProperty(name, prop) {
935
+ let syncedProperties = this.__syncedProperties;
936
+ if (syncedProperties === void 0) {
937
+ syncedProperties = {};
938
+ Object.defineProperty(this, "__syncedProperties", {
939
+ value: syncedProperties,
940
+ enumerable: false,
941
+ writable: true,
942
+ configurable: true
943
+ });
944
+ }
945
+ syncedProperties[name] = prop;
946
+ }
947
+ getSyncedProperties() {
948
+ return this.__syncedProperties ?? {};
949
+ }
950
+ update(updates) {
951
+ const syncedProps = this.getSyncedProperties();
952
+ this.applyingRemoteUpdate = true;
953
+ try {
954
+ for (const key of Object.keys(updates)) {
955
+ if (key !== "id") {
956
+ const localKey = syncedProps[key];
957
+ if (localKey) {
958
+ this[localKey] = updates[key];
959
+ } else {
960
+ console.warn(`Unknown property ${key} in ${this.constructor.name}`);
961
+ }
762
962
  }
963
+ }
964
+ } finally {
965
+ this.applyingRemoteUpdate = false;
966
+ }
967
+ }
968
+ toJson(attributes = []) {
969
+ const json = { id: this.id };
970
+ const syncedProps = this.getSyncedProperties();
971
+ for (const key of Object.keys(syncedProps)) {
972
+ const localKey = syncedProps[key];
973
+ if (attributes.length === 0 || attributes.includes(localKey)) {
974
+ json[key] = this[localKey];
975
+ }
976
+ }
977
+ return json;
978
+ }
979
+ };
980
+
981
+ // src/ModelSynchronization.ts
982
+ var toJsonOf = (model, attributes) => SyncModel.prototype.toJson.call(model, attributes);
983
+ var updateOf = (model, updates) => {
984
+ SyncModel.prototype.update.call(model, updates);
985
+ };
986
+ var detachOf = (model) => {
987
+ if (model) SyncModel.prototype.detach.call(model);
988
+ };
989
+ var withColibri = (action) => {
990
+ const colibri = Colibri.getInstance(false);
991
+ if (colibri) action(colibri);
992
+ else whenColibriCreated(action);
993
+ };
994
+ var warnedMinifiedNames = /* @__PURE__ */ new Set();
995
+ var warnIfMinified = (className, channel) => {
996
+ if (channel.length > 2 && !channel.includes("$") || warnedMinifiedNames.has(channel)) return;
997
+ warnedMinifiedNames.add(channel);
998
+ console.warn(
999
+ `Colibri: RegisterModelSync is syncing on channel '${channel}', derived from the class name '${className}', which looks minified. A minified build renames classes, so this will not sync with another build or with Unity. Pass the channel explicitly: RegisterModelSync({ name: '...', type: ${className || "YourModel"} }).`
1000
+ );
1001
+ };
1002
+ var isBare = (modelData) => Object.keys(modelData).every((key) => key === "id");
1003
+ var ownOnChannel = /* @__PURE__ */ new Map();
1004
+ var guardsOnChannel = /* @__PURE__ */ new Map();
1005
+ var END_CHANNEL = "colibri::reconnect";
1006
+ var endRequests = 0;
1007
+ var askForEnd = (colibri) => {
1008
+ const id = `colibri-web-${++endRequests}`;
1009
+ colibri.sendMessage(END_CHANNEL, "model::request", { id, again: true });
1010
+ return id;
1011
+ };
1012
+ var KNOWN_VALUES_KEPT = 8;
1013
+ var KNOWN_VALUES_MS = 1e4;
1014
+ var DELETED_HERE_MS = 6e4;
1015
+ var AFRESH_ANSWER_MS = 1e4;
1016
+ var RegisterModelSync = (registration) => {
1017
+ const name = registration.name || registration.type.name.toLowerCase();
1018
+ if (!registration.name) warnIfMinified(registration.type.name, name);
1019
+ const models = new BehaviorSubject([]);
1020
+ const deletedHere = /* @__PURE__ */ new Map();
1021
+ const rememberDeletedHere = (id) => {
1022
+ const now = Date.now();
1023
+ for (const [old, at] of deletedHere) {
1024
+ if (now - at < DELETED_HERE_MS) break;
1025
+ deletedHere.delete(old);
1026
+ }
1027
+ deletedHere.delete(id);
1028
+ deletedHere.set(id, now);
1029
+ };
1030
+ const afresh = /* @__PURE__ */ new Map();
1031
+ const recentlyDeletedHere = (id) => {
1032
+ const at = deletedHere.get(id);
1033
+ if (at === void 0) return false;
1034
+ if (Date.now() - at < DELETED_HERE_MS) return true;
1035
+ deletedHere.delete(id);
1036
+ return false;
1037
+ };
1038
+ const ownModels = /* @__PURE__ */ new WeakSet();
1039
+ const awaitingAnswer = /* @__PURE__ */ new Map();
1040
+ const answered = /* @__PURE__ */ new WeakSet();
1041
+ let catchingUpThrough;
1042
+ const deletedWhileAwaited = /* @__PURE__ */ new Set();
1043
+ const heldChanges = /* @__PURE__ */ new WeakMap();
1044
+ const changesToSend = /* @__PURE__ */ new WeakMap();
1045
+ const noteChangeToSend = (model, change) => {
1046
+ const toSend = changesToSend.get(model);
1047
+ if (toSend) toSend.add(change);
1048
+ else changesToSend.set(model, /* @__PURE__ */ new Set([change]));
1049
+ };
1050
+ const confirming = /* @__PURE__ */ new Map();
1051
+ const endConfirmation = (id) => {
1052
+ const confirmation = confirming.get(id);
1053
+ confirming.delete(id);
1054
+ return confirmation;
1055
+ };
1056
+ const knownValues = /* @__PURE__ */ new WeakMap();
1057
+ const askedAfterOutage = /* @__PURE__ */ new Map();
1058
+ let roundEnd;
1059
+ let guardEnds = [];
1060
+ let keptOut = /* @__PURE__ */ new WeakMap();
1061
+ const answerMayFollow = /* @__PURE__ */ new Map();
1062
+ let lastHeardBeforeOutage = 0;
1063
+ let disconnected = false;
1064
+ const hasOwn = (id) => models.value.some((m) => m.id === id && ownModels.has(m));
1065
+ const onChannel = ownOnChannel.get(name);
1066
+ if (onChannel) onChannel.add(hasOwn);
1067
+ else ownOnChannel.set(name, /* @__PURE__ */ new Set([hasOwn]));
1068
+ const guard = (end) => {
1069
+ guardEnds.push(end);
1070
+ };
1071
+ const guards = guardsOnChannel.get(name);
1072
+ if (guards) guards.add(guard);
1073
+ else guardsOnChannel.set(name, /* @__PURE__ */ new Set([guard]));
1074
+ const askFor = (colibri, model) => {
1075
+ awaitingAnswer.set(model.id, colibri);
1076
+ colibri.sendMessage(
1077
+ name,
1078
+ "model::request",
1079
+ answered.has(model) ? { id: model.id, again: true } : { id: model.id }
1080
+ );
1081
+ };
1082
+ const sendAfresh = (colibri, model) => {
1083
+ colibri.sendMessage(name, "model::request", { id: model.id });
1084
+ afresh.set(model.id, Date.now());
1085
+ answered.add(model);
1086
+ releaseHeldChanges(model);
1087
+ sendUpdate(colibri, model, toJsonOf(model));
1088
+ };
1089
+ const catchUpOnceAnswered = () => {
1090
+ if (!catchingUpThrough || awaitingAnswer.size > 0) return false;
1091
+ const colibri = catchingUpThrough;
1092
+ catchingUpThrough = void 0;
1093
+ colibri.sendMessage(name, "model::request");
1094
+ guardFrom(colibri);
1095
+ return true;
1096
+ };
1097
+ const guardFrom = (colibri) => {
1098
+ const end = askForEnd(colibri);
1099
+ for (const guardOnChannel of guardsOnChannel.get(name) ?? []) guardOnChannel(end);
1100
+ };
1101
+ const keepOut = (model, update) => {
1102
+ const end = guardEnds.at(-1);
1103
+ if (end === void 0) return;
1104
+ let kept = keptOut.get(model);
1105
+ if (!kept) keptOut.set(model, kept = /* @__PURE__ */ new Map());
1106
+ for (const key of Object.keys(update)) if (key !== "id") kept.set(key, end);
1107
+ };
1108
+ const keptOutOf = (model) => [...keptOut.get(model) ?? []].filter(([, end]) => guardEnds.includes(end)).map(([key]) => key);
1109
+ const endGuard = (end) => {
1110
+ guardEnds = end === void 0 ? [] : guardEnds.slice(guardEnds.indexOf(end) + 1);
1111
+ if (guardEnds.length > 0) return;
1112
+ keptOut = /* @__PURE__ */ new WeakMap();
1113
+ answerMayFollow.clear();
1114
+ };
1115
+ withColibri((colibri) => {
1116
+ catchingUpThrough = colibri;
1117
+ setTimeout(catchUpOnceAnswered, 0);
1118
+ onColibriDisconnected(colibri, () => {
1119
+ disconnected = true;
1120
+ endGuard();
1121
+ if (askedAfterOutage.size === 0) lastHeardBeforeOutage = lastHeardFrom(colibri) ?? Date.now();
1122
+ const since = (lastHeardFrom(colibri) ?? Date.now()) - 1e3;
1123
+ for (const [id, at] of deletedHere) {
1124
+ if (at >= since) colibri.sendMessage(name, "model::delete", { id });
1125
+ }
763
1126
  });
764
- var models = new BehaviorSubject([]);
765
- var onUpdate = function(modelData) {
766
- var model = models.value.find(function(m) {
767
- return m.id === modelData.id;
768
- });
769
- if (model) {
770
- model.update(modelData);
771
- models.next(_to_consumable_array(models.value));
772
- } else if (modelData.id) {
773
- var newModel = new registration.type(modelData.id);
774
- newModel.modelChanges$.subscribe(function(changes) {
775
- if (!newModel.ignoreNextChange) {
776
- SendMessage("".concat(name), "model::update", newModel.toJson(changes));
777
- }
778
- newModel.ignoreNextChange = false;
779
- models.next(_to_consumable_array(models.value));
780
- });
781
- newModel.update(modelData);
782
- models.next(_to_consumable_array(models.value).concat([
783
- newModel
784
- ]));
1127
+ onColibriReconnected(colibri, () => {
1128
+ disconnected = false;
1129
+ awaitingAnswer.clear();
1130
+ deletedWhileAwaited.clear();
1131
+ askedAfterOutage.clear();
1132
+ afresh.clear();
1133
+ for (const id of [...confirming.keys()]) {
1134
+ const confirmation = endConfirmation(id);
1135
+ const model = models.value.find((m) => m.id === id);
1136
+ if (confirmation && model && ownModels.has(model)) holdChanges(model, confirmation.props);
1137
+ }
1138
+ catchingUpThrough = colibri;
1139
+ for (const model of models.value) {
1140
+ if (!ownModels.has(model)) continue;
1141
+ if (answered.has(model)) askedAfterOutage.set(model.id, { shown: /* @__PURE__ */ new Map(), lost: /* @__PURE__ */ new Set() });
1142
+ askFor(colibri, model);
1143
+ }
1144
+ roundEnd = askedAfterOutage.size > 0 ? askForEnd(colibri) : void 0;
1145
+ catchUpOnceAnswered();
1146
+ });
1147
+ });
1148
+ RegisterChannel(name, (payload) => {
1149
+ if (payload.command === "model::update") {
1150
+ onUpdate(payload.payload);
1151
+ } else if (payload.command === "model::delete") {
1152
+ onDelete(payload.payload.id);
1153
+ } else {
1154
+ console.error(`Unknown model command: ${payload.command}`);
1155
+ }
1156
+ });
1157
+ RegisterChannel(END_CHANNEL, (message) => {
1158
+ if (message.command !== "model::update") return;
1159
+ const id = message.payload?.id;
1160
+ if (typeof id !== "string") return;
1161
+ if (id === roundEnd) endRound();
1162
+ if (guardEnds.includes(id)) endGuard(id);
1163
+ const confirmed = [...confirming].find(([, confirmation]) => confirmation.end === id);
1164
+ if (confirmed) endWait(confirmed[0]);
1165
+ });
1166
+ const onUpdate = (modelData) => {
1167
+ const model = models.value.find((m) => m.id === modelData.id);
1168
+ const id = modelData.id;
1169
+ const afreshSince = id === void 0 ? void 0 : afresh.get(id);
1170
+ if (id !== void 0 && afreshSince !== void 0) {
1171
+ const waiting = Date.now() - afreshSince < AFRESH_ANSWER_MS;
1172
+ if (isBare(modelData) || !waiting) afresh.delete(id);
1173
+ if (isBare(modelData) || waiting) return;
1174
+ }
1175
+ if (id !== void 0 && deletedWhileAwaited.delete(id) && !model && isBare(modelData)) return;
1176
+ const asker = id === void 0 ? void 0 : awaitingAnswer.get(id);
1177
+ if (id !== void 0 && asker) {
1178
+ takeAnswer(id, asker, model, modelData);
1179
+ return;
1180
+ }
1181
+ if (!model && id !== void 0 && isBare(modelData) && ownElsewhere(id)) return;
1182
+ applyUpdate(model, modelData);
1183
+ };
1184
+ const ownElsewhere = (id) => [...ownOnChannel.get(name) ?? []].some((has) => has !== hasOwn && has(id));
1185
+ const takeAnswer = (id, asker, model, modelData) => {
1186
+ if (model) answered.add(model);
1187
+ if (model && !ownModels.has(model)) {
1188
+ askedAfterOutage.delete(id);
1189
+ awaitingAnswer.delete(id);
1190
+ endConfirmation(id);
1191
+ if (!isBare(modelData)) applyUpdate(model, modelData);
1192
+ catchUpOnceAnswered();
1193
+ return;
1194
+ }
1195
+ if (!model || isBare(modelData)) {
1196
+ askedAfterOutage.delete(id);
1197
+ awaitingAnswer.delete(id);
1198
+ endConfirmation(id);
1199
+ if (model) {
1200
+ heldChanges.delete(model);
1201
+ sendUpdate(asker, model, toJsonOf(model));
1202
+ } else if (!isBare(modelData)) {
1203
+ applyUpdate(model, modelData);
1204
+ }
1205
+ catchUpOnceAnswered();
1206
+ return;
1207
+ }
1208
+ const afterOutage = askedAfterOutage.get(id);
1209
+ if (afterOutage) {
1210
+ const held2 = [...heldChanges.get(model) ?? []];
1211
+ for (const key of lostChanges(model, modelData, held2)) afterOutage.lost.add(key);
1212
+ for (const [key, value] of Object.entries(modelData)) afterOutage.shown.set(key, value);
1213
+ applyUpdate(model, withoutKeys(withoutChanges(modelData, model, held2), afterOutage.lost));
1214
+ return;
1215
+ }
1216
+ const confirmation = confirming.get(id);
1217
+ if (confirmation) {
1218
+ for (const key of confirmation.sent.keys()) {
1219
+ if (key in modelData) confirmation.shown.set(key, modelData[key]);
1220
+ }
1221
+ const held2 = [...heldChanges.get(model) ?? []];
1222
+ applyUpdate(model, withoutKeys(withoutChanges(modelData, model, held2), confirmation.sent.keys()));
1223
+ return;
1224
+ }
1225
+ awaitingAnswer.delete(id);
1226
+ const held = releaseHeldChanges(model);
1227
+ applyUpdate(model, withoutChanges(modelData, model, held));
1228
+ if (!models.value.includes(model)) {
1229
+ catchUpOnceAnswered();
1230
+ return;
1231
+ }
1232
+ if (sendOnTop(id, asker, model, modelData, held, [])) return;
1233
+ if (!catchUpOnceAnswered()) guardFrom(asker);
1234
+ const end = guardEnds.at(-1);
1235
+ if (end !== void 0) answerMayFollow.set(id, end);
1236
+ };
1237
+ const endRound = () => {
1238
+ roundEnd = void 0;
1239
+ const asked = [...askedAfterOutage];
1240
+ askedAfterOutage.clear();
1241
+ for (const [id, { shown, lost }] of asked) {
1242
+ const asker = awaitingAnswer.get(id);
1243
+ const model = models.value.find((m) => m.id === id);
1244
+ if (!asker || !model) continue;
1245
+ awaitingAnswer.delete(id);
1246
+ if (!ownModels.has(model)) continue;
1247
+ const held = releaseHeldChanges(model);
1248
+ if (lost.size > 0)
1249
+ remember(model, Object.fromEntries([...lost].map((key) => [key, shown.get(key)])));
1250
+ sendOnTop(id, asker, model, Object.fromEntries(shown), held, [...lost]);
1251
+ }
1252
+ catchUpOnceAnswered();
1253
+ };
1254
+ const sendOnTop = (id, asker, model, shown, held, lost) => {
1255
+ if (held.length === 0 && lost.length === 0) return false;
1256
+ const current = toJsonOf(model);
1257
+ const sent = held.length > 0 ? toJsonOf(model, held) : { id };
1258
+ for (const key of lost) sent[key] = current[key];
1259
+ sendUpdate(asker, model, sent);
1260
+ const differs = /* @__PURE__ */ new Map();
1261
+ for (const [key, value] of Object.entries(sent)) {
1262
+ const json = JSON.stringify(value);
1263
+ if (key === "id" || json === void 0) continue;
1264
+ if (!(key in shown) || JSON.stringify(shown[key]) !== json) differs.set(key, json);
1265
+ }
1266
+ if (differs.size === 0) return false;
1267
+ const replaced = /* @__PURE__ */ new Map();
1268
+ for (const key of differs.keys()) {
1269
+ replaced.set(key, key in shown ? JSON.stringify(shown[key]) : void 0);
1270
+ }
1271
+ askFor(asker, model);
1272
+ confirming.set(id, { sent: differs, replaced, props: held, shown: /* @__PURE__ */ new Map(), end: askForEnd(asker) });
1273
+ return true;
1274
+ };
1275
+ const endWait = (id) => {
1276
+ const confirmation = endConfirmation(id);
1277
+ const asker = awaitingAnswer.get(id);
1278
+ const model = models.value.find((m) => m.id === id);
1279
+ if (!confirmation || !asker || !model) return;
1280
+ awaitingAnswer.delete(id);
1281
+ const held = releaseHeldChanges(model);
1282
+ const theirs = { id };
1283
+ const again = [];
1284
+ for (const [key, json] of confirmation.sent) {
1285
+ const shown = confirmation.shown.has(key) ? JSON.stringify(confirmation.shown.get(key)) : void 0;
1286
+ if (shown === json) continue;
1287
+ if (shown === void 0 || shown === confirmation.replaced.get(key)) again.push(key);
1288
+ else theirs[key] = confirmation.shown.get(key);
1289
+ }
1290
+ applyUpdate(model, withoutChanges(theirs, model, held));
1291
+ const current = toJsonOf(model);
1292
+ const update = held.length > 0 ? toJsonOf(model, held) : { id };
1293
+ for (const key of again) update[key] = current[key];
1294
+ if (ownModels.has(model) && Object.keys(update).length > 1) sendUpdate(asker, model, update);
1295
+ catchUpOnceAnswered();
1296
+ };
1297
+ const sendUpdate = (colibri, model, update) => {
1298
+ colibri.sendMessage(name, "model::update", update);
1299
+ remember(model, update, lastHeardFrom(colibri) ?? Number.POSITIVE_INFINITY);
1300
+ keepOut(model, update);
1301
+ };
1302
+ const remember = (model, fields, heardAt) => {
1303
+ let known = knownValues.get(model);
1304
+ if (!known) knownValues.set(model, known = /* @__PURE__ */ new Map());
1305
+ const at = Date.now();
1306
+ for (const [key, field] of Object.entries(fields)) {
1307
+ const json = JSON.stringify(field);
1308
+ if (key === "id" || json === void 0) continue;
1309
+ const value = { json, at, sent: heardAt !== void 0 };
1310
+ known.set(key, heardAt === void 0 ? [value] : keepKnown([...known.get(key) ?? [], value], heardAt));
1311
+ }
1312
+ };
1313
+ const keepKnown = (values, heardAt) => {
1314
+ const split = values.findIndex((v) => v.at > heardAt);
1315
+ if (split < 0) return values.slice(-KNOWN_VALUES_KEPT);
1316
+ const after = values.slice(split);
1317
+ const newest = after.slice(KNOWN_VALUES_KEPT).slice(-1);
1318
+ return [...values.slice(0, split).slice(-KNOWN_VALUES_KEPT), ...after.slice(0, KNOWN_VALUES_KEPT), ...newest];
1319
+ };
1320
+ const lostChanges = (model, modelData, held) => {
1321
+ const known = knownValues.get(model);
1322
+ if (!known) return [];
1323
+ const since = lastHeardBeforeOutage - KNOWN_VALUES_MS;
1324
+ const heldKeys = new Set(held.length > 0 ? Object.keys(toJsonOf(model, held)) : []);
1325
+ const current = toJsonOf(model);
1326
+ return Object.entries(modelData).filter(([key, value]) => {
1327
+ const values = known.get(key) ?? [];
1328
+ const last = values.at(-1);
1329
+ if (!last?.sent || heldKeys.has(key) || !(key in current)) return false;
1330
+ const json = JSON.stringify(value);
1331
+ const earlier = values.filter((_, i) => i + 1 < values.length && values[i + 1].at >= since);
1332
+ return json !== last.json && earlier.some((v) => v.json === json) && // Nothing to send when this client has what the server has anyway.
1333
+ JSON.stringify(current[key]) !== json;
1334
+ }).map(([key]) => key);
1335
+ };
1336
+ const withoutKeys = (modelData, keys) => {
1337
+ const drop = new Set(keys);
1338
+ return Object.fromEntries(Object.entries(modelData).filter(([key]) => !drop.has(key)));
1339
+ };
1340
+ const applyUpdate = (model, modelData) => {
1341
+ if (model) {
1342
+ const unsent = [...changesToSend.get(model) ?? []];
1343
+ const update = withoutKeys(withoutChanges(modelData, model, unsent), keptOutOf(model));
1344
+ if (ownModels.has(model)) remember(model, update);
1345
+ updateOf(model, update);
1346
+ models.next([...models.value]);
1347
+ } else if (modelData.id) {
1348
+ if (recentlyDeletedHere(modelData.id)) return;
1349
+ const newModel = new registration.type(modelData.id);
1350
+ newModel.deletions.subscribe(() => {
1351
+ deleteHere(newModel);
1352
+ });
1353
+ newModel.modelChanges.subscribe((change) => {
1354
+ noteChangeToSend(newModel, change);
1355
+ });
1356
+ newModel.modelChanges$.subscribe((changes) => {
1357
+ changesToSend.delete(newModel);
1358
+ const update = toJsonOf(newModel, changes);
1359
+ SendMessage(name, "model::update", update);
1360
+ keepOut(newModel, update);
1361
+ models.next([...models.value]);
1362
+ });
1363
+ updateOf(newModel, modelData);
1364
+ models.next([...models.value, newModel]);
1365
+ }
1366
+ };
1367
+ const holdChanges = (model, changes) => {
1368
+ const held = heldChanges.get(model);
1369
+ if (held) for (const change of changes) held.add(change);
1370
+ else heldChanges.set(model, new Set(changes));
1371
+ };
1372
+ const releaseHeldChanges = (model) => {
1373
+ const held = [...heldChanges.get(model) ?? []];
1374
+ heldChanges.delete(model);
1375
+ return held;
1376
+ };
1377
+ const withoutChanges = (modelData, model, changes) => {
1378
+ if (changes.length === 0) return modelData;
1379
+ const changed = new Set(Object.keys(toJsonOf(model, changes)).filter((key) => key !== "id"));
1380
+ return Object.fromEntries(Object.entries(modelData).filter(([key]) => !changed.has(key)));
1381
+ };
1382
+ const onDelete = (id) => {
1383
+ const model = models.value.find((m) => m.id === id);
1384
+ detachOf(model);
1385
+ forget(id, model);
1386
+ };
1387
+ const deleteHere = (model) => {
1388
+ if (models.value.find((m) => m.id === model.id) !== model) return;
1389
+ rememberDeletedHere(model.id);
1390
+ forget(model.id, model);
1391
+ withColibri((colibri) => {
1392
+ colibri.sendMessage(name, "model::delete", { id: model.id });
1393
+ });
1394
+ };
1395
+ const forget = (id, model) => {
1396
+ if (model) heldChanges.delete(model);
1397
+ askedAfterOutage.delete(id);
1398
+ models.next(models.value.filter((m) => m.id !== id));
1399
+ endConfirmation(id);
1400
+ const answerEnd = answerMayFollow.get(id);
1401
+ answerMayFollow.delete(id);
1402
+ if (awaitingAnswer.delete(id)) {
1403
+ deletedWhileAwaited.add(id);
1404
+ catchUpOnceAnswered();
1405
+ } else if (answerEnd !== void 0 && guardEnds.includes(answerEnd)) {
1406
+ deletedWhileAwaited.add(id);
1407
+ }
1408
+ };
1409
+ const registerModel = (model) => {
1410
+ const listed = models.value.find((m) => m.id === model.id);
1411
+ if (listed === model) return;
1412
+ if (listed && ownModels.has(listed)) {
1413
+ console.warn(
1414
+ `Colibri: registerModel was given a second model with the id '${model.id}' on channel '${name}'. It replaces the first one, which no longer syncs.`
1415
+ );
1416
+ }
1417
+ const mustHold = () => !Colibri.getInstance(false) || disconnected || awaitingAnswer.has(model.id);
1418
+ model.modelChanges.subscribe((change) => {
1419
+ if (mustHold()) holdChanges(model, [change]);
1420
+ else noteChangeToSend(model, change);
1421
+ });
1422
+ model.modelChanges$.subscribe({
1423
+ next: () => {
1424
+ const changes = [...changesToSend.get(model) ?? []];
1425
+ changesToSend.delete(model);
1426
+ if (changes.length > 0) {
1427
+ const colibri = Colibri.getInstance(false);
1428
+ if (!colibri || mustHold()) holdChanges(model, changes);
1429
+ else sendUpdate(colibri, model, toJsonOf(model, changes));
785
1430
  }
786
- };
787
- var onDelete = function(id) {
788
- var model = models.value.find(function(m) {
789
- return m.id === id;
790
- });
791
- model === null || model === void 0 ? void 0 : model.delete();
792
- models.next(models.value.filter(function(m) {
793
- return m.id !== id;
794
- }));
795
- };
796
- var registerModel = function(model) {
797
- model.modelChanges$.subscribe(function(changes) {
798
- if (!model.ignoreNextChange) {
799
- SendMessage("".concat(name), "model::update", model.toJson(changes));
800
- }
801
- model.ignoreNextChange = false;
802
- });
803
- SendMessage("".concat(name), "model::update", model.toJson());
804
- models.next(_to_consumable_array(models.value).concat([
805
- model
806
- ]));
807
- };
808
- return [
809
- models.asObservable(),
810
- registerModel
811
- ];
1431
+ if (models.value.includes(model)) models.next([...models.value]);
1432
+ },
1433
+ // delete() and detach() end the stream: nothing more is sent for the model, neither held changes
1434
+ // nor the whole model after a reconnect.
1435
+ complete: () => {
1436
+ ownModels.delete(model);
1437
+ heldChanges.delete(model);
1438
+ changesToSend.delete(model);
1439
+ }
1440
+ });
1441
+ model.deletions.subscribe(() => {
1442
+ deleteHere(model);
1443
+ });
1444
+ const reused = recentlyDeletedHere(model.id);
1445
+ deletedHere.delete(model.id);
1446
+ ownModels.add(model);
1447
+ if (listed) {
1448
+ endConfirmation(model.id);
1449
+ askedAfterOutage.delete(model.id);
1450
+ detachOf(listed);
1451
+ models.next(models.value.map((m) => m === listed ? model : m));
1452
+ } else {
1453
+ models.next([...models.value, model]);
1454
+ }
1455
+ withColibri((colibri) => {
1456
+ if (disconnected || !ownModels.has(model)) return;
1457
+ if (reused) sendAfresh(colibri, model);
1458
+ else askFor(colibri, model);
1459
+ });
1460
+ };
1461
+ return [models.asObservable(), registerModel];
812
1462
  };
813
- // src/SyncModel.ts
814
- import { Subject as Subject2, bufferTime, filter, map, share } from "rxjs";
815
- var SyncModel = /*#__PURE__*/ function() {
816
- "use strict";
817
- function SyncModel(id) {
818
- var _this = this;
819
- _class_call_check(this, SyncModel);
820
- // TODO: move to ModelSynchronization or use a much better structure or something like that?
821
- this.ignoreNextChange = false;
822
- this.modelChanges = new Subject2();
823
- this.modelChanges$ = this.modelChanges.pipe(bufferTime(1), map(function(changes) {
824
- return changes.filter(_this.uniq);
825
- }), filter(function(changes) {
826
- return changes.length > 0;
827
- }), share());
828
- this.id = id;
829
- }
830
- _create_class(SyncModel, [
831
- {
832
- key: "uniq",
833
- value: function uniq(value, index, array) {
834
- return array.indexOf(value) === index;
835
- }
836
- },
837
- {
838
- key: "onModelChanges",
839
- value: function onModelChanges(prop) {
840
- this.modelChanges.next(prop);
841
- }
842
- },
843
- {
844
- key: "delete",
845
- value: function _delete() {
846
- this.modelChanges.complete();
847
- }
848
- },
849
- {
850
- key: "registerSyncedProperty",
851
- value: function registerSyncedProperty(name, prop) {
852
- if (!this.syncedProperties) {
853
- this.syncedProperties = {};
854
- }
855
- this.syncedProperties[name] = prop;
856
- }
857
- },
858
- {
859
- key: "update",
860
- value: function update(updates) {
861
- var syncedProps = Object.getPrototypeOf(this).syncedProperties;
862
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
863
- try {
864
- for(var _iterator = Object.keys(updates)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
865
- var key = _step.value;
866
- if (key !== "id") {
867
- var localKey = syncedProps[key];
868
- if (localKey) {
869
- this[localKey] = updates[key];
870
- this.ignoreNextChange = true;
871
- } else {
872
- console.warn("Unknown property ".concat(key, " in ").concat(this.constructor.name));
873
- }
874
- }
875
- }
876
- } catch (err) {
877
- _didIteratorError = true;
878
- _iteratorError = err;
879
- } finally{
880
- try {
881
- if (!_iteratorNormalCompletion && _iterator.return != null) {
882
- _iterator.return();
883
- }
884
- } finally{
885
- if (_didIteratorError) {
886
- throw _iteratorError;
887
- }
888
- }
889
- }
890
- }
891
- },
892
- {
893
- key: "toJson",
894
- value: function toJson() {
895
- var attributes = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
896
- var json = {
897
- id: this.id
898
- };
899
- var syncedProps = Object.getPrototypeOf(this).syncedProperties;
900
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
901
- try {
902
- for(var _iterator = Object.keys(syncedProps)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
903
- var key = _step.value;
904
- var localKey = syncedProps[key];
905
- if (attributes.length === 0 || attributes.includes(localKey)) {
906
- json[key] = this[localKey];
907
- }
908
- }
909
- } catch (err) {
910
- _didIteratorError = true;
911
- _iteratorError = err;
912
- } finally{
913
- try {
914
- if (!_iteratorNormalCompletion && _iterator.return != null) {
915
- _iterator.return();
916
- }
917
- } finally{
918
- if (_didIteratorError) {
919
- throw _iteratorError;
920
- }
921
- }
922
- }
923
- return json;
924
- }
925
- }
926
- ]);
927
- return SyncModel;
928
- }();
1463
+
929
1464
  // src/Synced.ts
930
- var Synced = function() {
931
- var syncedName = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
932
- return function Synced(target, key, descriptor) {
933
- if (!syncedName) syncedName = key.toString();
934
- syncedName = syncedName.toLowerCase();
935
- if (!_instanceof(target, SyncModel)) {
936
- console.error("Synced decorator can only be used on SyncModel properties");
937
- return;
938
- }
939
- var original = target[key];
940
- target.registerSyncedProperty(syncedName, key);
941
- if (!(descriptor === null || descriptor === void 0 ? void 0 : descriptor.get)) {
942
- Reflect.deleteProperty(target, key);
943
- Reflect.defineProperty(target, key, {
944
- get: function() {
945
- return original;
946
- },
947
- set: function(newVal) {
948
- console.log("Set ".concat(key.toString(), " to ").concat(newVal));
949
- original = newVal;
950
- },
951
- enumerable: true,
952
- configurable: true
953
- });
954
- } else {
955
- var originalAccessors = {
956
- get: descriptor.get,
957
- set: descriptor.set
958
- };
959
- descriptor.get = function() {
960
- var ret = originalAccessors.get.call(this);
961
- return ret;
962
- };
963
- descriptor.set = function(newval) {
964
- var model = this;
965
- model.modelChanges.next(String(key));
966
- if (originalAccessors.set) {
967
- originalAccessors.set.call(this, newval);
968
- }
969
- };
1465
+ function Synced(syncedName = "") {
1466
+ return function(value, context) {
1467
+ if (context.kind !== "accessor") {
1468
+ throw new Error("@Synced() must decorate an `accessor` member");
1469
+ }
1470
+ const key = String(context.name);
1471
+ const name = (syncedName || key).toLowerCase();
1472
+ context.addInitializer(function() {
1473
+ this.registerSyncedProperty(name, key);
1474
+ });
1475
+ return {
1476
+ get() {
1477
+ return value.get.call(this);
1478
+ },
1479
+ set(newVal) {
1480
+ value.set.call(this, newVal);
1481
+ if (!this.applyingRemoteUpdate) {
1482
+ this.modelChanges.next(key);
970
1483
  }
1484
+ }
971
1485
  };
1486
+ };
1487
+ }
1488
+ function synced(model, values, names = {}) {
1489
+ for (const [key, initial] of Object.entries(values)) {
1490
+ if (initial === void 0) {
1491
+ throw new Error(`synced(): '${key}' has no start value. undefined is not JSON: use null for none.`);
1492
+ }
1493
+ if (key in model) {
1494
+ throw new Error(
1495
+ `synced(): '${key}' is already a member of ${model.constructor.name}, a synced property or one of SyncModel's. Give it another name.`
1496
+ );
1497
+ }
1498
+ let value = initial;
1499
+ model.registerSyncedProperty((names[key] || key).toLowerCase(), key);
1500
+ Object.defineProperty(model, key, {
1501
+ enumerable: true,
1502
+ get: () => value,
1503
+ set: (newValue) => {
1504
+ value = newValue;
1505
+ if (!model.applyingRemoteUpdate) model.modelChanges.next(key);
1506
+ }
1507
+ });
1508
+ }
1509
+ }
1510
+
1511
+ // src/SyncTransform.ts
1512
+ var _physicsId_dec, _scale_dec, _rotation_dec, _position_dec, _active_dec, _a, _init, _active, _position, _rotation, _scale, _physicsId;
1513
+ var SyncTransform = class extends (_a = SyncModel, _active_dec = [Synced()], _position_dec = [Synced()], _rotation_dec = [Synced()], _scale_dec = [Synced()], _physicsId_dec = [Synced()], _a) {
1514
+ constructor() {
1515
+ super(...arguments);
1516
+ __privateAdd(this, _active, __runInitializers(_init, 8, this, true)), __runInitializers(_init, 11, this);
1517
+ __privateAdd(this, _position, __runInitializers(_init, 12, this, [0, 0, 0])), __runInitializers(_init, 15, this);
1518
+ __privateAdd(this, _rotation, __runInitializers(_init, 16, this, [0, 0, 0, 1])), __runInitializers(_init, 19, this);
1519
+ __privateAdd(this, _scale, __runInitializers(_init, 20, this, [1, 1, 1])), __runInitializers(_init, 23, this);
1520
+ __privateAdd(this, _physicsId, __runInitializers(_init, 24, this, "")), __runInitializers(_init, 27, this);
1521
+ }
1522
+ };
1523
+ _init = __decoratorStart(_a);
1524
+ _active = new WeakMap();
1525
+ _position = new WeakMap();
1526
+ _rotation = new WeakMap();
1527
+ _scale = new WeakMap();
1528
+ _physicsId = new WeakMap();
1529
+ __decorateElement(_init, 4, "active", _active_dec, SyncTransform, _active);
1530
+ __decorateElement(_init, 4, "position", _position_dec, SyncTransform, _position);
1531
+ __decorateElement(_init, 4, "rotation", _rotation_dec, SyncTransform, _rotation);
1532
+ __decorateElement(_init, 4, "scale", _scale_dec, SyncTransform, _scale);
1533
+ __decorateElement(_init, 4, "physicsId", _physicsId_dec, SyncTransform, _physicsId);
1534
+ __decoratorMetadata(_init, SyncTransform);
1535
+ var RegisterSyncTransforms = (modelId = "") => RegisterModelSync({
1536
+ name: modelId ? `synctransform_${modelId}` : "synctransform",
1537
+ type: SyncTransform
1538
+ });
1539
+ export {
1540
+ Colibri,
1541
+ ColibriError,
1542
+ DeleteRestApi,
1543
+ GetRestApi,
1544
+ PROTOCOL_VERSION,
1545
+ ProtocolMismatchError,
1546
+ PutRestApi,
1547
+ RegisterChannel,
1548
+ RegisterModelSync,
1549
+ RegisterOnce,
1550
+ RegisterSyncTransforms,
1551
+ RemoteLogger,
1552
+ SendMessage,
1553
+ Sync,
1554
+ SyncModel,
1555
+ SyncTransform,
1556
+ Synced,
1557
+ UnregisterChannel,
1558
+ synced,
1559
+ toHexColor,
1560
+ toRgbaColor
972
1561
  };
973
- export { Colibri, GetRestApi, PutRestApi, RegisterChannel, RegisterModelSync, RegisterOnce, RemoteLogger, SendMessage, Sync, SyncModel, Synced, UnregisterChannel };
974
1562
  //# sourceMappingURL=index.js.map