@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,646 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WSClient = void 0;
4
+ const sdkjs_1 = require("@classcad/sdkjs");
5
+ const base64_arraybuffer_1 = require("base64-arraybuffer");
6
+ const pako_1 = require("pako");
7
+ const uuid_1 = require("uuid");
8
+ const BuerliCadFacade_1 = require("../BuerliCadFacade");
9
+ const re_export_1 = require("../re-export");
10
+ const AwvNodeClient_1 = require("./AwvNodeClient");
11
+ const identity_1 = require("../session/identity");
12
+ /**
13
+ * How long graphic frames are collected before they are added to the drawing in one batch. Short enough to
14
+ * keep an interactive change immediate, long enough to merge the thousands of frames of a large model.
15
+ */
16
+ const GRAPHIC_BATCH_MS = 30;
17
+ /**
18
+ * Startup emission config of this connection, sent ONCE with SetEmissionConfig when
19
+ * the socket opens (the engine keeps the config per connection; nothing is
20
+ * attached to individual requests any more). Change it at any time with
21
+ * `setEmissionConfig()` - e.g. suppress graphics around a script and restore
22
+ * afterwards (see BuerliCadFacade.utils.withEmissionConfig).
23
+ *
24
+ * The server's WS default is full CONTENT in the neutral bundled form
25
+ * (snapshot + JSON graphic + messages on the Result frame). This set opts
26
+ * the interactive client INTO streaming - structure patches, immediate push,
27
+ * binary/compressed/multipackage graphics - which is what a live UI wants.
28
+ */
29
+ const DEFAULT_COMMAND_CONFIG = {
30
+ sendStructure: true,
31
+ sendStructure_Patch: true,
32
+ sendStructure_Immediately: true,
33
+ sendGraphic_Kernel: true,
34
+ sendGraphic_StructureObj: true,
35
+ sendGraphic_Sketch: true,
36
+ sendGraphic_Invisible: true,
37
+ sendGraphic_Compressed: true,
38
+ sendGraphic_Immediately: true,
39
+ sendGraphic_ImmediatelyBinary: true,
40
+ sendGraphic_Multipackage: true,
41
+ sendMessages: true,
42
+ sendMessages_Immediately: true,
43
+ };
44
+ /*
45
+ * Protocol (verified against ClassCAD 21.0.1-dev on localhost:9094):
46
+ * - Outgoing: raw JSON `{command, commandVersion, transactionID, ...}`
47
+ * - Incoming text: JSON frames with `{command, _from_, _transactionID_, ...}`
48
+ * May be multi-frame per request (Message, Structure, Patch frames before final Result)
49
+ * - Incoming binary: compressed SCG graphic packages (deflate-raw)
50
+ * - No Socket.IO envelopes, no BeginFrame/EndFrame wrapping
51
+ */
52
+ /**
53
+ * Connects buerli to a native ClassCAD engine through the engine's own WebSocket server (`classcad-cli worker`).
54
+ *
55
+ * The server owns the session. Without an invite it creates one for this connection, which lasts as long as the
56
+ * connection; others join it with an invite from {@link WSClient.createInvite}, passed as `config.invite`. A URL
57
+ * without a scheme (`/session`) is on the server the page came from.
58
+ *
59
+ * Connection flow:
60
+ * 1. WebSocket handshake (server auto-creates session)
61
+ * 2. SetEmissionConfig command stores this connection's emission flags on the server
62
+ * 3. `fetchTree()` retrieves initial object tree
63
+ * 4. Connection promise resolves
64
+ *
65
+ * Undo and redo: `undo()` / `redo()` send the engine's `Undo` / `Redo` commands, and the `UndoStack` frames the
66
+ * server sends after every undoable command and every undo / redo fill `cad.states` (see {@link WSClient.undo}).
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { init, WSClient } from '@classcad/client'
71
+ *
72
+ * // The native engine's own WebSocket server (classcad-cli worker)
73
+ * init(drawingId => new WSClient('ws://localhost:9094', drawingId))
74
+ * ```
75
+ * @example
76
+ * ```ts
77
+ * import { BuerliCadFacade, buildShareUrl, init, WSClient } from '@classcad/client'
78
+ * import type { SessionPeer } from '@classcad/client'
79
+ *
80
+ * // The host: a session of its own on the engine, and an invite to it
81
+ * let host!: WSClient
82
+ * init(drawingId => (host = new WSClient('ws://localhost:9094', drawingId, { identity: { app: 'my-app' } })))
83
+ * await new BuerliCadFacade().connect()
84
+ *
85
+ * host.on('peers_changed', (_client, peers: SessionPeer[]) => {
86
+ * console.log(peers.map(peer => `${peer.inviteName}: ${peer.role}`))
87
+ * })
88
+ * const invite = await host.createInvite('view', 'review')
89
+ * console.log('Join at', buildShareUrl(invite))
90
+ * // Later: the token stops working, its guests are cut off
91
+ * await host.revokeInvite(invite.invite)
92
+ * ```
93
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * import { BuerliCadFacade, init, WSClient } from '@classcad/client'
98
+ * import type { PresenceMessage } from '@classcad/client'
99
+ *
100
+ * // A guest: joins the host's session with its token
101
+ * let guest!: WSClient
102
+ * init(drawingId => (guest = new WSClient('ws://localhost:9094', drawingId, { invite: token })))
103
+ * await new BuerliCadFacade().connect()
104
+ * // With a 'view' invite the app keeps the guest from changing the model
105
+ * setReadOnly(guest.role === 'view')
106
+ *
107
+ * // The cameras follow each other
108
+ * guest.on('presence', (_client, msg: PresenceMessage) => {
109
+ * if (msg.channel === 'view') moveCamera(msg.data)
110
+ * })
111
+ * guest.sendPresence('view', myCamera())
112
+ * ```
113
+ * @category Clients
114
+ */
115
+ class WSClient extends AwvNodeClient_1.AwvNodeClient {
116
+ /** Snapshot of the guests currently sharing this session (main connection only). */
117
+ get peers() {
118
+ return Array.from(this._peers.values());
119
+ }
120
+ /** The address the client was given; one without a scheme (`/session`) is on the server the page came from. */
121
+ get url() {
122
+ return this._url;
123
+ }
124
+ /**
125
+ * @param _url - The server's WebSocket address, e.g. `ws://localhost:9094`, or a path on the page's own server.
126
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
127
+ * @param config - Sub-path, invite, identity and emission config ({@link WSClientConfig}).
128
+ */
129
+ constructor(_url, drawingId, config) {
130
+ super();
131
+ this._url = _url;
132
+ this._pending = new Map();
133
+ this._connected = false;
134
+ /**
135
+ * Graphic packages waiting to be added to the drawing. The server sends the graphic of a model as many small
136
+ * frames (thousands for a large assembly); adding each on its own updated the store once per frame. They are
137
+ * collected for a moment and added in one batch (@see flushGraphic).
138
+ */
139
+ this._graphicQueue = [];
140
+ /** The server owns the session: invites are honoured by joining with `?invite=` on the server URL. */
141
+ this.shareKind = 'invite';
142
+ // `role` and `inviteName` (from AwvNodeClient) are set from the server's
143
+ // `SessionJoined` frame when connecting with an invite. Enforcement is
144
+ // client-side for now — apps should suppress mutating commands for 'view'.
145
+ /** Guests currently sharing this session (main connection only), keyed by peerId. */
146
+ this._peers = new Map();
147
+ /** True while a full-tree resync (after a failed structure patch) is in flight. */
148
+ this._resyncing = false;
149
+ this.setDrawingId(drawingId);
150
+ this._config = config !== null && config !== void 0 ? config : {};
151
+ }
152
+ /**
153
+ * Opens the WebSocket, sets the connection's emission config, loads the structure tree and publishes `identity`.
154
+ * Rejects when the socket fails before that, or when the engine predates SetEmissionConfig.
155
+ */
156
+ connect() {
157
+ return new Promise((resolve, reject) => {
158
+ try {
159
+ const wsUrl = this.buildUrl();
160
+ this._ws = new WebSocket(wsUrl);
161
+ this._ws.binaryType = 'arraybuffer';
162
+ this._ws.onopen = () => {
163
+ this._connected = true;
164
+ // Store this connection's emission config on the server (per-connection
165
+ // config model: the engine keeps it for every following command), then
166
+ // fetch the initial object tree - the connection is not valid until
167
+ // both completed. SetEmissionConfig is a tracked request, so its reply settles
168
+ // like any other Result.
169
+ this.setEmissionConfig(Object.assign(Object.assign({}, DEFAULT_COMMAND_CONFIG), this._config.commandConfig))
170
+ .then(() => BuerliCadFacade_1.BuerliCadFacade.utils.fetchTree(this._drawingId))
171
+ .then(() => {
172
+ if (this._config.identity)
173
+ this.sendPresence(identity_1.CLIENT_CHANNEL, this._config.identity);
174
+ this.emit('connected', this, true);
175
+ this.syncState();
176
+ resolve(this);
177
+ })
178
+ .catch(e => {
179
+ console.error(e);
180
+ reject(e);
181
+ });
182
+ };
183
+ this._ws.onmessage = (ev) => {
184
+ if (ev.data instanceof ArrayBuffer) {
185
+ this.handleBinaryFrame(new Uint8Array(ev.data));
186
+ }
187
+ else if (typeof ev.data === 'string') {
188
+ this.handleTextFrame(ev.data);
189
+ }
190
+ };
191
+ this._ws.onerror = (ev) => {
192
+ this.syncState();
193
+ this.emit('conn_error', this, ev);
194
+ if (!this._connected) {
195
+ reject(ev);
196
+ }
197
+ };
198
+ this._ws.onclose = (ev) => {
199
+ const wasConnected = this._connected;
200
+ this._connected = false;
201
+ // Codes 1000 (normal) and 1005 (no status) indicate deliberate closure
202
+ const deliberate = ev.code === 1000 || ev.code === 1005;
203
+ if (!deliberate && wasConnected) {
204
+ this.emit('conn_error', this, ev.reason || `WebSocket closed with code ${ev.code}`);
205
+ }
206
+ // Graphic that arrived before the close is added, as it was before frames were batched
207
+ this.flushGraphic();
208
+ // Reject all pending requests
209
+ for (const [, pending] of this._pending) {
210
+ pending.reject(new Error('WebSocket closed'));
211
+ }
212
+ this._pending.clear();
213
+ // Presence is meaningless once disconnected.
214
+ if (this._peers.size > 0) {
215
+ this._peers.clear();
216
+ this.emit('peers_changed', this, this.peers);
217
+ }
218
+ this.clearIdentities();
219
+ this.syncState();
220
+ };
221
+ }
222
+ catch (error) {
223
+ reject(error);
224
+ }
225
+ });
226
+ }
227
+ /** Closes the WebSocket; the server ends the session if this connection made it. No `conn_error` is emitted. */
228
+ disconnect() {
229
+ return new Promise((resolve, reject) => {
230
+ try {
231
+ if (this._ws) {
232
+ this._ws.onclose = null;
233
+ this._ws.close();
234
+ this._ws = undefined;
235
+ }
236
+ this._connected = false;
237
+ this._pending.clear();
238
+ this.flushGraphic();
239
+ this.syncState();
240
+ resolve(this);
241
+ }
242
+ catch (error) {
243
+ reject(error);
244
+ }
245
+ });
246
+ }
247
+ /**
248
+ * Sends `command` to the server and resolves to its reply, once the server's `Result` frame arrives. Structure,
249
+ * graphic and messages that come before it go into the drawing on the way. Rejects with the reply when it carries
250
+ * an error, and when the socket closes first.
251
+ *
252
+ * @param _name - Not used by this client.
253
+ * @param command - The request.
254
+ */
255
+ requestByName(_name, command) {
256
+ return new Promise((resolve, reject) => {
257
+ const transactionID = (0, uuid_1.v4)();
258
+ try {
259
+ this._pending.set(transactionID, { resolve, reject, messages: [], maxLevel: undefined });
260
+ // Send the command as raw JSON — the Drogon server routes via CommandFactory
261
+ // based on the `command` field. commandVersion: 'v1' selects CommandProcessorJsonV1.
262
+ // Emission flags are NOT attached: the server keeps them per connection
263
+ // (set on connect and via setEmissionConfig); a `config` field only travels with
264
+ // the SetEmissionConfig command itself.
265
+ this.sendCommand(Object.assign(Object.assign({}, command), { commandVersion: 'v1', transactionID }));
266
+ }
267
+ catch (error) {
268
+ this._pending.delete(transactionID);
269
+ reject(error);
270
+ }
271
+ });
272
+ }
273
+ request(command) {
274
+ return this.requestByName('send', command);
275
+ }
276
+ /**
277
+ * Mints an invite token for this connection's session (multi-client invite
278
+ * model). The returned token can be handed to other clients, which join via
279
+ * `new WSClient(url, id, { invite })`. Server-side this is a controller-level
280
+ * meta command; it is rejected when this connection itself joined via invite.
281
+ *
282
+ * `name` is optional and purely for display (e.g. "workgroup"); it has no
283
+ * effect on behavior. Multiple tokens can be minted (e.g. a named group token
284
+ * plus an unnamed one-off token). The examples of {@link WSClient} show the host and a guest.
285
+ *
286
+ * @param role - What guests with the invite may do: `'edit'` (default) or `'view'`.
287
+ * @param name - A name to show for the invite.
288
+ */
289
+ createInvite(role = 'edit', name = '') {
290
+ return this.requestByName('createInvite', { command: 'CreateInvite', role, name }).then(sr => {
291
+ const r = sr.result;
292
+ const invite = { invite: r.invite, role: r.role, name: r.name, kind: 'invite' };
293
+ this.trackInvite(invite);
294
+ return invite;
295
+ });
296
+ }
297
+ /**
298
+ * Revokes a previously minted invite token. Any guests currently connected
299
+ * with that token are immediately disconnected, and the token can no longer
300
+ * be used to join. Owner-only; rejected on connections that joined via invite.
301
+ *
302
+ * @param invite - The invite token.
303
+ * @returns The token, whether it was revoked, and how many guests were cut off.
304
+ */
305
+ revokeInvite(invite) {
306
+ return this.requestByName('revokeInvite', { command: 'RevokeInvite', invite }).then(sr => {
307
+ this.untrackInvite(invite);
308
+ return sr.result;
309
+ });
310
+ }
311
+ /**
312
+ * Fire-and-forget ephemeral presence broadcast to the session's siblings
313
+ * (e.g. this client's camera viewpoint on the 'view' channel). Handled by a
314
+ * server fast-path that bypasses the command queue entirely; the server
315
+ * stamps the sender's peerId and fans the frame out. Siblings receive it via
316
+ * the `presence` event; late joiners get the last frame per channel as a
317
+ * snapshot. NOTE: the server matches on the exact serialized prefix
318
+ * `{"command":"Presence"`, so `command` must stay the first key here.
319
+ *
320
+ * The guest example of {@link WSClient} shares the camera this way.
321
+ *
322
+ * @param channel - The channel, e.g. `'view'` for a camera viewpoint.
323
+ * @param data - The payload, sent as it is. The server drops a frame larger than 8 KB.
324
+ */
325
+ sendPresence(channel, data) {
326
+ this.sendCommand({ command: 'Presence', channel, data });
327
+ }
328
+ /**
329
+ * Goes back to the state before the current one of the session's undo history, or to
330
+ * `options.state`. The server records a state after every command sent with
331
+ * `options.undoable` (api-js marks the modelling calls) and answers with the frames of the
332
+ * change and an UndoStack frame, which updates `cad.states` of every client in the session.
333
+ * The result is the history afterwards: `{ stack, current }`.
334
+ */
335
+ undo(options) {
336
+ return this.requestByName('undo', Object.assign({ command: 'Undo' }, ((options === null || options === void 0 ? void 0 : options.state) ? { state: options.state } : {})));
337
+ }
338
+ /** Goes forward to the state after the current one, or to `options.state` (see undo). */
339
+ redo(options) {
340
+ return this.requestByName('redo', Object.assign({ command: 'Redo' }, ((options === null || options === void 0 ? void 0 : options.state) ? { state: options.state } : {})));
341
+ }
342
+ // ---------------------------------------------------------------------------
343
+ // URL construction
344
+ // ---------------------------------------------------------------------------
345
+ buildUrl() {
346
+ var _a;
347
+ const path = (_a = this._config.path) !== null && _a !== void 0 ? _a : '/';
348
+ // A URL without a scheme ('/session') is on the server the page came from:
349
+ // an app served by the engine's host needs no address built into it.
350
+ const absolute = this._url.startsWith('/') && typeof window !== 'undefined'
351
+ ? `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}${this._url}`
352
+ : this._url;
353
+ const base = absolute.replace(/\/+$/, '');
354
+ const normalizedPath = path.startsWith('/') ? path : `/${path}`;
355
+ let url = `${base}${normalizedPath}`;
356
+ // Query params are the only channel available to browser WebSocket
357
+ // clients (no custom headers on the upgrade). Without an invite the
358
+ // server creates a fresh main session for this connection.
359
+ if (this._config.invite) {
360
+ const separator = url.includes('?') ? '&' : '?';
361
+ url += `${separator}invite=${encodeURIComponent(this._config.invite)}`;
362
+ }
363
+ return url;
364
+ }
365
+ // ---------------------------------------------------------------------------
366
+ // Outgoing
367
+ // ---------------------------------------------------------------------------
368
+ sendCommand(msg) {
369
+ if (this._ws && this._ws.readyState === WebSocket.OPEN) {
370
+ this._ws.send(JSON.stringify(msg));
371
+ }
372
+ }
373
+ // ---------------------------------------------------------------------------
374
+ // Incoming — binary frames
375
+ //
376
+ // With sendGraphic_ImmediatelyBinary the Drogon server raw-deflates the whole
377
+ // text envelope (`{command: "Graphic", _from_, _transactionID_, graphic, …}`)
378
+ // into one binary frame. Inflate, parse, then run it through the same handler
379
+ // the text path uses — which knows how to deal with compressed inner fields.
380
+ // ---------------------------------------------------------------------------
381
+ handleBinaryFrame(data) {
382
+ try {
383
+ const inflated = (0, pako_1.inflate)(data, { raw: true, to: 'string' });
384
+ const frame = JSON.parse(inflated);
385
+ if (Array.isArray(frame)) {
386
+ for (const f of frame)
387
+ this.handleFrame(f);
388
+ }
389
+ else {
390
+ this.handleFrame(frame);
391
+ }
392
+ }
393
+ catch (e) {
394
+ console.warn('[WSClient] failed to decode binary frame', e);
395
+ }
396
+ }
397
+ // ---------------------------------------------------------------------------
398
+ // Incoming — text frames
399
+ //
400
+ // The Drogon server (CommandProcessorJsonV1) sends responses as JSON text
401
+ // frames. With *_Immediately flags, a single request may produce multiple
402
+ // frames before the final `command: "Result"` frame:
403
+ //
404
+ // { command: "Message", _from_, _transactionID_, messages, maxLevel }
405
+ // { command: "Structure", _from_, _transactionID_, structure }
406
+ // { command: "Patch", _from_, _transactionID_, structurePatch }
407
+ // { command: "Graphic", _from_, _transactionID_, graphic }
408
+ // { command: "Result", _from_, _transactionID_, result, ... } ← final
409
+ //
410
+ // All frames share the same `_transactionID_`.
411
+ // ---------------------------------------------------------------------------
412
+ handleTextFrame(raw) {
413
+ let data;
414
+ try {
415
+ data = JSON.parse(raw);
416
+ }
417
+ catch (_a) {
418
+ return;
419
+ }
420
+ if (Array.isArray(data)) {
421
+ for (const item of data) {
422
+ this.handleFrame(item);
423
+ }
424
+ }
425
+ else {
426
+ this.handleFrame(data);
427
+ }
428
+ }
429
+ /**
430
+ * When the server is configured with `sendStructure_Compressed` /
431
+ * `sendGraphic_Compressed`, the corresponding payload field arrives as a
432
+ * base64 string of raw-deflated JSON instead of an inline object. Decode it
433
+ * back to the structured form before handing it to the drawing APIs.
434
+ */
435
+ decodeMaybeCompressed(value) {
436
+ if (value === undefined || value === null)
437
+ return undefined;
438
+ if (typeof value !== 'string')
439
+ return value;
440
+ try {
441
+ const bytes = new Uint8Array((0, base64_arraybuffer_1.decode)(value));
442
+ const inflated = (0, pako_1.inflate)(bytes, { raw: true, to: 'string' });
443
+ return JSON.parse(inflated);
444
+ }
445
+ catch (e) {
446
+ console.warn('[WSClient] failed to inflate compressed payload', e);
447
+ return undefined;
448
+ }
449
+ }
450
+ /** Adds the queued graphic packages to the drawing in one call. */
451
+ flushGraphic() {
452
+ var _a;
453
+ if (this._graphicFlushTimer !== undefined) {
454
+ clearTimeout(this._graphicFlushTimer);
455
+ this._graphicFlushTimer = undefined;
456
+ }
457
+ if (this._graphicQueue.length === 0)
458
+ return;
459
+ const packages = this._graphicQueue;
460
+ this._graphicQueue = [];
461
+ (_a = (0, sdkjs_1.getDrawing)(this._drawingId)) === null || _a === void 0 ? void 0 : _a.api.graphic.addPackages(packages);
462
+ }
463
+ handleFrame(data) {
464
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
465
+ // Sent by the server as the first frame after a successful invite join.
466
+ // Carries the role attached to the invite; the sessionId is never revealed.
467
+ if (data.command === 'SessionJoined') {
468
+ this.role = data.role === 'view' ? 'view' : 'edit';
469
+ this.inviteName = (_a = data.inviteName) !== null && _a !== void 0 ? _a : '';
470
+ this.emit('session_joined', this, this.role, this.inviteName);
471
+ return;
472
+ }
473
+ // Ephemeral presence from a session sibling (camera viewpoints etc.), or
474
+ // the 'leave' channel when a peer disconnects. Apps subscribe via
475
+ // client.on('presence', (client, msg: PresenceMessage) => ...).
476
+ if (data.command === 'Presence') {
477
+ const msg = { channel: (_b = data.channel) !== null && _b !== void 0 ? _b : '', peerId: (_c = data.peerId) !== null && _c !== void 0 ? _c : '', data: (_d = data.data) !== null && _d !== void 0 ? _d : {} };
478
+ this.noteIdentity(msg);
479
+ this.emit('presence', this, msg);
480
+ return;
481
+ }
482
+ // Presence events, delivered only to the main (owner) connection: a guest
483
+ // joined or left the shared session. A GUI can use these to show who is
484
+ // connected (e.g. dots per invite token).
485
+ if (data.command === 'PeerJoined') {
486
+ const peer = {
487
+ peerId: (_e = data.peerId) !== null && _e !== void 0 ? _e : '',
488
+ invite: (_f = data.invite) !== null && _f !== void 0 ? _f : '',
489
+ inviteName: (_g = data.inviteName) !== null && _g !== void 0 ? _g : '',
490
+ role: data.role === 'view' ? 'view' : 'edit',
491
+ };
492
+ this._peers.set(peer.peerId, peer);
493
+ this.emit('peer_joined', this, peer);
494
+ this.emit('peers_changed', this, this.peers);
495
+ return;
496
+ }
497
+ // The session's undo history changed (an undoable command, an undo / redo, by this client or
498
+ // a sibling), or this guest just joined: take it over into cad.states.
499
+ if (data.command === 'UndoStack') {
500
+ this.applyUndoStack(data);
501
+ return;
502
+ }
503
+ if (data.command === 'PeerLeft') {
504
+ const peerId = (_h = data.peerId) !== null && _h !== void 0 ? _h : '';
505
+ const peer = this._peers.get(peerId);
506
+ this._peers.delete(peerId);
507
+ this.emit('peer_left', this, peer !== null && peer !== void 0 ? peer : { peerId, invite: (_j = data.invite) !== null && _j !== void 0 ? _j : '', inviteName: (_k = data.inviteName) !== null && _k !== void 0 ? _k : '', role: 'edit' });
508
+ this.emit('peers_changed', this, this.peers);
509
+ return;
510
+ }
511
+ const transactionID = data._transactionID_;
512
+ const pending = transactionID ? this._pending.get(transactionID) : undefined;
513
+ const drawing = (0, sdkjs_1.getDrawing)(this._drawingId);
514
+ // Queued graphic goes into the drawing before a structure change or a settled request, so both keep the
515
+ // order in which the server sent them.
516
+ if (data.structure || data.structurePatch || data.command === 'Result') {
517
+ this.flushGraphic();
518
+ }
519
+ // --- Apply side-effects immediately regardless of frame type ---
520
+ // Full structure snapshot (object inline, or base64 raw-deflate JSON when sendStructure_Compressed)
521
+ if (data.structure) {
522
+ const structure = this.decodeMaybeCompressed(data.structure);
523
+ if (structure)
524
+ drawing.api.structure.set(structure);
525
+ }
526
+ // Structure patches: array of JSON Patch ops, or base64 raw-deflate JSON when sendStructure_Compressed
527
+ if (data.structurePatch) {
528
+ const patches = this.decodeMaybeCompressed(data.structurePatch);
529
+ if (patches && !drawing.api.structure.applyPatches(patches)) {
530
+ // Patches are relative to a shared per-session baseline; a failed
531
+ // block means this client's tree has diverged and would stay wrong
532
+ // forever. Recover by re-fetching the full tree once.
533
+ this.resyncStructure();
534
+ }
535
+ }
536
+ // Graphic package: object inline, or base64 raw-deflate JSON when sendGraphic_Compressed. Collected and
537
+ // added in batches; a Result frame adds everything at once, so the request settles with its graphic.
538
+ if (data.graphic) {
539
+ const pkg = this.decodeMaybeCompressed(data.graphic);
540
+ if (pkg) {
541
+ this._graphicQueue.push(pkg);
542
+ if (data.command === 'Result') {
543
+ this.flushGraphic();
544
+ }
545
+ else if (this._graphicFlushTimer === undefined) {
546
+ this._graphicFlushTimer = setTimeout(() => this.flushGraphic(), GRAPHIC_BATCH_MS);
547
+ }
548
+ }
549
+ }
550
+ // Accumulate messages from intermediate Message frames
551
+ if (pending && data.messages) {
552
+ for (const msg of data.messages) {
553
+ pending.messages.push(msg);
554
+ if (pending.maxLevel === undefined || msg.level > pending.maxLevel) {
555
+ pending.maxLevel = msg.level;
556
+ }
557
+ }
558
+ }
559
+ // Inflate stream data if present (base64-encoded deflate-raw)
560
+ let streamData;
561
+ if (data.streamData) {
562
+ streamData = {};
563
+ for (const [key, value] of Object.entries(data.streamData)) {
564
+ try {
565
+ const decoded = (0, base64_arraybuffer_1.decode)(value);
566
+ streamData[key] = (0, pako_1.inflate)(new Uint8Array(decoded), { raw: true });
567
+ }
568
+ catch (_o) {
569
+ streamData[key] = value;
570
+ }
571
+ }
572
+ }
573
+ // --- Settle the pending request on the final Result frame ---
574
+ if (data.command === 'Result' && pending && transactionID) {
575
+ this._pending.delete(transactionID);
576
+ let jobResult = data.result;
577
+ if (typeof ((_l = data.result) === null || _l === void 0 ? void 0 : _l.result) !== 'undefined') {
578
+ jobResult = data.result.result;
579
+ }
580
+ // Merge any messages from the Result frame with previously accumulated ones
581
+ const resultMessages = (_m = data.messages) !== null && _m !== void 0 ? _m : [];
582
+ const allMessages = [...pending.messages];
583
+ for (const msg of resultMessages) {
584
+ // Avoid duplicates if messages were already sent via intermediate frames
585
+ if (!allMessages.some(m => m.message === msg.message && m.level === msg.level)) {
586
+ allMessages.push(msg);
587
+ }
588
+ }
589
+ // The Drogon server sends INFO-level trace messages (COMMANDCALL, RETURN)
590
+ // for every command. These are not present in SocketIO/WASM server responses
591
+ // and must be excluded so that consumer code checking messages.length === 0
592
+ // for successful commands works consistently across all transports.
593
+ const messages = allMessages.filter(m => m.level > re_export_1.MessageLevel.info);
594
+ let maxLevel;
595
+ for (const msg of messages) {
596
+ if (maxLevel === undefined || msg.level > maxLevel) {
597
+ maxLevel = msg.level;
598
+ }
599
+ }
600
+ const sr = {
601
+ result: jobResult,
602
+ maxLevel,
603
+ messages,
604
+ streamData,
605
+ };
606
+ const hadError = typeof sr.maxLevel !== 'undefined' && sr.maxLevel >= re_export_1.MessageLevel.error;
607
+ if (hadError) {
608
+ pending.reject(sr);
609
+ }
610
+ else {
611
+ pending.resolve(sr);
612
+ }
613
+ }
614
+ }
615
+ /**
616
+ * Recovers from a structure patch that failed to apply: fetches the full
617
+ * tree from the server. The GetTree result carries the complete structure
618
+ * and graphic, so the drawing heals entirely — and since the server
619
+ * broadcasts result frames to all session siblings, any sibling that
620
+ * diverged the same way heals along with it. Guarded so a burst of failing
621
+ * patches triggers only one round trip.
622
+ */
623
+ resyncStructure() {
624
+ if (this._resyncing)
625
+ return;
626
+ this._resyncing = true;
627
+ console.warn('[WSClient] structure patch failed to apply — resyncing the full tree');
628
+ BuerliCadFacade_1.BuerliCadFacade.utils
629
+ .fetchTree(this._drawingId)
630
+ .catch(e => console.error('[WSClient] structure resync failed', e))
631
+ .finally(() => {
632
+ this._resyncing = false;
633
+ });
634
+ }
635
+ // ---------------------------------------------------------------------------
636
+ // State
637
+ // ---------------------------------------------------------------------------
638
+ syncState() {
639
+ var _a, _b, _c, _d, _e;
640
+ const dr = (0, sdkjs_1.getDrawing)(this._drawingId);
641
+ const isOpen = ((_a = this._ws) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN;
642
+ (_c = (_b = dr === null || dr === void 0 ? void 0 : dr.api) === null || _b === void 0 ? void 0 : _b.cad) === null || _c === void 0 ? void 0 : _c.setActive(isOpen);
643
+ (_e = (_d = dr === null || dr === void 0 ? void 0 : dr.api) === null || _d === void 0 ? void 0 : _d.cad) === null || _e === void 0 ? void 0 : _e.setConnected(isOpen);
644
+ }
645
+ }
646
+ exports.WSClient = WSClient;