@reeve-iot/workload-client 0.0.0-stage → 1.0.1

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -2
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +11 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/session/MessageDeduplicator.d.ts +22 -0
  8. package/dist/session/MessageDeduplicator.d.ts.map +1 -0
  9. package/dist/session/MessageDeduplicator.js +49 -0
  10. package/dist/session/MessageDeduplicator.js.map +1 -0
  11. package/dist/session/SessionDataKind.d.ts +13 -0
  12. package/dist/session/SessionDataKind.d.ts.map +1 -0
  13. package/dist/session/SessionDataKind.js +11 -0
  14. package/dist/session/SessionDataKind.js.map +1 -0
  15. package/dist/session/SessionEnvelope.d.ts +40 -0
  16. package/dist/session/SessionEnvelope.d.ts.map +1 -0
  17. package/dist/session/SessionEnvelope.js +9 -0
  18. package/dist/session/SessionEnvelope.js.map +1 -0
  19. package/dist/session/SessionProtocol.d.ts +61 -0
  20. package/dist/session/SessionProtocol.d.ts.map +1 -0
  21. package/dist/session/SessionProtocol.js +283 -0
  22. package/dist/session/SessionProtocol.js.map +1 -0
  23. package/dist/session/WorkloadSessionClient.d.ts +114 -0
  24. package/dist/session/WorkloadSessionClient.d.ts.map +1 -0
  25. package/dist/session/WorkloadSessionClient.js +462 -0
  26. package/dist/session/WorkloadSessionClient.js.map +1 -0
  27. package/dist/session/backoff.d.ts +32 -0
  28. package/dist/session/backoff.d.ts.map +1 -0
  29. package/dist/session/backoff.js +54 -0
  30. package/dist/session/backoff.js.map +1 -0
  31. package/dist/session/owner.d.ts +34 -0
  32. package/dist/session/owner.d.ts.map +1 -0
  33. package/dist/session/owner.js +2 -0
  34. package/dist/session/owner.js.map +1 -0
  35. package/dist/session/rest.d.ts +83 -0
  36. package/dist/session/rest.d.ts.map +1 -0
  37. package/dist/session/rest.js +140 -0
  38. package/dist/session/rest.js.map +1 -0
  39. package/dist/session/transport.d.ts +51 -0
  40. package/dist/session/transport.d.ts.map +1 -0
  41. package/dist/session/transport.js +190 -0
  42. package/dist/session/transport.js.map +1 -0
  43. package/dist/session/types.d.ts +114 -0
  44. package/dist/session/types.d.ts.map +1 -0
  45. package/dist/session/types.js +19 -0
  46. package/dist/session/types.js.map +1 -0
  47. package/dist/tls/caCertificate.d.ts +5 -0
  48. package/dist/tls/caCertificate.d.ts.map +1 -0
  49. package/dist/tls/caCertificate.js +26 -0
  50. package/dist/tls/caCertificate.js.map +1 -0
  51. package/dist/tls/trustedCaCertificates.d.ts +4 -0
  52. package/dist/tls/trustedCaCertificates.d.ts.map +1 -0
  53. package/dist/tls/trustedCaCertificates.js +16 -0
  54. package/dist/tls/trustedCaCertificates.js.map +1 -0
  55. package/package.json +63 -4
  56. package/src/index.ts +59 -0
  57. package/src/session/MessageDeduplicator.ts +55 -0
  58. package/src/session/SessionDataKind.ts +14 -0
  59. package/src/session/SessionEnvelope.ts +32 -0
  60. package/src/session/SessionProtocol.ts +351 -0
  61. package/src/session/WorkloadSessionClient.ts +597 -0
  62. package/src/session/backoff.ts +68 -0
  63. package/src/session/owner.ts +39 -0
  64. package/src/session/rest.ts +228 -0
  65. package/src/session/transport.ts +224 -0
  66. package/src/session/types.ts +130 -0
  67. package/src/tls/caCertificate.ts +29 -0
  68. package/src/tls/trustedCaCertificates.ts +18 -0
@@ -0,0 +1,26 @@
1
+ import { X509Certificate } from 'node:crypto';
2
+ const CERTIFICATE_BLOCK = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
3
+ export class CaCertificateError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'CaCertificateError';
7
+ }
8
+ }
9
+ export function readCaCertificates(value) {
10
+ const normalized = value.replace(/\\n/g, '\n').replace(/\r/g, '');
11
+ const blocks = [...normalized.matchAll(CERTIFICATE_BLOCK)];
12
+ const remainder = normalized.replace(CERTIFICATE_BLOCK, '').trim();
13
+ if (blocks.length === 0 || remainder.length > 0) {
14
+ throw new CaCertificateError('REEVE_TRUSTED_CA_CERTIFICATES must contain only PEM certificates');
15
+ }
16
+ return blocks.map((block) => {
17
+ const pem = `-----BEGIN CERTIFICATE-----\n${(block[1] ?? '').replace(/\s+/g, '')}\n-----END CERTIFICATE-----\n`;
18
+ try {
19
+ return new X509Certificate(pem).toString();
20
+ }
21
+ catch {
22
+ throw new CaCertificateError('REEVE_TRUSTED_CA_CERTIFICATES contains an invalid PEM certificate');
23
+ }
24
+ });
25
+ }
26
+ //# sourceMappingURL=caCertificate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caCertificate.js","sourceRoot":"","sources":["../../src/tls/caCertificate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,MAAM,iBAAiB,GAAG,iEAAiE,CAAC;AAE5F,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAC3C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAClE,MAAM,MAAM,GAAG,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC;IAC3D,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAEnE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,kBAAkB,CAAC,kEAAkE,CAAC,CAAC;IACnG,CAAC;IAED,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAC1B,MAAM,GAAG,GAAG,gCAAgC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,+BAA+B,CAAC;QAChH,IAAI,CAAC;YACH,OAAO,IAAI,eAAe,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC7C,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,kBAAkB,CAAC,mEAAmE,CAAC,CAAC;QACpG,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { CaCertificateError, readCaCertificates } from './caCertificate.js';
2
+ export { CaCertificateError, readCaCertificates };
3
+ export declare function applyTrustedCaCertificates(value?: string | undefined): void;
4
+ //# sourceMappingURL=trustedCaCertificates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trustedCaCertificates.d.ts","sourceRoot":"","sources":["../../src/tls/trustedCaCertificates.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE5E,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,CAAC;AAElD,wBAAgB,0BAA0B,CAAC,KAAK,qBAA4C,GAAG,IAAI,CAYlG"}
@@ -0,0 +1,16 @@
1
+ import * as tls from 'node:tls';
2
+ import { CaCertificateError, readCaCertificates } from './caCertificate.js';
3
+ export { CaCertificateError, readCaCertificates };
4
+ export function applyTrustedCaCertificates(value = process.env.REEVE_TRUSTED_CA_CERTIFICATES) {
5
+ if (value === undefined || value.trim() === '')
6
+ return;
7
+ const certificates = readCaCertificates(value);
8
+ const getCertificates = tls.getCACertificates;
9
+ const setCertificates = tls.setDefaultCACertificates;
10
+ if (typeof getCertificates !== 'function' || typeof setCertificates !== 'function') {
11
+ throw new CaCertificateError('Applying REEVE_TRUSTED_CA_CERTIFICATES requires a newer Node.js version');
12
+ }
13
+ const defaults = getCertificates.call(tls, 'default');
14
+ setCertificates.call(tls, [...defaults, ...certificates]);
15
+ }
16
+ //# sourceMappingURL=trustedCaCertificates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trustedCaCertificates.js","sourceRoot":"","sources":["../../src/tls/trustedCaCertificates.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE5E,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,CAAC;AAElD,MAAM,UAAU,0BAA0B,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B;IAC1F,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO;IAEvD,MAAM,YAAY,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,eAAe,GAAG,GAAG,CAAC,iBAAiB,CAAC;IAC9C,MAAM,eAAe,GAAG,GAAG,CAAC,wBAAwB,CAAC;IACrD,IAAI,OAAO,eAAe,KAAK,UAAU,IAAI,OAAO,eAAe,KAAK,UAAU,EAAE,CAAC;QACnF,MAAM,IAAI,kBAAkB,CAAC,yEAAyE,CAAC,CAAC;IAC1G,CAAC;IAED,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IACtD,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,GAAG,YAAY,CAAC,CAAC,CAAC;AAC5D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@reeve-iot/workload-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "TypeScript session client for the Reeve workload gateway: lets a Node.js sidecar connect to the Reeve host over WebSocket, keep the session alive and exchange data messages.",
5
+ "license": "MIT",
6
+ "homepage": "https://github.com/reeve-iot/reeve/tree/main/sdk/node-workload-client#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/reeve-iot/reeve/issues"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/reeve-iot/reeve.git",
13
+ "directory": "sdk/node-workload-client"
14
+ },
15
+ "keywords": [
16
+ "reeve",
17
+ "home-automation",
18
+ "workload",
19
+ "websocket",
20
+ "sidecar",
21
+ "adapter"
22
+ ],
23
+ "type": "module",
24
+ "main": "./dist/index.js",
25
+ "module": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "engines": {
40
+ "node": ">=18"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "clean": "rm -rf dist",
45
+ "test": "vitest run",
46
+ "test:all": "RUN_DOTNET_CONFORMANCE=1 vitest run",
47
+ "test:conformance": "RUN_DOTNET_CONFORMANCE=1 vitest run tests/wireCompat.dotnet.test.ts tests/e2e.dotnetGateway.dotnet.test.ts",
48
+ "test:watch": "vitest",
49
+ "lint": "tsc -p tsconfig.json --noEmit",
50
+ "prepack": "npm run clean && npm run build"
51
+ },
52
+ "dependencies": {
53
+ "ws": "^8.16.0"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^26.2.0",
57
+ "@types/ws": "^8.5.10",
58
+ "typescript": "^7.0.0",
59
+ "vitest": "^5.0.0"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "provenance": true
64
+ }
65
+ }
package/src/index.ts ADDED
@@ -0,0 +1,59 @@
1
+ export {
2
+ WorkloadSessionClient,
3
+ PROTOCOL_VERSION,
4
+ type WorkloadSessionClientOptions,
5
+ } from './session/WorkloadSessionClient.js';
6
+
7
+ export type { WorkloadSessionOwner, WorkloadSessionObserver } from './session/owner.js';
8
+
9
+ export {
10
+ type WorkloadClientTransport,
11
+ type WorkloadClientTransportFactory,
12
+ WsWorkloadClientTransport,
13
+ WsWorkloadClientTransportFactory,
14
+ } from './session/transport.js';
15
+
16
+ export { ReconnectBackoff, type ReconnectBackoffOptions } from './session/backoff.js';
17
+ export { MessageDeduplicator } from './session/MessageDeduplicator.js';
18
+
19
+ export {
20
+ WorkloadRestClient,
21
+ WorkloadRestEnvVars,
22
+ WorkloadRestError,
23
+ WorkloadNotConsentedError,
24
+ WorkloadUnauthorizedError,
25
+ type WorkloadSelfConfig,
26
+ type WorkloadRestClientOptions,
27
+ type FetchLike,
28
+ type FetchLikeResponse,
29
+ } from './session/rest.js';
30
+
31
+ export { SessionProtocol, MAX_FRAME_BYTES, SnapshotEntryTooLargeError } from './session/SessionProtocol.js';
32
+ export {
33
+ type SessionEnvelope,
34
+ type SessionParseResult,
35
+ type PayloadReadResult,
36
+ SessionParseError,
37
+ } from './session/SessionEnvelope.js';
38
+ export { SessionDataKind, SESSION_DATA_KINDS } from './session/SessionDataKind.js';
39
+
40
+ export {
41
+ SessionFrameType,
42
+ SESSION_FRAME_TYPES,
43
+ type ProtocolRange,
44
+ type HelloFrame,
45
+ type HelloAckFrame,
46
+ type ReauthFrame,
47
+ type AckFrame,
48
+ type CloseFrame,
49
+ type ErrorFrame,
50
+ type AdapterStatus,
51
+ type AdapterHealthMessage,
52
+ type DiscoveredDeviceMessage,
53
+ type DeviceStateMessage,
54
+ type AdapterCommand,
55
+ type AdapterCommandResponse,
56
+ type SnapshotPayload,
57
+ } from './session/types.js';
58
+
59
+ export { applyTrustedCaCertificates, CaCertificateError } from './tls/trustedCaCertificates.js';
@@ -0,0 +1,55 @@
1
+ /** A bounded de-dup window over frame `messageId`s, reflecting the session's AT-LEAST-ONCE delivery contract.
2
+ * FIFO eviction keeps a long session from leaking; best-effort per-connection, not a durable exactly-once store. */
3
+ export class MessageDeduplicator {
4
+ /** Default number of recent message ids to remember. */
5
+ static readonly DEFAULT_CAPACITY = 4096;
6
+
7
+ private readonly cap: number;
8
+ private readonly seen = new Set<string>();
9
+ private readonly order: string[] = [];
10
+
11
+ constructor(capacity: number = MessageDeduplicator.DEFAULT_CAPACITY) {
12
+ if (!Number.isInteger(capacity) || capacity <= 0) {
13
+ throw new RangeError(`Capacity must be a positive integer (got ${capacity}).`);
14
+ }
15
+ this.cap = capacity;
16
+ }
17
+
18
+ /** The bounded number of recent ids retained. */
19
+ get capacity(): number {
20
+ return this.cap;
21
+ }
22
+
23
+ /** The number of ids currently tracked. */
24
+ get count(): number {
25
+ return this.seen.size;
26
+ }
27
+
28
+ /** Records `messageId` as seen: `true` on first sighting (process the frame), `false` for a duplicate within
29
+ * the current window (drop it). Adding past capacity evicts the oldest. */
30
+ trySee(messageId: string): boolean {
31
+ if (this.seen.has(messageId)) {
32
+ return false;
33
+ }
34
+ this.seen.add(messageId);
35
+ this.order.push(messageId);
36
+ if (this.order.length > this.cap) {
37
+ const evicted = this.order.shift();
38
+ if (evicted !== undefined) {
39
+ this.seen.delete(evicted);
40
+ }
41
+ }
42
+ return true;
43
+ }
44
+
45
+ /** Whether `messageId` is currently in the window, WITHOUT recording it. */
46
+ hasSeen(messageId: string): boolean {
47
+ return this.seen.has(messageId);
48
+ }
49
+
50
+ /** Clears the window. */
51
+ clear(): void {
52
+ this.seen.clear();
53
+ this.order.length = 0;
54
+ }
55
+ }
@@ -0,0 +1,14 @@
1
+ /** The sub-discriminator for a DATA frame, so the gateway routes deterministically rather than by shape. OPEN by
2
+ * design: `dataKind` is a free camelCase STRING, and downstream kinds never appear here. */
3
+ export const SessionDataKind = {
4
+ State: 'state',
5
+ Discovered: 'discovered',
6
+ Health: 'health',
7
+ } as const;
8
+
9
+ /** A DATA-frame kind: one of the well-known generic kinds, OR any downstream/Matter string (open). */
10
+ export type SessionDataKind = string;
11
+
12
+ /** The set of WELL-KNOWN generic data-kind strings. NOT a closed allowlist for parsing — an unrecognized
13
+ * downstream `dataKind` is retained verbatim, not rejected. */
14
+ export const SESSION_DATA_KINDS: ReadonlySet<string> = new Set(Object.values(SessionDataKind));
@@ -0,0 +1,32 @@
1
+ import type { SessionDataKind } from './SessionDataKind.js';
2
+ import type { SessionFrameType } from './types.js';
3
+
4
+ /** The WS session frame envelope, camelCase, ported from the .NET record. `messageId` is the de-dup key
5
+ * under at-least-once delivery; `dataKind` is present ONLY on DATA frames and stays off the wire otherwise. */
6
+ export interface SessionEnvelope {
7
+ messageId: string;
8
+ type: SessionFrameType;
9
+ payload?: unknown;
10
+ dataKind?: SessionDataKind;
11
+ }
12
+
13
+ /** Defined, non-throwing failure reasons for parsing/reading a session frame (mirrors .NET `SessionParseError`). */
14
+ export const SessionParseError = {
15
+ None: 'none',
16
+ MalformedJson: 'malformedJson',
17
+ MissingMessageId: 'missingMessageId',
18
+ UnknownFrameType: 'unknownFrameType',
19
+ PayloadTypeMismatch: 'payloadTypeMismatch',
20
+ } as const;
21
+
22
+ export type SessionParseError = (typeof SessionParseError)[keyof typeof SessionParseError];
23
+
24
+ /** Result of parsing a raw wire string into a {@link SessionEnvelope}. Never throws. */
25
+ export type SessionParseResult =
26
+ | { isSuccess: true; envelope: SessionEnvelope; error: typeof SessionParseError.None }
27
+ | { isSuccess: false; envelope: undefined; error: Exclude<SessionParseError, typeof SessionParseError.None> };
28
+
29
+ /** Result of reading a typed payload out of a {@link SessionEnvelope}. Never throws. */
30
+ export type PayloadReadResult<T> =
31
+ | { isSuccess: true; payload: T; error: typeof SessionParseError.None }
32
+ | { isSuccess: false; payload: undefined; error: Exclude<SessionParseError, typeof SessionParseError.None> };
@@ -0,0 +1,351 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { SessionDataKind } from './SessionDataKind.js';
3
+ import {
4
+ type SessionEnvelope,
5
+ type PayloadReadResult,
6
+ type SessionParseResult,
7
+ SessionParseError,
8
+ } from './SessionEnvelope.js';
9
+ import {
10
+ SessionFrameType,
11
+ SESSION_FRAME_TYPES,
12
+ type HelloFrame,
13
+ type HelloAckFrame,
14
+ type ReauthFrame,
15
+ type AckFrame,
16
+ type CloseFrame,
17
+ type ErrorFrame,
18
+ type SnapshotPayload,
19
+ type AdapterCommand,
20
+ type AdapterCommandResponse,
21
+ type DeviceStateMessage,
22
+ type DiscoveredDeviceMessage,
23
+ type AdapterHealthMessage,
24
+ } from './types.js';
25
+
26
+ const textEncoder = new TextEncoder();
27
+ const textDecoder = new TextDecoder('utf-8', { fatal: false });
28
+
29
+ /** The largest frame the workload gateway accepts, in bytes of UTF-8 JSON. A larger frame closes the session. */
30
+ export const MAX_FRAME_BYTES = 1024 * 1024;
31
+
32
+ /** Thrown by {@link SessionProtocol.createSnapshotFrames} when one snapshot entry does not fit a frame on its own. */
33
+ export class SnapshotEntryTooLargeError extends Error {
34
+ constructor(
35
+ readonly section: 'devices' | 'states',
36
+ readonly index: number,
37
+ readonly frameBytes: number,
38
+ readonly maxFrameBytes: number,
39
+ ) {
40
+ super(
41
+ `Snapshot ${section}[${index}] needs a ${frameBytes}-byte SNAPSHOT frame on its own, above the gateway's ` +
42
+ `${maxFrameBytes}-byte frame limit; shrink that entry (its metadata or telemetry).`,
43
+ );
44
+ this.name = 'SnapshotEntryTooLargeError';
45
+ }
46
+ }
47
+
48
+ /** Byte-compatible on the wire with the .NET `SessionProtocol`: camelCase STRING discriminators, never ordinals,
49
+ * and `parse`/`tryRead*` never throw so a socket read-loop survives a hostile or newer peer. */
50
+ export const SessionProtocol = {
51
+ createHello(hello: HelloFrame): SessionEnvelope {
52
+ return envelope(SessionFrameType.Hello, hello);
53
+ },
54
+
55
+ createHelloAck(ack: HelloAckFrame): SessionEnvelope {
56
+ return envelope(SessionFrameType.HelloAck, ack);
57
+ },
58
+
59
+ createReauth(reauth: ReauthFrame): SessionEnvelope {
60
+ return envelope(SessionFrameType.Reauth, reauth);
61
+ },
62
+
63
+ createClose(close: CloseFrame): SessionEnvelope {
64
+ return envelope(SessionFrameType.Close, close);
65
+ },
66
+
67
+ createError(error: ErrorFrame): SessionEnvelope {
68
+ return envelope(SessionFrameType.Error, error);
69
+ },
70
+
71
+ createSnapshot(snapshot: SnapshotPayload): SessionEnvelope {
72
+ return envelope(SessionFrameType.Snapshot, snapshot);
73
+ },
74
+
75
+ /** Splits a snapshot into as few SNAPSHOT frames as fit under `maxFrameBytes` each, keeping entry order.
76
+ * The gateway upserts every entry, so several frames apply as one snapshot. Always returns at least one frame;
77
+ * throws {@link SnapshotEntryTooLargeError} before returning anything when one entry cannot fit alone. */
78
+ createSnapshotFrames(snapshot: SnapshotPayload, maxFrameBytes: number = MAX_FRAME_BYTES): SessionEnvelope[] {
79
+ const emptyBytes = snapshotFrameBytes([], []);
80
+ const frames: SessionEnvelope[] = [];
81
+ let devices: DiscoveredDeviceMessage[] = [];
82
+ let states: DeviceStateMessage[] = [];
83
+ let size = emptyBytes;
84
+
85
+ const place = (section: 'devices' | 'states', index: number, entryBytes: number, count: number): void => {
86
+ if (emptyBytes + entryBytes > maxFrameBytes) {
87
+ throw new SnapshotEntryTooLargeError(section, index, emptyBytes + entryBytes, maxFrameBytes);
88
+ }
89
+ const cost = entryBytes + (count > 0 ? 1 : 0);
90
+ if (size + cost <= maxFrameBytes) {
91
+ size += cost;
92
+ return;
93
+ }
94
+ frames.push(envelope(SessionFrameType.Snapshot, { devices, states }));
95
+ devices = [];
96
+ states = [];
97
+ size = emptyBytes + entryBytes;
98
+ };
99
+
100
+ (snapshot.devices ?? []).forEach((device, index) => {
101
+ place('devices', index, snapshotFrameBytes([device], []) - emptyBytes, devices.length);
102
+ devices.push(device);
103
+ });
104
+ (snapshot.states ?? []).forEach((state, index) => {
105
+ place('states', index, snapshotFrameBytes([], [state]) - emptyBytes, states.length);
106
+ states.push(state);
107
+ });
108
+
109
+ frames.push(envelope(SessionFrameType.Snapshot, { devices, states }));
110
+ return frames;
111
+ },
112
+
113
+ createCommand(command: AdapterCommand): SessionEnvelope {
114
+ return envelope(SessionFrameType.Command, command);
115
+ },
116
+
117
+ createCommandResponse(response: AdapterCommandResponse): SessionEnvelope {
118
+ return envelope(SessionFrameType.CommandResponse, response);
119
+ },
120
+
121
+ /** Creates an Ack envelope for the given `ackedMessageId`. */
122
+ createAck(ackedMessageId: string): SessionEnvelope {
123
+ const frame: AckFrame = { ackedMessageId };
124
+ return envelope(SessionFrameType.Ack, frame);
125
+ },
126
+
127
+ /** Creates a payload-less Heartbeat envelope. */
128
+ createHeartbeat(): SessionEnvelope {
129
+ return { messageId: newMessageId(), type: SessionFrameType.Heartbeat };
130
+ },
131
+
132
+ /** The GENERIC extensibility seam: a DATA envelope carrying `payload` verbatim under an ARBITRARY `dataKind`,
133
+ * so a downstream package can add a kind without editing this client. The typed helpers route through here. */
134
+ createData(payload: unknown, dataKind: string): SessionEnvelope {
135
+ return dataEnvelope(payload, dataKind);
136
+ },
137
+
138
+ /** Creates a DATA(state) envelope, stamped with `dataKind:"state"`. */
139
+ createDataState(state: DeviceStateMessage): SessionEnvelope {
140
+ return dataEnvelope(state, SessionDataKind.State);
141
+ },
142
+
143
+ /** Creates a DATA(discovered) envelope, stamped with `dataKind:"discovered"`. */
144
+ createDataDiscovered(discovered: DiscoveredDeviceMessage): SessionEnvelope {
145
+ return dataEnvelope(discovered, SessionDataKind.Discovered);
146
+ },
147
+
148
+ /** Creates a DATA(health) envelope, stamped with `dataKind:"health"`. */
149
+ createDataHealth(health: AdapterHealthMessage): SessionEnvelope {
150
+ return dataEnvelope(health, SessionDataKind.Health);
151
+ },
152
+
153
+ /** Serializes an envelope to its canonical camelCase wire JSON string (undefined fields omitted). */
154
+ serialize(env: SessionEnvelope): string {
155
+ return JSON.stringify(toWire(env));
156
+ },
157
+
158
+ /** Serializes an envelope to UTF-8 wire bytes. */
159
+ serializeToUtf8Bytes(env: SessionEnvelope): Uint8Array {
160
+ return textEncoder.encode(SessionProtocol.serialize(env));
161
+ },
162
+
163
+ /** Parses a raw wire string into a {@link SessionEnvelope}. Never throws. */
164
+ parse(json: string): SessionParseResult {
165
+ if (typeof json !== 'string' || json.trim().length === 0) {
166
+ return fail(SessionParseError.MalformedJson);
167
+ }
168
+
169
+ let root: unknown;
170
+ try {
171
+ root = JSON.parse(json);
172
+ } catch {
173
+ return fail(SessionParseError.MalformedJson);
174
+ }
175
+
176
+ if (typeof root !== 'object' || root === null || Array.isArray(root)) {
177
+ return fail(SessionParseError.MalformedJson);
178
+ }
179
+
180
+ const obj = root as Record<string, unknown>;
181
+
182
+ const messageId = obj['messageId'];
183
+ if (typeof messageId !== 'string' || messageId.length === 0) {
184
+ return fail(SessionParseError.MissingMessageId);
185
+ }
186
+
187
+ const typeRaw = obj['type'];
188
+ if (typeof typeRaw !== 'string') {
189
+ return fail(SessionParseError.UnknownFrameType);
190
+ }
191
+ const frameType = parseFrameType(typeRaw);
192
+ if (frameType === undefined) {
193
+ return fail(SessionParseError.UnknownFrameType);
194
+ }
195
+
196
+ const rawPayload = obj['payload'];
197
+ const payload = rawPayload === null || rawPayload === undefined ? undefined : rawPayload;
198
+
199
+ let dataKind: SessionDataKind | undefined;
200
+ if (frameType === SessionFrameType.Data && typeof obj['dataKind'] === 'string') {
201
+ dataKind = parseDataKind(obj['dataKind']);
202
+ }
203
+
204
+ const env: SessionEnvelope = { messageId, type: frameType };
205
+ if (payload !== undefined) env.payload = payload;
206
+ if (dataKind !== undefined) env.dataKind = dataKind;
207
+ return { isSuccess: true, envelope: env, error: SessionParseError.None };
208
+ },
209
+
210
+ /** Parses UTF-8 wire bytes into a {@link SessionEnvelope}. Never throws. */
211
+ parseBytes(utf8: Uint8Array): SessionParseResult {
212
+ try {
213
+ return SessionProtocol.parse(textDecoder.decode(utf8));
214
+ } catch {
215
+ return fail(SessionParseError.MalformedJson);
216
+ }
217
+ },
218
+
219
+ tryReadHelloAck(env: SessionEnvelope): PayloadReadResult<HelloAckFrame> {
220
+ return readPayload<HelloAckFrame>(env, SessionFrameType.HelloAck);
221
+ },
222
+
223
+ tryReadAck(env: SessionEnvelope): PayloadReadResult<AckFrame> {
224
+ return readPayload<AckFrame>(env, SessionFrameType.Ack);
225
+ },
226
+
227
+ tryReadCommand(env: SessionEnvelope): PayloadReadResult<AdapterCommand> {
228
+ return readPayload<AdapterCommand>(env, SessionFrameType.Command);
229
+ },
230
+
231
+ tryReadCommandResponse(env: SessionEnvelope): PayloadReadResult<AdapterCommandResponse> {
232
+ return readPayload<AdapterCommandResponse>(env, SessionFrameType.CommandResponse);
233
+ },
234
+
235
+ tryReadReauth(env: SessionEnvelope): PayloadReadResult<ReauthFrame> {
236
+ return readPayload<ReauthFrame>(env, SessionFrameType.Reauth);
237
+ },
238
+
239
+ tryReadClose(env: SessionEnvelope): PayloadReadResult<CloseFrame> {
240
+ return readPayload<CloseFrame>(env, SessionFrameType.Close);
241
+ },
242
+
243
+ tryReadError(env: SessionEnvelope): PayloadReadResult<ErrorFrame> {
244
+ return readPayload<ErrorFrame>(env, SessionFrameType.Error);
245
+ },
246
+
247
+ tryReadSnapshot(env: SessionEnvelope): PayloadReadResult<SnapshotPayload> {
248
+ return readPayload<SnapshotPayload>(env, SessionFrameType.Snapshot);
249
+ },
250
+
251
+ /** Reads a DATA frame's payload as `T` ONLY when its `dataKind` equals `expectedDataKind`. Returns a defined
252
+ * `PayloadTypeMismatch` — never throws — on any mismatch or a missing/non-object payload. */
253
+ tryReadData<T>(env: SessionEnvelope, expectedDataKind: string): PayloadReadResult<T> {
254
+ if (env.type !== SessionFrameType.Data || env.dataKind !== expectedDataKind) {
255
+ return payloadFail(SessionParseError.PayloadTypeMismatch);
256
+ }
257
+ const payload = env.payload;
258
+ if (payload === undefined || payload === null || typeof payload !== 'object') {
259
+ return payloadFail(SessionParseError.PayloadTypeMismatch);
260
+ }
261
+ return { isSuccess: true, payload: payload as T, error: SessionParseError.None };
262
+ },
263
+ };
264
+
265
+ function newMessageId(): string {
266
+ return randomUUID();
267
+ }
268
+
269
+ function envelope<T>(type: SessionFrameType, payload: T): SessionEnvelope {
270
+ return { messageId: newMessageId(), type, payload };
271
+ }
272
+
273
+ function dataEnvelope<T>(payload: T, dataKind: SessionDataKind): SessionEnvelope {
274
+ return { messageId: newMessageId(), type: SessionFrameType.Data, payload, dataKind };
275
+ }
276
+
277
+ function fail(error: Exclude<SessionParseError, typeof SessionParseError.None>): SessionParseResult {
278
+ return { isSuccess: false, envelope: undefined, error };
279
+ }
280
+
281
+ function stripUndefined(value: unknown): unknown {
282
+ if (Array.isArray(value)) {
283
+ return value.map(stripUndefined);
284
+ }
285
+ if (value !== null && typeof value === 'object') {
286
+ const out: Record<string, unknown> = {};
287
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
288
+ if (v !== undefined) {
289
+ out[k] = stripUndefined(v);
290
+ }
291
+ }
292
+ return out;
293
+ }
294
+ return value;
295
+ }
296
+
297
+ const MEASURE_MESSAGE_ID = '00000000-0000-0000-0000-000000000000';
298
+
299
+ function snapshotFrameBytes(devices: DiscoveredDeviceMessage[], states: DeviceStateMessage[]): number {
300
+ const payload: SnapshotPayload = { devices, states };
301
+ return textEncoder.encode(
302
+ JSON.stringify(toWire({ messageId: MEASURE_MESSAGE_ID, type: SessionFrameType.Snapshot, payload })),
303
+ ).length;
304
+ }
305
+
306
+ function toWire(env: SessionEnvelope): Record<string, unknown> {
307
+ const wire: Record<string, unknown> = { messageId: env.messageId, type: env.type };
308
+ if (env.payload !== undefined) {
309
+ wire['payload'] = stripUndefined(env.payload);
310
+ }
311
+ if (env.dataKind !== undefined) {
312
+ wire['dataKind'] = env.dataKind;
313
+ }
314
+ return wire;
315
+ }
316
+
317
+ function parseFrameType(raw: string): SessionFrameType | undefined {
318
+ if (raw.length === 0) return undefined;
319
+ const first = raw[0]!;
320
+ if (first === '-' || first === '+' || (first >= '0' && first <= '9')) return undefined;
321
+
322
+ const lower = raw.toLowerCase();
323
+ for (const value of SESSION_FRAME_TYPES) {
324
+ if (value.toLowerCase() === lower) return value as SessionFrameType;
325
+ }
326
+ return undefined;
327
+ }
328
+
329
+ function parseDataKind(raw: string): SessionDataKind | undefined {
330
+ if (raw.length === 0) return undefined;
331
+ const first = raw[0]!;
332
+ if (first === '-' || first === '+' || (first >= '0' && first <= '9')) return undefined;
333
+ return raw;
334
+ }
335
+
336
+ function readPayload<T>(env: SessionEnvelope, expected: SessionFrameType): PayloadReadResult<T> {
337
+ if (env.type !== expected) {
338
+ return payloadFail(SessionParseError.PayloadTypeMismatch);
339
+ }
340
+ const payload = env.payload;
341
+ if (payload === undefined || payload === null || typeof payload !== 'object') {
342
+ return payloadFail(SessionParseError.PayloadTypeMismatch);
343
+ }
344
+ return { isSuccess: true, payload: payload as T, error: SessionParseError.None };
345
+ }
346
+
347
+ function payloadFail<T>(
348
+ error: Exclude<SessionParseError, typeof SessionParseError.None>,
349
+ ): PayloadReadResult<T> {
350
+ return { isSuccess: false, payload: undefined, error };
351
+ }