@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,137 @@
1
+ /**
2
+ * The token exchange of the ClassCAD backend.
3
+ *
4
+ * @advanced
5
+ * @category Engine Keys
6
+ */
7
+ export declare const DEFAULT_KEY_URL = "https://europe-west1-classcad-app.cloudfunctions.net/api/v1/key";
8
+ /**
9
+ * An engine key, and when it expires.
10
+ *
11
+ * What a WASMClient's `getKey` may resolve to: see the examples of {@link WASMClient} and {@link requestEngineKey}.
12
+ *
13
+ * @category Engine Keys
14
+ */
15
+ export type EngineKey = {
16
+ /** The key the engine starts with. */
17
+ key: string;
18
+ /** When the key expires, in milliseconds since 1970 (as `Date.now()`). */
19
+ exp: number;
20
+ };
21
+ /**
22
+ * Where an engine's key comes from: a key, a ClassCAD access token, or a function of the app's own.
23
+ *
24
+ * The first one given is used, in this order: `classcadKey`, `getKey`, `token`.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { resolveEngineKey } from '@classcad/client'
29
+ * import type { EngineKeySource } from '@classcad/client'
30
+ *
31
+ * // A key from a token exchange of one's own (a self-hosted backend), named for the account's records
32
+ * const source: EngineKeySource = {
33
+ * token: 'ccpk_…',
34
+ * keyUrl: 'https://keys.example.com/api/v1/key',
35
+ * client: 'configurator 2.1',
36
+ * }
37
+ * const key = await resolveEngineKey(source)
38
+ * ```
39
+ * @category Engine Keys
40
+ */
41
+ export type EngineKeySource = {
42
+ /** An engine key itself; when given, nothing is fetched. */
43
+ classcadKey?: string;
44
+ /** A ClassCAD access token: `ccpk_…` in web pages, `ccsk_…` on servers. */
45
+ token?: string;
46
+ /** Or the app supplies keys itself, for example from its own sign-in (POST /key with a Firebase ID token). */
47
+ getKey?: () => Promise<string | EngineKey>;
48
+ /** The token exchange, DEFAULT_KEY_URL unless given. */
49
+ keyUrl?: string;
50
+ /** The engine the key is for: `'wasm'` (default) or `'native'`. */
51
+ appType?: 'wasm' | 'native';
52
+ /** Who asks, for the account's records. */
53
+ client?: string;
54
+ };
55
+ /**
56
+ * The error when there is no key for an engine: no token, the key service cannot be reached, or it refused.
57
+ *
58
+ * {@link WASMClient.connect} rejects with it.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { EngineKeyError, resolveEngineKey } from '@classcad/client'
63
+ *
64
+ * // Checks a page's token before the app starts, and says why it fails
65
+ * try {
66
+ * await resolveEngineKey({ token: 'ccpk_…' })
67
+ * } catch (error) {
68
+ * if (error instanceof EngineKeyError && error.status && error.status < 500) {
69
+ * showError(`ClassCAD refused the key: ${error.message}`) // e.g. a domain the account has not registered
70
+ * } else {
71
+ * showError('The ClassCAD key service cannot be reached')
72
+ * }
73
+ * }
74
+ * ```
75
+ * @category Engine Keys
76
+ */
77
+ export declare class EngineKeyError extends Error {
78
+ status?: number | undefined;
79
+ code?: string | undefined;
80
+ /**
81
+ * @param message - What went wrong; the key service's own words when it refused.
82
+ * @param status - The HTTP status of the key service's answer, when it answered.
83
+ * @param code - The key service's error code, when it gave one.
84
+ */
85
+ constructor(message: string, status?: number | undefined, code?: string | undefined);
86
+ }
87
+ /**
88
+ * Asks the token exchange for a key.
89
+ *
90
+ * Sends `source.token` to `source.keyUrl` (default {@link DEFAULT_KEY_URL}) every time; {@link resolveEngineKey}
91
+ * caches the key. Throws an {@link EngineKeyError} without a token, when the service cannot be reached, and with
92
+ * its reason when it refuses.
93
+ *
94
+ * @param source - The access token, and optionally `keyUrl`, `appType` and `client`.
95
+ * @example
96
+ * ```ts
97
+ * import { requestEngineKey } from '@classcad/client'
98
+ *
99
+ * // The app's server: hands its signed-in users engine keys, with the secret token only it knows
100
+ * export async function engineKeyRoute(request: Request): Promise<Response> {
101
+ * if (!(await isSignedIn(request))) return new Response('Sign in first', { status: 401 })
102
+ * const key = await requestEngineKey({ token: process.env.CLASSCAD_SECRET_TOKEN, client: 'my-app server' })
103
+ * return Response.json(key) // { key, exp }, what a WASMClient's getKey returns
104
+ * }
105
+ * ```
106
+ * @advanced
107
+ * @category Engine Keys
108
+ */
109
+ export declare function requestEngineKey(source: EngineKeySource): Promise<EngineKey>;
110
+ /**
111
+ * The key for an engine start: the given key, the app's own, or one for the access token.
112
+ *
113
+ * Throws EngineKeyError when there is none, with the service's reason (an unregistered
114
+ * domain, a revoked token, a plan without the native engine).
115
+ *
116
+ * A key for a token is cached in `localStorage` (where there is one), per token, page origin and key service. It is
117
+ * used until a minute before it expires and renewed in the background once less than a quarter of its life, or less
118
+ * than a day, is left. When the service cannot be reached, a cached key that has not expired is used; a refusal
119
+ * (an HTTP 4xx) is final. {@link WASMClient} calls it on `connect`.
120
+ *
121
+ * @param source - The key, the app's `getKey`, or the access token to get one with.
122
+ * @returns The key.
123
+ * @example
124
+ * ```ts
125
+ * import { resolveEngineKey } from '@classcad/client'
126
+ *
127
+ * // A server that starts a native engine of its own, with a secret access token
128
+ * const key = await resolveEngineKey({
129
+ * token: process.env.CLASSCAD_SECRET_TOKEN,
130
+ * appType: 'native',
131
+ * client: 'render farm',
132
+ * })
133
+ * await startEngine(key)
134
+ * ```
135
+ * @category Engine Keys
136
+ */
137
+ export declare function resolveEngineKey(source: EngineKeySource): Promise<string>;
@@ -0,0 +1,6 @@
1
+ export { BooleanOperationType, ChamferType, CLASSCAD_VERSION, CLASSCAD_VERSION_QUALITY, DataType, ExtrusionType, FlipType, NOID, OrientationType, ReorientedType, SVGModusType, ViewType, WorkAxisType, WorkCoordSystemType, WorkPlaneType, WorkPointType, } from '@classcad/api-js';
2
+ export { MessageLevel, ScgClassType, ScgGraphicType } from '@classcad/api-js';
3
+ export type { FacadeReturn, GraphicID, Message, ObjectID, ObjectIdent, ScgArrayMem, ScgGraphicArc, ScgGraphicCone, ScgGraphicContainer, ScgGraphicCylinder, ScgGraphicEdge, ScgGraphicElement, ScgGraphicLine, ScgGraphicMesh, ScgGraphicPackage, ScgGraphicPlane, ScgGraphicSphere, ScgIdMem, ScgMember, ScgObject, ScgPoint, ScgPointMem, ScgRealMem, ScgStringMem, ScgStructure, ScgStructurePatch, ScgStructurePatchOp, ScgTree, WorkGeomType, } from '@classcad/api-js';
4
+ export { CCClasses, classMap, ContainerType, CurveTypes, EdgeTypes, EntityTypes, GraphicType, MemberType, MeshTypes, PointTypes, } from '@classcad/sdkjs';
5
+ export type { ArrayMem, IdMem, IGraphicArc, IGraphicCone, IGraphicContainer, IGraphicCylinder, IGraphicEdge, IGraphicElement, IGraphicLine, IGraphicMesh, IGraphicPackage, IGraphicPlane, IGraphicSphere, IStructureMember, IStructureObject, IStructurePatch, IStructureProtocol, IStructureTree, PointMem, PointMemValue, RealMem, StringMem, } from '@classcad/sdkjs';
6
+ export type { AngularDimensionParam, APIParam, CircularPatternConstraint, ConstraintValueParam, CylindricalConstraint, DiameterDimensionParam, DimensionParam, ExpressionParam, ExprMemToAdd, ExprMemToModify, FastenedConstraint, FastenedOriginConstraint, GroupConstraint, InstanceParam, LimitedValue, LimitsParam, LinearDimensionParam, LinearPatternConstraint, MateParam, ParallelConstraint, PlanarConstraint, RadialDimensionParam, RevoluteConstraint, SliderConstraint, } from '@classcad/api-js';
@@ -0,0 +1,108 @@
1
+ import { OfferRefusal, PresenceMessage, SessionInvite, SessionPeer } from './types';
2
+ /**
3
+ * What the engine emitted for one command: its messages and its graphic packages.
4
+ *
5
+ * @internal
6
+ */
7
+ export type EngineReply = {
8
+ messages: Record<string, any>[];
9
+ binaryMessages: Record<string, any>[];
10
+ };
11
+ /**
12
+ * How a {@link SessionHost} reaches its broker and its page's engine.
13
+ *
14
+ * @internal
15
+ */
16
+ export type SessionHostOptions = {
17
+ /** Where guests join: the session address of a ClassCAD MCP on this machine, or of the share relay. */
18
+ url: string;
19
+ /**
20
+ * The sign-in an offer shows, where the session address wants one (the share relay): a Firebase ID
21
+ * token of the reader's ClassCAD account, a fresh one when `refresh` is set. Without it, none is shown
22
+ * (an MCP's listener asks for none).
23
+ */
24
+ auth?: (refresh: boolean) => Promise<string | null | undefined>;
25
+ /** The broker will not take an invite (the plan does not share, another account offers it, the sign-in does not hold): it is offered no more. */
26
+ onRefused?: (invite: SessionInvite, refusal: OfferRefusal) => void;
27
+ /** Runs a guest's command on the engine — the page's own view follows — and returns what the engine emitted. */
28
+ execute: (command: Record<string, any>) => Promise<EngineReply>;
29
+ /** Every graphic container of the model as it is now. */
30
+ containers: () => unknown[];
31
+ /** The engine's undo history as it is now (its last UndoStack frame), for a guest that joins. */
32
+ undoStack?: () => Record<string, any> | undefined;
33
+ /** A guest joined the session. */
34
+ onPeerJoined: (peer: SessionPeer) => void;
35
+ /** A guest left it, or was cut off. */
36
+ onPeerLeft: (peer: SessionPeer) => void;
37
+ /** What a guest published (and 'leave' when it went). */
38
+ onPresence: (msg: PresenceMessage) => void;
39
+ };
40
+ /** One engine reply, taken apart. */
41
+ type Pieces = {
42
+ /** The command the reply answers, and its transaction id: every frame of the reply carries both. */
43
+ from: string;
44
+ tx: unknown;
45
+ /** JSON-Patch blocks against the structure, in emission order. */
46
+ patches: unknown[][];
47
+ /** Graphic packages (the containers the command changed). */
48
+ packages: Record<string, any>[];
49
+ /** GetTree/Sync: the structure. */
50
+ structure?: unknown;
51
+ /** The engine's undo history, when the command changed it (an undoable command, an undo / redo). */
52
+ undoStack?: Record<string, any>;
53
+ /** The Result frame without structure and graphic. */
54
+ result: Record<string, any>;
55
+ };
56
+ /** Translates one reply of the engine into what a server's frames are made of. */
57
+ export declare function pieces(req: Record<string, any>, res: EngineReply): Pieces;
58
+ /**
59
+ * A page's side of a shared session: offers invites at a ClassCAD MCP on the
60
+ * same machine or on the share relay, and serves the guests that join with
61
+ * them as a ClassCAD server would. `WASMClient` makes one with its first
62
+ * invite; an app has no need to use it directly.
63
+ *
64
+ * @internal
65
+ */
66
+ export declare class SessionHost {
67
+ private opts;
68
+ /** The host's peer id, as guests see it on presence frames. */
69
+ readonly hostId: string;
70
+ private offers;
71
+ private guests;
72
+ private hostPresence;
73
+ private closed;
74
+ constructor(opts: SessionHostOptions);
75
+ /** The guests that are in the session right now. */
76
+ get peers(): SessionPeer[];
77
+ /** Makes an invite joinable: keeps a connection to the broker open for it, whatever happens to the broker. */
78
+ offer(invite: SessionInvite): void;
79
+ /** Takes an invite back: nobody joins with it any more, and whoever did is cut off. Returns how many were. */
80
+ revoke(token: string): number;
81
+ /** A command of the page itself, and what the engine emitted for it: the guests get it like any other. */
82
+ deliver(command: Record<string, any>, reply: EngineReply): void;
83
+ /** Presence from the host to every guest (kept for those who join later). */
84
+ sendPresence(channel: string, data: Record<string, any>): void;
85
+ /** The page stops hosting: every guest is closed, every invite taken back. */
86
+ close(): void;
87
+ /** The broker's session address, with what this connection is for. */
88
+ private address;
89
+ /** Opens the standing connection for an invite, and opens it again whenever it is lost. */
90
+ private announce;
91
+ /** The broker will not take an invite: it is offered no more, and the page is told why. */
92
+ private refused;
93
+ /** Opens the connection the broker joins to one guest's. */
94
+ private meet;
95
+ /** Sends a guest one frame, if its connection still takes any. */
96
+ private raw;
97
+ /** Takes a guest in: the handshake a server gives, then its commands and presence. */
98
+ private serve;
99
+ /** A guest is gone: the others and the page are told. */
100
+ private leave;
101
+ /** A guest's presence frame: kept for those who join later and relayed to everyone else, as a server does. */
102
+ private presence;
103
+ /** A guest's command: answered here (emission config, what a guest may not do), or run on the page's engine. */
104
+ private command;
105
+ /** One engine reply, to everyone it concerns, each in the form its connection asked for. */
106
+ private send;
107
+ }
108
+ export {};
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The presence channel identities are published on.
3
+ *
4
+ * @advanced
5
+ * @category Session Sharing
6
+ */
7
+ export declare const CLIENT_CHANNEL = "client";
8
+ /**
9
+ * What a participant says about itself.
10
+ *
11
+ * Give it to a {@link WSClient} or {@link WASMClient} as `identity`; the others in the session find it in the
12
+ * client's `identities`, by peer id.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { init, WASMClient } from '@classcad/client'
17
+ * import type { ClientIdentity } from '@classcad/client'
18
+ *
19
+ * // Says who this page is, and lists who else is in the session
20
+ * const identity: ClientIdentity = { app: 'configurator', version: '2.1.0', name: 'Ada', kind: 'app' }
21
+ * init(drawingId => {
22
+ * const client = new WASMClient(drawingId, { token: 'ccpk_…', identity })
23
+ * client.on('identities_changed', (_client, identities: Record<string, ClientIdentity>) =>
24
+ * showParticipants(Object.values(identities).map(i => `${i.name ?? i.app}${i.kind === 'agent' ? ' (AI)' : ''}`)),
25
+ * )
26
+ * return client
27
+ * })
28
+ * ```
29
+ * @category Session Sharing
30
+ */
31
+ export type ClientIdentity = {
32
+ /** The program: 'buerligons', 'classcad-mcp', … */
33
+ app: string;
34
+ /** The program's version. */
35
+ version?: string;
36
+ /** A name to show for this participant ("Claude Code", a person's name). */
37
+ name?: string;
38
+ /** 'agent' for an AI agent's session, 'app' for a person at an app. */
39
+ kind?: 'app' | 'agent';
40
+ };
41
+ /**
42
+ * A 'client' frame is remote input: only what has the right shape gets in.
43
+ *
44
+ * @internal
45
+ */
46
+ export declare const sanitizeIdentity: (raw: unknown) => ClientIdentity | null;
@@ -0,0 +1,164 @@
1
+ import { DrawingID } from '@classcad/sdkjs';
2
+ import type { AwvNodeClient } from '../io/AwvNodeClient';
3
+ /**
4
+ * The presence channel a participant's selection is published on.
5
+ *
6
+ * @advanced
7
+ * @category Session Sharing
8
+ */
9
+ export declare const SELECTION_CHANNEL = "selection";
10
+ /**
11
+ * The presence channel requests to select something are sent on.
12
+ *
13
+ * @advanced
14
+ * @category Session Sharing
15
+ */
16
+ export declare const SELECT_CHANNEL = "select";
17
+ /**
18
+ * One selected thing: a face, edge or vertex of a body, or an object of the
19
+ * model tree (a sketch entity, a dimension, a feature). {@link readSelection} has an example.
20
+ *
21
+ * @advanced
22
+ * @category Session Sharing
23
+ */
24
+ export type SelectionItem = {
25
+ /** What was selected. */
26
+ kind: 'face' | 'edge' | 'vertex' | 'object';
27
+ /** The model tree object: the picked object itself, or the owner of the picked geometry (a solid). */
28
+ objectId: number;
29
+ /** The product or assembly instance the pick was made in. */
30
+ prodRefId?: number | null;
31
+ /** Geometry: the body's graphic container. It is replaced whenever the body is rebuilt. */
32
+ containerId?: number;
33
+ /** Geometry: the element in the container. This is the id API calls take for a face, an edge or a vertex. */
34
+ graphicId?: number;
35
+ /** Geometry: the element's type (plane, cylinder, line, arc, …). Objects: their class. */
36
+ type?: string;
37
+ /** Objects: their name in the model tree. */
38
+ name?: string;
39
+ };
40
+ /**
41
+ * The 'selection' channel's payload: what a participant has selected.
42
+ *
43
+ * `total` counts the whole selection; `items` may be cut to fit a presence frame. The example of
44
+ * {@link syncSelection} reads the frames of the others.
45
+ *
46
+ * @advanced
47
+ * @category Session Sharing
48
+ */
49
+ export type SelectionFrame = {
50
+ /** The selected things; the first ones, when the selection does not fit a presence frame. */
51
+ items: SelectionItem[];
52
+ /** How many things are selected. */
53
+ total: number;
54
+ };
55
+ /**
56
+ * What a request names: a tree object by its id, or geometry by its element id (and container and product, when known).
57
+ *
58
+ * {@link applySelection} and {@link SelectFrame} have examples.
59
+ *
60
+ * @advanced
61
+ * @category Session Sharing
62
+ */
63
+ export type SelectTarget = {
64
+ /** A model tree object. */
65
+ objectId?: number;
66
+ /** The product or assembly instance to select the geometry in; by default the part, or its first instance. */
67
+ prodRefId?: number | null;
68
+ /** Geometry: the body's graphic container. A body rebuilt since has another one; the element is looked up then. */
69
+ containerId?: number;
70
+ /** Geometry: the face, edge or vertex. */
71
+ graphicId?: number;
72
+ };
73
+ /**
74
+ * The 'select' channel's payload: a request (`items`), or the note that the request `id` is over (`done`).
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { SELECT_CHANNEL } from '@classcad/client'
79
+ * import type { SelectFrame, WSClient } from '@classcad/client'
80
+ *
81
+ * // Asks the others in the session to select an edge (they run syncSelection)
82
+ * const id = crypto.randomUUID()
83
+ * const request: SelectFrame = { id, items: [{ graphicId: edgeId }], replace: true }
84
+ * client.sendPresence(SELECT_CHANNEL, request)
85
+ * // Right after: the request is over, so the frame the server keeps asks for nothing
86
+ * client.sendPresence(SELECT_CHANNEL, { id, done: true } satisfies SelectFrame)
87
+ * ```
88
+ * @advanced
89
+ * @category Session Sharing
90
+ */
91
+ export type SelectFrame = {
92
+ /** The request's id; a peer follows each id once. */
93
+ id: string;
94
+ /** What to select. */
95
+ items?: SelectTarget[];
96
+ /** `false` adds to the selection; by default it is replaced. */
97
+ replace?: boolean;
98
+ /** The request `id` is over. */
99
+ done?: boolean;
100
+ };
101
+ /**
102
+ * The drawing's selection (interaction.selected), as session items.
103
+ *
104
+ * @param drawingId - The drawing.
105
+ * @example
106
+ * ```ts
107
+ * import { readSelection } from '@classcad/client'
108
+ *
109
+ * // Tells an assistant what "this" means: the selection, by the engine's ids
110
+ * const faces = readSelection(drawingId).filter(item => item.kind === 'face')
111
+ * const prompt = `Selected faces: ${faces.map(face => `${face.graphicId} (${face.type})`).join(', ')}`
112
+ * ```
113
+ * @advanced
114
+ * @category Session Sharing
115
+ */
116
+ export declare function readSelection(drawingId: DrawingID): SelectionItem[];
117
+ /**
118
+ * Selects `targets` in the drawing — what a peer asked for.
119
+ *
120
+ * Returns how many of them were found. `replace: false` adds to the selection.
121
+ *
122
+ * @param drawingId - The drawing.
123
+ * @param targets - What to select; targets that are not in the drawing (any more) are skipped.
124
+ * @param replace - `true` (default) replaces the selection, `false` adds to it.
125
+ * @example
126
+ * ```ts
127
+ * import { applySelection } from '@classcad/client'
128
+ *
129
+ * // Selects the faces a script found, adding them to what is selected
130
+ * const found = applySelection(drawingId, faceIds.map(graphicId => ({ graphicId })), false)
131
+ * if (found < faceIds.length) console.warn(`${faceIds.length - found} faces are not in the model any more`)
132
+ * ```
133
+ * @advanced
134
+ * @category Session Sharing
135
+ */
136
+ export declare function applySelection(drawingId: DrawingID, targets: SelectTarget[], replace?: boolean): number;
137
+ /**
138
+ * Shares the selection of a client's drawing with its session: publishes it on change, selects what a peer asks for.
139
+ *
140
+ * Call it when the client is created; it returns the function that stops it. On a client that
141
+ * is in no shared session it does nothing.
142
+ *
143
+ * @param client - The drawing's client, e.g. from {@link onClient}.
144
+ * @returns A function that stops sharing the selection.
145
+ * @example
146
+ * ```ts
147
+ * import { onClient, SELECTION_CHANNEL, syncSelection, WASMClient, WSClient } from '@classcad/client'
148
+ * import type { PresenceMessage, SelectionFrame } from '@classcad/client'
149
+ *
150
+ * // Every shared drawing shows its selection to the others, and selects what they ask for
151
+ * let stop: (() => void) | undefined
152
+ * onClient(client => {
153
+ * if (!(client instanceof WSClient || client instanceof WASMClient)) return
154
+ * stop?.()
155
+ * stop = syncSelection(client)
156
+ * // What the others have selected
157
+ * client.on('presence', (_client, msg: PresenceMessage) => {
158
+ * if (msg.channel === SELECTION_CHANNEL) highlightForPeer(msg.peerId, msg.data as SelectionFrame)
159
+ * })
160
+ * })
161
+ * ```
162
+ * @category Session Sharing
163
+ */
164
+ export declare function syncSelection(client: AwvNodeClient): () => void;
@@ -0,0 +1,131 @@
1
+ import { DrawingID } from '@classcad/sdkjs';
2
+ import type { AwvNodeClient } from '../io/AwvNodeClient';
3
+ import { SessionInvite, SessionShareState, ShareKind } from './types';
4
+ /**
5
+ * Query parameter carrying a share token, by {@link ShareKind}: `invite`.
6
+ *
7
+ * @advanced
8
+ * @category Session Sharing
9
+ */
10
+ export declare const SHARE_PARAM: Record<ShareKind, string>;
11
+ /**
12
+ * The client that serves `drawingId`, or null before the drawing is connected.
13
+ *
14
+ * @param drawingId - The drawing.
15
+ * @example
16
+ * ```ts
17
+ * import { getSessionShareClient } from '@classcad/client'
18
+ *
19
+ * // Ends the sharing of a drawing: every invite taken back, every guest cut off
20
+ * const client = getSessionShareClient(drawingId)
21
+ * for (const invite of client?.invites ?? []) await client?.revokeInvite(invite.invite)
22
+ * ```
23
+ * @advanced
24
+ * @category Session Sharing
25
+ */
26
+ export declare function getSessionShareClient(drawingId: DrawingID): AwvNodeClient | null;
27
+ /**
28
+ * Reads a share token from a page URL (`?invite=…`).
29
+ *
30
+ * Returns null when the page is a plain host. {@link buildShareUrl} has an example of both sides.
31
+ *
32
+ * @param search - The query string to read; by default the page's (`window.location.search`).
33
+
34
+ * @category Session Sharing
35
+ */
36
+ export declare function getShareTokenFromUrl(search?: string): {
37
+ /** How the token is honoured. */
38
+ kind: ShareKind;
39
+ /** The token. */
40
+ token: string;
41
+ } | null;
42
+ /**
43
+ * Builds the link to hand to a guest: the current page with the invite token as query parameter.
44
+ *
45
+ * A guest is another app window, or an MCP's `use_session`. `base` defaults to the page's origin + path.
46
+ *
47
+ * @param invite - The invite, as `createInvite` returns it.
48
+ * @param base - The page the link opens; by default the current one.
49
+ * @example
50
+ * ```ts
51
+ * import { BuerliCadFacade, buildShareUrl, DEFAULT_SESSION_URL, getShareTokenFromUrl } from '@classcad/client'
52
+ * import { init, WASMClient, WSClient } from '@classcad/client'
53
+ *
54
+ * // One page, two roles: opened with a share link it joins as a guest, else it hosts the engine itself
55
+ * const shared = getShareTokenFromUrl()
56
+ * let client!: WASMClient | WSClient
57
+ * init(drawingId =>
58
+ * shared
59
+ * ? (client = new WSClient(DEFAULT_SESSION_URL, drawingId, { invite: shared.token }))
60
+ * : (client = new WASMClient(drawingId, { token: 'ccpk_…' })),
61
+ * )
62
+ * await new BuerliCadFacade().connect()
63
+ *
64
+ * // The host's button: a link to this page for a colleague
65
+ * shareButton.hidden = Boolean(shared)
66
+ * shareButton.onclick = async () => {
67
+ * const invite = await client.createInvite('edit')
68
+ * await navigator.clipboard.writeText(buildShareUrl(invite)) // https://my.app/editor?invite=…
69
+ * }
70
+ * ```
71
+ * @category Session Sharing
72
+ */
73
+ export declare function buildShareUrl(invite: Pick<SessionInvite, 'invite' | 'kind'>, base?: {
74
+ origin: string;
75
+ pathname: string;
76
+ }): string;
77
+ /**
78
+ * Current sharing state of a drawing (stable object until something changes).
79
+ *
80
+ * @param drawingId - The drawing.
81
+ * @example
82
+ * ```ts
83
+ * import { getSessionShareState, subscribeSessionShare } from '@classcad/client'
84
+ *
85
+ * // A badge without a framework: who is in the session, kept up to date
86
+ * const render = () => {
87
+ * const share = getSessionShareState(drawingId)
88
+ * const names = share.peers.map(peer => share.identities[peer.peerId]?.name ?? (peer.inviteName || 'Guest'))
89
+ * badge.hidden = !share.supported
90
+ * badge.textContent = share.isGuest ? `Guest (${share.role})` : `With you: ${names.join(', ') || 'nobody'}`
91
+ * }
92
+ * const unsubscribe = subscribeSessionShare(drawingId, render)
93
+ * ```
94
+ * @category Session Sharing
95
+ */
96
+ export declare function getSessionShareState(drawingId: DrawingID): SessionShareState;
97
+ /**
98
+ * Subscribes to sharing changes of a drawing: its client, connection, role, peers, invites and identities.
99
+ *
100
+ * It fires when the client is (re)created, connects or loses its connection, joins a session (`session_joined`),
101
+ * and when peers, invites or identities change. Returns the unsubscribe function.
102
+ *
103
+ * With {@link getSessionShareState} it fits React's `useSyncExternalStore`.
104
+ *
105
+ * @param drawingId - The drawing.
106
+ * @param callback - Called on every change; read the new state with {@link getSessionShareState}.
107
+ * @example
108
+ * ```tsx
109
+ * import { useSyncExternalStore } from 'react'
110
+ * import { getSessionShareState, subscribeSessionShare } from '@classcad/client'
111
+ *
112
+ * // A React hook for a drawing's sharing state
113
+ * export function useSessionShare(drawingId: string) {
114
+ * return useSyncExternalStore(
115
+ * onChange => subscribeSessionShare(drawingId, onChange),
116
+ * () => getSessionShareState(drawingId),
117
+ * )
118
+ * }
119
+ *
120
+ * export function Guests({ drawingId }: { drawingId: string }) {
121
+ * const { peers, invites } = useSessionShare(drawingId)
122
+ * return (
123
+ * <span>
124
+ * {peers.length} guests, {invites.length} invites
125
+ * </span>
126
+ * )
127
+ * }
128
+ * ```
129
+ * @category Session Sharing
130
+ */
131
+ export declare function subscribeSessionShare(drawingId: DrawingID, callback: () => void): () => void;