# @hiyve/semantic-relay-client

Framework-agnostic browser client for the Hiyve Semantic Relay — a WebTransport (HTTP/3 / QUIC) datagram service co-deployed with the signaling server, built for high-frequency, fire-and-forget, room-scoped messaging.

For React applications, use [`@hiyve/react-semantic-relay`](../react-semantic-relay) which wraps this client with a context provider and topic-scoped pub/sub hooks.

## Installation

```bash
npm install @hiyve/semantic-relay-client
```

## Quick start

```typescript
import { SemanticRelayClient } from '@hiyve/semantic-relay-client';

const client = new SemanticRelayClient({
  url: 'https://semantic.hiyve.tv:4443/relay',
  roomId: 'lesson-abc',
  userId: 'alice@example.com',
  token: jwtFromBackend,
  serverCertificateHashes, // optional; required for self-signed dev/prod certs
});

const session = await client.connect();
console.log('session id', session.sessionId, 'peers', session.peers);

const unsubscribe = client.subscribe('instrument-notes', ({ payload, userId }) => {
  console.log(`${userId} played`, payload);
});

client.publish('instrument-notes', { midi: 60, on: true, velocity: 100 });

// Later:
unsubscribe();
client.dispose();
```

> `serverCertificateHashes` is a `RelayCertHash[]` of SHA-256 fingerprints — see the [WebTransport docs](https://developer.mozilla.org/docs/Web/API/WebTransport/WebTransport) for derivation. Production deployments using a public CA can omit it.

## Options

| Option | Required | Description |
|---|---|---|
| `url` | yes | Base WebTransport URL (`https://...:4443/relay`). |
| `roomId` | yes | Room identifier — relay-side broadcast scope. |
| `userId` | yes | Sender identity attached to every published message. |
| `token` | yes | Short-lived auth token minted by the app backend. |
| `serverCertificateHashes` | no | SHA-256 certificate hashes for self-signed certs. |
| `onError` | no | Connection / publish / decode errors. |
| `onConnectionChange` | no | Notification when the connection state changes (`connecting`, `connected`, `closed`, `error`). |
| `onDebug` | no | Debug logger; pairs with `createDebugLogger('hiyve:semantic-relay')`. |
| `maxSeenMessages` | no | Per-topic dedupe cache size (default 200). |
| `pruneCount` | no | Dedupe entries dropped when the cache is full (default 50). |
| `retryDelaysMs` | no | Connect-retry backoff (default `[200, 800, 2000]`). Auth failures bypass. |

The client wraps relay messages in a small envelope; serialization, framing, and identity stamping are handled internally.

## Limits

- One sender per connection (peer routing is server-side).
- Up to 100 participants per room (relay-enforced).
- Max envelope size ~1200 bytes (`MAX_DATAGRAM_BYTES`); larger messages should fragment at the application layer.

## Browser support

WebTransport is available in Chrome, Edge, and Firefox. Safari requires an experimental flag at the time of writing. Consumers should fall back to a different transport when `globalThis.WebTransport` is undefined.

## Types & constants

| Export | Description |
|---|---|
| `SemanticRelayClient` | The client class. |
| `RelayCertHash` | Shape of a single SHA-256 cert hash entry. |
| `RelayConnectionState` | `'idle' \| 'connecting' \| 'connected' \| 'error' \| 'closed'`. |
| `RelayEnvelope<T>` | Wire envelope shape. |
| `RelayMessage<T>` | Subscriber-visible message: `{ topic, payload, userId, messageId, timestamp }`. |
| `RelayOptions` | Constructor options shape. |
| `DefaultedRelayOptions` | Options after defaults are applied. |
| `RelaySubscribeHandler<T>` | Callback signature for `subscribe`. |
| `SessionInfo` | Session metadata returned by `connect()`. |
| `DEFAULT_OPTIONS` | The full default options object. |
| `mergeOptions(user)` | Merge user options on top of `DEFAULT_OPTIONS`. |
| `MAX_DATAGRAM_BYTES` | Max envelope size (~1200). |
| `SESSION_ID_HEADER_BYTES` | Bytes reserved for the session-id header in each datagram. |
| `DEFAULT_MAX_SEEN_MESSAGES` | Default dedupe cache size. |
| `DEFAULT_PRUNE_COUNT` | Default prune count when the cache is full. |
| `DEFAULT_RETRY_DELAYS_MS` | Default reconnect backoff schedule. |
| `DEFAULT_CONNECT_TIMEOUT_MS` | Default connect timeout. |
| `SESSION_INFO_TYPE` | Tag for `SessionInfo` messages on the control topic. |

## License

MIT
