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

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 +60 -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,84 @@
1
+ import { DrawingID } from '@classcad/sdkjs';
2
+ import { RedoOptions, ServerRequest, ServerResponse, UndoOptions } from '../types/ComClient';
3
+ import { AwvNodeClient } from './AwvNodeClient';
4
+ /**
5
+ * The Socket.IO events of the ClassCAD server's protocol.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare enum SocketIOEvent {
10
+ CONNECT = "connect",
11
+ INIT = "init",
12
+ PERMISSION = "permission",
13
+ CONNECT_ERROR = "connect_error",
14
+ CONNECT_TIMEOUT = "connect_timeout",
15
+ SEND = "send",
16
+ BINARY = "binary",
17
+ JSON = "json",
18
+ UNDO = "undo",
19
+ REDO = "redo"
20
+ }
21
+ /**
22
+ * Connects the SDK to a ClassCAD server (`classcad-socketio`) over Socket.IO.
23
+ *
24
+ * The server runs the engine and keeps the drawing's undo history, so `undo`, `redo` and `undoable` requests work
25
+ * with this client. It cannot share its session (`shareKind` is null). When the connection drops and comes back, the
26
+ * client reconnects the drawing, recalculates it and emits `reconnect`.
27
+ *
28
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { init, SocketIOClient } from '@classcad/client'
33
+ *
34
+ * // The ClassCAD server (classcad-socketio); a connection that drops is picked up again
35
+ * init(drawingId => {
36
+ * const client = new SocketIOClient('ws://localhost:9091', drawingId)
37
+ * client.on('conn_error', () => notify('The connection to ClassCAD is lost'))
38
+ * client.on('reconnect', () => notify('Connected again; the model was recalculated'))
39
+ * return client
40
+ * })
41
+ * ```
42
+ * @category Clients
43
+ */
44
+ export declare class SocketIOClient extends AwvNodeClient {
45
+ private url;
46
+ private _socket;
47
+ private _version;
48
+ private _transactions;
49
+ /**
50
+ * @param url - The server's address, e.g. `ws://localhost:9091`.
51
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
52
+ */
53
+ constructor(url: string, drawingId: DrawingID);
54
+ /**
55
+ * Opens the connection, registers the drawing with the server and loads its structure tree. Rejects on a
56
+ * connection error or timeout.
57
+ */
58
+ connect(): Promise<SocketIOClient>;
59
+ /** Closes the connection to the server. */
60
+ disconnect(): Promise<AwvNodeClient>;
61
+ /**
62
+ * Sends `command` to the server as the event `name` and resolves to the reply once all its frames have arrived.
63
+ * Structure patches and graphic go into the drawing on the way. Rejects with the reply when it carries an error.
64
+ *
65
+ * @param name - The server's event: `send` for requests, `undo`, `redo`.
66
+ * @param command - The request.
67
+ */
68
+ requestByName(name: string, command?: ServerRequest): Promise<ServerResponse>;
69
+ protected request(command: ServerRequest): Promise<ServerResponse>;
70
+ /**
71
+ * Steps back in the drawing's undo history on the server: to `options.state` when given.
72
+ *
73
+ * @param options - The state to go back to, and options for the server.
74
+ */
75
+ undo(options?: UndoOptions): Promise<ServerResponse>;
76
+ /**
77
+ * Steps forward in the drawing's undo history on the server: to `options.state` when given.
78
+ *
79
+ * @param options - The state to go forward to, and options for the server.
80
+ */
81
+ redo(options?: RedoOptions): Promise<ServerResponse>;
82
+ protected ack(): void;
83
+ protected syncState(): void;
84
+ }
@@ -0,0 +1,56 @@
1
+ import { EventEmitter } from 'events';
2
+ import { StrictEventEmitter } from 'strict-event-emitter-types';
3
+ import { IGraphicPackage, IStructurePatch } from '../re-export';
4
+ import { ServerError, ServerMessage, ServerResult } from '../types/ComClient';
5
+ type Command = 'Blob' | 'Result' | 'Endpoint' | 'Patch' | 'ErrorMessage' | 'InfoMessage';
6
+ type ResultFrom = 'Execute' | 'GetTree' | 'ip' | 'EndFrame' | 'BeginFrame' | string;
7
+ type TransactionBlob = {
8
+ command: 'Blob';
9
+ type: 'Binary';
10
+ data: IGraphicPackage;
11
+ size: number;
12
+ };
13
+ type TransactionResult = ServerResult & {
14
+ command: 'Result';
15
+ from: ResultFrom;
16
+ };
17
+ type TransactionResponse = {
18
+ results: TransactionResult[];
19
+ patches: IStructurePatch[];
20
+ blobs: TransactionBlob[];
21
+ errors: ServerError[];
22
+ messages: ServerMessage[];
23
+ };
24
+ type TransactionEvents = {
25
+ result: TransactionResult;
26
+ patches: IStructurePatch[];
27
+ blob: TransactionBlob;
28
+ error: ServerError;
29
+ finished: TransactionResponse;
30
+ message: ServerMessage;
31
+ };
32
+ type TransactionEmitter = StrictEventEmitter<EventEmitter, TransactionEvents>;
33
+ declare const Transaction_base: new () => TransactionEmitter;
34
+ export declare class Transaction extends Transaction_base {
35
+ transactionID: string;
36
+ protected bytes: number;
37
+ protected bytesUncompressed: number;
38
+ protected time: number;
39
+ results: TransactionResult[];
40
+ patches: IStructurePatch[];
41
+ blobs: TransactionBlob[];
42
+ errors: ServerError[];
43
+ messages: ServerMessage[];
44
+ constructor(transactionID?: string);
45
+ handleData(data: any): void;
46
+ protected handleItem(object: ServerResult & {
47
+ from: ResultFrom;
48
+ command: Command;
49
+ type: string;
50
+ transactionID: string;
51
+ data?: any;
52
+ ops?: any;
53
+ attributes?: any;
54
+ }): void;
55
+ }
56
+ export {};
@@ -0,0 +1,239 @@
1
+ import { DrawingID } from '@classcad/sdkjs';
2
+ import { Remote } from 'comlink';
3
+ import { ScgGraphicPackage } from '../re-export';
4
+ import { RedoOptions, ServerRequest, ServerResponse, UndoOptions } from '../types/ComClient';
5
+ import { AwvNodeClient } from './AwvNodeClient';
6
+ import { ClientIdentity } from '../session/identity';
7
+ import { SessionInvite, SessionPeer, SessionRole, ShareKind } from '../session/types';
8
+ import { EngineKey } from './engineKey';
9
+ /**
10
+ * Where a page that hosts its own engine is joined: the session address of a ClassCAD MCP on the same machine.
11
+ *
12
+ * The default of the {@link WASMClient} option `sessionUrl`. 127.0.0.1 on
13
+ * purpose: `localhost` may be IPv6 in the browser and IPv4 in the MCP.
14
+ *
15
+ * @category Session Sharing
16
+ */
17
+ export declare const DEFAULT_SESSION_URL = "ws://127.0.0.1:9098/session";
18
+ /**
19
+ * The Emscripten module of the WASM engine.
20
+ *
21
+ * @internal
22
+ */
23
+ export type ClassCADWasm = EmscriptenModule & {
24
+ FS: typeof FS;
25
+ init: (json: string) => void;
26
+ execute: (json: string, module: ClassCADWasm, onSend: (module: ClassCADWasm, message: string) => void, onSendBinary: (module: ClassCADWasm, ptrPayload: number, len: number) => void) => void;
27
+ };
28
+ /**
29
+ * What the engine's worker is started with: the key and whether the engine logs to the console.
30
+ *
31
+ * @internal
32
+ */
33
+ export type WASMClientConfig = {
34
+ cclasses?: {
35
+ type: 'classcadkey';
36
+ key: string;
37
+ };
38
+ logToConsole?: boolean;
39
+ };
40
+ declare class classCadWorkerApi {
41
+ init(url: string, config?: Partial<WASMClientConfig> & {
42
+ siteLocation: Location;
43
+ }): Promise<void>;
44
+ execute(command: ServerRequest): Promise<{
45
+ messages: ServerResponse[];
46
+ binaryMessages: ScgGraphicPackage[];
47
+ }>;
48
+ }
49
+ /**
50
+ * Runs the ClassCAD engine in the browser, as WebAssembly in a web worker, and hosts its session for guests.
51
+ *
52
+ * `connect` gets the engine's key first: from `token` (fetched from ClassCAD, cached in `localStorage` and renewed),
53
+ * `getKey` or `classcadKey` (see {@link resolveEngineKey}). Then it loads the engine from `url`, by default from
54
+ * ClassCAD's CDN in the version this package is made for, and starts it in a worker. A public access token
55
+ * (`ccpk_…`, from classcad.ch/account) may sit in a web page; it yields keys for the account's registered domains
56
+ * and for localhost.
57
+ *
58
+ * Nobody can connect to a page, so the page hosts its session itself. With the first invite
59
+ * ({@link WASMClient.createInvite}) it offers its invites at `sessionUrl`, a ClassCAD MCP on the same machine or the
60
+ * ClassCAD share relay, where guests join with `?invite=<token>` as they would join a server. Undo and redo are not
61
+ * supported by this client.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import { init, WASMClient } from '@classcad/client'
66
+ *
67
+ * // A public access token from classcad.ch/account; it works on the account's domains and on localhost
68
+ * init(drawingId => new WASMClient(drawingId, { token: 'ccpk_…' }))
69
+ * ```
70
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * import { init, WASMClient } from '@classcad/client'
75
+ * import type { EngineKey } from '@classcad/client'
76
+ *
77
+ * // The app's own sign-in: its server hands signed-in users a key (see requestEngineKey)
78
+ * init(
79
+ * drawingId =>
80
+ * new WASMClient(drawingId, {
81
+ * getKey: async () => {
82
+ * const res = await fetch('/api/engine-key', { headers: { authorization: `Bearer ${await idToken()}` } })
83
+ * if (!res.ok) throw new Error(`No engine key: ${res.status}`)
84
+ * return (await res.json()) as EngineKey
85
+ * },
86
+ * }),
87
+ * )
88
+ * ```
89
+ * @category Clients
90
+ */
91
+ export declare class WASMClient extends AwvNodeClient {
92
+ protected service: Remote<classCadWorkerApi> | undefined;
93
+ private config;
94
+ private keySource;
95
+ private worker;
96
+ private url;
97
+ /** Invites are honoured: guests join at `sessionUrl` with `?invite=<token>`. */
98
+ readonly shareKind: ShareKind;
99
+ private sessionUrl;
100
+ private sessionAuth;
101
+ private identity;
102
+ private host;
103
+ /** The engine's last UndoStack frame: what a guest gets when it joins. */
104
+ private undoStack;
105
+ /** The guests in this page's session. */
106
+ get peers(): SessionPeer[];
107
+ /**
108
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
109
+ * @param config - The engine's key (`token`, `getKey` or `classcadKey`), where the engine is loaded from, and the
110
+ * session's settings.
111
+ */
112
+ constructor(drawingId: DrawingID, config: {
113
+ /** A ClassCAD access token (`ccpk_…`, from classcad.ch/account): the engine's key is fetched, cached and renewed with it. */
114
+ token?: string;
115
+ /** Or the app supplies the key itself, for example from its own sign-in. */
116
+ getKey?: () => Promise<string | EngineKey>;
117
+ /** The token exchange, if not ClassCAD's (see {@link DEFAULT_KEY_URL}). */
118
+ keyUrl?: string;
119
+ /** An engine key itself; when given, nothing is fetched. */
120
+ classcadKey?: string;
121
+ /**
122
+ * Where the engine's files are (`ClassCADWasmWorker.js` and the engine), when they are hosted elsewhere. A path
123
+ * is taken on the page's origin. By default ClassCAD's CDN, in the engine version this package is made for.
124
+ */
125
+ url?: string;
126
+ /** Lets the engine log to the browser console. Default `false`. */
127
+ logToConsole?: boolean;
128
+ /**
129
+ * Where guests of this page's session join: the session address of a local ClassCAD MCP (default
130
+ * {@link DEFAULT_SESSION_URL}), or of the ClassCAD share relay (`wss://<relay>/session`), which wants
131
+ * `sessionAuth`.
132
+ */
133
+ sessionUrl?: string;
134
+ /**
135
+ * The sign-in the relay takes an invite with: a Firebase ID token of the reader's ClassCAD account, a
136
+ * fresh one when `refresh` is set.
137
+ */
138
+ sessionAuth?: (refresh: boolean) => Promise<string | null | undefined>;
139
+ /** Who this client is, for the guests of its session. */
140
+ identity?: ClientIdentity;
141
+ });
142
+ /**
143
+ * Gets the engine's key, loads the engine's worker from `url` and starts the engine. Rejects with an
144
+ * {@link EngineKeyError} when there is no key, and when the engine cannot be loaded.
145
+ */
146
+ connect(): Promise<WASMClient>;
147
+ /** Ends the session (guests are closed, invites taken back) and terminates the engine's worker. */
148
+ disconnect(): Promise<AwvNodeClient>;
149
+ /**
150
+ * Runs one raw engine command: applies what the engine emitted for it
151
+ * (structure, patches, graphic) to the drawing's store and returns it as it
152
+ * came. Every command takes this way, the page's own and a guest's — the
153
+ * page's view follows both.
154
+ */
155
+ private run;
156
+ /** Like run(), for the page itself: its guests get the reply too, and stream data comes back inflated. */
157
+ private executeRaw;
158
+ /**
159
+ * Runs `command` on the engine and resolves to its reply. What the command changed (structure, graphic) goes into
160
+ * the drawing, and to the session's guests. Rejects with the reply when it carries an error.
161
+ *
162
+ * @param name - Not used by this client.
163
+ * @param command - The request.
164
+ */
165
+ requestByName(name: string, command?: ServerRequest): Promise<ServerResponse>;
166
+ protected request(command: ServerRequest): Promise<ServerResponse>;
167
+ /** The page's session host, made with the first invite (see session/host.ts). */
168
+ private hosting;
169
+ /**
170
+ * Mints an invite for this page's session. Guests join with it at the
171
+ * session address (`sessionUrl`: a local ClassCAD MCP, or the share relay),
172
+ * which introduces them to this page; the invite stays joinable until it is
173
+ * revoked or the client disconnects.
174
+ *
175
+ * When the share relay will not take the invite (no sign-in, a plan that does not share), it is dropped and the
176
+ * client emits `invite_refused`.
177
+ *
178
+ * @param role - What guests with the invite may do: `'edit'` (default) or `'view'`.
179
+ * @param name - A name to show for the invite.
180
+ * @example
181
+ * ```ts
182
+ * import { BuerliCadFacade, buildShareUrl, init, WASMClient } from '@classcad/client'
183
+ * import type { OfferRefusal, SessionInvite } from '@classcad/client'
184
+ *
185
+ * // The engine in the page; guests join from anywhere through the share relay
186
+ * let client!: WASMClient
187
+ * init(
188
+ * drawingId =>
189
+ * (client = new WASMClient(drawingId, {
190
+ * token: 'ccpk_…',
191
+ * sessionUrl: 'wss://<relay>/session',
192
+ * // The relay takes invites from signed-in ClassCAD accounts
193
+ * sessionAuth: refresh => classcadIdToken(refresh),
194
+ * })),
195
+ * )
196
+ * await new BuerliCadFacade().connect()
197
+ *
198
+ * client.on('invite_refused', (_client, invite: SessionInvite, refusal: OfferRefusal) =>
199
+ * showError(refusal.code === 4403 ? 'Your plan does not share sessions' : `${invite.name}: ${refusal.reason}`),
200
+ * )
201
+ * const invite = await client.createInvite('edit', 'team')
202
+ * const link = buildShareUrl(invite)
203
+ * ```
204
+ */
205
+ createInvite(role?: SessionRole, name?: string): Promise<SessionInvite>;
206
+ /**
207
+ * Takes an invite back; guests that joined with it are cut off.
208
+ *
209
+ * @param invite - The invite token.
210
+ * @returns The token, whether this client had made it, and how many guests were cut off.
211
+ */
212
+ revokeInvite(invite: string): Promise<{
213
+ /** The token. */
214
+ invite: string;
215
+ /** Whether this client had made the invite. */
216
+ revoked: boolean;
217
+ /** How many guests were cut off. */
218
+ kicked: number;
219
+ }>;
220
+ /**
221
+ * Presence to the guests of this page's session (see WSClient.sendPresence). Nothing happens while nobody was invited.
222
+ *
223
+ * @param channel - The channel, e.g. `'view'` for a camera viewpoint.
224
+ * @param data - The payload, sent as it is; the last one per channel is kept for guests who join later.
225
+ */
226
+ sendPresence(channel: string, data: Record<string, any>): void;
227
+ /**
228
+ * Goes back to the state before the current one of the engine's undo history, or to
229
+ * `options.state`. The engine records a state after every command sent with
230
+ * `options.undoable` (api-js marks the modelling calls) and reports the history in an
231
+ * UndoStack message, which updates `cad.states`. The result is the history afterwards:
232
+ * `{ stack, current }`. An engine from before undo answers without one; nothing happens then.
233
+ */
234
+ undo(options?: UndoOptions): Promise<ServerResponse>;
235
+ /** Goes forward to the state after the current one, or to `options.state` (see undo). */
236
+ redo(options?: RedoOptions): Promise<ServerResponse>;
237
+ protected syncState(): void;
238
+ }
239
+ export {};
@@ -0,0 +1,242 @@
1
+ import { DrawingID } from '@classcad/sdkjs';
2
+ import { EmissionConfig, RedoOptions, ServerRequest, ServerResponse, UndoOptions } from '../types/ComClient';
3
+ import { AwvNodeClient } from './AwvNodeClient';
4
+ import { SessionInvite, SessionPeer, SessionRole, ShareKind } from '../session/types';
5
+ import { ClientIdentity } from '../session/identity';
6
+ export type { SessionInvite, SessionPeer, SessionRole, PresenceMessage } from '../session/types';
7
+ /**
8
+ * Options of a {@link WSClient}: sub-path, an invite to join a shared session, identity and emission config.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { getShareTokenFromUrl, init, WSClient } from '@classcad/client'
13
+ * import type { WSClientConfig } from '@classcad/client'
14
+ *
15
+ * const config: WSClientConfig = {
16
+ * // Joins a shared session when the page was opened with a share link
17
+ * invite: getShareTokenFromUrl()?.token,
18
+ * identity: { app: 'configurator', version: '2.1.0', name: 'Ada', kind: 'app' },
19
+ * // This app shows no hidden objects
20
+ * commandConfig: { sendGraphic_Invisible: false },
21
+ * }
22
+ * init(drawingId => new WSClient('ws://localhost:9094', drawingId, config))
23
+ * ```
24
+ * @category Clients
25
+ */
26
+ export type WSClientConfig = {
27
+ /** WebSocket sub-path: '/', '/command', or '/api'. Defaults to '/'. */
28
+ path?: string;
29
+ /**
30
+ * Invite token for joining a shared session as a guest (sent as query param).
31
+ * Without it the server creates a fresh main session that lives for the
32
+ * duration of this connection; use `createInvite()` to let others join it.
33
+ * The server confirms an invite join with a `SessionJoined` frame carrying
34
+ * the invite's role — see the `session_joined` event and the `role` property.
35
+ */
36
+ invite?: string;
37
+ /**
38
+ * Who this client is, for the others in the session: published once after
39
+ * connecting on the 'client' presence channel (see {@link ClientIdentity}).
40
+ */
41
+ identity?: ClientIdentity;
42
+ /**
43
+ * Startup emission config of this connection, merged on top of
44
+ * the client's defaults and sent once with SetEmissionConfig on connect. Set
45
+ * individual flags to false to disable them; change them later with
46
+ * `setEmissionConfig()`. Not to be confused with v1.common.setDatabaseSettings,
47
+ * which decides what the engine TESSELLATES - this decides what it SENDS.
48
+ *
49
+ * The defaults turn on the structure, every graphic category and messages, and stream them: structure patches,
50
+ * graphic as compressed binary frames, one package per object, messages as they come.
51
+ */
52
+ commandConfig?: Partial<EmissionConfig>;
53
+ };
54
+ /**
55
+ * Connects the SDK to a native ClassCAD engine through the engine's own WebSocket server (`classcad-cli worker`).
56
+ *
57
+ * The server owns the session. Without an invite it creates one for this connection, which lasts as long as the
58
+ * connection; others join it with an invite from {@link WSClient.createInvite}, passed as `config.invite`. A URL
59
+ * without a scheme (`/session`) is on the server the page came from.
60
+ *
61
+ * Connection flow:
62
+ * 1. WebSocket handshake (server auto-creates session)
63
+ * 2. SetEmissionConfig command stores this connection's emission flags on the server
64
+ * 3. `fetchTree()` retrieves initial object tree
65
+ * 4. Connection promise resolves
66
+ *
67
+ * Undo and redo: `undo()` / `redo()` send the engine's `Undo` / `Redo` commands, and the `UndoStack` frames the
68
+ * server sends after every undoable command and every undo / redo fill `cad.states` (see {@link WSClient.undo}).
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * import { init, WSClient } from '@classcad/client'
73
+ *
74
+ * // The native engine's own WebSocket server (classcad-cli worker)
75
+ * init(drawingId => new WSClient('ws://localhost:9094', drawingId))
76
+ * ```
77
+ * @example
78
+ * ```ts
79
+ * import { BuerliCadFacade, buildShareUrl, init, WSClient } from '@classcad/client'
80
+ * import type { SessionPeer } from '@classcad/client'
81
+ *
82
+ * // The host: a session of its own on the engine, and an invite to it
83
+ * let host!: WSClient
84
+ * init(drawingId => (host = new WSClient('ws://localhost:9094', drawingId, { identity: { app: 'my-app' } })))
85
+ * await new BuerliCadFacade().connect()
86
+ *
87
+ * host.on('peers_changed', (_client, peers: SessionPeer[]) => {
88
+ * console.log(peers.map(peer => `${peer.inviteName}: ${peer.role}`))
89
+ * })
90
+ * const invite = await host.createInvite('view', 'review')
91
+ * console.log('Join at', buildShareUrl(invite))
92
+ * // Later: the token stops working, its guests are cut off
93
+ * await host.revokeInvite(invite.invite)
94
+ * ```
95
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * import { BuerliCadFacade, init, WSClient } from '@classcad/client'
100
+ * import type { PresenceMessage } from '@classcad/client'
101
+ *
102
+ * // A guest: joins the host's session with its token
103
+ * let guest!: WSClient
104
+ * init(drawingId => (guest = new WSClient('ws://localhost:9094', drawingId, { invite: token })))
105
+ * await new BuerliCadFacade().connect()
106
+ * // With a 'view' invite the app keeps the guest from changing the model
107
+ * setReadOnly(guest.role === 'view')
108
+ *
109
+ * // The cameras follow each other
110
+ * guest.on('presence', (_client, msg: PresenceMessage) => {
111
+ * if (msg.channel === 'view') moveCamera(msg.data)
112
+ * })
113
+ * guest.sendPresence('view', myCamera())
114
+ * ```
115
+ * @category Clients
116
+ */
117
+ export declare class WSClient extends AwvNodeClient {
118
+ private _url;
119
+ private _ws;
120
+ private _pending;
121
+ private _connected;
122
+ private _config;
123
+ /**
124
+ * Graphic packages waiting to be added to the drawing. The server sends the graphic of a model as many small
125
+ * frames (thousands for a large assembly); adding each on its own updated the store once per frame. They are
126
+ * collected for a moment and added in one batch (@see flushGraphic).
127
+ */
128
+ private _graphicQueue;
129
+ private _graphicFlushTimer;
130
+ /** The server owns the session: invites are honoured by joining with `?invite=` on the server URL. */
131
+ readonly shareKind: ShareKind;
132
+ /** Guests currently sharing this session (main connection only), keyed by peerId. */
133
+ private _peers;
134
+ /** Snapshot of the guests currently sharing this session (main connection only). */
135
+ get peers(): SessionPeer[];
136
+ /** The address the client was given; one without a scheme (`/session`) is on the server the page came from. */
137
+ get url(): string;
138
+ /**
139
+ * @param _url - The server's WebSocket address, e.g. `ws://localhost:9094`, or a path on the page's own server.
140
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
141
+ * @param config - Sub-path, invite, identity and emission config ({@link WSClientConfig}).
142
+ */
143
+ constructor(_url: string, drawingId: DrawingID, config?: WSClientConfig);
144
+ /**
145
+ * Opens the WebSocket, sets the connection's emission config, loads the structure tree and publishes `identity`.
146
+ * Rejects when the socket fails before that, or when the engine predates SetEmissionConfig.
147
+ */
148
+ connect(): Promise<WSClient>;
149
+ /** Closes the WebSocket; the server ends the session if this connection made it. No `conn_error` is emitted. */
150
+ disconnect(): Promise<AwvNodeClient>;
151
+ /**
152
+ * Sends `command` to the server and resolves to its reply, once the server's `Result` frame arrives. Structure,
153
+ * graphic and messages that come before it go into the drawing on the way. Rejects with the reply when it carries
154
+ * an error, and when the socket closes first.
155
+ *
156
+ * @param _name - Not used by this client.
157
+ * @param command - The request.
158
+ */
159
+ requestByName(_name: string, command?: ServerRequest): Promise<ServerResponse>;
160
+ protected request(command: ServerRequest): Promise<ServerResponse>;
161
+ /**
162
+ * Mints an invite token for this connection's session (multi-client invite
163
+ * model). The returned token can be handed to other clients, which join via
164
+ * `new WSClient(url, id, { invite })`. Server-side this is a controller-level
165
+ * meta command; it is rejected when this connection itself joined via invite.
166
+ *
167
+ * `name` is optional and purely for display (e.g. "workgroup"); it has no
168
+ * effect on behavior. Multiple tokens can be minted (e.g. a named group token
169
+ * plus an unnamed one-off token). The examples of {@link WSClient} show the host and a guest.
170
+ *
171
+ * @param role - What guests with the invite may do: `'edit'` (default) or `'view'`.
172
+ * @param name - A name to show for the invite.
173
+ */
174
+ createInvite(role?: SessionRole, name?: string): Promise<SessionInvite>;
175
+ /**
176
+ * Revokes a previously minted invite token. Any guests currently connected
177
+ * with that token are immediately disconnected, and the token can no longer
178
+ * be used to join. Owner-only; rejected on connections that joined via invite.
179
+ *
180
+ * @param invite - The invite token.
181
+ * @returns The token, whether it was revoked, and how many guests were cut off.
182
+ */
183
+ revokeInvite(invite: string): Promise<{
184
+ /** The token. */
185
+ invite: string;
186
+ /** Whether the token was known and is revoked now. */
187
+ revoked: boolean;
188
+ /** How many guests were cut off. */
189
+ kicked: number;
190
+ }>;
191
+ /**
192
+ * Fire-and-forget ephemeral presence broadcast to the session's siblings
193
+ * (e.g. this client's camera viewpoint on the 'view' channel). Handled by a
194
+ * server fast-path that bypasses the command queue entirely; the server
195
+ * stamps the sender's peerId and fans the frame out. Siblings receive it via
196
+ * the `presence` event; late joiners get the last frame per channel as a
197
+ * snapshot. NOTE: the server matches on the exact serialized prefix
198
+ * `{"command":"Presence"`, so `command` must stay the first key here.
199
+ *
200
+ * The guest example of {@link WSClient} shares the camera this way.
201
+ *
202
+ * @param channel - The channel, e.g. `'view'` for a camera viewpoint.
203
+ * @param data - The payload, sent as it is. The server drops a frame larger than 8 KB.
204
+ */
205
+ sendPresence(channel: string, data: Record<string, any>): void;
206
+ /**
207
+ * Goes back to the state before the current one of the session's undo history, or to
208
+ * `options.state`. The server records a state after every command sent with
209
+ * `options.undoable` (api-js marks the modelling calls) and answers with the frames of the
210
+ * change and an UndoStack frame, which updates `cad.states` of every client in the session.
211
+ * The result is the history afterwards: `{ stack, current }`.
212
+ */
213
+ undo(options?: UndoOptions): Promise<ServerResponse>;
214
+ /** Goes forward to the state after the current one, or to `options.state` (see undo). */
215
+ redo(options?: RedoOptions): Promise<ServerResponse>;
216
+ private buildUrl;
217
+ private sendCommand;
218
+ private handleBinaryFrame;
219
+ private handleTextFrame;
220
+ /**
221
+ * When the server is configured with `sendStructure_Compressed` /
222
+ * `sendGraphic_Compressed`, the corresponding payload field arrives as a
223
+ * base64 string of raw-deflated JSON instead of an inline object. Decode it
224
+ * back to the structured form before handing it to the drawing APIs.
225
+ */
226
+ private decodeMaybeCompressed;
227
+ /** Adds the queued graphic packages to the drawing in one call. */
228
+ private flushGraphic;
229
+ private handleFrame;
230
+ /** True while a full-tree resync (after a failed structure patch) is in flight. */
231
+ private _resyncing;
232
+ /**
233
+ * Recovers from a structure patch that failed to apply: fetches the full
234
+ * tree from the server. The GetTree result carries the complete structure
235
+ * and graphic, so the drawing heals entirely — and since the server
236
+ * broadcasts result frames to all session siblings, any sibling that
237
+ * diverged the same way heals along with it. Guarded so a burst of failing
238
+ * patches triggers only one round trip.
239
+ */
240
+ private resyncStructure;
241
+ protected syncState(): void;
242
+ }