@classcad/client 0.0.0-stage → 3.0.0-beta.20261119090857

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.
Files changed (108) hide show
  1. package/README.md +20 -2
  2. package/bin/buerli-classcad.cjs +23 -0
  3. package/build/cjs/BuerliCadFacade.js +718 -0
  4. package/build/cjs/cclass/utils/assembly.js +687 -0
  5. package/build/cjs/cclass/utils/base.js +136 -0
  6. package/build/cjs/cclass/utils/index.js +99 -0
  7. package/build/cjs/cclass/utils/part.js +153 -0
  8. package/build/cjs/classcadEngine.js +33 -0
  9. package/build/cjs/createApi.js +71 -0
  10. package/build/cjs/createUnwrappedApi.js +43 -0
  11. package/build/cjs/facade.js +103 -0
  12. package/build/cjs/globals.js +157 -0
  13. package/build/cjs/index.js +102 -0
  14. package/build/cjs/io/AwvNodeClient.js +290 -0
  15. package/build/cjs/io/SocketIOClient.js +339 -0
  16. package/build/cjs/io/Transaction.js +134 -0
  17. package/build/cjs/io/WASMClient.js +433 -0
  18. package/build/cjs/io/WSClient.js +646 -0
  19. package/build/cjs/io/engineKey.js +202 -0
  20. package/build/cjs/re-export.js +35 -0
  21. package/build/cjs/session/host.js +479 -0
  22. package/build/cjs/session/identity.js +38 -0
  23. package/build/cjs/session/selection.js +283 -0
  24. package/build/cjs/session/share.js +229 -0
  25. package/build/cjs/session/types.js +23 -0
  26. package/build/cjs/test/SocketIOClient.spec.js +178 -0
  27. package/build/cjs/types/ComClient.js +10 -0
  28. package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
  29. package/build/cjs/utils/createRecursiveScene.js +140 -0
  30. package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
  31. package/build/cjs/utils/index.js +20 -0
  32. package/build/cjs/utils/polyline.js +65 -0
  33. package/build/cjs/utils/waitForSelect.js +29 -0
  34. package/build/esm/BuerliCadFacade.js +714 -0
  35. package/build/esm/cclass/utils/assembly.js +665 -0
  36. package/build/esm/cclass/utils/base.js +127 -0
  37. package/build/esm/cclass/utils/index.js +62 -0
  38. package/build/esm/cclass/utils/part.js +144 -0
  39. package/build/esm/classcadEngine.js +30 -0
  40. package/build/esm/createApi.js +66 -0
  41. package/build/esm/createUnwrappedApi.js +39 -0
  42. package/build/esm/facade.js +98 -0
  43. package/build/esm/globals.js +150 -0
  44. package/build/esm/index.js +80 -0
  45. package/build/esm/io/AwvNodeClient.js +286 -0
  46. package/build/esm/io/SocketIOClient.js +332 -0
  47. package/build/esm/io/Transaction.js +130 -0
  48. package/build/esm/io/WASMClient.js +429 -0
  49. package/build/esm/io/WSClient.js +642 -0
  50. package/build/esm/io/engineKey.js +196 -0
  51. package/build/esm/re-export.js +3 -0
  52. package/build/esm/session/host.js +474 -0
  53. package/build/esm/session/identity.js +34 -0
  54. package/build/esm/session/selection.js +277 -0
  55. package/build/esm/session/share.js +221 -0
  56. package/build/esm/session/types.js +20 -0
  57. package/build/esm/test/SocketIOClient.spec.js +178 -0
  58. package/build/esm/types/ComClient.js +7 -0
  59. package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
  60. package/build/esm/utils/createRecursiveScene.js +136 -0
  61. package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
  62. package/build/esm/utils/index.js +4 -0
  63. package/build/esm/utils/polyline.js +60 -0
  64. package/build/esm/utils/waitForSelect.js +23 -0
  65. package/build/types/BuerliCadFacade.d.ts +410 -0
  66. package/build/types/cclass/utils/assembly.d.ts +180 -0
  67. package/build/types/cclass/utils/base.d.ts +55 -0
  68. package/build/types/cclass/utils/index.d.ts +46 -0
  69. package/build/types/cclass/utils/part.d.ts +46 -0
  70. package/build/types/classcadEngine.d.ts +40 -0
  71. package/build/types/createApi.d.ts +65 -0
  72. package/build/types/createUnwrappedApi.d.ts +36 -0
  73. package/build/types/facade.d.ts +9 -0
  74. package/build/types/globals.d.ts +79 -0
  75. package/build/types/index.d.ts +82 -0
  76. package/build/types/io/AwvNodeClient.d.ts +182 -0
  77. package/build/types/io/SocketIOClient.d.ts +84 -0
  78. package/build/types/io/Transaction.d.ts +56 -0
  79. package/build/types/io/WASMClient.d.ts +239 -0
  80. package/build/types/io/WSClient.d.ts +242 -0
  81. package/build/types/io/engineKey.d.ts +137 -0
  82. package/build/types/re-export.d.ts +6 -0
  83. package/build/types/session/host.d.ts +108 -0
  84. package/build/types/session/identity.d.ts +46 -0
  85. package/build/types/session/selection.d.ts +164 -0
  86. package/build/types/session/share.d.ts +131 -0
  87. package/build/types/session/types.d.ts +113 -0
  88. package/build/types/test/SocketIOClient.spec.d.ts +0 -0
  89. package/build/types/types/ComClient.d.ts +307 -0
  90. package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
  91. package/build/types/utils/createRecursiveScene.d.ts +24 -0
  92. package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
  93. package/build/types/utils/index.d.ts +4 -0
  94. package/build/types/utils/polyline.d.ts +43 -0
  95. package/build/types/utils/waitForSelect.d.ts +4 -0
  96. package/doc/api/advanced/connection.md +488 -0
  97. package/doc/api/clients.md +2045 -0
  98. package/doc/api/engine-keys.md +230 -0
  99. package/doc/api/index.md +58 -0
  100. package/doc/api/modeling.md +682 -0
  101. package/doc/api/other.md +33 -0
  102. package/doc/api/session-sharing.md +706 -0
  103. package/package.json +59 -4
  104. package/test/classcadEngine.test.cjs +44 -0
  105. package/test/connect.test.cjs +81 -0
  106. package/test/engineKey.test.cjs +80 -0
  107. package/test/onClient.test.cjs +82 -0
  108. package/typedoc.json +8 -0
@@ -0,0 +1,479 @@
1
+ "use strict";
2
+ // Session sharing — hosting a session from a page.
3
+ //
4
+ // An engine that runs in the page (WASMClient) has no server around it. To
5
+ // share its session all the same, the page speaks the server's part of the
6
+ // session protocol itself: this module. Guests connect with the client they
7
+ // would use against a ClassCAD server (WSClient, a ClassCAD MCP) and get a
8
+ // server's frames: SessionJoined, the presence snapshot, every command's
9
+ // StructurePatch / Graphic / Result, presence.
10
+ //
11
+ // A page cannot listen, so somebody has to introduce the guests: a ClassCAD
12
+ // MCP on the same machine, or the ClassCAD share relay (classcad-ai's
13
+ // packages/relay), where guests join from anywhere. For every invite the page
14
+ // keeps a connection to that session address open. When a guest joins there
15
+ // with that invite, the broker says so and the page opens one more connection,
16
+ // which the broker joins to the guest's. From then on host and guest talk to
17
+ // each other; the broker in the middle only passes the bytes.
18
+ //
19
+ // page ── ?host=<invite> ────────────────► MCP / relay ◄── ?invite=<invite> ── guest
20
+ // page ── ?host=<invite>&guest=<id> ─────► └─ joined to the guest's connection
21
+ //
22
+ // The relay takes an offer only from a signed-in account (`auth`). A browser's
23
+ // WebSocket sends no headers, so the sign-in rides as a protocol next to
24
+ // PAGE_PROTOCOL; a refusal comes back as a close code, 4000 + the HTTP status.
25
+ //
26
+ // The engine speaks an older dialect than a server (Patch/ops, binary
27
+ // packages, the value nested in `result`); pieces() translates it. The same
28
+ // translation serves the MCP's own engine: packages/mcp/src/share/hub.ts in
29
+ // the classcad-ai repository is this module's twin, keep them in step.
30
+ //
31
+ // Where a page differs from a server: its engine always generates everything a
32
+ // command changed, so a guest's emission config only decides the FORM of what
33
+ // that guest is sent (streamed frames, or bundled on the Result), never what
34
+ // the others get.
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SessionHost = void 0;
37
+ exports.pieces = pieces;
38
+ const uuid_1 = require("uuid");
39
+ /** The emission config a fresh connection has on a server: full content, bundled on the Result. */
40
+ const DEFAULT_EMISSION = {
41
+ sendStructure: true,
42
+ sendStructure_Patch: false,
43
+ sendStructure_Compressed: false,
44
+ sendStructure_Immediately: false,
45
+ sendStructure_ImmediatelyBinary: false,
46
+ sendGraphic_Kernel: true,
47
+ sendGraphic_StructureObj: true,
48
+ sendGraphic_Sketch: true,
49
+ sendGraphic_Invisible: true,
50
+ sendGraphic_Compressed: false,
51
+ sendGraphic_Immediately: false,
52
+ sendGraphic_ImmediatelyBinary: false,
53
+ sendGraphic_Multipackage: false,
54
+ sendGraphic_UseDraco: false,
55
+ sendGraphic_UseDracoHybrid: false,
56
+ sendGraphic_AdvancedNotifications: false,
57
+ sendMessages: true,
58
+ sendMessages_Immediately: false,
59
+ sendMessages_MinLevel: 31,
60
+ storeState: false,
61
+ safeApi: false,
62
+ };
63
+ /** Pulls: they change nothing, so they concern only the one who asked. */
64
+ const READS = new Set(['GetTree', 'Sync']);
65
+ /** The engine's message level for an error; a Result at this level rejects in the client. */
66
+ const ERROR = 51;
67
+ /** A server relays presence frames of up to 8 KB and drops larger ones without a word. So does a page. */
68
+ const PRESENCE_MAX_BYTES = 8 * 1024;
69
+ /** Channels a guest may not publish on: the host's, and the server's own. */
70
+ const RESERVED_CHANNELS = new Set(['config', 'leave']);
71
+ /** The MCP may restart (an update, its idle exit), the network may drop: look for the broker again soon, and keep looking. */
72
+ const MAX_BACKOFF_MS = 5000;
73
+ /** The protocol a page names when it offers to a broker that wants a sign-in; the sign-in rides next to it as `bearer.<token>`. */
74
+ const PAGE_PROTOCOL = 'classcad-session';
75
+ /** How a broker refuses a page (4000 + the HTTP status): a sign-in it does not take, a plan that does not share, an invite offered by another account. */
76
+ const UNAUTHORIZED = 4401;
77
+ const FORBIDDEN = 4403;
78
+ const CONFLICT = 4409;
79
+ /** A Result frame that fails `req`, the way a server words an error. */
80
+ const errorResult = (req, message) => ({
81
+ command: 'Result',
82
+ _from_: String(req.command),
83
+ _transactionID_: req.transactionID,
84
+ maxLevel: ERROR,
85
+ messages: [{ message, level: ERROR, levelStr: 'ERROR', code: 0, timestamp: Date.now() }],
86
+ });
87
+ /** A streaming connection (WSClient) takes patches and graphics as frames of their own. */
88
+ const streams = (cfg) => cfg.sendStructure_Patch === true;
89
+ /** Translates one reply of the engine into what a server's frames are made of. */
90
+ function pieces(req, res) {
91
+ var _a, _b, _c, _d, _e, _f, _g, _h;
92
+ const from = String(req.command);
93
+ const tx = req.transactionID;
94
+ const out = {
95
+ from,
96
+ tx,
97
+ patches: [],
98
+ packages: (_a = res.binaryMessages) !== null && _a !== void 0 ? _a : [],
99
+ result: { command: 'Result', _from_: from, _transactionID_: tx },
100
+ };
101
+ // Errors the engine reported on the side (errorState 2 and up).
102
+ const side = [];
103
+ let answer;
104
+ for (const m of (_b = res.messages) !== null && _b !== void 0 ? _b : []) {
105
+ if ((m === null || m === void 0 ? void 0 : m.command) === 'Patch' && Array.isArray(m.ops) && m.ops.length)
106
+ out.patches.push(m.ops);
107
+ else if ((m === null || m === void 0 ? void 0 : m.command) === 'ErrorMessage' && Number((_c = m.attributes) === null || _c === void 0 ? void 0 : _c.errorState) >= 2)
108
+ side.push({
109
+ level: ERROR,
110
+ levelStr: 'ERROR',
111
+ code: (_e = (_d = m.attributes) === null || _d === void 0 ? void 0 : _d.errorCode) !== null && _e !== void 0 ? _e : 0,
112
+ message: String((_g = (_f = m.attributes) === null || _f === void 0 ? void 0 : _f.errorMessage) !== null && _g !== void 0 ? _g : 'engine error'),
113
+ });
114
+ else if ((m === null || m === void 0 ? void 0 : m.command) === 'Result')
115
+ answer !== null && answer !== void 0 ? answer : (answer = m);
116
+ else if ((m === null || m === void 0 ? void 0 : m.command) === 'UndoStack')
117
+ out.undoStack = m;
118
+ }
119
+ if (!answer) {
120
+ out.result = errorResult(req, side.length ? side.map(e => e.message).join('; ') : `the engine returned no result for ${from}`);
121
+ return out;
122
+ }
123
+ if (READS.has(from)) {
124
+ out.structure = (_h = answer.structure) !== null && _h !== void 0 ? _h : answer.result;
125
+ return out;
126
+ }
127
+ let value = answer.result;
128
+ let maxLevel = typeof answer.maxLevel === 'number' ? answer.maxLevel : undefined;
129
+ let messages = Array.isArray(answer.messages) ? answer.messages : undefined;
130
+ let streamData = answer.streamData;
131
+ // The engine nests an Execute's value next to its level and messages: { result, maxLevel, messages }.
132
+ if (from === 'Execute' && value && typeof value === 'object' && !Array.isArray(value) && 'result' in value) {
133
+ if (typeof value.maxLevel === 'number')
134
+ maxLevel = Math.max(maxLevel !== null && maxLevel !== void 0 ? maxLevel : 0, value.maxLevel);
135
+ if (Array.isArray(value.messages))
136
+ messages = [...(messages !== null && messages !== void 0 ? messages : []), ...value.messages];
137
+ streamData !== null && streamData !== void 0 ? streamData : (streamData = value.streamData);
138
+ value = value.result;
139
+ }
140
+ // An error reported only on the side must not pass as an empty success.
141
+ if (from === 'Execute' && side.length && (maxLevel !== null && maxLevel !== void 0 ? maxLevel : 0) < ERROR && value == null) {
142
+ maxLevel = ERROR;
143
+ messages = [...(messages !== null && messages !== void 0 ? messages : []), ...side];
144
+ }
145
+ out.result.result = value;
146
+ if (maxLevel !== undefined)
147
+ out.result.maxLevel = maxLevel;
148
+ if (messages === null || messages === void 0 ? void 0 : messages.length)
149
+ out.result.messages = messages;
150
+ if (streamData)
151
+ out.result.streamData = streamData;
152
+ return out;
153
+ }
154
+ /**
155
+ * A page's side of a shared session: offers invites at a ClassCAD MCP on the
156
+ * same machine or on the share relay, and serves the guests that join with
157
+ * them as a ClassCAD server would. `WASMClient` makes one with its first
158
+ * invite; an app has no need to use it directly.
159
+ *
160
+ * @internal
161
+ */
162
+ class SessionHost {
163
+ constructor(opts) {
164
+ this.opts = opts;
165
+ /** The host's peer id, as guests see it on presence frames. */
166
+ this.hostId = (0, uuid_1.v4)();
167
+ this.offers = new Map();
168
+ this.guests = new Set();
169
+ this.hostPresence = new Map();
170
+ this.closed = false;
171
+ }
172
+ /** The guests that are in the session right now. */
173
+ get peers() {
174
+ return Array.from(this.guests, g => g.peer);
175
+ }
176
+ /** Makes an invite joinable: keeps a connection to the broker open for it, whatever happens to the broker. */
177
+ offer(invite) {
178
+ if (this.closed || this.offers.has(invite.invite))
179
+ return;
180
+ const offer = { invite, control: null, backoff: 500 };
181
+ this.offers.set(invite.invite, offer);
182
+ void this.announce(offer);
183
+ }
184
+ /** Takes an invite back: nobody joins with it any more, and whoever did is cut off. Returns how many were. */
185
+ revoke(token) {
186
+ var _a;
187
+ const offer = this.offers.get(token);
188
+ if (!offer)
189
+ return 0;
190
+ this.offers.delete(token);
191
+ if (offer.timer)
192
+ clearTimeout(offer.timer);
193
+ try {
194
+ (_a = offer.control) === null || _a === void 0 ? void 0 : _a.close();
195
+ }
196
+ catch (_b) {
197
+ /* already closed */
198
+ }
199
+ let kicked = 0;
200
+ for (const guest of Array.from(this.guests)) {
201
+ if (guest.peer.invite !== token)
202
+ continue;
203
+ try {
204
+ guest.ws.close();
205
+ }
206
+ catch (_c) {
207
+ /* already closed */
208
+ }
209
+ this.leave(guest);
210
+ kicked++;
211
+ }
212
+ return kicked;
213
+ }
214
+ /** A command of the page itself, and what the engine emitted for it: the guests get it like any other. */
215
+ deliver(command, reply) {
216
+ if (this.closed || this.guests.size === 0)
217
+ return;
218
+ this.send(command.transactionID ? command : Object.assign(Object.assign({}, command), { transactionID: (0, uuid_1.v4)() }), reply, null);
219
+ }
220
+ /** Presence from the host to every guest (kept for those who join later). */
221
+ sendPresence(channel, data) {
222
+ if (channel === 'leave')
223
+ return;
224
+ this.hostPresence.set(channel, data);
225
+ const text = JSON.stringify({ command: 'Presence', channel, peerId: this.hostId, data });
226
+ for (const guest of this.guests)
227
+ this.raw(guest, text);
228
+ }
229
+ /** The page stops hosting: every guest is closed, every invite taken back. */
230
+ close() {
231
+ this.closed = true;
232
+ for (const token of Array.from(this.offers.keys()))
233
+ this.revoke(token);
234
+ for (const guest of Array.from(this.guests)) {
235
+ try {
236
+ guest.ws.close();
237
+ }
238
+ catch (_a) {
239
+ /* already closed */
240
+ }
241
+ this.leave(guest);
242
+ }
243
+ }
244
+ // ── The broker (an MCP, or the relay) ──
245
+ /** The broker's session address, with what this connection is for. */
246
+ address(params) {
247
+ return `${this.opts.url.replace(/\/+$/, '')}/?${params}`;
248
+ }
249
+ /** Opens the standing connection for an invite, and opens it again whenever it is lost. */
250
+ async announce(offer) {
251
+ const offered = () => !this.closed && this.offers.has(offer.invite.invite);
252
+ if (!offered())
253
+ return;
254
+ let ws;
255
+ const retry = () => {
256
+ if (!offered())
257
+ return;
258
+ offer.timer = setTimeout(() => void this.announce(offer), Math.min(offer.backoff, MAX_BACKOFF_MS));
259
+ offer.backoff = Math.min(offer.backoff * 2, MAX_BACKOFF_MS);
260
+ };
261
+ // The sign-in, where the broker wants one: a fresh one after it did not take the last.
262
+ const fresh = offer.refresh === true;
263
+ let protocols;
264
+ if (this.opts.auth) {
265
+ let token;
266
+ try {
267
+ token = await this.opts.auth(fresh);
268
+ }
269
+ catch (_a) {
270
+ // (no token without a network, say: it is asked for again with the next look)
271
+ return retry();
272
+ }
273
+ if (!offered())
274
+ return;
275
+ if (!token)
276
+ return this.refused(offer, { code: UNAUTHORIZED, reason: 'Sign in to share this session.' });
277
+ protocols = [PAGE_PROTOCOL, `bearer.${token}`];
278
+ }
279
+ try {
280
+ ws = new WebSocket(this.address(`host=${encodeURIComponent(offer.invite.invite)}`), protocols);
281
+ }
282
+ catch (_b) {
283
+ return retry();
284
+ }
285
+ offer.control = ws;
286
+ ws.onopen = () => {
287
+ offer.backoff = 500;
288
+ };
289
+ ws.onmessage = ev => {
290
+ let note = null;
291
+ try {
292
+ note = JSON.parse(typeof ev.data === 'string' ? ev.data : '');
293
+ }
294
+ catch (_a) {
295
+ return;
296
+ }
297
+ // Somebody joined with this invite: meet them on a connection of their own.
298
+ if (note && note.relay === 'guest' && typeof note.guest === 'string')
299
+ this.meet(offer.invite, note.guest);
300
+ };
301
+ ws.onclose = ev => {
302
+ if (offer.control === ws)
303
+ offer.control = null;
304
+ // Refused for good: the plan does not share, another account offers the invite, or a fresh sign-in did
305
+ // not hold either. A sign-in that did not hold (it ran out, say) is tried once more, fresh.
306
+ if (ev.code === FORBIDDEN || ev.code === CONFLICT || (ev.code === UNAUTHORIZED && fresh))
307
+ return this.refused(offer, { code: ev.code, reason: ev.reason });
308
+ offer.refresh = ev.code === UNAUTHORIZED;
309
+ retry();
310
+ };
311
+ ws.onerror = () => {
312
+ /* onclose follows and looks for the broker again */
313
+ };
314
+ }
315
+ /** The broker will not take an invite: it is offered no more, and the page is told why. */
316
+ refused(offer, refusal) {
317
+ var _a, _b;
318
+ if (!this.offers.has(offer.invite.invite))
319
+ return;
320
+ this.revoke(offer.invite.invite);
321
+ (_b = (_a = this.opts).onRefused) === null || _b === void 0 ? void 0 : _b.call(_a, offer.invite, refusal);
322
+ }
323
+ /** Opens the connection the broker joins to one guest's. */
324
+ meet(invite, guestId) {
325
+ let ws;
326
+ try {
327
+ ws = new WebSocket(this.address(`host=${encodeURIComponent(invite.invite)}&guest=${encodeURIComponent(guestId)}`));
328
+ }
329
+ catch (_a) {
330
+ return;
331
+ }
332
+ ws.onopen = () => this.serve(ws, invite);
333
+ }
334
+ // ── The guests ──
335
+ /** Sends a guest one frame, if its connection still takes any. */
336
+ raw(guest, text) {
337
+ if (guest.ws.readyState !== WebSocket.OPEN)
338
+ return;
339
+ try {
340
+ guest.ws.send(text);
341
+ }
342
+ catch (_a) {
343
+ /* closing */
344
+ }
345
+ }
346
+ /** Takes a guest in: the handshake a server gives, then its commands and presence. */
347
+ serve(ws, invite) {
348
+ var _a, _b;
349
+ if (this.closed || !this.offers.has(invite.invite))
350
+ return ws.close();
351
+ const peer = { peerId: (0, uuid_1.v4)(), invite: invite.invite, inviteName: invite.name, role: invite.role };
352
+ const guest = { peer, ws, config: Object.assign({}, DEFAULT_EMISSION), presence: new Map() };
353
+ this.raw(guest, JSON.stringify({ command: 'SessionJoined', role: invite.role, inviteName: invite.name }));
354
+ // The snapshot: what everyone already here last said, per channel.
355
+ for (const [channel, data] of this.hostPresence)
356
+ this.raw(guest, JSON.stringify({ command: 'Presence', channel, peerId: this.hostId, data }));
357
+ for (const other of this.guests)
358
+ for (const [channel, data] of other.presence)
359
+ this.raw(guest, JSON.stringify({ command: 'Presence', channel, peerId: other.peer.peerId, data }));
360
+ // The undo history as it is, as a server sends it to a guest that joins.
361
+ const undoStack = (_b = (_a = this.opts).undoStack) === null || _b === void 0 ? void 0 : _b.call(_a);
362
+ if (undoStack)
363
+ this.raw(guest, JSON.stringify(undoStack));
364
+ this.guests.add(guest);
365
+ this.opts.onPeerJoined(peer);
366
+ ws.onmessage = ev => {
367
+ if (this.closed || typeof ev.data !== 'string')
368
+ return;
369
+ let req;
370
+ try {
371
+ req = JSON.parse(ev.data);
372
+ }
373
+ catch (_a) {
374
+ return;
375
+ }
376
+ if (!req || typeof req !== 'object' || typeof req.command !== 'string')
377
+ return;
378
+ if (req.command === 'Presence')
379
+ return this.presence(guest, req, ev.data.length);
380
+ void this.command(guest, req);
381
+ };
382
+ ws.onclose = () => this.leave(guest);
383
+ ws.onerror = () => this.leave(guest);
384
+ }
385
+ /** A guest is gone: the others and the page are told. */
386
+ leave(guest) {
387
+ if (!this.guests.delete(guest))
388
+ return;
389
+ const left = JSON.stringify({ command: 'Presence', channel: 'leave', peerId: guest.peer.peerId, data: {} });
390
+ for (const other of this.guests)
391
+ this.raw(other, left);
392
+ this.opts.onPeerLeft(guest.peer);
393
+ this.opts.onPresence({ channel: 'leave', peerId: guest.peer.peerId, data: {} });
394
+ }
395
+ /** A guest's presence frame: kept for those who join later and relayed to everyone else, as a server does. */
396
+ presence(guest, frame, bytes) {
397
+ const channel = typeof frame.channel === 'string' ? frame.channel : '';
398
+ const data = frame.data;
399
+ if (!channel || bytes > PRESENCE_MAX_BYTES || !data || typeof data !== 'object' || Array.isArray(data))
400
+ return;
401
+ if (RESERVED_CHANNELS.has(channel))
402
+ return;
403
+ guest.presence.set(channel, data);
404
+ const text = JSON.stringify({ command: 'Presence', channel, peerId: guest.peer.peerId, data });
405
+ for (const other of this.guests)
406
+ if (other !== guest)
407
+ this.raw(other, text);
408
+ this.opts.onPresence({ channel, peerId: guest.peer.peerId, data });
409
+ }
410
+ /** A guest's command: answered here (emission config, what a guest may not do), or run on the page's engine. */
411
+ async command(guest, req) {
412
+ const name = req.command;
413
+ const answer = (result) => this.raw(guest, JSON.stringify({ command: 'Result', _from_: name, _transactionID_: req.transactionID, result }));
414
+ if (name === 'GetEmissionConfig')
415
+ return answer(Object.assign({}, guest.config));
416
+ if (name === 'SetEmissionConfig') {
417
+ const wanted = req.config && typeof req.config === 'object' ? req.config : {};
418
+ for (const [key, value] of Object.entries(wanted)) {
419
+ if (key in DEFAULT_EMISSION && typeof value === typeof DEFAULT_EMISSION[key])
420
+ guest.config[key] = value;
421
+ }
422
+ return answer(Object.assign({}, guest.config));
423
+ }
424
+ if (name === 'CreateInvite' || name === 'RevokeInvite')
425
+ return this.raw(guest, JSON.stringify(errorResult(req, `${name}: only the host of a session can do that, and this connection joined it by invite.`)));
426
+ try {
427
+ this.send(req, await this.opts.execute(req), guest);
428
+ }
429
+ catch (err) {
430
+ this.raw(guest, JSON.stringify(errorResult(req, err instanceof Error ? err.message : String(err))));
431
+ }
432
+ }
433
+ /** One engine reply, to everyone it concerns, each in the form its connection asked for. */
434
+ send(req, res, origin) {
435
+ const read = READS.has(String(req.command));
436
+ // A pull concerns only the one who asked; the page's own are its own.
437
+ const recipients = read ? (origin && this.guests.has(origin) ? [origin] : []) : Array.from(this.guests);
438
+ if (!recipients.length)
439
+ return;
440
+ const p = pieces(req, res);
441
+ const head = { _from_: p.from, _transactionID_: p.tx };
442
+ const version = { version: 11 };
443
+ let patchFrames = null;
444
+ let graphicFrames = null;
445
+ for (const guest of recipients) {
446
+ const cfg = guest.config;
447
+ const result = Object.assign({}, p.result);
448
+ if (read) {
449
+ result.structure = p.structure;
450
+ if (cfg.sendGraphic_Kernel !== false)
451
+ result.graphic = { containers: this.opts.containers(), properties: version };
452
+ }
453
+ else if (streams(cfg)) {
454
+ if (cfg.sendStructure !== false) {
455
+ patchFrames !== null && patchFrames !== void 0 ? patchFrames : (patchFrames = p.patches.map(ops => JSON.stringify(Object.assign(Object.assign({ command: 'StructurePatch' }, head), { structurePatch: ops }))));
456
+ for (const frame of patchFrames)
457
+ this.raw(guest, frame);
458
+ }
459
+ if (cfg.sendGraphic_Kernel !== false && p.packages.length) {
460
+ graphicFrames !== null && graphicFrames !== void 0 ? graphicFrames : (graphicFrames = p.packages.map(pkg => JSON.stringify(Object.assign(Object.assign({ command: 'Graphic' }, head), { graphic: pkg }))));
461
+ for (const frame of graphicFrames)
462
+ this.raw(guest, frame);
463
+ }
464
+ }
465
+ else if (cfg.sendGraphic_Kernel !== false && p.packages.length) {
466
+ // Bundled: what the command changed rides on its Result. The structure
467
+ // does not (it would cost a pull per command): GetTree returns it.
468
+ result.graphic = { containers: p.packages.flatMap(pkg => { var _a; return (_a = pkg === null || pkg === void 0 ? void 0 : pkg.containers) !== null && _a !== void 0 ? _a : []; }), properties: version };
469
+ }
470
+ if (cfg.sendMessages === false)
471
+ delete result.messages;
472
+ this.raw(guest, JSON.stringify(result));
473
+ // The undo history follows the Result, as on a server.
474
+ if (p.undoStack)
475
+ this.raw(guest, JSON.stringify(p.undoStack));
476
+ }
477
+ }
478
+ }
479
+ exports.SessionHost = SessionHost;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ // Session sharing — who the participants are.
3
+ //
4
+ // A session's protocol knows connections by their peer id and, on the host's
5
+ // side, by the invite they joined with. What a participant IS (which app, in
6
+ // which version, whose) it says itself, on the 'client' presence channel: once
7
+ // after connecting, and the server keeps the frame for those who join later.
8
+ // Give a WSClient an `identity` and it does so; every client collects what the
9
+ // others said (`identities`).
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.sanitizeIdentity = exports.CLIENT_CHANNEL = void 0;
12
+ /**
13
+ * The presence channel identities are published on.
14
+ *
15
+ * @advanced
16
+ * @category Session Sharing
17
+ */
18
+ exports.CLIENT_CHANNEL = 'client';
19
+ /**
20
+ * A 'client' frame is remote input: only what has the right shape gets in.
21
+ *
22
+ * @internal
23
+ */
24
+ const sanitizeIdentity = (raw) => {
25
+ if (!raw || typeof raw !== 'object')
26
+ return null;
27
+ const data = raw;
28
+ if (typeof data.app !== 'string' || !data.app)
29
+ return null;
30
+ const text = (v) => (typeof v === 'string' && v ? v.slice(0, 80) : undefined);
31
+ return {
32
+ app: data.app.slice(0, 80),
33
+ version: text(data.version),
34
+ name: text(data.name),
35
+ kind: data.kind === 'agent' ? 'agent' : 'app',
36
+ };
37
+ };
38
+ exports.sanitizeIdentity = sanitizeIdentity;